@aibyzero/cm-workflow 0.16.4 → 0.16.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (283) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +22 -0
  3. package/CHANGELOG.md +57 -0
  4. package/README.md +22 -4
  5. package/THIRD_PARTY_NOTICES.md +9 -0
  6. package/VERSION +1 -1
  7. package/docs/architecture.md +43 -0
  8. package/docs/execution-optimizations.md +33 -0
  9. package/docs/external-models.md +114 -0
  10. package/docs/fixes/.reviews/20260929-bootstrap-unchanged-review-r1.md +7 -0
  11. package/docs/fixes/.reviews/20260930-develop-package-limit-recovery-r4.md +9 -0
  12. package/docs/fixes/20260929-bootstrap-rule-refresh-conflict.md +22 -0
  13. package/docs/fixes/20260929-bootstrap-unchanged-review.md +26 -0
  14. package/docs/fixes/20260930-develop-package-limit-recovery.md +65 -0
  15. package/docs/human-correction.md +31 -0
  16. package/docs/installation.md +48 -7
  17. package/docs/js-workflow-control.md +293 -33
  18. package/docs/live-evidence-drivers.md +62 -0
  19. package/docs/next-steps.md +15 -10
  20. package/docs/runtime-failover.md +1 -1
  21. package/docs/untested-branches.md +27 -4
  22. package/docs/user-guide.md +23 -8
  23. package/install-codex.sh +28 -11
  24. package/package.json +1 -1
  25. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  26. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  27. package/runtime/js/cm-ai/claude-review-adapter.mjs +7 -4
  28. package/runtime/js/cm-ai/claude-review-stream.mjs +12 -0
  29. package/runtime/js/cm-ai/claude-tool-preview.mjs +4 -4
  30. package/runtime/js/cm-ai/cm-ai-admission.mjs +115 -41
  31. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  32. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +208 -34
  33. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  34. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  35. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +181 -57
  36. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +15 -58
  37. package/runtime/js/cm-ai/codex-config.mjs +3 -2
  38. package/runtime/js/cm-ai/codex-review-adapter.mjs +56 -17
  39. package/runtime/js/cm-ai/committed-rule-basis.mjs +76 -0
  40. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  41. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  42. package/runtime/js/cm-ai/drive-bootstrap.mjs +315 -0
  43. package/runtime/js/cm-ai/drive-core.mjs +47 -9
  44. package/runtime/js/cm-ai/durable-runner-state.mjs +413 -56
  45. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  46. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  47. package/runtime/js/cm-ai/execution-policy.mjs +58 -0
  48. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  49. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  50. package/runtime/js/cm-ai/external-group-models.mjs +53 -0
  51. package/runtime/js/cm-ai/external-model-launch.mjs +23 -0
  52. package/runtime/js/cm-ai/external-models.mjs +52 -0
  53. package/runtime/js/cm-ai/external-run-guard.mjs +96 -0
  54. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  55. package/runtime/js/cm-ai/host-bootstrap.mjs +126 -29
  56. package/runtime/js/cm-ai/host-check.mjs +30 -4
  57. package/runtime/js/cm-ai/host-conversation-execution.mjs +66 -20
  58. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  59. package/runtime/js/cm-ai/host-progress.mjs +80 -0
  60. package/runtime/js/cm-ai/host-project-execution.mjs +16 -11
  61. package/runtime/js/cm-ai/host-qa-executor.mjs +23 -9
  62. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +23 -6
  63. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  64. package/runtime/js/cm-ai/host-session.mjs +12 -4
  65. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  66. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +16 -5
  67. package/runtime/js/cm-ai/host.mjs +1 -1
  68. package/runtime/js/cm-ai/knowledge-closeout.mjs +56 -0
  69. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  70. package/runtime/js/cm-ai/legacy-model-run-preview.mjs +24 -0
  71. package/runtime/js/cm-ai/legacy-model-settings.mjs +59 -0
  72. package/runtime/js/cm-ai/live-evidence.mjs +96 -0
  73. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  74. package/runtime/js/cm-ai/model-configuration-file.mjs +63 -0
  75. package/runtime/js/cm-ai/model_configuration_write.py +214 -0
  76. package/runtime/js/cm-ai/native-usage-log.mjs +26 -0
  77. package/runtime/js/cm-ai/operator-guidance.mjs +86 -0
  78. package/runtime/js/cm-ai/owned-process-cleanup.mjs +22 -0
  79. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  80. package/runtime/js/cm-ai/provider-review-observation.mjs +68 -9
  81. package/runtime/js/cm-ai/provider-usage.mjs +39 -0
  82. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  83. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  84. package/runtime/js/cm-ai/review-package.mjs +438 -31
  85. package/runtime/js/cm-ai/review-presentation.mjs +45 -0
  86. package/runtime/js/cm-ai/review-reconciliation.mjs +20 -0
  87. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  88. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  89. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  90. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  91. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  92. package/runtime/js/cm-ai/status-projection.mjs +93 -0
  93. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  94. package/runtime/js/cm-ai/task-runner.mjs +658 -75
  95. package/runtime/js/cm-ai/tool-preview.mjs +8 -4
  96. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  97. package/runtime/js/cm-ai/worker-claude.mjs +63 -19
  98. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -9
  99. package/runtime/js/cm-ai/worker-codex.mjs +45 -19
  100. package/runtime/js/cm-fix/cause-evidence.mjs +5 -3
  101. package/runtime/js/cm-fix/cause-invocation.mjs +6 -3
  102. package/runtime/js/cm-fix/cause-package.mjs +10 -1
  103. package/runtime/js/cm-fix/execution.mjs +279 -52
  104. package/runtime/js/cm-fix/final-review.mjs +18 -10
  105. package/runtime/js/cm-fix/host-review.mjs +32 -9
  106. package/runtime/js/cm-fix/host.mjs +6 -1
  107. package/runtime/js/cm-fix/layout.mjs +1 -1
  108. package/runtime/js/cm-fix/progress.mjs +5 -0
  109. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  110. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  111. package/runtime/js/cm-fix/review-reconciliation.mjs +64 -0
  112. package/runtime/js/cm-prd/analysis.mjs +2 -1
  113. package/runtime/js/cm-prd/change.mjs +28 -10
  114. package/runtime/js/cm-prd/draft.mjs +5 -2
  115. package/runtime/js/cm-prd/response-recovery.mjs +23 -0
  116. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  117. package/runtime/js/cm-prd/review-publication.mjs +27 -15
  118. package/runtime/js/cm-prd/review-time.mjs +29 -0
  119. package/runtime/js/cm-prd/self-check.mjs +6 -3
  120. package/runtime/js/cm-prd/session.mjs +53 -6
  121. package/runtime/js/cm-prd/summary.mjs +3 -1
  122. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  123. package/runtime/js/cm-security/finalize.mjs +32 -0
  124. package/runtime/js/spec-task-line.mjs +117 -0
  125. package/runtime/js/specs-status.mjs +10 -3
  126. package/runtime/review.md +5 -0
  127. package/runtime/task-gates.md +6 -0
  128. package/runtime/workflow-config.md +10 -1
  129. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  130. package/scripts/cm-ai-admission.mjs +18 -11
  131. package/scripts/cm-ai-admission.test.mjs +65 -1
  132. package/scripts/cm-ai-batch-drive.mjs +135 -34
  133. package/scripts/cm-ai-batch-drive.test.mjs +209 -3
  134. package/scripts/cm-ai-batch-host.mjs +63 -24
  135. package/scripts/cm-ai-batch-host.test.mjs +2 -1
  136. package/scripts/cm-ai-batch-run.mjs +101 -34
  137. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  138. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  139. package/scripts/cm-ai-bootstrap-flow.test.mjs +159 -0
  140. package/scripts/cm-ai-bootstrap-merge.test.mjs +162 -0
  141. package/scripts/cm-ai-bootstrap.test.mjs +174 -89
  142. package/scripts/cm-ai-conversation-entry-ops.test.mjs +97 -2
  143. package/scripts/cm-ai-develop-driver-gaps.test.mjs +924 -0
  144. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  145. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  146. package/scripts/cm-ai-drive.mjs +526 -60
  147. package/scripts/cm-ai-drive.test.mjs +336 -10
  148. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  149. package/scripts/cm-ai-host.mjs +142 -43
  150. package/scripts/cm-ai-host.test.mjs +232 -12
  151. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  152. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  153. package/scripts/cm-ai-operator-guidance.test.mjs +94 -0
  154. package/scripts/cm-ai-progress.test.mjs +521 -0
  155. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  156. package/scripts/cm-ai-qa-config-revision.test.mjs +187 -15
  157. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  158. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  159. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  160. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  161. package/scripts/cm-ai-review-failure.test.mjs +977 -0
  162. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  163. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  164. package/scripts/cm-ai-run.mjs +206 -62
  165. package/scripts/cm-ai-run.test.mjs +6 -4
  166. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  167. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  168. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  169. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  170. package/scripts/cm-ai-supersede.test.mjs +571 -17
  171. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  172. package/scripts/cm-bootstrap-review-recovery.test.mjs +70 -0
  173. package/scripts/cm-capability-gate.test.mjs +21 -2
  174. package/scripts/cm-check-drive.test.mjs +2 -1
  175. package/scripts/cm-check-host.test.mjs +1 -1
  176. package/scripts/cm-check-runtime.sh +12 -1
  177. package/scripts/cm-claude-developer-worker.test.mjs +3 -1
  178. package/scripts/cm-claude-install-layout.test.mjs +26 -0
  179. package/scripts/cm-claude-probe.test.mjs +10 -2
  180. package/scripts/cm-claude-review-stream.test.mjs +25 -0
  181. package/scripts/cm-claude-worker.test.mjs +11 -4
  182. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  183. package/scripts/cm-codex-plugin-metadata.py +83 -0
  184. package/scripts/cm-codex-plugin-metadata.test.mjs +55 -0
  185. package/scripts/cm-efficiency-checks.test.mjs +37 -0
  186. package/scripts/cm-efficiency-diagnostics.test.mjs +74 -0
  187. package/scripts/cm-efficiency-offline.mjs +35 -0
  188. package/scripts/cm-efficiency-policy.test.mjs +48 -0
  189. package/scripts/cm-efficiency-presentation.test.mjs +35 -0
  190. package/scripts/cm-efficiency-response.test.mjs +117 -0
  191. package/scripts/cm-efficiency-usage.test.mjs +148 -0
  192. package/scripts/cm-external-batch-host.test.mjs +157 -0
  193. package/scripts/cm-external-fix-host.test.mjs +281 -0
  194. package/scripts/cm-external-fix-reconciliation.test.mjs +105 -0
  195. package/scripts/cm-external-group-models.test.mjs +60 -0
  196. package/scripts/cm-external-model-host.test.mjs +180 -0
  197. package/scripts/cm-external-model-recovery.test.mjs +108 -0
  198. package/scripts/cm-external-models.test.mjs +89 -0
  199. package/scripts/cm-external-process-cleanup.test.mjs +71 -0
  200. package/scripts/cm-external-qa-fix.test.mjs +170 -0
  201. package/scripts/cm-external-review-reconciliation.test.mjs +314 -0
  202. package/scripts/cm-failover.mjs +8 -8
  203. package/scripts/cm-fix-abandon.test.mjs +123 -5
  204. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  205. package/scripts/cm-fix-drive.mjs +70 -23
  206. package/scripts/cm-fix-drive.test.mjs +36 -1
  207. package/scripts/cm-fix-final-review.test.mjs +11 -6
  208. package/scripts/cm-fix-host.mjs +24 -14
  209. package/scripts/cm-fix-protected-edits.test.mjs +12 -0
  210. package/scripts/cm-fix-rediagnosis.test.mjs +168 -0
  211. package/scripts/cm-fix-review-budget.test.mjs +147 -0
  212. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  213. package/scripts/cm-host-check.test.mjs +6 -3
  214. package/scripts/cm-host-qa-executor.test.mjs +213 -17
  215. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  216. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  217. package/scripts/cm-knowledge-closeout.test.mjs +160 -0
  218. package/scripts/cm-live-evidence.test.mjs +64 -0
  219. package/scripts/cm-log-event.mjs +25 -2
  220. package/scripts/cm-log-event.py +15 -0
  221. package/scripts/cm-log-event.test.mjs +31 -0
  222. package/scripts/cm-model-setup.mjs +79 -0
  223. package/scripts/cm-prd-completion.test.mjs +75 -0
  224. package/scripts/cm-prd-draft.test.mjs +14 -0
  225. package/scripts/cm-prd-drive.mjs +32 -11
  226. package/scripts/cm-prd-drive.test.mjs +15 -0
  227. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  228. package/scripts/cm-prd-host.mjs +13 -4
  229. package/scripts/cm-prd-review-gate.mjs +126 -81
  230. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  231. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  232. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  233. package/scripts/cm-prd-self-check.test.mjs +6 -0
  234. package/scripts/cm-prd-summary.test.mjs +9 -0
  235. package/scripts/cm-release-smoke.sh +5 -1
  236. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  237. package/scripts/cm-review-inventory.test.mjs +253 -1
  238. package/scripts/cm-runtime-i18n.mjs +15 -4
  239. package/scripts/cm-runtime-install.mjs +8 -4
  240. package/scripts/cm-runtime.mjs +116 -23
  241. package/scripts/cm-runtime.test.mjs +121 -12
  242. package/scripts/cm-security.test.mjs +32 -0
  243. package/scripts/cm-spec-manifest.mjs +28 -10
  244. package/scripts/cm-spec-manifest.test.mjs +8 -4
  245. package/scripts/cm-spec-task-line.test.mjs +138 -0
  246. package/scripts/cm-specs-status.test.mjs +12 -1
  247. package/scripts/cm-task-gate-correction.test.mjs +117 -0
  248. package/scripts/cm-task-gate.mjs +164 -20
  249. package/scripts/cm-task-gate.py +2 -1
  250. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  251. package/scripts/cm-test-drive.mjs +10 -4
  252. package/scripts/cm-test-drive.test.mjs +14 -1
  253. package/scripts/cm-tool-preview-context.test.mjs +12 -0
  254. package/scripts/cm-usage-report.py +22 -3
  255. package/scripts/cm-workflow-config.mjs +10 -1
  256. package/scripts/fixtures/bootstrap-review-runner.mjs +102 -0
  257. package/scripts/fixtures/claude-review-process.mjs +1 -0
  258. package/scripts/fixtures/live-evidence-driver.mjs +35 -0
  259. package/scripts/fixtures/process-cleanup.mjs +101 -0
  260. package/scripts/test-cm-log-event.py +2 -0
  261. package/scripts/test-cm-native-usage.py +62 -0
  262. package/scripts/test-cm-prd-review-gate.py +2 -1
  263. package/scripts/test-external-model-setup.py +91 -0
  264. package/scripts/test-model-configuration-write.py +201 -0
  265. package/scripts/test-npm-install.py +11 -2
  266. package/scripts/test-scan-public-safety.py +1 -1
  267. package/scripts/test-spec-manifest.py +16 -8
  268. package/scripts/test-task-gate.py +2 -2
  269. package/scripts/test-workflow-config.py +1 -0
  270. package/scripts/validate-public-repo.py +1 -0
  271. package/skills/cm-ai/SKILL.md +2 -2
  272. package/skills/cm-ai/references/N1-init.md +1 -1
  273. package/skills/cm-ai/references/N8-finish.md +5 -0
  274. package/skills/cm-ai/references/js-host.md +270 -43
  275. package/skills/cm-ai/references/knowledge-closeout.md +90 -0
  276. package/skills/cm-fix/SKILL.md +1 -1
  277. package/skills/cm-fix/references/js-host.md +52 -3
  278. package/skills/cm-prd/references/js-change-recovery.md +1 -1
  279. package/skills/cm-prd/references/js-host.md +6 -0
  280. package/skills/cm-runtime/SKILL.md +29 -6
  281. package/skills/cm-security/SKILL.md +4 -2
  282. package/skills/cm-security/references/scan-contract.md +1 -0
  283. package/templates/cm-workflow.yml +1 -1
