@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
@@ -7,6 +7,7 @@ import {digest,hex,id,json,need,shape,text,validIdentity} from './effect-contrac
7
7
  import {readQaAttachment} from './qa-attachment.mjs';
8
8
  import {writeCmAiQaStatus} from './cm-ai-run-finalizer.mjs';
9
9
  import {scanRows} from './log-rows.mjs';
10
+ import {QA_MAX_ROUNDS,qaRoundLimit,nonProductSupersession} from './qa-round-budget.mjs';
10
11
  import {readExecutionSnapshot} from './execution-snapshot.mjs';
11
12
  import {beforeFirstQaRound,qaRevisionChain,readQaConfigRevision} from './qa-config-revision.mjs';
12
13
 
@@ -29,7 +30,9 @@ export function recordCmAiQaAttachment({specsDir,codeProject,feature,identity,re
29
30
  }
30
31
 
31
32
  export function readDecision(raw,identity,packageDigest) {
32
- const decision=json(raw);shape(decision,['decisionId','identity','packageDigest','status','reason','score','at']);
33
+ const decision=json(raw);shape(decision,['decisionId','identity','packageDigest','status','reason','score','at',
34
+ ...(Object.hasOwn(decision,'changedFilesSource')?['changedFilesSource']:[])]);
35
+ if(Object.hasOwn(decision,'changedFilesSource'))need(['review_package','handoff_only','unavailable'].includes(decision.changedFilesSource));
33
36
  id(decision.decisionId);validIdentity(decision.identity);hex(decision.packageDigest);
34
37
  need(sameIdentity(decision.identity,identity)&&decision.packageDigest===packageDigest,'qa_decision_mismatch');
35
38
  need(['triggered','skipped','blocked'].includes(decision.status));
@@ -38,7 +41,7 @@ export function readDecision(raw,identity,packageDigest) {
38
41
  &&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:Z|[+-]\d{2}:\d{2})$/.test(decision.at)
39
42
  &&Number.isFinite(Date.parse(decision.at)));
40
43
  if(decision.score!==null)need(Number.isInteger(decision.score)&&decision.score>=4&&decision.score<=20);
41
- if(decision.status==='skipped')need(Number.isInteger(decision.score)&&decision.score<=7);
44
+ if(decision.status==='skipped'&&decision.score!==null)need(decision.score<=7);
42
45
  if(decision.status==='triggered'&&decision.score!==null)need(decision.score>=8);
43
46
  return json({...decision,at:decision.at.endsWith('Z')?`${decision.at.slice(0,-1)}+00:00`:decision.at});
44
47
  }
@@ -69,7 +72,8 @@ function existingDecision(specsDir,feature,identity,packageDigest,decision,previ
69
72
  const row=effectiveQaDecisionRow(matches,'qa_decision_conflict');
70
73
  if(row.decision_id===decision.decisionId){
71
74
  need(row.status===decision.status&&row.reason===decision.reason&&row.score===decision.score&&row.at===decision.at
72
- &&(row.previous_decision_id??null)===previousDecisionId,'qa_decision_conflict');
75
+ &&(row.previous_decision_id??null)===previousDecisionId
76
+ &&(row.changed_files_source??null)===(decision.changedFilesSource??null),'qa_decision_conflict');
73
77
  return true;
74
78
  }
75
79
  // Only the single recorded timeout decision can be superseded, and once.
@@ -104,11 +108,12 @@ export function recordCmAiQaDecision(input) {
104
108
  const decision=readDecision(input.decision,input.identity,input.packageDigest);
105
109
  if(existingDecision(input.specsDir,input.feature,input.identity,input.packageDigest,decision,previousDecisionId))return;
106
110
  const detail=(decision.status==='triggered'?`触发:${decision.reason}`:
107
- decision.status==='skipped'?`跳过:评分${decision.score}`:`阻塞:${decision.reason}`)
111
+ decision.status==='skipped'?`跳过:${decision.reason}`:`阻塞:${decision.reason}`)
108
112
  +(previousDecisionId===null?'':`(重新评估,替代 ${previousDecisionId})`);
109
113
  const data={node:'N6',feature:input.feature,task:input.identity.taskId,attempt:input.identity.attempt,
110
114
  repository_id:input.identity.repositoryId,package_digest:input.packageDigest,decision_id:decision.decisionId,
111
115
  status:decision.status,reason:decision.reason,score:decision.score,
116
+ ...(Object.hasOwn(decision,'changedFilesSource')?{changed_files_source:decision.changedFilesSource}:{}),
112
117
  ...(previousDecisionId===null?{}:{previous_decision_id:previousDecisionId})};
113
118
  const args=[writer,'--workflow','cm-ai','--event','qa','--runtime','codex','--project-root',input.codeProject,
114
119
  '--specs-dir',input.specsDir,'--run-id',input.identity.runId,'--at',decision.at,'--detail',detail,
@@ -154,7 +159,8 @@ function findDecisionRow(input) {
154
159
  export function findCmAiQaDecision(input) {
155
160
  const row=findDecisionRow(input);if(row===null)return null;
156
161
  return readDecision({status:row.status,decisionId:row.decision_id,identity:input.identity,
157
- packageDigest:input.packageDigest,reason:row.reason,score:row.score,at:row.at},input.identity,input.packageDigest);
162
+ packageDigest:input.packageDigest,reason:row.reason,score:row.score,at:row.at,
163
+ ...(Object.hasOwn(row,'changed_files_source')?{changedFilesSource:row.changed_files_source}:{})},input.identity,input.packageDigest);
158
164
  }