@@ -1,7 +1,11 @@
1
1
  // JSONL transport only. The existing host/runner owns decisions and durable state.
2
2
  import {executionDiagnostic,need} from './effect-contract.mjs';
3
+ import {diagnosticReason} from './diagnostic-reason.mjs';
3
4
 
4
5
  const LIMIT=64*1024;
6
+ // One wording for every host that stops on an over-limit line.
7
+ export const inputLimitReason=limit=>`an input line exceeded --input-limit ${Number.isSafeInteger(limit)?limit:LIMIT} bytes `
8
+ +`(default ${LIMIT}, maximum ${4*1024*1024}); restart the same run with --mode resume and a larger --input-limit`;
5
9
  export function parseHostInputLimit(raw){
6
10
  if(raw===undefined)return LIMIT;
7
11
  const value=Number(raw);
@@ -9,7 +13,7 @@ export function parseHostInputLimit(raw){
9
13
  &&value>=LIMIT&&value<=4*1024*1024,'invalid_arguments');
10
14
  return value;
11
15
  }
12
- const operationNames=new Set(['replace_inputs','read_batch','recover_final_review','abandon_step','advance','start','plan_design','promote_design','select_design_reviews','status','fix_status','fix_advance','fix_action','fix_run','decision','complete','qa','qa_result','prepare_revision','prepare_save',
16
+ const operationNames=new Set(['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',
13
17
  'context_refresh','finish','completion_evidence','run_finalize','review_findings','review_disposition','save_draft','save_design','correct_findings','prepare_summary','publish_summary','inspect_correction','resume_correction','cancel','resume','prepare_judge_revision','cause_review_package','cause_review','red_test','baseline','author_tests','repair','regression','retrospective','learning_writeback','handoff','final_review_package','final_review','publish_review','check_n5','post_review_regression','publish_dossier','walkthrough']);
14
18
 
15
19
  // Which contract codes may reach the peer is a deliberate boundary: the host
@@ -22,11 +26,15 @@ const operationNames=new Set(['replace_inputs','read_batch','recover_final_revie
22
26
  function reportRequestFailure(errorOutput,operation,error){
23
27
  try{
24
28
  const detail=executionDiagnostic(error);
29
+ const reason=diagnosticReason(error);
25
30
  errorOutput.write(JSON.stringify({diagnostic:'host_request_failed',operation,
26
- ...(detail??{detail:'unavailable'})})+'\n');
31
+ ...(detail??{detail:'unavailable'}),...(reason?{reason}:{})})+'\n');
27
32
  }catch{/* diagnostics never change the reply */}
28
33
  }
29
34
 
35
+ // A line above the transport limit ends the session. Carry a code and the
36
+ // limit so every host can name it instead of a generic launch failure.
37
+ const tooLarge=limit=>Object.assign(new Error('request_too_large'),{code:'request_too_large',limit});
30
38
  export async function serveCmAiHost({host,input,output,toolBridge=null,inputLimit=LIMIT,errorOutput=process.stderr}){
31
39
  if(!Number.isSafeInteger(inputLimit)||inputLimit<LIMIT||inputLimit>4*1024*1024)throw Error('input_limit_invalid');
32
40
  let pending=null,buffer=Buffer.alloc(0),failure=null,closeRequested=false;
@@ -93,13 +101,13 @@ export async function serveCmAiHost({host,input,output,toolBridge=null,inputLimi
93
101
  let start=0;
94
102
  for(let end=0;end<bytes.length;end++){
95
103
  if(bytes[end]!==10)continue;
96
- if(buffer.length+end-start>inputLimit)throw Error('request_too_large');
104
+ if(buffer.length+end-start>inputLimit)throw tooLarge(inputLimit);
97
105
  const line=Buffer.concat([buffer,bytes.subarray(start,end)]);
98
106
  buffer=Buffer.alloc(0);start=end+1;
99
107
  if(line.length)await dispatch(line);
100
108
  if(closeRequested)break reading;
101
109
  }
102
- if(buffer.length+bytes.length-start>inputLimit)throw Error('request_too_large');
110
+ if(buffer.length+bytes.length-start>inputLimit)throw tooLarge(inputLimit);
103
111
  buffer=Buffer.concat([buffer,bytes.subarray(start)]);
104
112
  }
105
113
  if(buffer.length&&!closeRequested)await dispatch(buffer);
@@ -47,7 +47,7 @@ export function createHostToolBridge({responseLimit=64*1024}={}){
47
47
  reply=json(raw,responseLimit);shape(reply,['type','sessionId','callId','requestDigest','result']);
48
48
  need(reply.type==='host_result'&&pending!==null&&!closed,'host_response_mismatch');
49
49
  for(const key of ['sessionId','callId','requestDigest'])need(reply[key]===pending.request[key],'host_response_mismatch');
50
- }catch{return {accepted:false,code:'host_response_mismatch'};}
50
+ }catch(error){return {accepted:false,code:error?.code==='limit_exceeded'?'host_response_too_large':'host_response_mismatch'};}
51
51
  const call=pending;pending=null;clearTimeout(call.timer);call.signal.removeEventListener('abort',call.abort);
52
52
  call.resolve(reply.result);return {accepted:true,callId:reply.callId};
53
53
  },
@@ -6,6 +6,7 @@ import {createHostQaDecisionProvider} from './host-qa-policy.mjs';
6
6
  import {createHostQaExecutor} from './host-qa-executor.mjs';
7
7
  import {loadConfig} from '../../../scripts/cm-workflow-config.mjs';
8
8
  import {validateTestCases} from '../../../scripts/validate-test-cases.mjs';
9
+ import {QA_ENVIRONMENT_CARRIERS} from './qa-environment.mjs';
9
10
 
10
11
  // Browser capability is a property of the launching session, not of the project.
11
12
  // The host cannot probe whether this session can drive a browser; it can only
@@ -26,10 +27,18 @@ export function featureHasBrowserCases(specsDir,feature,codeProject){
26
27
  }
27
28
 
28
29
  export function readBrowserCapability(value,applicable){
29
- if(!applicable){need(value===undefined,'invalid_arguments');return null;}
30
- need(value!==undefined,'browser_capability_required');
31
- need(['available','unavailable'].includes(value),'invalid_arguments');
32
- need(value==='available','browser_capability_unavailable');
30
+ const carriers=Array.isArray(applicable)?[...new Set(applicable)].sort():applicable?['browser']:[];
31
+ const invalid=reason=>{throw Object.assign(new Error('invalid_arguments'),{code:'invalid_arguments',reason});};
32
+ if(!carriers.every(carrier=>Object.values(QA_ENVIRONMENT_CARRIERS).some(values=>values.includes(carrier))))
33
+ invalid(`QA environment carrier is not supported: ${carriers.join(', ')}`);
34
+ if(carriers.length===0){
35
+ if(value!==undefined)invalid('--browser-qa 只在启用 QA(--workflow-config 的 qa 不为 null)且本 feature 有 blocking 或策略启用的交互式用例时使用;本次没有适用的交互式 QA,去掉 --browser-qa');
36
+ return null;
37
+ }
38
+ const reason=`--browser-qa available|unavailable declares whether this session can run interactive QA for carrier(s): ${carriers.join(', ')}.`;
39
+ if(value===undefined)throw Object.assign(new Error('browser_capability_required'),{code:'browser_capability_required',reason});
40
+ if(!['available','unavailable'].includes(value))invalid('--browser-qa 只接受 available 或 unavailable');
41
+ if(value!=='available')throw Object.assign(new Error('browser_capability_unavailable'),{code:'browser_capability_unavailable',reason});
33
42
  return 'available';
34
43
  }
35
44
 
@@ -41,7 +50,9 @@ export function readHostWorkflowConfiguration(file){
41
50
 
42
51
  export function validateHostWorkflowConfiguration(raw){
43
52
  const config=json(raw);
44
- shape(config,['qa','documentationPaths','applicableAgentFiles']);
53
+ shape(config,['qa','documentationPaths','applicableAgentFiles',
54
+ ...(Object.hasOwn(config,'knowledgeCloseout')?['knowledgeCloseout']:[])]);
55
+ if(Object.hasOwn(config,'knowledgeCloseout'))need(typeof config.knowledgeCloseout==='boolean','invalid_workflow_config');
45
56
  for(const key of ['documentationPaths','applicableAgentFiles'])
46
57
  need(Array.isArray(config[key])&&config[key].length<=256&&config[key].every(item=>typeof item==='string'),'invalid_workflow_config');
47
58
  if(config.qa!==null){
@@ -16,5 +16,5 @@ export function createCmAiHost(options) {
16
16
  ...(qaExecutor===undefined?{}:{qaExecutor}),
17
17
  ...(documentationProvider===undefined?{}:{documentationProvider}),
18
18
  ...(qaDecisionProvider===undefined?{}:{qaDecisionProvider})});
19
- return Object.freeze({handle:entry.handle,inspectFixAssociation:runner.inspectFixAssociation,acceptCompletedFix:runner.acceptCompletedFix,attachQa:runner.attachQa,reviseQa:runner.reviseQa,supersedeEvidence:runner.supersedeEvidence});
19
+ return Object.freeze({handle:entry.handle,inspectFixAssociation:runner.inspectFixAssociation,acceptCompletedFix:runner.acceptCompletedFix,attachQa:runner.attachQa,reviseQa:runner.reviseQa,supersedeEvidence:runner.supersedeEvidence,rebindSpecification:runner.rebindSpecification});
20
20
  }
@@ -0,0 +1,56 @@
1
+ // Advisory read-only closeout over the original documentation inspection.
2
+ // A report is neither a Review receipt nor authority to change files or finish.
3
+ import {freeze,json,need,shape} from './effect-contract.mjs';
4
+
5
+ export const CLOSEOUT_VERSION=1;
6
+ export const CLOSEOUT_AREAS=Object.freeze(['code','runtime','documentation','rules','memory','residue']);
7
+ export function readCloseoutPolicy(raw){
8
+ const value=json(raw);shape(value,['version','enabled']);
9
+ need(value.version===CLOSEOUT_VERSION&&typeof value.enabled==='boolean','closeout_policy_unsupported');
10
+ return freeze(value);
11
+ }
12
+ export function closeoutPolicyCandidates(execution,mode,snapshot=null){
13
+ if(!execution?.documentationProvider&&!execution?.documentationResult)return [null];
14
+ const workflow=execution.configuration.workflow?.configuration??execution.configuration.workflow;
15
+ const explicit=workflow&&Object.hasOwn(workflow,'knowledgeCloseout');
16
+ const requested=readCloseoutPolicy({version:CLOSEOUT_VERSION,enabled:explicit?workflow.knowledgeCloseout:true});
17
+ if(mode==='create')return [requested];
18
+ const init=snapshot?.records.find(row=>row.payload.type==='init');
19
+ if(init){
20
+ const saved=init.payload.config.knowledgeCloseout;
21
+ if(saved===undefined){need(!explicit,'closeout_policy_changed');return [null];}
22
+ const policy=readCloseoutPolicy(saved);
23
+ need(!explicit||policy.enabled===requested.enabled,'closeout_policy_changed');
24
+ return [policy];
25
+ }
26
+ // An interrupted empty initializer has no init record. Only an exact original
27
+ // fingerprint may select one of these supported configurations; never guess.
28
+ return explicit?[requested]:[requested,readCloseoutPolicy({version:CLOSEOUT_VERSION,enabled:false}),null];
29
+ }
30
+ export function readCloseoutReport(raw){
31
+ const report=json(raw,16*1024);shape(report,['version','items']);
32
+ need(report.version===CLOSEOUT_VERSION&&Array.isArray(report.items)
33
+ &&report.items.length===CLOSEOUT_AREAS.length,'closeout_report_invalid');
34
+ const seen=new Set();
35
+ const string=(value,max)=>need(typeof value==='string'&&value.trim().length>0
36
+ &&Buffer.byteLength(value,'utf8')<=max&&!/[\x00-\x1f\x7f]/.test(value),'closeout_report_invalid');
37
+ for(const item of report.items){
38
+ shape(item,['area','status','evidence','detail']);
39
+ need(CLOSEOUT_AREAS.includes(item.area)&&!seen.has(item.area),'closeout_report_invalid');seen.add(item.area);
40
+ need(['checked','issues','unverified','out_of_scope','not_applicable'].includes(item.status),'closeout_report_invalid');
41
+ string(item.detail,1000);
42
+ need(Array.isArray(item.evidence)&&item.evidence.length<=8,'closeout_report_invalid');
43
+ item.evidence.forEach(value=>string(value,1000));
44
+ need(!['checked','issues'].includes(item.status)||item.evidence.length>0,'closeout_report_invalid');
45
+ }
46
+ return freeze(report);
47
+ }
48
+ export function closeoutSummary(policy,documentation=null,reason='report_not_provided'){
49
+ if(policy===null)return {};
50
+ readCloseoutPolicy(policy);
51
+ const report=policy.enabled&&documentation?.closeout?readCloseoutReport(documentation.closeout):null;
52
+ return {knowledgeCloseout:{...policy,status:!policy.enabled?'disabled':report?'reported':'not_completed',
53
+ reason:!policy.enabled?'explicitly_disabled':report?'advisory_only':reason,
54
+ ...(documentation?{identity:documentation.identity,packageDigest:documentation.packageDigest,
55
+ contextDigest:documentation.contextDigest,syncId:documentation.syncId}:{}),items:report?.items??[]}};
56
+ }
@@ -0,0 +1,42 @@
1
+ // Diagnostic only. A resume whose launch inputs differ from creation is still
2
+ // refused with fingerprint_mismatch; this names the differing input so the
3
+ // operator can find the exit. The comparison reads the journal's own init
4
+ // record (the runner configuration it bound) and never widens what opens.
5
+ import {digest} from './effect-contract.mjs';
6
+
7
+ const UNLISTED='其余启动配置与创建时不同:--workflow-config、--protected-conversation-config、--bootstrap-config、'
8
+ +'QA/文档设置或创建时的任务选择(journal 只保存它们的指纹)。请用创建时的同一组文件与参数恢复。';
9
+
10
+ export function explainFingerprintMismatch({snapshot,definition,execution,fingerprints}){
11
+ try{
12
+ if(snapshot.fingerprints.workflow!==fingerprints.workflow)
13
+ return execution===null?'该运行由 cm-ai-host.mjs 创建,不能用无执行适配的 cm-ai-run.mjs 恢复'
14
+ :'该运行由无执行适配的控制入口 cm-ai-run.mjs 创建,不能用 cm-ai-host.mjs 恢复';
15
+ if(snapshot.fingerprints.inputs!==fingerprints.inputs)return `运行定义的 feature/task 与创建时不同(本次 ${definition.feature}/${definition.identity.taskId})`;
16
+ const bound=snapshot.records[0]?.payload?.config;
17
+ if(!bound)return UNLISTED;
18
+ const found=[];
19
+ const changed=[['scope','scope'],['requirements','requirements'],['identity','identity'],['root','codeProject']]
20
+ .filter(([key,field])=>digest(bound[key])!==digest(key==='root'?definition.codeProject:definition[field]))
21
+ .map(([,field])=>field);
22
+ if(changed.length)found.push(`运行定义字段 ${changed.join('、')} 与创建时不同`);
23
+ if(execution!==null){
24
+ const developer=execution.developer??{},reviewer=execution.reviewers?.[0]??{},was=bound.reviewers?.[0]??{};
25
+ if(bound.developer?.provider!==developer.provider)
26
+ found.push(`--runtime:创建时为 ${bound.developer?.provider},本次为 ${developer.provider}(驱动 PLAN 未写 runtime 时默认 codex)`);
27
+ else if(bound.developer?.requestedModel!==developer.requestedModel)
28
+ found.push(`开发模式不同:创建时开发者为 ${bound.developer?.requestedModel},本次为 ${developer.requestedModel}(--protected-config 是否使用须与创建时一致)`);
29
+ if(was.requestedModel==='unconfigured'&&reviewer.requestedModel!=='unconfigured')
30
+ found.push('--review-config:创建时没有审查配置,运行已绑定为“未配置审查”,resume 不能补加;'
31
+ +'本运行只能 status/cancel。要审查这次开发:cancel 后以带 --review-config 的新运行重做(--supersede-reviewed-evidence)');
32
+ else if(was.requestedModel!=='unconfigured'&&reviewer.requestedModel==='unconfigured')
33
+ found.push(`--review-config:创建时用了审查模型 ${was.requestedModel},本次没有提供;请带上创建时的 review.json`);
34
+ else if(was.requestedModel!==reviewer.requestedModel||was.provider!==reviewer.provider)
35
+ found.push(`审查配置:创建时为 ${was.provider}/${was.requestedModel},本次为 ${reviewer.provider}/${reviewer.requestedModel}`);
36
+ const host=bound.excludedContexts?.[0],current=execution.excludedContexts?.[0];
37
+ if(host!==current)found.push(`--host-context:创建会话为 ${host},本次按 ${current} 恢复;换会话恢复请加 --original-host-context ${host}`);
38
+ if(bound.timeoutMs!==execution.timeoutMs&&!found.length)found.push('开发模式或受保护配置与创建时不同');
39
+ }
40
+ return found.length?found.join(';'):UNLISTED;
41
+ }catch{return UNLISTED;}
42
+ }
@@ -0,0 +1,24 @@
1
+ // Historical experimental snapshots remain immutable and need their original executor.
2
+ import {digest,json,need,shape,validIdentity} from './effect-contract.mjs';
3
+ import {externalPair} from './external-models.mjs';
4
+ export function previewLegacyModelRun(raw){
5
+ const value=json(raw,64*1024),{snapshotDigest,...body}=value;
6
+ const experimental=value.schemaVersion===1&&value.kind==='cm-model-run-snapshot'&&value.population==='experimental-model-v1';
7
+ const policy=value.version===2&&value.kind==='cm-model-policy-snapshot'&&value.resolverVersion==='model-policy-resolver-v1';
8
+ need((experimental||policy)&&value.locked===true&&digest(body)===snapshotDigest,'legacy_model_snapshot_invalid');
9
+ shape(value,experimental?['schemaVersion','kind','population','locked','definition','selection','snapshotDigest']:
10
+ ['version','kind','resolverVersion','definition','selection','locked','snapshotDigest',...(Object.hasOwn(value,'modelPolicyFix')?['modelPolicyFix']:[])]);
11
+ validIdentity(value.definition.identity);
12
+ need(value.definition.version===2&&value.definition.population===(experimental?'experimental-model-v1':'model-policy-v2'),'legacy_model_snapshot_invalid');
13
+ const {previewDigest,...selection}=value.selection;
14
+ need(selection.schemaVersion===1&&selection.kind==='cm-model-preview'&&selection.executionAvailable===false
15
+ &&digest(selection)===previewDigest,'legacy_model_preview_invalid');
16
+ const stages=Object.fromEntries(Object.entries(selection.stages).map(([stage,choice])=>{
17
+ need(['developer','reviewer','test_analysis'].includes(stage),'legacy_model_preview_invalid');
18
+ const {provider,...pair}=choice.tuple;
19
+ return [stage,{provider,...externalPair(provider,pair),mode:choice.mode,source:choice.source}];
20
+ }));
21
+ return {readOnly:true,validation:'snapshot and selection digest; not execution ownership',
22
+ identity:value.definition.identity,population:value.definition.population,snapshotDigest,stages,
23
+ effectiveModel:'unknown',providerConfirmed:false,resume:'original executor required; no migration'};
24
+ }
@@ -0,0 +1,59 @@
1
+ // Read-only compatibility. These historical defaults never select a new run.
2
+ import {digest,json,need,shape} from './effect-contract.mjs';
3
+ import {externalPair} from './external-models.mjs';
4
+ const defaults={codex:{general:'gpt-6-astra',code:'gpt-6.1-sol'},claude:{general:'claude-fable-5',code:'claude-opus-5-5'}};
5
+ const tuple=(provider,raw)=>{
6
+ const value=json(raw);shape(value,['provider','model','effort']);need(value.provider===provider,'legacy_provider_conflict');
7
+ return externalPair(provider,{model:value.model,effort:value.effort});
8
+ };
9
+ function choices(raw){
10
+ const value=json(raw);shape(value,['schemaVersion','presetVersion','choices']);
11
+ need([1,2].includes(value.schemaVersion)&&value.presetVersion==='two-tier-v1','legacy_schema_unsupported');
12
+ const result={};
13
+ for(const provider of ['codex','claude'])result[provider]={developer:{model:defaults[provider].code,effort:'high'},reviewer:{model:defaults[provider].code,effort:'high'}};
14
+ if(value.schemaVersion===1){
15
+ shape(value.choices,['codex','claude']);
16
+ for(const provider of ['codex','claude']){
17
+ shape(value.choices[provider],['general','code']);
18
+ for(const entry of Object.values(value.choices[provider]))need(tuple(provider,entry).effort==='high','legacy_effort_invalid');
19
+ result[provider]={developer:tuple(provider,value.choices[provider].code),reviewer:tuple(provider,value.choices[provider].code)};
20
+ }
21
+ }else{
22
+ shape(value.choices,Object.keys(value.choices));
23
+ for(const [provider,stages] of Object.entries(value.choices)){
24
+ need(Object.hasOwn(defaults,provider),'invalid_external_provider');shape(stages,Object.keys(stages));
25
+ for(const [stage,entry] of Object.entries(stages)){
26
+ need(['general','developer','reviewer'].includes(stage),'legacy_stage_invalid');
27
+ shape(entry,Object.keys(entry));need(Object.keys(entry).length>0&&Object.keys(entry).every(key=>['provider','model','effort'].includes(key)),'legacy_tuple_invalid');
28
+ const selected=tuple(provider,{provider,model:defaults[provider][stage==='general'?'general':'code'],effort:'high',...entry});
29
+ if(stage!=='general')result[provider][stage]=selected;
30
+ }
31
+ }
32
+ }
33
+ return result;
34
+ }
35
+ export function previewLegacyExternalModels({settings,task=null,project=null,global=null}){
36
+ const base=choices(settings);
37
+ for(const layer of [task,project,global])if(layer!==null){
38
+ shape(layer,['schemaVersion','stages']);need(layer.schemaVersion===1,'legacy_schema_unsupported');
39
+ shape(layer.stages,Object.keys(layer.stages));
40
+ for(const [stage,row] of Object.entries(layer.stages)){
41
+ need(['developer','reviewer','test_analysis'].includes(stage),'legacy_stage_invalid');
42
+ need(['manual','recommended'].includes(row?.mode),'legacy_mode_invalid');
43
+ shape(row,['mode',...(row.mode==='manual'?['provider','model','effort']:[])]);
44
+ if(row.mode==='manual'){const {mode,...raw}=row;tuple(raw.provider,raw);}
45
+ }
46
+ }
47
+ const selected=Object.fromEntries(['developer','reviewer'].map(stage=>{
48
+ const row=[task,project,global].map(layer=>layer?.stages[stage]).find(value=>value!==undefined);
49
+ if(row===undefined)return [stage,null];
50
+ need(row.mode==='manual','legacy_recommendation_requires_explicit_choice');
51
+ shape(row,['mode','provider','model','effort']);const {mode,...raw}=row;
52
+ return [stage,{provider:raw.provider,pair:tuple(raw.provider,raw)}];
53
+ }));
54
+ return Object.fromEntries(Object.keys(base).map(provider=>{
55
+ const effective=Object.fromEntries(['developer','reviewer'].map(stage=>[stage,selected[stage]?.provider===provider?selected[stage].pair:base[provider][stage]]));
56
+ const conflict=digest(effective.developer)!==digest(effective.reviewer);
57
+ return [provider,{...effective,conflict,pair:conflict?null:effective.developer}];
58
+ }));
59
+ }
@@ -0,0 +1,96 @@
1
+ // Current-session execution transport. The host owns evidence semantics;
2
+ // this responder only binds a fresh reply to its original live request.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {randomUUID} from 'node:crypto';
6
+ import {setTimeout as delay} from 'node:timers/promises';
7
+
8
+ const KINDS=new Set(['qa_logic','qa_browser','verification_precheck','prd_materials']);
9
+ const fail=code=>{throw Error(code);};
10
+ const inside=(root,file)=>file===root||file.startsWith(root+path.sep);
11
+ function resolvedFutureRoot(file){
12
+ let existing=path.resolve(file);const tail=[];
13
+ while(!fs.existsSync(existing)){
14
+ const parent=path.dirname(existing);if(parent===existing)break;
15
+ tail.unshift(path.basename(existing));existing=parent;
16
+ }
17
+ return path.join(fs.realpathSync(existing),...tail);
18
+ }
19
+ function ordinaryAncestors(file){
20
+ let current=path.parse(file).root;
21
+ for(const part of file.slice(current.length).split(path.sep).filter(Boolean)){
22
+ current=path.join(current,part);
23
+ try{const stat=fs.lstatSync(current);
24
+ if(!stat.isDirectory()||stat.isSymbolicLink())fail('live_evidence_unsafe_directory');
25
+ }catch(error){if(error.code!=='ENOENT')throw error;}
26
+ }
27
+ }
28
+ export function createLiveEvidence(config,{base,protectedRoots=[],notify=()=>{},maxBytes=65536,allowedKinds=[...KINDS]}={}){
29
+ if(config===undefined)return {has:()=>false,answer:async()=>null};
30
+ if(!config||typeof config!=='object'||Array.isArray(config)
31
+ ||Object.keys(config).some(key=>!['directory','kinds','timeoutMs'].includes(key))
32
+ ||typeof config.directory!=='string'||!config.directory.trim()
33
+ ||!Array.isArray(config.kinds)||!config.kinds.length
34
+ ||new Set(config.kinds).size!==config.kinds.length
35
+ ||!config.kinds.every(kind=>KINDS.has(kind)&&allowedKinds.includes(kind)))fail('live_evidence_invalid_config');
36
+ const timeout=config.timeoutMs??900000;
37
+ if(!Number.isSafeInteger(timeout)||timeout<1||timeout>3600000
38
+ ||!Number.isSafeInteger(maxBytes)||maxBytes<1||maxBytes>4194304)fail('live_evidence_invalid_limit');
39
+ const directory=path.resolve(base??process.cwd(),config.directory);
40
+ const validateDirectory=()=>{
41
+ ordinaryAncestors(directory);
42
+ for(const root of protectedRoots.filter(Boolean)){
43
+ const resolved=resolvedFutureRoot(root),lexical=path.resolve(root);
44
+ if([resolved,lexical].some(value=>inside(value,directory)||inside(directory,value)))fail('live_evidence_protected_directory');
45
+ }
46
+ if(fs.existsSync(directory)){
47
+ const stat=fs.lstatSync(directory);
48
+ if((stat.mode&0o077)!==0||typeof process.getuid==='function'&&stat.uid!==process.getuid())
49
+ fail('live_evidence_directory_not_private');
50
+ }
51
+ };
52
+ validateDirectory();
53
+ const kinds=new Set(config.kinds),seen=new Set();let exchange=null;
54
+ return {has:kind=>kinds.has(kind),async answer(row,{signal}={}){
55
+ if(!kinds.has(row.kind))return null;
56
+ if(signal?.aborted)fail('live_evidence_cancelled');
57
+ if(row.type!=='host_request'||!row.sessionId||!row.callId
58
+ ||typeof row.requestDigest!=='string'||!/^[a-f0-9]{64}$/.test(row.requestDigest))fail('live_evidence_invalid_request');
59
+ const key=JSON.stringify([row.sessionId,row.callId]);
60
+ if(seen.has(key))fail('live_evidence_duplicate_call');
61
+ seen.add(key);validateDirectory();
62
+ if(exchange===null){
63
+ fs.mkdirSync(directory,{recursive:true,mode:0o700});validateDirectory();
64
+ exchange=path.join(directory,randomUUID());fs.mkdirSync(exchange,{mode:0o700});
65
+ }
66
+ // File names never contain caller-controlled identifiers.
67
+ const stem=path.join(exchange,randomUUID()),requestFile=stem+'.request.json',resultFile=stem+'.result.json';
68
+ fs.writeFileSync(requestFile,JSON.stringify(row)+'\n',{flag:'wx',mode:0o600});
69
+ notify(requestFile);const end=Date.now()+timeout;
70
+ while(true){
71
+ if(signal?.aborted)fail('live_evidence_cancelled');
72
+ let fd;
73
+ try{
74
+ fd=fs.openSync(resultFile,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW|fs.constants.O_NONBLOCK);
75
+ const before=fs.fstatSync(fd);
76
+ if(!before.isFile()||before.nlink!==1||before.size>maxBytes)fail('live_evidence_unsafe_result');
77
+ const bytes=fs.readFileSync(fd),after=fs.fstatSync(fd);
78
+ if(bytes.length>maxBytes||before.size!==after.size||before.mtimeMs!==after.mtimeMs)fail('live_evidence_result_changed');
79
+ let value;try{value=JSON.parse(bytes.toString('utf8'));}catch{fail('live_evidence_invalid_json');}
80
+ if(!value||Array.isArray(value)||Object.keys(value).sort().join(',')!=='callId,requestDigest,result,sessionId,type'
81
+ ||value.type!=='host_result'||value.sessionId!==row.sessionId||value.callId!==row.callId
82
+ ||value.requestDigest!==row.requestDigest)fail('live_evidence_binding_mismatch');
83
+ return value.result;
84
+ }catch(error){if(error.code!=='ENOENT')throw error;}
85
+ finally{if(fd!==undefined)fs.closeSync(fd);}
86
+ if(Date.now()>=end)fail('live_evidence_timeout');
87
+ try{await delay(Math.min(100,end-Date.now()),undefined,{signal});}
88
+ catch(error){if(error.name==='AbortError')fail('live_evidence_cancelled');throw error;}
89
+ }
90
+ }};
91
+ }
92
+
93
+ export function driverLiveEvidence(plan,options){
94
+ return createLiveEvidence(plan.liveEvidence,{...options,notify:file=>process.stderr.write(
95
+ `[drive] live_evidence_request: ${file}\n[drive] Read the live request, execute its task, then atomically write the matching .result.json host_result.\n`)});
96
+ }
@@ -0,0 +1,21 @@
1
+ // Bounded, no-follow reader for the specs-local JSONL log. Leaf module: it has
2
+ // no workflow imports, so read-only inspectors (admission included) can share it.
3
+ import fs from 'node:fs';
4
+ import {json,need} from './effect-contract.mjs';
5
+
6
+ const MiB=1024*1024;
7
+ export function scanRows(log,visit) {
8
+ let descriptor;
9
+ try {
10
+ const stat=fs.lstatSync(log);need(stat.isFile()&&!stat.isSymbolicLink(),'qa_log_failed');
11
+ descriptor=fs.openSync(log,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);
12
+ const chunk=Buffer.alloc(64*1024);let pending=Buffer.alloc(0);
13
+ const consume=line=>{if(line.length){need(line.length<=MiB,'qa_log_failed');
14
+ visit(json(JSON.parse(new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(line)),MiB));}};
15
+ while(true){const size=fs.readSync(descriptor,chunk,0,chunk.length,null);if(size===0)break;
16
+ pending=Buffer.concat([pending,chunk.subarray(0,size)]);let newline;
17
+ while((newline=pending.indexOf(10))!==-1){consume(pending.subarray(0,newline));pending=pending.subarray(newline+1);}
18
+ need(pending.length<=MiB,'qa_log_failed');}
19
+ consume(pending);
20
+ } finally {if(descriptor!==undefined)fs.closeSync(descriptor);}
21
+ }
@@ -0,0 +1,63 @@
1
+ // Local bounded declarative JSON. No global state, secrets, or store migrations.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {createHash} from 'node:crypto';
5
+ import {spawnSync} from 'node:child_process';
6
+ import {fileURLToPath} from 'node:url';
7
+ import {need,digest} from './effect-contract.mjs';
8
+ const LIMIT=64*1024;
9
+ const RUN_DIRECTORIES=new Set(['.reviews','.cm-model-runtime-v1','.cm-model-reviews-v1','.cm-model-runtime-v2','.cm-model-reviews-v2','.cm-model-fix-runtime-v1','.cm-external-models-v1']);
10
+ const RUN_FILES=new Set(['.cm-task-owner.json','.cm-model-code-owner-v1.json','.cm-model-project-owner-v2.json','.cm-model-snapshot-v1.json','.cm-model-fix-owner-v1.json']);
11
+ export function parseModelJson(text){
12
+ need(typeof text==='string'&&Buffer.byteLength(text)<=LIMIT,'model_configuration_too_large');
13
+ let value;try{value=JSON.parse(text);}catch{need(false,'invalid_model_json');}
14
+ const tokens=text.match(/"(?:\\[\s\S]|[^"\\])*"|[{}\[\]:,]|[^\s{}\[\]:,]+/g)??[];let index=0;
15
+ const walk=depth=>{
16
+ need(depth<=32,'model_configuration_too_deep');const token=tokens[index++];
17
+ if(token==='{'){
18
+ const keys=new Set();if(tokens[index]==='}'){index++;return;}
19
+ for(;;){const key=JSON.parse(tokens[index++]);need(!keys.has(key),'duplicate_model_json_key');keys.add(key);index++;walk(depth+1);
20
+ if(tokens[index++]==='}')return;}
21
+ }
22
+ if(token==='['){if(tokens[index]===']'){index++;return;}for(;;){walk(depth+1);if(tokens[index++]===']')return;}}
23
+ };
24
+ walk(0);return value;
25
+ }
26
+ const match=(a,b)=>['dev','ino','size','mtimeMs','ctimeMs','nlink'].every(k=>a[k]===b[k]);
27
+ export function readModelJsonRecord(file){
28
+ const before=fs.lstatSync(file);need(before.isFile()&&!before.isSymbolicLink()&&before.nlink===1&&before.size<=LIMIT,'invalid_model_configuration_file');
29
+ const fd=fs.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);
30
+ try{
31
+ need(match(before,fs.fstatSync(fd)),'model_configuration_changed');const bytes=fs.readFileSync(fd);const text=bytes.toString('utf8');
32
+ need(bytes.equals(Buffer.from(text))&&match(before,fs.fstatSync(fd))&&match(before,fs.lstatSync(file)),'model_configuration_changed');
33
+ return {value:parseModelJson(text),sha256:createHash('sha256').update(bytes).digest('hex')};
34
+ }finally{fs.closeSync(fd);}
35
+ }
36
+ export const readModelJson=file=>readModelJsonRecord(file).value;
37
+ export function assertModelOutputPath(file){
38
+ const target=path.resolve(file);
39
+ need(!target.split(path.sep).some(segment=>RUN_DIRECTORIES.has(segment.toLowerCase()))
40
+ &&!RUN_FILES.has(path.basename(target).toLowerCase()),'model_output_run_path_forbidden');
41
+ return target;
42
+ }
43
+ export function writeModelJson(file,value,{expectedDigest,expectedSha256,replace=true,createParents=false,sourceGuard=null}={}){
44
+ const target=assertModelOutputPath(file);
45
+ need(path.basename(target).toLowerCase()!=='.cm-model-config.lock','model_output_run_path_forbidden');
46
+ // No downgrade to a path-based writer if the platform/helper is unavailable.
47
+ need(process.platform!=='win32'&&fs.existsSync('/usr/bin/python3'),'model_secure_write_unavailable');
48
+ let before=null;
49
+ try{const info=fs.lstatSync(target);need(info.isFile()&&!info.isSymbolicLink()&&info.nlink===1,'invalid_model_configuration_file');
50
+ need(replace,'model_configuration_exists');before=readModelJsonRecord(target);
51
+ }catch(e){if(e.code!=='ENOENT')throw e;}
52
+ if(expectedDigest!==undefined)need(expectedDigest===null?before===null:before!==null&&digest(before.value)===expectedDigest,'model_configuration_changed');
53
+ if(expectedSha256!==undefined)need((before?.sha256??null)===expectedSha256,'model_configuration_changed');
54
+ const bytes=Buffer.from(JSON.stringify(value,null,2)+'\n');need(bytes.length<=LIMIT,'model_configuration_too_large');
55
+ const request={target,bytes:bytes.toString('base64'),expectedSha256:before?.sha256??null,replace,createParents,sourceGuard};
56
+ const helper=fileURLToPath(new URL('./model_configuration_write.py',import.meta.url));
57
+ const result=spawnSync('/usr/bin/python3',['-I','-B',helper],{input:JSON.stringify(request),encoding:'utf8',
58
+ env:{PATH:'/usr/bin:/bin',LANG:'C.UTF-8'},timeout:10000,maxBuffer:4096,shell:false});
59
+ // A started helper may already have published before timeout/response loss.
60
+ if(result.error||result.signal)need(false,result.error?.code==='ENOENT'?'model_secure_write_unavailable':'model_configuration_write_unknown');
61
+ let response;try{response=JSON.parse(result.stdout);}catch{need(false,'model_configuration_write_unknown');}
62
+ need(response?.ok===true&&result.status===0,response?.ok===false&&/^model_|^invalid_model_|^unsupported_model_/.test(response.code)?response.code:'model_configuration_write_unknown');
63
+ }