159
165
 
160
166
  // True when the effective decision is the linked replacement of a timed-out
@@ -204,16 +210,33 @@ function partialPassCases(items,code){
204
210
  // elapsed since case_start (log times are whole seconds) and an explicit operator
205
211
  // attestation (--qa-environment-failure), recorded on the superseded row.
206
212
  // A session-declared BLOCKED, any FAIL or other BLOCKED refuses.
207
- function timedOutCases(items,code,requestTimeoutMs,attestation=null){
213
+ // Q06/Q11: the same holds for a call stopped by a host death or a hard-invalid
214
+ // answer. Rows the session itself declared BLOCKED (host_declared_blocked), and
215
+ // rows the host judged BLOCKED for an evidence, environment or cleanup gap
216
+ // (blocked_reason, written by current executors), are host or answer problems
217
+ // too: they are listed as host_blocked_cases. An unresolved [需确认], a missing
218
+ // capability, a FAIL, or an older row that cannot tell still refuses.
219
+ const HOST_JUDGED_BLOCKED=['evidence','environment','cleanup'];
220
+ // context {specsDir,feature}: the approved test contract decides [需确认].
221
+ function timedOutCases(items,code,requestTimeoutMs,attestation=null,allowHostBlocked=false,context=null){
208
222
  need(attestation===null||validEnvironmentFailureReason(attestation),code);
209
223
  need(requestTimeoutMs===null||Number.isSafeInteger(requestTimeoutMs)&&requestTimeoutMs>0&&requestTimeoutMs<=3600000,code);
210
224
  need(!items.some(({row})=>['complete','abandoned','superseded'].includes(row.phase)
211
225
  ||(row.phase==='case_complete'&&row.result!=='PASS')),code);
212
- const started=new Map(),timedOut=[];
226
+ const started=new Map(),timedOut=[],hostBlocked=[];
213
227
  for(const {row} of items){
214
228
  if(row.phase==='case_start'){id(row.case_id);started.set(row.case_id,row.at);}
215
229
  if(row.phase!=='case_blocked')continue;
216
- id(row.case_id);need(row.result==='BLOCKED'&&row.host_declared_blocked!==true,code);
230
+ id(row.case_id);need(row.result==='BLOCKED',code);
231
+ if(row.host_declared_blocked===true||HOST_JUDGED_BLOCKED.includes(row.blocked_reason)){
232
+ // An original FAIL the host downgraded, a row that does not keep the
233
+ // session's verdict, and an unresolved [需确认] in the approved contract
234
+ // refuse before any host-fault eligibility.
235
+ need(allowHostBlocked&&context!==null&&['PASS','BLOCKED'].includes(row.answered_verdict)
236
+ &&(row.host_declared_blocked!==true||row.answered_verdict==='BLOCKED')
237
+ &&!['needs_confirmation','unavailable'].includes(row.blocked_reason),code);
238
+ hostBlocked.push(row.case_id);continue;
239
+ }
217
240
  if(Object.hasOwn(row,'host_request_timeout'))need(row.host_request_timeout===true,code);
218
241
  else{
219
242
  const elapsed=Date.parse(row.at)-Date.parse(started.get(row.case_id));
@@ -222,9 +245,11 @@ function timedOutCases(items,code,requestTimeoutMs,attestation=null){
222
245
  }
223
246
  timedOut.push(row.case_id);
224
247
  }
225
- need(timedOut.length>0,code);
248
+ need(timedOut.length+hostBlocked.length>0,code);
249
+ if(hostBlocked.length){const contract=contractCases(context.specsDir,context.feature,code);
250
+ for(const caseId of hostBlocked)need(!confirmationPending(contract.get(caseId)),code);}
226
251
  const passed=items.filter(({row})=>row.phase==='case_complete').map(({row})=>row.case_id);
227
- return {timedOut:[...new Set(timedOut)].sort(),passed:[...new Set(passed)].sort()};
252
+ return {timedOut:[...new Set(timedOut)].sort(),hostBlocked:[...new Set(hostBlocked)].sort(),passed:[...new Set(passed)].sort()};
228
253
  }
229
254
 
230
255
  // host-check reports a command that produced no exit code as `unavailable`
@@ -293,7 +318,10 @@ function passBacking(items,specsDir,feature,cases,code){
293
318
  // incomplete: the call wrote its fixed report but no complete row (a pre-fix host
294
319
  // rejected stale_qa in between). The report is then the only result; its counts
295
320
  // stand in for the complete row and every other rule applies unchanged.
296
- function recoverableCases(items,specsDir,environment,code='qa_rerun_not_blocked_by_evidence',environmentFailure=false,legacyRule=false,incomplete=false){
321
+ // verdictRule (recovery_rule 3): a browser BLOCKED counts as a host fault only
322
+ // when the durable case row keeps the session's own verdict (answered_verdict)
323
+ // and it was not a FAIL; rows without it (older format) are not recoverable here.
324
+ function recoverableCases(items,specsDir,environment,code='qa_rerun_not_blocked_by_evidence',environmentFailure=false,legacyRule=false,incomplete=false,verdictRule=false){
297
325
  const completes=items.filter(({row})=>row.phase==='complete'),start=items[0]?.row;
298
326
  need(completes.length===(incomplete?0:1)&&start?.phase==='start'&&!(incomplete&&(legacyRule||environmentFailure)),code);
299
327
  let complete=incomplete?null:completes[0].row;
@@ -336,12 +364,23 @@ function recoverableCases(items,specsDir,environment,code='qa_rerun_not_blocked_
336
364
  // executor appended when the session answered, not by the mutable report.
337
365
  const declaredInLog=new Set(items.filter(({row})=>row.phase==='case_blocked'&&row.host_declared_blocked===true)
338
366
  .map(({row})=>row.case_id));
367
+ const blockedRows=new Map(items.filter(({row})=>row.phase==='case_blocked').map(({row})=>[row.case_id,row]));
368
+ // An original FAIL the host downgraded, a missing capability and an unresolved
369
+ // [需确认] refuse before any host-fault eligibility.
370
+ const sessionVerdictOk=row=>{
371
+ if(!verdictRule)return true;
372
+ const logged=blockedRows.get(row.id);
373
+ if(!logged||['needs_confirmation','unavailable'].includes(logged.blocked_reason))return false;
374
+ if(row.hostRequestTimeout===true&&logged.host_request_timeout===true&&!Object.hasOwn(logged,'answered_verdict'))return true;
375
+ return ['PASS','BLOCKED'].includes(logged.answered_verdict)
376
+ &&(logged.answered_verdict!=='BLOCKED'||logged.host_declared_blocked===true);
377
+ };
339
378
  const eligible=row=>(
340
379
  row.kind==='logic'&&resolved(row)&&(row.staticVerdict==='INSUFFICIENT_EVIDENCE'
341
380
  // Blocked only by a mapped command without exit code, derived from the
342
381
  // recorded command rows; the executor's marker has to agree.
343
382
  ||row.staticVerdict==='SUPPORTED'&&mapped(row,unavailableCommand)&&row.commandUnavailable===true)
344
- ||row.kind==='browser'&&resolved(row)&&(typeof row.evidenceProblem==='string'&&row.evidenceProblem.length>0
383
+ ||row.kind==='browser'&&resolved(row)&&sessionVerdictOk(row)&&(typeof row.evidenceProblem==='string'&&row.evidenceProblem.length>0
345
384
  ||row.cleanup==='failed'||row.hostRequestTimeout===true||declaredInLog.has(row.id)&&row.hostDeclaredBlocked===true
346
385
  ||environment!=null&&row.environment!=null&&digest(row.environment)!==digest(environment))
347
386
  ||unavailableCommand(row));
@@ -381,12 +420,12 @@ function validateConfigurationSupersession(row,specsDir,code){
381
420
 
382
421
  // Abandonment reuses a round; superseded completed evidence advances it.
383
422
  function validateRunSequence(items,code='qa_round_invalid',specsDir){
384
- const starts=[],ids=new Set();let current=null,abandoned=false,superseded=false;
423
+ const starts=[],ids=new Set();let current=null,abandoned=false,superseded=false,freed=0;
385
424
  for(const item of items){
386
425
  const row=item.row;
387
426
  if(row.phase==='start'){
388
427
  id(row.operation_id);need(!ids.has(row.operation_id),code);ids.add(row.operation_id);
389
- need(row.attempt===(current?current.attempt+(abandoned?0:1):1)&&row.attempt<=3,code);
428
+ need(row.attempt===(current?current.attempt+(abandoned?0:1):1)&&row.attempt<=qaRoundLimit(freed),code);
390
429
  if(abandoned){
391
430
  // Legacy successors retain their plan; explicit links may bind a fresh plan.
392
431
  if(row.previous_test_run_id===undefined)need(row.mode===current.mode&&row.case_count===current.case_count,code);
@@ -401,30 +440,35 @@ function validateRunSequence(items,code='qa_round_invalid',specsDir){
401
440
  }else{
402
441
  need(current&&row.operation_id===current.operation_id&&row.attempt===current.attempt&&!abandoned&&!superseded,code);
403
442
  if(row.phase==='superseded'){
404
- need(current.attempt<3&&row.previous_test_run_id===current.operation_id
443
+ need(current.attempt<qaRoundLimit(freed+(nonProductSupersession(row.reason)?1:0))&&row.previous_test_run_id===current.operation_id
405
444
  &&row.mode===current.mode&&row.case_count===current.case_count,code);
406
445
  const prior=items.filter(entry=>entry.position<item.position&&entry.row.operation_id===row.operation_id);
407
446
  if(row.reason==='qa_configuration_revision'){
408
447
  need(prior.filter(entry=>entry.row.phase==='complete').length===1,code);
409
448
  validateConfigurationSupersession(row,specsDir,code);
410
449
  }else if(row.reason==='host_request_timeout'){
411
- const cases=timedOutCases(prior,code,row.request_timeout_ms??null,row.legacy_timeout_attestation??null);
450
+ // Rows before host_blocked_cases existed could list no such case.
451
+ const cases=timedOutCases(prior,code,row.request_timeout_ms??null,row.legacy_timeout_attestation??null,
452
+ Object.hasOwn(row,'host_blocked_cases'),{specsDir,feature:row.feature});
412
453
  need(row.request_timeout_ms!==null&&JSON.stringify(row.timed_out_cases)===JSON.stringify(cases.timedOut)
454
+ &&JSON.stringify(row.host_blocked_cases??[])===JSON.stringify(cases.hostBlocked)
455
+ &&(!Object.hasOwn(row,'host_blocked_cases')||cases.hostBlocked.length>0)
413
456
  &&JSON.stringify(row.partial_pass_cases)===JSON.stringify(cases.passed),code);
414
457
  }else{
415
458
  const declared=row.reason==='declared_environment_failure';
416
459
  need(declared?validEnvironmentFailureReason(row.environment_failure_reason):row.reason==='host_evidence_problem',code);
417
460
  // Rows without recovery_rule were written by released versions before
418
461
  // this change (the pre-branch format) under the original rule.
419
- const legacy=row.recovery_rule===undefined;need(legacy||row.recovery_rule===2,code);
462
+ const legacy=row.recovery_rule===undefined;need(legacy||[2,3].includes(row.recovery_rule),code);
420
463
  // incomplete_report: the superseded call had a fixed report but no complete row.
421
464
  const incomplete=row.incomplete_report===true;
422
465
  need(row.incomplete_report===undefined||incomplete&&!legacy&&!declared
423
466
  &&!prior.some(entry=>entry.row.phase==='complete'),code);
424
- const cases=recoverableCases(prior,specsDir,row.expected_environment,code,declared,legacy,incomplete);
467
+ const cases=recoverableCases(prior,specsDir,row.expected_environment,code,declared,legacy,incomplete,row.recovery_rule===3);
425
468
  need(JSON.stringify(row.blocked_cases)===JSON.stringify(cases.blocked)
426
469
  &&(declared?JSON.stringify(row.failed_cases)===JSON.stringify(cases.failed):row.failed_cases===undefined),code);
427
470
  }
471
+ if(nonProductSupersession(row.reason))freed++;
428
472
  superseded=true;
429
473
  }
430
474
  if(row.phase==='abandoned'){
@@ -439,7 +483,7 @@ function validateRunSequence(items,code='qa_round_invalid',specsDir){
439
483
  }
440
484
  }
441
485
  }
442
- need(starts.length>0,code);return starts;
486
+ need(starts.length>0,code);starts.freed=freed;return starts;
443
487
  }
444
488
 
445
489
  function qaRunRows(input){
@@ -472,9 +516,11 @@ export function inspectCmAiQaRecovery(input,{blocked=false,environment=null,envi
472
516
  const declared=recorded?recorded.reason==='declared_environment_failure':environmentFailure!==null;
473
517
  const prior=runs.filter(({row})=>row.phase!=='superseded');
474
518
  const incomplete=recorded?recorded.incomplete_report===true:!prior.some(({row})=>row.phase==='complete');
519
+ // A fresh supersession is written under recovery_rule 3; a recorded row keeps its own rule.
475
520
  const cases=recoverableCases(prior,input.specsDir,environment,'qa_rerun_not_blocked_by_evidence',declared,
476
- recorded!==undefined&&recorded.recovery_rule===undefined,incomplete);
477
- need(start.attempt<3,'qa_round_invalid');
521
+ recorded!==undefined&&recorded.recovery_rule===undefined,incomplete,recorded===undefined||recorded.recovery_rule===3);
522
+ // A recorded supersession is already counted in starts.freed.
523
+ need(start.attempt<qaRoundLimit(starts.freed+(recorded===undefined&&!declared?1:0)),'qa_round_invalid');
478
524
  return {testRunId:start.operation_id,qaRound:start.attempt,mode:start.mode,caseCount:start.case_count,
479
525
  blockedCases:cases.blocked,failedCases:cases.failed,superseded:recorded!==undefined,incompleteReport:incomplete};
480
526
  }
@@ -486,10 +532,12 @@ export function inspectCmAiQaRecovery(input,{blocked=false,environment=null,envi
486
532
  need(recorded===undefined?!exists:recorded.reason==='host_request_timeout','qa_execution_unknown');
487
533
  const timeout=recorded?recorded.request_timeout_ms??null:requestTimeoutMs;
488
534
  const attested=recorded?recorded.legacy_timeout_attestation??null:attestation;
489
- const cases=timedOutCases(runs.filter(({row})=>row.phase!=='superseded'),'qa_execution_unknown',timeout,attested);
490
- need(start.attempt<3,'qa_round_invalid');
535
+ const cases=timedOutCases(runs.filter(({row})=>row.phase!=='superseded'),'qa_execution_unknown',timeout,attested,
536
+ recorded===undefined||Object.hasOwn(recorded,'host_blocked_cases'),{specsDir:input.specsDir,feature:start.feature});
537
+ need(start.attempt<qaRoundLimit(starts.freed+(recorded===undefined?1:0)),'qa_round_invalid');
491
538
  return {testRunId:start.operation_id,qaRound:start.attempt,mode:start.mode,caseCount:start.case_count,
492
- timedOutCases:cases.timedOut,partialPassCases:cases.passed,requestTimeoutMs:timeout,attestation:attested,superseded:recorded!==undefined};
539
+ timedOutCases:cases.timedOut,hostBlockedCases:cases.hostBlocked,partialPassCases:cases.passed,
540
+ requestTimeoutMs:timeout,attestation:attested,superseded:recorded!==undefined};
493
541
  }
494
542
  const passed=partialPassCases(runs,'qa_execution_unknown');
495
543
  // A report without complete is an unconfirmed result: a host that found the run
@@ -610,7 +658,7 @@ export function recordCmAiQaRun(input) {
610
658
  need(Number.isSafeInteger(input.caseCount)&&input.caseCount>0);
611
659
  need(['start','complete','abandoned','superseded'].includes(input.phase));
612
660
  const qaRound=input.qaRound??1;
613
- need(Number.isSafeInteger(qaRound)&&qaRound>=1&&qaRound<=3,'qa_round_invalid');
661
+ need(Number.isSafeInteger(qaRound)&&qaRound>=1&&qaRound<=QA_MAX_ROUNDS,'qa_round_invalid');
614
662
  const binding={specsDir:input.specsDir,feature:input.feature,identity:input.identity,packageDigest:input.packageDigest};
615
663
  let passed=[],blockedCases=[],failedCases=[],declaredFailure=null,incompleteReport=false,timedOut=null;
616
664
  if(Object.hasOwn(input,'environmentFailure'))need(input.phase==='superseded'&&!input.configurationRevision
@@ -654,6 +702,9 @@ export function recordCmAiQaRun(input) {
654
702
  scanRows(path.join(input.specsDir,'运行日志.jsonl'),row=>{
655
703
  need(!(row.event==='test_run'&&row.operation_id===input.testRunId),'qa_round_invalid');
656
704
  });
705
+ // Q14: a round beyond three starts only when host-caused rounds gave one back.
706
+ const prior=qaRunRows(binding);
707
+ need(qaRound<=qaRoundLimit(prior.length?validateRunSequence(prior,'qa_round_invalid',input.specsDir).freed:0),'qa_round_invalid');
657
708
  if(previous===null)need(qaRound===1,'qa_round_invalid');
658
709
  else if(!Object.hasOwn(input,'previousTestRunId')){
659
710
  const failure=inspectCmAiQaFailure({...binding,testRunId:previous.testRunId});
@@ -687,10 +738,11 @@ export function recordCmAiQaRun(input) {
687
738
  if(input.phase==='abandoned')Object.assign(data,{previous_test_run_id:input.testRunId,reason:'host_terminated',partial_pass_cases:passed});
688
739
  if(timedOut)Object.assign(data,{previous_test_run_id:input.testRunId,reason:'host_request_timeout',
689
740
  timed_out_cases:timedOut.timedOutCases,partial_pass_cases:timedOut.partialPassCases,
741
+ ...(timedOut.hostBlockedCases.length?{host_blocked_cases:timedOut.hostBlockedCases}:{}),
690
742
  ...(timedOut.requestTimeoutMs===null?{}:{request_timeout_ms:timedOut.requestTimeoutMs}),
691
743
  ...(timedOut.attestation===null?{}:{legacy_timeout_attestation:timedOut.attestation})});
692
744
  else if(input.phase==='superseded')Object.assign(data,{previous_test_run_id:input.testRunId,
693
- reason:declaredFailure===null?'host_evidence_problem':'declared_environment_failure',recovery_rule:2,
745
+ reason:declaredFailure===null?'host_evidence_problem':'declared_environment_failure',recovery_rule:3,
694
746
  blocked_cases:blockedCases,expected_environment:input.expectedEnvironment??null,
695
747
  ...(incompleteReport?{incomplete_report:true}:{}),
696
748
  ...(declaredFailure===null?{}:{failed_cases:failedCases,environment_failure_reason:declaredFailure})});
@@ -782,7 +834,7 @@ function inspectQaResult(input,failureSource,historical=false) {
782
834
  need(candidates.length>0,'qa_result_invalid');
783
835
  for(const {row} of candidates)need(typeof row.operation_id==='string'
784
836
  &&/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(row.operation_id)
785
- &&Number.isSafeInteger(row.attempt)&&row.attempt>=1&&row.attempt<=3,'qa_result_invalid');
837
+ &&Number.isSafeInteger(row.attempt)&&row.attempt>=1&&row.attempt<=QA_MAX_ROUNDS,'qa_result_invalid');
786
838
  const latestStarts=candidates.filter(item=>item.row.phase==='start');
787
839
  need(latestStarts.length>0,'qa_result_incomplete');
788
840
  validateRunSequence(candidates,'qa_result_invalid',input.specsDir);
@@ -14,8 +14,11 @@ function relativeFile(value){
14
14
 
15
15
  // Pure validation also used by offline baseline/package readers. Never repairs
16
16
  // or requires the present filesystem merely to read historical evidence.
17
+ // A proposal is applied once per selected root, so this also bounds the
18
+ // apply subprocesses one develop journals (durable-runner-state.mjs).
19
+ export const MAX_CODE_PROJECTS=256;
17
20
  export function validateCodeProjectPaths(raw){
18
- const values=json(raw);need(Array.isArray(values)&&values.length>0&&values.length<=256,'invalid_code_projects');
21
+ const values=json(raw);need(Array.isArray(values)&&values.length>0&&values.length<=MAX_CODE_PROJECTS,'invalid_code_projects');
19
22
  const selected=values.map(relativeFile).sort(),aliases=selected.map(value=>value.toLowerCase());
20
23
  for(let i=0;i<aliases.length;i++)for(let j=0;j<i;j++)
21
24
  need(aliases[i]!==aliases[j]&&!aliases[i].startsWith(aliases[j]+'/')
@@ -0,0 +1,111 @@
1
+ // Execution choices and stale-command protection, not human authentication.
2
+ import fs from 'node:fs';
3
+ import {digest,json,need,shape,validIdentity,hex,id} from './effect-contract.mjs';
4
+ import {parseModelJson} from './model-configuration-file.mjs';
5
+
6
+ export const CONTROL_RECOVERY_OPERATIONS=Object.freeze(['abandon_review','abandon_effect','develop_redo',
7
+ 'bootstrap_review_recover','reconcile_review']);
8
+ export const CONTROL_FIX_RECOVERY_OPERATIONS=Object.freeze(['abandon_step','abandon_review','rediagnose',
9
+ 'rerun_blocked_step','recover_final_review','reconcile_review']);
10
+ export function readControlPolicy(raw){
11
+ const value=json(raw);shape(value,['version','development','bootstrap','qa','qaFix']);
12
+ need(value.version===2&&['conversation','provider'].includes(value.development)
13
+ &&['disabled','write'].includes(value.bootstrap)&&['disabled','run'].includes(value.qa)
14
+ &&['disabled','manual','auto'].includes(value.qaFix),'invalid_input');
15
+ need(value.qaFix==='disabled'||value.qa==='run','invalid_input');
16
+ return value;
17
+ }
18
+ export function readControlPolicyFile(file){
19
+ const before=fs.lstatSync(file);
20
+ need(before.isFile()&&!before.isSymbolicLink()&&before.nlink===1&&before.size<=65536,'invalid_input');
21
+ const fd=fs.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);
22
+ try{
23
+ const bytes=fs.readFileSync(fd),after=fs.fstatSync(fd),current=fs.lstatSync(file);
24
+ need([after,current].every(s=>['dev','ino','size','mtimeMs','ctimeMs'].every(k=>s[k]===before[k]))
25
+ &&bytes.length===before.size,'snapshot_changed');
26
+ const text=bytes.toString('utf8');need(Buffer.from(text).equals(bytes),'invalid_input');
27
+ return readControlPolicy(parseModelJson(text));
28
+ }finally{fs.closeSync(fd);}
29
+ }
30
+ export function controlPolicyFromSnapshot(snapshot){
31
+ return snapshot.records.find(row=>row.payload.type==='init')?.payload.config?.controlPolicy??null;
32
+ }
33
+ export function assertControlEntry(snapshot,policy){
34
+ const saved=controlPolicyFromSnapshot(snapshot);
35
+ need((saved===null)===(policy===null),'fingerprint_mismatch');
36
+ if(saved!==null)need(digest(readControlPolicy(saved))===digest(readControlPolicy(policy)),'fingerprint_mismatch');
37
+ }
38
+ export function readControlTarget(raw){
39
+ const v=json(raw);shape(v,['version','identity','state','code','packageDigest','effectId','invocationId','revision',
40
+ ...(Object.hasOwn(v,'child')?['child']:[])]);
41
+ need(v.version===2&&typeof v.state==='string'&&(v.code===null||typeof v.code==='string'),'invalid_input');
42
+ validIdentity(v.identity);hex(v.revision);
43
+ if(v.packageDigest!==null)hex(v.packageDigest);
44
+ for(const key of ['effectId','invocationId'])if(v[key]!==null)id(v[key]);
45
+ if(Object.hasOwn(v,'child'))readFixControlTarget(v.child);
46
+ return v;
47
+ }
48
+ export function readFixControlTarget(raw){
49
+ const v=json(raw);shape(v,['runId','revision','stage']);id(v.runId);hex(v.revision);
50
+ need(typeof v.stage==='string'&&v.stage.length>0&&v.stage.length<=128,'invalid_input');return v;
51
+ }
52
+ export function controlTarget(status,snapshot){
53
+ const intent=snapshot.records.findLast(row=>row.payload.type==='effect-intent')?.payload.effect??null;
54
+ const registration=snapshot.records.findLast(row=>row.payload.type==='review-invocation-registered')?.payload;
55
+ return readControlTarget({version:2,identity:status.identity,state:status.state,code:status.code??null,
56
+ packageDigest:status.packageDigest??null,effectId:intent?.id??null,
57
+ invocationId:registration?.binding?.invocationId??null,revision:snapshot.revision});
58
+ }
59
+ export function isControlRecovery(request){
60
+ return CONTROL_RECOVERY_OPERATIONS.includes(request.operation)
61
+ ||request.operation==='fix_action'&&CONTROL_FIX_RECOVERY_OPERATIONS.includes(request.fixOperation);
62
+ }
63
+ export function assertExpectedControl(expected,current){
64
+ need(expected!==undefined,'invalid_input');
65
+ need(digest(readControlTarget(expected))===digest(readControlTarget(current)),'snapshot_changed');
66
+ }
67
+ // The existing store owns the writer lock. This guard never queues a previewed
68
+ // command behind another mutation; validation and invocation share that owner.
69
+ export function withControlPolicyHost(host,{identity,snapshot,launchTarget=null}){
70
+ let busy=false;
71
+ return {...host,async handle(raw){
72
+ let ownsBusy=false,checking=true;
73
+ try{
74
+ const request=json(raw);need(request.version===2,'fingerprint_mismatch');
75
+ if(busy&&!['status','cancel','fix_status'].includes(request.operation))return {outcome:'rejected',code:'host_busy'};
76
+ const recovering=isControlRecovery(request);
77
+ need(recovering||!Object.hasOwn(request,'expectedControl'),'invalid_input');
78
+ const {expectedControl,...wire}=request;wire.version=1;
79
+ // A busy poll cannot publish a recovery target.
80
+ if(busy)return host.handle(wire);
81
+ busy=true;ownsBusy=true;
82
+ if(recovering){
83
+ checking=false;
84
+ const status=await host.handle({version:1,requestId:request.requestId,operation:'status',identity});
85
+ checking=true;
86
+ if(request.operation==='fix_action'){
87
+ need(expectedControl!==undefined,'invalid_input');readControlTarget(expectedControl);
88
+ need(Object.hasOwn(expectedControl,'child'),'invalid_input');
89
+ const {child,...parent}=expectedControl;assertExpectedControl(parent,controlTarget(status,snapshot()));
90
+ wire.expectedFixControl=readFixControlTarget(child);
91
+ }else assertExpectedControl(expectedControl,controlTarget(status,snapshot()));
92
+ need(digest(wire.identity)===digest(status.identity),'snapshot_changed');
93
+ }
94
+ checking=false;
95
+ const result=await host.handle(wire);
96
+ if(request.operation==='fix_status'&&result.childControlTarget){
97
+ const parent=await host.handle({version:1,requestId:request.requestId,operation:'status',identity});
98
+ return {...result,controlTarget:{...controlTarget(parent,snapshot()),child:readFixControlTarget(result.childControlTarget)}};
99
+ }
100
+ if(result.identity&&result.state&&request.operation==='status')
101
+ return {...result,controlTarget:controlTarget(result,snapshot()),
102
+ ...(launchTarget?{launchControlTarget:launchTarget(snapshot())}: {})};
103
+ return result;
104
+ }catch(error){
105
+ if(checking&&['invalid_input','snapshot_changed','fingerprint_mismatch'].includes(error.code))
106
+ return {outcome:'rejected',code:error.code,reason:error.code==='snapshot_changed'
107
+ ?'恢复目标已经变化;先核对当前状态和原操作,不自动更新旧目标后重试。':'恢复需要 status 返回的当前 controlTarget;旧运行使用原兼容入口。'};
108
+ throw error;
109
+ }finally{if(ownsBusy)busy=false;}
110
+ }};
111
+ }
@@ -20,6 +20,9 @@ Application status is applied (note explains the lesson and action) or no_releva
20
20
  Retrospective status is no_new_lesson (candidates empty and reason null), lesson_candidate (1-3 candidates and reason null),
21
21
  or writeback_pending (1-3 candidates and a reason). Each candidate has classification (structured or memory_only),
22
22
  trigger, action and evidence (relative file paths). The host binds identities and computes digests; do not invent hashes.
23
+ Bounds (an answer over any bound is rejected; lengths count UTF-16 code units, so an emoji counts as 2): application.note is one line of at most 512;
24
+ retrospective reason and each candidate trigger and action are one line of at most 240;
25
+ 1-3 candidates, each with 1-8 distinct relative evidence paths of at most 512; a blocked reason is at most 1000 bytes.
23
26
  Without learningInput, return only outcome and reason. A blocked result may include reason explaining why implementation is impossible (string, at most 1000 UTF-8 bytes, no NUL); application and retrospective are optional when blocked.
24
27
  The top-level reason explains blocked outcomes; otherwise it must be null. Use null when no explanation is available.
25
28
  Use outcome blocked when implementation is not possible. Do not claim implementation if no implementation was made.
@@ -86,6 +89,10 @@ export function validateDeveloperValue(value,request) {
86
89
  const input=request.payload.learningInput;
87
90
  validTaskLearningInput(input,request.identity,input.feature);
88
91
  shape(value.application,['status','note']);shape(value.retrospective,['status','candidates','reason']);
92
+ // Name the most common bound in the failure (the Learning constructor below
93
+ // enforces the same rule, with the generic code).
94
+ if(typeof value.application.note==='string')need(value.application.note.length<=512
95
+ &&!/[\n\r\0\u2028\u2029]/u.test(value.application.note),'application_note_limit');
89
96
  const binding={feature:input.feature,identity:request.identity,learningDigest:input.learningDigest};
90
97
  return {outcome:'implemented',
91
98
  application:createCmAiTaskLearningApplication({...binding,...value.application}),
@@ -50,7 +50,9 @@ export function attemptAnswerName(root,name,attempt){
50
50
  }
51
51
 
52
52
  // Returns {mode,gap}; gap is a refusal for a bootstrap case this driver does not support.
53
- export function inspectDriverBootstrap({advance,definition,permissions}){
53
+ export function inspectDriverBootstrap({advance,definition,permissions,controlPolicy=null}){
54
+ if(controlPolicy?.bootstrap==='disabled'&&permissions.includes('--bootstrap-config'))
55
+ return {mode:null,gap:'invalid_arguments: bootstrap disabled 禁止 --bootstrap-config;驾驶员未读取配置、未启动宿主'};
54
56
  if(!advance||!permissions.includes('--bootstrap-config'))return {mode:null,gap:null};
55
57
  let task;
56
58
  try{task=inspectCmAiBootstrapTask({specsDir:definition.specsDir,codeProject:definition.codeProject,
@@ -59,7 +61,8 @@ export function inspectDriverBootstrap({advance,definition,permissions}){
59
61
  }
60
62
  if(task.mode!=='instructions')return {mode:task.mode,gap:null};
61
63
  const gap=line=>({mode:'instructions',gap:`${line};可由当前 AI 会话用 cm-ai-host.mjs serve 应答 init_generate/init_verify`});
62
- if(permissions.includes('--protected-config'))return gap('规范任务不支持 --protected-config(provider 开发)驾驶');
64
+ if(controlPolicy?controlPolicy.development==='provider':permissions.includes('--protected-config'))
65
+ return gap(controlPolicy?'规范任务不支持 provider 开发驾驶':'规范任务不支持 --protected-config(provider 开发)驾驶');
63
66
  if(Object.hasOwn(definition,'codeProjects'))return gap('多代码根(codeProjects)规范任务驾驶员尚不支持');
64
67
  let selection;
65
68
  // The host's own reader: a regular, non-symlink file of at most 64 KiB with only selection.
@@ -186,9 +189,9 @@ function readVerify(root,name,{definition,plan,attempt}){
186
189
  // only when the develop effect starts, and the task entry inside it
187
190
  // (host-bootstrap.mjs run()), so both are required here; everything else the host
188
191
  // checks at launch runs before host_ready, before any command.
189
- function authorizeRulesLaunch({definition,plan,permissions}){
192
+ function authorizeRulesLaunch({definition,plan,permissions,controlPolicy=null}){
190
193
  const refusal=';驾驶员不运行 init-verify 命令、不启动宿主';
191
- refuse(permissions.includes('--allow-bootstrap-write'),
194
+ refuse(controlPolicy?controlPolicy.bootstrap==='write':permissions.includes('--allow-bootstrap-write'),
192
195
  `规范任务需要 --allow-bootstrap-write:宿主写规范前要求这一授权(bootstrap_write_authorization_required)${refusal}`);
193
196
  const protection=permissions.indexOf('--protected-conversation-config');
194
197
  if(protection!==-1)try{readConversationProtection(permissions[protection+1]);}
@@ -209,14 +212,14 @@ function authorizeRulesLaunch({definition,plan,permissions}){
209
212
  `${definition.identity.taskId} 不是当前可进入的 bootstrap 任务(nextTask ${entry?.id??'无'},宿主以 bootstrap_task_required 拒绝)${refusal}`);
210
213
  }
211
214
 
212
- export function readBootstrapRulesAnswers({answers,operation,definition,plan,permissions,bootstrap,reachable}){
215
+ export function readBootstrapRulesAnswers({answers,operation,definition,plan,permissions,bootstrap,reachable,controlPolicy=null}){
213
216
  const result=new Map(),slug=`.reviews/${definition.feature.replace(/^\d+\./,'')}-${definition.identity.taskId}`;
214
217
  const pair=attempt=>`answers/init-generate-a${attempt}.json 与 answers/init-verify-a${attempt}.json`;
215
218
  if(reachable.reviewAfterDevelop)
216
- stop(2,`规范任务的 advance 不能带 --allow-review-attempt 1 直接进入第 2 轮:修订答案须在读取首轮审查 findings 之后编写。请从 PLAN.permissions 移除 --allow-review-attempt 1,先 advance 到 awaiting_review;再用返回的 packageDigest 执行 decision,读取 ${slug}-r1.md 的 findings;若要求修改,写 ${pair(2)} 后 advance。`);
219
+ stop(2,`规范任务不能预先进入第 2 轮:修订答案须在读取首轮审查 findings 之后编写。首轮自动审查后停在 changes_requested;读取 ${slug}-r1.md 的 findings;若要求修改,写 ${pair(2)} 后 advance。`);
217
220
  if(reachable.reviewFirst)
218
- stop(2,`规范修订答案须在读取首轮审查 findings 之后编写:请先以 decision 和当前 packageDigest ${reachable.packageDigest} 单独运行审查,读取 ${slug}-r1.md 的 findings,写 ${pair(2)} 后再 advance(不要带 --allow-review-attempt 1 advance)`);
219
- if(reachable.attempts.length)authorizeRulesLaunch({definition,plan,permissions});
221
+ stop(2,`规范修订答案须在读取首轮审查 findings 之后编写:请先以 decision 和当前 packageDigest ${reachable.packageDigest} 单独运行审查,读取 ${slug}-r1.md 的 findings,写 ${pair(2)} 后再 advance`);
222
+ if(reachable.attempts.length)authorizeRulesLaunch({definition,plan,permissions,controlPolicy});
220
223
  for(const attempt of reachable.attempts){
221
224
  const names=['init-generate','init-verify'].map(name=>attemptAnswerName(answers??'',name,attempt));
222
225
  for(const name of names){
@@ -47,11 +47,20 @@ export const hostResponseFailed=row=>Boolean(row.error||row.result?.state==='unk
47
47
  // leave the host waiting forever on the same call. Say why and end the session.
48
48
  const rejectedReplyHint=code=>code==='host_response_too_large'
49
49
  ?'应答超过宿主输入上限:在 PLAN.permissions 加 "--input-limit","<字节数>"(65536–4194304,默认 65536)'
50
+ :code==='host_response_late'?'应答到得太晚:宿主已按应答期限或取消停止等待这次反问(期限见 CM_HOST_ANSWER_TIMEOUT_MINUTES)'
50
51
  :'应答与宿主这次反问不匹配(会话、调用或请求摘要不对)';
51
52
 
52
53
  // beforeRequest runs after host_ready, i.e. after the host itself accepted every
53
54
  // launch input, admission and the run store, and before the operation is sent.
54
55
  // A returned refusal closes the session without any operation and exits 2.
56
+ // A driver that deliberately leaves a host question unanswered (a re-asked
57
+ // confirmation the current user must decide) ends with exit code 2, whatever the
58
+ // host's final row says, so callers see a stop that needs a person.
59
+ let deliberateStop=false;
60
+ export function deliberatelyUnanswered(message){
61
+ if(!deliberateStop){deliberateStop=true;process.on('exit',()=>{process.exitCode=2;});}
62
+ return Object.assign(new Error(message),{code:'confirm_reask_decision_required'});
63
+ }
55
64
  export function driveHost({host,args,cwd,operation,request={},answers,paths,answerFor,beforeRequest=null}){
56
65
  const child=spawn(process.execPath,[host,...args],{cwd,stdio:['pipe','pipe','pipe']});
57
66
  const control=new AbortController();