@iowarp/clio-coder 0.3.8 → 0.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (333) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/README.md +7 -3
  3. package/dist/{acp-U67UHUK2.js → acp-7LOELQFP.js} +6 -6
  4. package/dist/{agents-YU6SGALZ.js → agents-FIBG2SHA.js} +27 -25
  5. package/dist/assets/codewiki.json +1 -1
  6. package/dist/{auth-5ZPJOIVG.js → auth-OI4LIH2I.js} +11 -12
  7. package/dist/{builtins-C6JMZVV6.js → builtins-AD25UL3C.js} +5 -5
  8. package/dist/{chunk-5FR74PWO.js → chunk-2JDWVJND.js} +2 -2
  9. package/dist/chunk-3DPEIQKN.js +113 -0
  10. package/dist/{chunk-4SPRNWDE.js → chunk-3DUR4WUA.js} +15 -15
  11. package/dist/{chunk-VHN4MY6O.js → chunk-3MRC2YSQ.js} +2 -2
  12. package/dist/{chunk-5DHKRSMQ.js → chunk-3UUY7R3Z.js} +11 -7
  13. package/dist/{chunk-IGWKHNIQ.js → chunk-3V5AYSEQ.js} +8 -8
  14. package/dist/{chunk-FHJEP5SW.js → chunk-465CC7FK.js} +8 -5
  15. package/dist/{chunk-5WIGXA4T.js → chunk-47CMYGET.js} +111 -4
  16. package/dist/{chunk-A3WNZD3P.js → chunk-4H6ULJ3H.js} +67 -21
  17. package/dist/{chunk-TB5666IT.js → chunk-4LJX2PUC.js} +3 -3
  18. package/dist/{chunk-XWSF374K.js → chunk-56KB5IJP.js} +2 -2
  19. package/dist/{chunk-SPULKLCF.js → chunk-5DQRIYDZ.js} +2 -2
  20. package/dist/{chunk-2HEJ2F35.js → chunk-5HFBWUMU.js} +20 -8
  21. package/dist/{chunk-WNIJTQQK.js → chunk-5PVQ4SRS.js} +78 -6
  22. package/dist/{chunk-DYIM5TJT.js → chunk-5QKCQQ3E.js} +262 -6
  23. package/dist/{chunk-TYPGUK6W.js → chunk-5T7RBWN2.js} +111 -5
  24. package/dist/{chunk-IIZWH4XA.js → chunk-774ILSRL.js} +2 -2
  25. package/dist/chunk-7C6RYZGQ.js +391 -0
  26. package/dist/{chunk-TANS5ZJS.js → chunk-AD7Y7STJ.js} +3 -3
  27. package/dist/{chunk-RWSI4YD7.js → chunk-AEYBF3TB.js} +33 -12
  28. package/dist/{chunk-DGSYXYMX.js → chunk-AMKHQW3C.js} +2 -2
  29. package/dist/{chunk-VWZOAB7K.js → chunk-B5XRQOLB.js} +7 -7
  30. package/dist/{chunk-WXY7KU3G.js → chunk-BVDVID7E.js} +2 -2
  31. package/dist/{chunk-PMDBGQSJ.js → chunk-CA42X6KT.js} +2 -2
  32. package/dist/{chunk-HLE42MG7.js → chunk-D73KXYPF.js} +3 -3
  33. package/dist/{chunk-5Q2VVUKB.js → chunk-DG4M6ZUE.js} +3 -3
  34. package/dist/{chunk-ME6CCNFO.js → chunk-EBOC7MT3.js} +6 -6
  35. package/dist/{chunk-MXKJU4JB.js → chunk-ECUO3KDP.js} +48 -7
  36. package/dist/{chunk-26LEYJZH.js → chunk-FALJGAWU.js} +2 -2
  37. package/dist/{chunk-GWS3VEIW.js → chunk-FWDFM5ZU.js} +24 -3
  38. package/dist/{chunk-7RGZWPB6.js → chunk-GAYUJ7LE.js} +67 -13
  39. package/dist/{chunk-VCBR6CU7.js → chunk-HAY4ZE2P.js} +2 -2
  40. package/dist/{chunk-FBVTI2TJ.js → chunk-HCBCAYZU.js} +11 -130
  41. package/dist/{chunk-WSB3FPX7.js → chunk-HJB5IUKP.js} +32 -136
  42. package/dist/{chunk-J3YUBZWY.js → chunk-HKO36JWF.js} +33 -5
  43. package/dist/{chunk-E77JEWSD.js → chunk-HPCTNZM2.js} +6 -36
  44. package/dist/{chunk-FJ3H4MN5.js → chunk-IHKBWSXF.js} +2 -2
  45. package/dist/{chunk-NMPKI6XL.js → chunk-JEQQR47K.js} +37 -18
  46. package/dist/{chunk-3BINW3FP.js → chunk-KV2AOLDF.js} +24 -4
  47. package/dist/{chunk-YS5VLNH5.js → chunk-LXPJXFM5.js} +7 -7
  48. package/dist/{chunk-7RFXX52T.js → chunk-MIX5N5AC.js} +271 -41
  49. package/dist/{chunk-K4XHGFR5.js → chunk-MLOK6ZOS.js} +1297 -218
  50. package/dist/{chunk-ZNLWCMVZ.js → chunk-MV2VUEJC.js} +2 -2
  51. package/dist/{chunk-MVVUPGPW.js → chunk-MXHC5QYU.js} +6 -6
  52. package/dist/{chunk-5H3GB5BO.js → chunk-N3PBVRTZ.js} +4 -382
  53. package/dist/{chunk-2HFZQUHL.js → chunk-N5XKWMDW.js} +17 -7
  54. package/dist/{chunk-5C3AQNDW.js → chunk-NNNWO6F2.js} +124 -36
  55. package/dist/{chunk-GU2UIAFZ.js → chunk-NQ6UCCOD.js} +3 -3
  56. package/dist/{chunk-N22QMJKY.js → chunk-NZU6YDNV.js} +4 -4
  57. package/dist/{chunk-ZVJ5BLO2.js → chunk-O6I4CIEU.js} +151 -13
  58. package/dist/{chunk-XN3L4EYL.js → chunk-OEDBCISO.js} +2 -2
  59. package/dist/{chunk-VAWNZU7Z.js → chunk-P3JGPQFL.js} +2 -2
  60. package/dist/{chunk-IJ7RPIYJ.js → chunk-PNY46YEY.js} +20 -3
  61. package/dist/{chunk-U6MBIEMB.js → chunk-PZ4I4JE2.js} +56 -35
  62. package/dist/{chunk-GPIEI3LY.js → chunk-QQ7EKM72.js} +2 -2
  63. package/dist/{chunk-WLFILSD5.js → chunk-R7LNVMCS.js} +66 -28
  64. package/dist/{chunk-GOXNB3AO.js → chunk-RAPCMZL4.js} +75 -4
  65. package/dist/chunk-RKKLTLYB.js +45 -0
  66. package/dist/{chunk-TT36MB5S.js → chunk-RKRLDWD3.js} +3 -1
  67. package/dist/{chunk-TTHACPOM.js → chunk-S4COXYBG.js} +456 -18
  68. package/dist/{chunk-WWCZ5F23.js → chunk-T3Z6VAAF.js} +69 -10
  69. package/dist/{chunk-GN57SG4G.js → chunk-TD7UE2L5.js} +9 -7
  70. package/dist/{chunk-TLQJPP24.js → chunk-TEO2TLVN.js} +523 -322
  71. package/dist/{chunk-FCSXB6T2.js → chunk-UOSL25KY.js} +14 -2
  72. package/dist/{chunk-KTYTFRMB.js → chunk-VKBMFOYV.js} +17 -15
  73. package/dist/{chunk-PT7HYKEM.js → chunk-VO2LKSTM.js} +2 -2
  74. package/dist/{chunk-P43ETTHK.js → chunk-VPTUJU4P.js} +2 -2
  75. package/dist/{chunk-WEH5XRJQ.js → chunk-WIE7ZOSW.js} +2 -2
  76. package/dist/{chunk-EMYUUSFG.js → chunk-WXCJ7VME.js} +5 -5
  77. package/dist/{chunk-4DGYLA73.js → chunk-XDOQXGFO.js} +22 -7
  78. package/dist/{chunk-JOZYP4GM.js → chunk-YKOFT37S.js} +5 -5
  79. package/dist/chunk-YSEHGPCT.js +127 -0
  80. package/dist/{chunk-HFSBBKSQ.js → chunk-YW7UVM5V.js} +138 -3
  81. package/dist/cli/index.js +27 -27
  82. package/dist/{clio-QVTYJ57A.js → clio-LT5V7SSZ.js} +6 -6
  83. package/dist/{code-nav-FGGFIE7L.js → code-nav-LMW275PA.js} +4 -4
  84. package/dist/{config-LW5IJFQN.js → config-RXS5T3JT.js} +71 -43
  85. package/dist/{configure-7XIZCOU4.js → configure-2WYWSCSD.js} +14 -15
  86. package/dist/{context-Y6Y7QPR6.js → context-I3BTOTCS.js} +12 -12
  87. package/dist/{context-L3WL3X7K.js → context-MVOORGMF.js} +34 -33
  88. package/dist/{context-N52ZA626.js → context-PALKKQYL.js} +20 -20
  89. package/dist/{context-clear-MBQRLSDQ.js → context-clear-N2WOYZ2K.js} +34 -33
  90. package/dist/{context-index-HVMFQHK3.js → context-index-HNG3MOME.js} +2 -2
  91. package/dist/{context-working-set-GS6DSO7F.js → context-working-set-MIEVECVZ.js} +10 -11
  92. package/dist/{dispatch-runner-22ZCNOM3.js → dispatch-runner-VVA4SRRH.js} +34 -33
  93. package/dist/doctor-TWBWFK5V.js +165 -0
  94. package/dist/{eval-BEC2WHDA.js → eval-IJ5VEZDJ.js} +2016 -142
  95. package/dist/{evidence-REJUMSKM.js → evidence-L5APPXNV.js} +29 -28
  96. package/dist/{evolve-PY5ZBA5K.js → evolve-RGNKFJ52.js} +29 -28
  97. package/dist/{extensions-HVKU65YU.js → extensions-7WYWUX5A.js} +9 -3
  98. package/dist/{fleet-7WZEWRFA.js → fleet-6CNVBZZP.js} +87 -55
  99. package/dist/{fleet-commands-UVHWM76J.js → fleet-commands-L2SXSYEI.js} +6 -6
  100. package/dist/{fleet-graph-6ULH7PES.js → fleet-graph-2J3OOIPO.js} +14 -12
  101. package/dist/{fleet-preflight-J53T6CCE.js → fleet-preflight-CZRJ4JP5.js} +3 -4
  102. package/dist/{fleet-validate-72PC4SLA.js → fleet-validate-C5RI6DP7.js} +16 -15
  103. package/dist/{init-OG3TPGQG.js → init-VBN2ACVA.js} +50 -48
  104. package/dist/{library-CNTMPLRF.js → library-JHGUMLY2.js} +13 -11
  105. package/dist/{memory-6IS7F275.js → memory-K4OQIYWG.js} +31 -30
  106. package/dist/{models-ENRJDA5W.js → models-2NCZUWDD.js} +23 -22
  107. package/dist/{monitor-XLDVO7TN.js → monitor-MMVTJABD.js} +35 -34
  108. package/dist/{orchestrator-6KSPYRHA.js → orchestrator-ZKBPCHW6.js} +1627 -294
  109. package/dist/{reset-RZ4ER727.js → reset-DD5JGOY3.js} +3 -3
  110. package/dist/{run-Y2CNK5RU.js → run-QEGNX7FL.js} +56 -55
  111. package/dist/{share-A55GYP6Z.js → share-JKD3BQMW.js} +13 -11
  112. package/dist/{skills-ALC5J6AT.js → skills-LMQIKDOZ.js} +14 -12
  113. package/dist/{skills-eval-JPBEBYQU.js → skills-eval-I7X2774U.js} +34 -32
  114. package/dist/{steer-GGWFUJUD.js → steer-CF5TDANS.js} +3 -3
  115. package/dist/{support-MIETYA5E.js → support-I7LOJLIF.js} +4 -4
  116. package/dist/{targets-VGNXIR3S.js → targets-RUSR6B5Z.js} +58 -32
  117. package/dist/{terminal-lease-WOBR64YA.js → terminal-lease-QYVORFR4.js} +6 -4
  118. package/dist/{trace-PNCASAXC.js → trace-ODOQIVIW.js} +61 -6
  119. package/dist/{upgrade-FUSUAGHR.js → upgrade-XANW3FXB.js} +17 -16
  120. package/dist/{usage-N4MKVHKD.js → usage-4H7ZRXQT.js} +88 -44
  121. package/dist/{verifiers-YAWOJ3H2.js → verifiers-UZXNBZEB.js} +6 -6
  122. package/dist/{verify-LTDHYBGY.js → verify-BVKWTNDL.js} +5 -5
  123. package/dist/{wiki-generate-6M7GHTBJ.js → wiki-generate-MY7WV2QI.js} +49 -47
  124. package/dist/worker/entry.js +29 -33
  125. package/docs/alcf-provider.md +1 -1
  126. package/docs/architecture.md +1 -1
  127. package/docs/artifact-versions.md +6 -1
  128. package/docs/built-in-agents.md +1 -1
  129. package/docs/capacity-and-scheduling.md +23 -2
  130. package/docs/commands-and-modes.md +1 -1
  131. package/docs/configuration-and-targets.md +30 -3
  132. package/docs/context-engine.md +63 -4
  133. package/docs/documentation-coverage.md +3 -3
  134. package/docs/documentation-guide.md +1 -1
  135. package/docs/environment-variables.md +2 -0
  136. package/docs/eval-runner.md +262 -11
  137. package/docs/evals-internal.md +72 -2
  138. package/docs/evidence-and-memory.md +11 -10
  139. package/docs/evolution.md +1 -1
  140. package/docs/extensions-and-sharing.md +3 -1
  141. package/docs/fleet-dispatch.md +4 -4
  142. package/docs/installation-and-lifecycle.md +1 -1
  143. package/docs/middleware-and-components.md +1 -1
  144. package/docs/model-catalog.md +1 -1
  145. package/docs/observability.md +53 -2
  146. package/docs/proactive-memory.md +127 -14
  147. package/docs/prompt-envelope-and-tools.md +19 -1
  148. package/docs/provider-adapter-cookbook.md +1 -1
  149. package/docs/release-cut-checklist.md +19 -3
  150. package/docs/safety-model.md +1 -1
  151. package/docs/scientific-validation.md +1 -1
  152. package/docs/skills-marketplace.md +1 -1
  153. package/docs/tool-usage.md +1 -1
  154. package/docs/trace-store.md +1 -1
  155. package/docs/troubleshooting.md +87 -0
  156. package/docs/tui-design.md +1 -1
  157. package/docs/worker-dispatch-mechanics.md +1 -1
  158. package/package.json +2 -1
  159. package/src/cli/agents.ts +1 -1
  160. package/src/cli/config-inspect.ts +33 -6
  161. package/src/cli/config.ts +1 -1
  162. package/src/cli/doctor-state-size.ts +82 -0
  163. package/src/cli/doctor.ts +3 -1
  164. package/src/cli/eval.ts +80 -16
  165. package/src/cli/extensions.ts +5 -1
  166. package/src/cli/fleet.ts +32 -3
  167. package/src/cli/targets.ts +44 -13
  168. package/src/cli/trace.ts +63 -4
  169. package/src/cli/usage.ts +63 -14
  170. package/src/core/bus-events.ts +29 -1
  171. package/src/core/cache-telemetry.ts +42 -0
  172. package/src/core/config.ts +18 -0
  173. package/src/core/defaults.ts +36 -6
  174. package/src/core/endpoint-key.ts +27 -0
  175. package/src/core/residency-target-key.ts +25 -0
  176. package/src/core/response-schema.ts +36 -2
  177. package/src/domains/config/classify.ts +3 -0
  178. package/src/domains/context/codewiki/coordinator.ts +12 -4
  179. package/src/domains/dispatch/admission.ts +40 -3
  180. package/src/domains/dispatch/capacity-lease.ts +98 -9
  181. package/src/domains/dispatch/contract.ts +11 -0
  182. package/src/domains/dispatch/execution-plan.ts +44 -4
  183. package/src/domains/dispatch/extension.ts +166 -42
  184. package/src/domains/dispatch/fleet-run.ts +23 -3
  185. package/src/domains/dispatch/heartbeat.ts +32 -8
  186. package/src/domains/dispatch/index.ts +3 -0
  187. package/src/domains/dispatch/orphan-recovery.ts +5 -0
  188. package/src/domains/dispatch/reservation-store.ts +116 -8
  189. package/src/domains/dispatch/state.ts +4 -0
  190. package/src/domains/dispatch/worker-spawn.ts +25 -11
  191. package/src/domains/dispatch/write-boundary-enforcer.ts +20 -3
  192. package/src/domains/dispatch/write-boundary.ts +62 -1
  193. package/src/domains/eval/artifacts/store.ts +62 -0
  194. package/src/domains/eval/compare/behavioral.ts +224 -0
  195. package/src/domains/eval/compare/compare.ts +355 -2
  196. package/src/domains/eval/compare/envelope.ts +128 -0
  197. package/src/domains/eval/compare/gates.ts +24 -6
  198. package/src/domains/eval/compare/thresholds.ts +30 -3
  199. package/src/domains/eval/execution-provenance.ts +240 -0
  200. package/src/domains/eval/metrics/aggregate.ts +136 -0
  201. package/src/domains/eval/metrics/call-ledger-stream.ts +112 -0
  202. package/src/domains/eval/metrics/tracked.ts +413 -0
  203. package/src/domains/eval/provenance.ts +117 -0
  204. package/src/domains/eval/reports/comparison.ts +128 -0
  205. package/src/domains/eval/reports/junit.ts +17 -3
  206. package/src/domains/eval/reports/markdown.ts +3 -3
  207. package/src/domains/eval/reports/text.ts +14 -0
  208. package/src/domains/eval/run-compare.ts +20 -0
  209. package/src/domains/eval/runners/clio-run.ts +127 -0
  210. package/src/domains/eval/runners/external-command.ts +28 -3
  211. package/src/domains/eval/schema/adapter.ts +111 -0
  212. package/src/domains/eval/schema/artifact.ts +20 -0
  213. package/src/domains/eval/schema/behavioral-metrics.ts +204 -0
  214. package/src/domains/eval/schema/behavioral.ts +520 -0
  215. package/src/domains/eval/schema/execution-envelope.ts +194 -0
  216. package/src/domains/eval/schema/serving.ts +74 -0
  217. package/src/domains/eval/schema/suite.ts +38 -8
  218. package/src/domains/eval/schema/validate.ts +58 -3
  219. package/src/domains/eval/schema/verdict.ts +237 -0
  220. package/src/domains/eval/suites/resolve.ts +2 -0
  221. package/src/domains/eval/suites/run.ts +264 -33
  222. package/src/domains/eval/verifiers/command.ts +2 -1
  223. package/src/domains/eval/workspaces/temp-copy.ts +145 -13
  224. package/src/domains/evidence/build.ts +2 -13
  225. package/src/domains/evidence/eval.ts +2 -12
  226. package/src/domains/evidence/findings-markdown.ts +33 -0
  227. package/src/domains/evidence/run-trust.ts +7 -113
  228. package/src/domains/evidence/trust-projection.ts +2 -2
  229. package/src/domains/extensions/compatibility.ts +285 -0
  230. package/src/domains/extensions/discovery.ts +38 -3
  231. package/src/domains/extensions/resources.ts +1 -1
  232. package/src/domains/extensions/state.ts +12 -3
  233. package/src/domains/extensions/types.ts +2 -0
  234. package/src/domains/lifecycle/doctor.ts +69 -1
  235. package/src/domains/memory/index.ts +14 -0
  236. package/src/domains/memory/task-bank-promotion.ts +64 -0
  237. package/src/domains/memory/task-memory-policy.ts +77 -8
  238. package/src/domains/memory/task-memory-spend.ts +131 -0
  239. package/src/domains/memory/task-memory-status.ts +7 -0
  240. package/src/domains/memory/task-memory-telemetry.ts +2 -0
  241. package/src/domains/middleware/index.ts +1 -0
  242. package/src/domains/middleware/memory-intervention.ts +69 -5
  243. package/src/domains/middleware/memory-step-endpoint.ts +71 -0
  244. package/src/domains/observability/background-memory-usage.ts +140 -0
  245. package/src/domains/observability/cost.ts +1 -1
  246. package/src/domains/observability/index.ts +7 -0
  247. package/src/domains/observability/out-of-turn-usage.ts +51 -2
  248. package/src/domains/observability/trace-store.ts +192 -2
  249. package/src/domains/prompts/compiler.ts +100 -13
  250. package/src/domains/providers/endpoint-capacity.ts +96 -0
  251. package/src/domains/providers/index.ts +10 -0
  252. package/src/domains/providers/models/local-models/clio-local-coding-targets.yaml +243 -1
  253. package/src/domains/providers/runtime-resolution.ts +8 -1
  254. package/src/domains/providers/runtimes/common/probe-helpers.ts +31 -9
  255. package/src/domains/providers/runtimes/local-native/llamacpp-anthropic.ts +1 -1
  256. package/src/domains/providers/runtimes/local-native/llamacpp-completion.ts +1 -1
  257. package/src/domains/providers/runtimes/local-native/llamacpp-embed.ts +1 -1
  258. package/src/domains/providers/runtimes/local-native/llamacpp-rerank.ts +1 -1
  259. package/src/domains/providers/runtimes/local-native/llamacpp.ts +4 -1
  260. package/src/domains/providers/runtimes/local-native/lmstudio.ts +4 -1
  261. package/src/domains/providers/runtimes/local-native/ollama-native.ts +6 -1
  262. package/src/domains/providers/types/capability-flags.ts +2 -0
  263. package/src/domains/providers/types/target-descriptor.ts +2 -0
  264. package/src/domains/resources/prompts/loader.ts +95 -33
  265. package/src/domains/safety/call-target.ts +52 -0
  266. package/src/domains/safety/run-effects.ts +35 -4
  267. package/src/domains/session/context-accounting.ts +52 -1
  268. package/src/domains/session/context-ledger.ts +37 -13
  269. package/src/domains/session/index.ts +6 -0
  270. package/src/domains/session/prompt-cache.ts +140 -0
  271. package/src/domains/session/prompt-manifest.ts +42 -0
  272. package/src/engine/acp/adapter.ts +18 -3
  273. package/src/engine/ai.ts +35 -0
  274. package/src/engine/apis/llamacpp-residency.ts +55 -3
  275. package/src/engine/apis/lmstudio.ts +25 -5
  276. package/src/engine/apis/ollama-native.ts +2 -1
  277. package/src/engine/apis/openai-completions.ts +80 -17
  278. package/src/engine/apis/residency-lock.ts +3 -1
  279. package/src/engine/apis/residency.ts +34 -1
  280. package/src/engine/provider-payload.ts +29 -1
  281. package/src/entry/orchestrator.ts +176 -30
  282. package/src/interactive/chat-loop-messages.ts +26 -7
  283. package/src/interactive/chat-loop.ts +318 -41
  284. package/src/interactive/chat-panel.ts +62 -8
  285. package/src/interactive/clio-editor.ts +45 -8
  286. package/src/interactive/context-activity.ts +5 -1
  287. package/src/interactive/context-meter.ts +1 -1
  288. package/src/interactive/context-overlay.ts +40 -10
  289. package/src/interactive/cost-overlay.ts +64 -6
  290. package/src/interactive/dispatch-board.ts +84 -12
  291. package/src/interactive/fleet-run-preview.ts +41 -15
  292. package/src/interactive/handoff-round.ts +41 -2
  293. package/src/interactive/interactive-application.ts +24 -1
  294. package/src/interactive/interactive-input-runtime.ts +8 -0
  295. package/src/interactive/interactive-presentation.ts +4 -0
  296. package/src/interactive/interactive-shell.ts +20 -17
  297. package/src/interactive/interactive-slash-runtime.ts +27 -4
  298. package/src/interactive/memory-overlay.ts +8 -0
  299. package/src/interactive/mutation-preview.ts +295 -0
  300. package/src/interactive/overlay-general-openers.ts +16 -0
  301. package/src/interactive/overlay-key-routing.ts +38 -0
  302. package/src/interactive/overlay-lifecycle.ts +38 -5
  303. package/src/interactive/overlay-permission-lifecycle.ts +22 -2
  304. package/src/interactive/overlay-session-lifecycle.ts +73 -9
  305. package/src/interactive/overlays/ask-user.ts +91 -19
  306. package/src/interactive/overlays/help-reference.ts +4 -0
  307. package/src/interactive/overlays/prompts.ts +11 -1
  308. package/src/interactive/overlays/settings.ts +35 -1
  309. package/src/interactive/permission-hint.ts +34 -2
  310. package/src/interactive/permission-overlay.ts +159 -9
  311. package/src/interactive/prewarm.ts +197 -0
  312. package/src/interactive/render-trace.ts +162 -15
  313. package/src/interactive/renderers/tool-execution.ts +4 -0
  314. package/src/interactive/side-question.ts +58 -1
  315. package/src/interactive/status/controller.ts +11 -0
  316. package/src/interactive/status/state-machine.ts +54 -2
  317. package/src/interactive/status/types.ts +7 -0
  318. package/src/interactive/terminal-lease.ts +2 -0
  319. package/src/interactive/turn-context.ts +299 -31
  320. package/src/interactive/turn-persistence.ts +14 -4
  321. package/src/interactive/turn-prewarm.ts +364 -0
  322. package/src/interactive/turn-queues.ts +7 -4
  323. package/src/interactive/turn-runtime.ts +8 -1
  324. package/src/interactive/turn-state.ts +23 -0
  325. package/src/interactive/view/view-overlay.ts +28 -3
  326. package/src/tools/ask-user.ts +43 -2
  327. package/src/tools/dispatch-plan.ts +17 -9
  328. package/src/tools/dispatch-scout.ts +1 -1
  329. package/src/tools/registry.ts +16 -0
  330. package/dist/chunk-AOCYTWAV.js +0 -449
  331. package/dist/chunk-HWUFFB6L.js +0 -83
  332. package/dist/chunk-R346GLFC.js +0 -31
  333. package/dist/doctor-M7YEDGAE.js +0 -91
@@ -1,18 +1,12 @@
1
1
  import { createRequire as __clioCreateRequire } from "node:module"; const require = __clioCreateRequire(import.meta.url);
2
- import {
3
- protectedArtifactFromSessionEntry,
4
- protectedArtifactStateFromSessionEntries,
5
- readAuditRows,
6
- readSessionEntriesForId,
7
- responseModelIdObservationFromRecord
8
- } from "./chunk-YS5VLNH5.js";
9
2
  import {
10
3
  RUN_RECEIPT_INTEGRITY_ALGORITHM,
11
4
  RUN_RECEIPT_INTEGRITY_VERSION,
12
- adaptFinishContractCompletionStatus,
13
5
  adaptGateDecisionReviewStatus,
14
6
  adaptGroundedEvidenceValidationStatus,
15
7
  composeTrustStatus,
8
+ formatTrustAxes,
9
+ formatTrustSummary,
16
10
  inspectRunReceiptTrustStatus,
17
11
  isReceiptIntegrity,
18
12
  isTrustStatusIdentifier,
@@ -21,10 +15,19 @@ import {
21
15
  parseEvalArtifactV4,
22
16
  redactArtifactForStorage,
23
17
  retiredIntegrityVersionOf,
18
+ sha256,
24
19
  sumEvalHarnessMetrics,
20
+ trustVerdict,
25
21
  verifyReceiptIntegrity,
26
22
  withReceiptIntegrity
27
- } from "./chunk-K4XHGFR5.js";
23
+ } from "./chunk-MLOK6ZOS.js";
24
+ import {
25
+ protectedArtifactFromSessionEntry,
26
+ protectedArtifactStateFromSessionEntries,
27
+ readAuditRows,
28
+ readSessionEntriesForId,
29
+ responseModelIdObservationFromRecord
30
+ } from "./chunk-LXPJXFM5.js";
28
31
  import {
29
32
  applyTaskWorktree,
30
33
  captureWorkspaceSnapshot,
@@ -32,11 +35,11 @@ import {
32
35
  createTaskWorktree,
33
36
  createWriteBoundaryEnforcer,
34
37
  gitCheckoutRoot
35
- } from "./chunk-MXKJU4JB.js";
38
+ } from "./chunk-ECUO3KDP.js";
36
39
  import {
37
40
  executionPlanAncestors,
38
41
  spliceExecutionPlan
39
- } from "./chunk-J3YUBZWY.js";
42
+ } from "./chunk-HKO36JWF.js";
40
43
  import {
41
44
  parseRigorOverride,
42
45
  resolveRigor
@@ -44,7 +47,7 @@ import {
44
47
  import {
45
48
  FLEET_COMMAND_BASE_ENV,
46
49
  normalizeWriteBoundary
47
- } from "./chunk-E77JEWSD.js";
50
+ } from "./chunk-HPCTNZM2.js";
48
51
  import {
49
52
  LOCAL_NODE_ID,
50
53
  computeSettingsFingerprint,
@@ -55,7 +58,7 @@ import {
55
58
  receiptAttestationFields,
56
59
  routeFactVerdict,
57
60
  spawnNativeWorker
58
- } from "./chunk-2HEJ2F35.js";
61
+ } from "./chunk-5HFBWUMU.js";
59
62
  import {
60
63
  AGENT_LEDGER_PROMPT_MAX_CHARS,
61
64
  RETRYABLE_OUTCOMES,
@@ -95,7 +98,7 @@ import {
95
98
  serializeWorkerRuntimeDescriptor,
96
99
  toolPromptHintsForNames,
97
100
  validateJobSpec
98
- } from "./chunk-A3WNZD3P.js";
101
+ } from "./chunk-4H6ULJ3H.js";
99
102
  import {
100
103
  decideRoute,
101
104
  defaultRoutingIntent,
@@ -113,7 +116,7 @@ import {
113
116
  routingIntentRejection,
114
117
  sameRouteIdentity,
115
118
  toRouteCandidate
116
- } from "./chunk-P43ETTHK.js";
119
+ } from "./chunk-VPTUJU4P.js";
117
120
  import {
118
121
  appliesRecipeResultContract,
119
122
  gateRouteCorrelation,
@@ -123,38 +126,36 @@ import {
123
126
  withAttemptRole
124
127
  } from "./chunk-H7IXIC72.js";
125
128
  import {
126
- WRITE_ROOT_REFUSED_TOOLS,
127
129
  assessFinishContract
128
- } from "./chunk-5H3GB5BO.js";
130
+ } from "./chunk-7C6RYZGQ.js";
131
+ import {
132
+ WRITE_ROOT_REFUSED_TOOLS
133
+ } from "./chunk-N3PBVRTZ.js";
129
134
  import {
130
135
  compareCodepoints
131
136
  } from "./chunk-A2NJGIB3.js";
132
- import {
133
- isSkillActivation
134
- } from "./chunk-GOXNB3AO.js";
135
- import {
136
- DEFAULT_AUTONOMY_LEVEL,
137
- autonomyDenyRejection,
138
- mapAutonomy
139
- } from "./chunk-HWUFFB6L.js";
140
- import {
141
- parseJsonObjectPayload,
142
- parseVerifierResult,
143
- pathBoundaryCovers,
144
- resultContractAuthorship,
145
- validateRecipeResult
146
- } from "./chunk-TTHACPOM.js";
147
137
  import {
148
138
  agentSpecFingerprint,
149
139
  assertAgentSpecPolicy,
150
140
  classify,
151
141
  isUserVisibleAgent,
152
142
  normalizeAgentSpec,
153
- resolveAgentToolCompatibility
154
- } from "./chunk-AOCYTWAV.js";
143
+ parseJsonObjectPayload,
144
+ parseVerifierResult,
145
+ pathBoundaryCovers,
146
+ resolveAgentToolCompatibility,
147
+ resultContractAuthorship,
148
+ validateRecipeResult
149
+ } from "./chunk-S4COXYBG.js";
155
150
  import {
156
151
  detectValidationCommand
157
152
  } from "./chunk-MV3K5QF2.js";
153
+ import {
154
+ DEFAULT_AUTONOMY_LEVEL,
155
+ autonomyDenyRejection,
156
+ isSkillActivation,
157
+ mapAutonomy
158
+ } from "./chunk-RAPCMZL4.js";
158
159
  import {
159
160
  isProjectVerifierCheckId,
160
161
  isVerificationScriptName
@@ -181,16 +182,20 @@ import {
181
182
  } from "./chunk-CGKSTWHD.js";
182
183
  import {
183
184
  canonicalizeWireModelId,
185
+ endpointCapacitiesForStatuses,
186
+ endpointCapacityForStatus,
187
+ endpointLabel,
184
188
  firstRuntimeResolutionError,
189
+ foregroundStreamUsage,
185
190
  isDispatchEligibleRuntime,
186
191
  resolveModelCapabilities,
187
192
  resolveRuntimeTarget,
188
193
  runtimeResolutionWarnings,
189
194
  runtimeTargetSnapshot
190
- } from "./chunk-7RFXX52T.js";
195
+ } from "./chunk-MIX5N5AC.js";
191
196
  import {
192
197
  ceilChars
193
- } from "./chunk-RWSI4YD7.js";
198
+ } from "./chunk-AEYBF3TB.js";
194
199
  import {
195
200
  attributeCommitMessage,
196
201
  gitCommitAttributionEnabled,
@@ -203,13 +208,11 @@ import {
203
208
  } from "./chunk-FQ4SKYE4.js";
204
209
  import {
205
210
  BusChannels
206
- } from "./chunk-TT36MB5S.js";
211
+ } from "./chunk-RKRLDWD3.js";
207
212
  import {
213
+ assertSafeId,
208
214
  atomicWrite
209
- } from "./chunk-3BINW3FP.js";
210
- import {
211
- assertSafeId
212
- } from "./chunk-R346GLFC.js";
215
+ } from "./chunk-KV2AOLDF.js";
213
216
  import {
214
217
  AI_AGENT_NAME
215
218
  } from "./chunk-6EJMN2Y3.js";
@@ -223,7 +226,7 @@ import {
223
226
  DEFAULT_DELEGATION_TURN_TIMEOUT_MS,
224
227
  DEFAULT_SETTINGS,
225
228
  THINKING_LEVELS
226
- } from "./chunk-4DGYLA73.js";
229
+ } from "./chunk-XDOQXGFO.js";
227
230
  import {
228
231
  GUARDRAIL_DEFAULTS,
229
232
  resolveGuardrail
@@ -248,7 +251,7 @@ import {
248
251
  } from "./chunk-BNAZZHFG.js";
249
252
  import {
250
253
  resolveEffectivePricing
251
- } from "./chunk-PT7HYKEM.js";
254
+ } from "./chunk-VO2LKSTM.js";
252
255
  import {
253
256
  init_esm_shims
254
257
  } from "./chunk-3R73A4XB.js";
@@ -1069,7 +1072,7 @@ function clone(lease) {
1069
1072
  function valid(value) {
1070
1073
  if (typeof value !== "object" || value === null) return false;
1071
1074
  const lease = value;
1072
- return typeof lease.leaseId === "string" && typeof lease.assignmentId === "string" && typeof lease.nodeId === "string" && (lease.host === void 0 || typeof lease.host === "string") && Number.isInteger(lease.ownerPid) && typeof lease.processBirthToken === "string" && typeof lease.acquiredAt === "string" && typeof lease.expiresAt === "string" && typeof lease.heartbeatAt === "string" && (lease.reservationOwnerId === null || typeof lease.reservationOwnerId === "string") && (lease.reservationMemberId === null || typeof lease.reservationMemberId === "string");
1075
+ return typeof lease.leaseId === "string" && typeof lease.assignmentId === "string" && typeof lease.nodeId === "string" && (lease.endpointKey === void 0 || typeof lease.endpointKey === "string") && (lease.host === void 0 || typeof lease.host === "string") && Number.isInteger(lease.ownerPid) && typeof lease.processBirthToken === "string" && typeof lease.acquiredAt === "string" && typeof lease.expiresAt === "string" && typeof lease.heartbeatAt === "string" && (lease.reservationOwnerId === null || typeof lease.reservationOwnerId === "string") && (lease.reservationMemberId === null || typeof lease.reservationMemberId === "string");
1073
1076
  }
1074
1077
  function validTimestamp(value) {
1075
1078
  if (typeof value !== "string") return false;
@@ -1133,6 +1136,7 @@ var MEMBER_STATUSES = /* @__PURE__ */ new Set(["held", "consumed", "released"]);
1133
1136
  function heldReservationUsage(values) {
1134
1137
  let global = 0;
1135
1138
  const nodes = {};
1139
+ const endpoints = {};
1136
1140
  for (const value of values) {
1137
1141
  if (typeof value !== "object" || value === null)
1138
1142
  throw new Error("dispatch capacity store has invalid reservation records");
@@ -1142,6 +1146,7 @@ function heldReservationUsage(values) {
1142
1146
  if (record.status !== "active") continue;
1143
1147
  const byWave = /* @__PURE__ */ new Map();
1144
1148
  const byNodeWave = /* @__PURE__ */ new Map();
1149
+ const byEndpointWave = /* @__PURE__ */ new Map();
1145
1150
  for (const raw of record.members) {
1146
1151
  if (typeof raw !== "object" || raw === null)
1147
1152
  throw new Error("dispatch capacity store has invalid reservation records");
@@ -1154,13 +1159,34 @@ function heldReservationUsage(values) {
1154
1159
  const nodeWaves = byNodeWave.get(member.nodeId) ?? /* @__PURE__ */ new Map();
1155
1160
  nodeWaves.set(wave, (nodeWaves.get(wave) ?? 0) + 1);
1156
1161
  byNodeWave.set(member.nodeId, nodeWaves);
1162
+ if (member.endpointKey !== void 0 && typeof member.endpointKey !== "string")
1163
+ throw new Error("dispatch capacity store has invalid reservation records");
1164
+ if (typeof member.endpointKey === "string") {
1165
+ const endpointWaves = byEndpointWave.get(member.endpointKey) ?? /* @__PURE__ */ new Map();
1166
+ endpointWaves.set(wave, (endpointWaves.get(wave) ?? 0) + 1);
1167
+ byEndpointWave.set(member.endpointKey, endpointWaves);
1168
+ }
1157
1169
  }
1158
1170
  global += Math.max(0, ...byWave.values());
1159
1171
  for (const [id, waves] of byNodeWave) nodes[id] = (nodes[id] ?? 0) + Math.max(0, ...waves.values());
1172
+ for (const [key, waves] of byEndpointWave) endpoints[key] = (endpoints[key] ?? 0) + Math.max(0, ...waves.values());
1160
1173
  }
1161
- return { global, nodes };
1174
+ return { global, nodes, endpoints };
1162
1175
  }
1163
- function assertCapacity(file, nodeId, limits) {
1176
+ function describeEndpointCapacityHolders(holders) {
1177
+ const parts = [];
1178
+ const add = (count, singular, plural) => {
1179
+ if (count > 0) parts.push(`${count} ${count === 1 ? singular : plural}`);
1180
+ };
1181
+ add(holders.leases, "active lease", "active leases");
1182
+ add(holders.reservations, "held reservation", "held reservations");
1183
+ add(holders.foregroundStreams, "foreground stream", "foreground streams");
1184
+ if (parts.length === 0) return "no active lease, held reservation, or foreground stream currently holds a slot";
1185
+ const named = parts.length === 1 ? parts[0] : parts.length === 2 ? `${parts[0]} and ${parts[1]}` : `${parts.slice(0, -1).join(", ")}, and ${parts.at(-1)}`;
1186
+ const total = holders.leases + holders.reservations + holders.foregroundStreams;
1187
+ return `${named} ${total === 1 ? "holds" : "hold"} ${total === 1 ? "the slot" : "the slots"}`;
1188
+ }
1189
+ function assertCapacity(file, nodeId, endpointKey, limits) {
1164
1190
  const held2 = heldReservationUsage(file.reservations);
1165
1191
  const globalUsed = file.leases.length + held2.global;
1166
1192
  if (globalUsed >= limits.global) {
@@ -1175,6 +1201,23 @@ function assertCapacity(file, nodeId, limits) {
1175
1201
  if (used >= nodeLimit)
1176
1202
  throw new Error(`dispatch: admission denied: node '${nodeId}' capacity reached (${used}/${nodeLimit})`);
1177
1203
  }
1204
+ if (endpointKey !== void 0) {
1205
+ const endpointLimit = limits.endpoints[endpointKey];
1206
+ if (endpointLimit !== void 0) {
1207
+ if (endpointLimit < 1)
1208
+ throw new Error(`dispatch: admission denied: endpoint '${endpointLabel(endpointKey)}' capacity unavailable`);
1209
+ const holders = {
1210
+ leases: file.leases.filter((lease) => lease.endpointKey === endpointKey).length,
1211
+ reservations: held2.endpoints[endpointKey] ?? 0,
1212
+ foregroundStreams: foregroundStreamUsage()[endpointKey] ?? 0
1213
+ };
1214
+ const used = holders.leases + holders.reservations + holders.foregroundStreams;
1215
+ if (used >= endpointLimit)
1216
+ throw new Error(
1217
+ `dispatch: admission denied: endpoint '${endpointLabel(endpointKey)}' capacity reached (${used}/${endpointLimit} slots): ${describeEndpointCapacityHolders(holders)}; collect in-flight runs or point workers at a second server`
1218
+ );
1219
+ }
1220
+ }
1178
1221
  }
1179
1222
  function acquireCapacityLease(input) {
1180
1223
  return withStateFileLockSync(capacityStateLockPath(), () => {
@@ -1188,10 +1231,12 @@ function acquireCapacityLease(input) {
1188
1231
  );
1189
1232
  const existing = file.leases.find((lease2) => lease2.assignmentId === input.assignmentId);
1190
1233
  if (existing) {
1191
- if (existing.nodeId !== input.nodeId) {
1234
+ if (existing.nodeId !== input.nodeId || existing.endpointKey !== input.endpointKey) {
1192
1235
  const without = { ...file, leases: file.leases.filter((lease2) => lease2 !== existing) };
1193
- assertCapacity(without, input.nodeId, input.limits);
1236
+ assertCapacity(without, input.nodeId, input.endpointKey, input.limits);
1194
1237
  existing.nodeId = input.nodeId;
1238
+ if (input.endpointKey === void 0) delete existing.endpointKey;
1239
+ else existing.endpointKey = input.endpointKey;
1195
1240
  }
1196
1241
  existing.heartbeatAt = new Date(nowMs).toISOString();
1197
1242
  existing.expiresAt = new Date(nowMs + (input.ttlMs ?? DEFAULT_CAPACITY_LEASE_TTL_MS)).toISOString();
@@ -1199,7 +1244,7 @@ function acquireCapacityLease(input) {
1199
1244
  return clone(existing);
1200
1245
  }
1201
1246
  input.onAcquiredUnderLock?.(file);
1202
- assertCapacity(file, input.nodeId, input.limits);
1247
+ assertCapacity(file, input.nodeId, input.endpointKey, input.limits);
1203
1248
  const token = input.processBirthToken ?? processBirthToken(input.ownerPid ?? process.pid);
1204
1249
  if (!token) throw new Error("dispatch: cannot establish process birth token");
1205
1250
  const at = new Date(nowMs).toISOString();
@@ -1207,6 +1252,7 @@ function acquireCapacityLease(input) {
1207
1252
  leaseId: `lease-${nowMs.toString(36)}-${randomBytes(6).toString("hex")}`,
1208
1253
  assignmentId: input.assignmentId,
1209
1254
  nodeId: input.nodeId,
1255
+ ...input.endpointKey !== void 0 ? { endpointKey: input.endpointKey } : {},
1210
1256
  host: hostname(),
1211
1257
  ownerPid: input.ownerPid ?? process.pid,
1212
1258
  processBirthToken: token,
@@ -1278,8 +1324,23 @@ function capacityDrain(nowMs = Date.now()) {
1278
1324
  function capacityLeaseUsage(options) {
1279
1325
  const leases = listCapacityLeases(options);
1280
1326
  const nodes = {};
1281
- for (const lease of leases) nodes[lease.nodeId] = (nodes[lease.nodeId] ?? 0) + 1;
1282
- return { global: leases.length, nodes };
1327
+ const foreground = foregroundStreamUsage();
1328
+ const endpoints = { ...foreground };
1329
+ const endpointHolders = Object.fromEntries(
1330
+ Object.entries(foreground).map(([endpointKey, foregroundStreams]) => [
1331
+ endpointKey,
1332
+ { leases: 0, reservations: 0, foregroundStreams }
1333
+ ])
1334
+ );
1335
+ for (const lease of leases) {
1336
+ nodes[lease.nodeId] = (nodes[lease.nodeId] ?? 0) + 1;
1337
+ if (lease.endpointKey !== void 0) {
1338
+ endpoints[lease.endpointKey] = (endpoints[lease.endpointKey] ?? 0) + 1;
1339
+ const holders = endpointHolders[lease.endpointKey] ?? { leases: 0, reservations: 0, foregroundStreams: 0 };
1340
+ endpointHolders[lease.endpointKey] = { ...holders, leases: holders.leases + 1 };
1341
+ }
1342
+ }
1343
+ return { global: leases.length, nodes, endpoints, endpointHolders };
1283
1344
  }
1284
1345
  function createNodeLeaseUsageReader(options) {
1285
1346
  const cacheMs = options.cacheMs ?? 200;
@@ -1487,7 +1548,7 @@ function renderDispatchReviewerTask(originalTask, builderRunId, cycle, intent) {
1487
1548
 
1488
1549
  // src/domains/dispatch/receipt-findings.ts
1489
1550
  init_esm_shims();
1490
- import { createHash as createHash12 } from "node:crypto";
1551
+ import { createHash as createHash11 } from "node:crypto";
1491
1552
 
1492
1553
  // src/domains/evidence/index.ts
1493
1554
  init_esm_shims();
@@ -1502,12 +1563,14 @@ init_esm_shims();
1502
1563
 
1503
1564
  // src/domains/dispatch/extension.ts
1504
1565
  init_esm_shims();
1505
- import { createHash as createHash9, randomBytes as randomBytes6 } from "node:crypto";
1566
+ import { createHash as createHash8, randomBytes as randomBytes6 } from "node:crypto";
1506
1567
  import { existsSync as existsSync12, readdirSync as readdirSync4, readFileSync as readFileSync12 } from "node:fs";
1507
1568
  import { isAbsolute as isAbsolute2, relative, resolve as resolvePath, sep } from "node:path";
1569
+ import { performance as performance5 } from "node:perf_hooks";
1508
1570
 
1509
1571
  // src/engine/acp/adapter.ts
1510
1572
  init_esm_shims();
1573
+ import { performance as performance4 } from "node:perf_hooks";
1511
1574
 
1512
1575
  // src/engine/acp/event-mapper.ts
1513
1576
  init_esm_shims();
@@ -2276,7 +2339,14 @@ function errorEvents(messageText2) {
2276
2339
  function startAcpDelegationRun(input) {
2277
2340
  const connectTimeoutMs = input.agent.connectTimeoutMs ?? DEFAULT_DELEGATION_CONNECT_TIMEOUT_MS;
2278
2341
  const turnTimeoutMs = input.agent.turnTimeoutMs ?? DEFAULT_DELEGATION_TURN_TIMEOUT_MS;
2279
- const heartbeatAt = { current: Date.now() };
2342
+ const now = input.now ?? Date.now;
2343
+ const monotonicNow = input.monotonicNow ?? (() => performance4.now());
2344
+ const heartbeatWallAnchor = now();
2345
+ const heartbeatMonotonicAnchor = monotonicNow();
2346
+ const heartbeatAt = {
2347
+ current: heartbeatWallAnchor,
2348
+ monotonic: heartbeatMonotonicAnchor
2349
+ };
2280
2350
  const queue = new AsyncEventQueue();
2281
2351
  const usage = emptyUsage();
2282
2352
  const mapper = new AcpEventMapper();
@@ -2303,7 +2373,9 @@ function startAcpDelegationRun(input) {
2303
2373
  cancelTimer = null;
2304
2374
  };
2305
2375
  const emit = (event) => {
2306
- heartbeatAt.current = Date.now();
2376
+ const stamp = monotonicNow();
2377
+ heartbeatAt.monotonic = stamp;
2378
+ heartbeatAt.current = heartbeatWallAnchor + (stamp - heartbeatMonotonicAnchor);
2307
2379
  queue.push(event);
2308
2380
  };
2309
2381
  const mediator = new AcpToolMediator({
@@ -2478,62 +2550,6 @@ function startAcpDelegationRun(input) {
2478
2550
  // src/domains/prompts/compiler.ts
2479
2551
  init_esm_shims();
2480
2552
  import { join as join3 } from "node:path";
2481
-
2482
- // src/domains/prompts/hash.ts
2483
- init_esm_shims();
2484
- import { createHash as createHash2 } from "node:crypto";
2485
- function sha256(input) {
2486
- return createHash2("sha256").update(input, "utf8").digest("hex");
2487
- }
2488
- function canonicalJson2(value) {
2489
- return serialize(value);
2490
- }
2491
- function serialize(value) {
2492
- if (value === null) return "null";
2493
- if (typeof value === "number") {
2494
- if (!Number.isFinite(value)) {
2495
- throw new Error(`canonicalJson: non-finite number ${String(value)} is not representable`);
2496
- }
2497
- return JSON.stringify(value);
2498
- }
2499
- if (typeof value === "string" || typeof value === "boolean") {
2500
- return JSON.stringify(value);
2501
- }
2502
- if (typeof value === "bigint") {
2503
- throw new Error("canonicalJson: bigint is not representable");
2504
- }
2505
- if (typeof value === "symbol" || typeof value === "function") {
2506
- throw new Error(`canonicalJson: ${typeof value} is not representable`);
2507
- }
2508
- if (value === void 0) {
2509
- throw new Error("canonicalJson: undefined is not representable at root");
2510
- }
2511
- if (Array.isArray(value)) {
2512
- const parts = [];
2513
- for (let i = 0; i < value.length; i++) {
2514
- if (!(i in value) || value[i] === void 0) {
2515
- parts.push("null");
2516
- continue;
2517
- }
2518
- parts.push(serialize(value[i]));
2519
- }
2520
- return `[${parts.join(",")}]`;
2521
- }
2522
- if (typeof value === "object") {
2523
- const obj = value;
2524
- const keys = Object.keys(obj).sort();
2525
- const parts = [];
2526
- for (const key of keys) {
2527
- const child = obj[key];
2528
- if (child === void 0) continue;
2529
- parts.push(`${JSON.stringify(key)}:${serialize(child)}`);
2530
- }
2531
- return `{${parts.join(",")}}`;
2532
- }
2533
- throw new Error(`canonicalJson: unsupported value of type ${typeof value}`);
2534
- }
2535
-
2536
- // src/domains/prompts/compiler.ts
2537
2553
  var FLEET_ROUTING_GUIDANCE = 'Fleet routing: pin the `agent` id from the Fleet section; agent:"auto" baselines from the task text and is a fallback, not a router.';
2538
2554
  var WORKER_CLAIM_GUIDANCE = 'Never claim a completion, a validation, or a file change that no tool call in this run supports. If you did not run it or write it here, say "not verified" and report what you did do.';
2539
2555
  function lookupFragment(table, id, role) {
@@ -2745,15 +2761,45 @@ function renderProjectBlock(contextFiles) {
2745
2761
 
2746
2762
  ${trimmedFiles}`;
2747
2763
  }
2748
- function renderMemoryBlock(memorySection) {
2764
+ function renderMemoryBlock(memorySection, legacyDuplicateHeader = false) {
2749
2765
  const trimmed = memorySection?.trim() ?? "";
2750
- return trimmed.length === 0 ? "" : `# Memory
2766
+ if (trimmed.length === 0) return "";
2767
+ if (legacyDuplicateHeader) return `# Memory
2768
+
2769
+ ${trimmed}`;
2770
+ return /^#\s+Memory\s*$/.test(trimmed.split("\n", 1)[0] ?? "") ? trimmed : `# Memory
2751
2771
 
2752
2772
  ${trimmed}`;
2753
2773
  }
2754
2774
  function estimatePromptTokens(text) {
2755
2775
  return ceilChars(text.trim().length);
2756
2776
  }
2777
+ var SESSION_PROMPT_SECTION_ORDER = [
2778
+ "identity",
2779
+ "operating-contract",
2780
+ "delegation",
2781
+ "skills",
2782
+ "safety",
2783
+ "tool-contract",
2784
+ "fleet",
2785
+ "retrieval-hints",
2786
+ "project-context",
2787
+ "memory",
2788
+ "runtime"
2789
+ ];
2790
+ var LEGACY_SESSION_PROMPT_SECTION_ORDER = [
2791
+ "identity",
2792
+ "operating-contract",
2793
+ "delegation",
2794
+ "skills",
2795
+ "safety",
2796
+ "runtime",
2797
+ "tool-contract",
2798
+ "fleet",
2799
+ "retrieval-hints",
2800
+ "memory",
2801
+ "project-context"
2802
+ ];
2757
2803
  function compile(table, inputs) {
2758
2804
  const identity = lookupFragment(table, inputs.identity, "identity");
2759
2805
  const operatingContract = lookupFragment(table, inputs.operatingContract, "operating contract");
@@ -2773,24 +2819,29 @@ function compile(table, inputs) {
2773
2819
  const docsRouting = selfAwareness && sessionHasContext(session) ? table.byId.get("identity.docs-routing") : void 0;
2774
2820
  if (selfAwareness) {
2775
2821
  const packageRoot = resolvePackageRoot();
2776
- const rendered = selfAwareness.body.replace("{CLIO_DOCS_PATH}", join3(packageRoot, "docs")).replace("{CLIO_SRC_PATH}", join3(packageRoot, "src")).replace("{CLIO_CODEWIKI_PATH}", join3(packageRoot, "dist", "assets", "codewiki.json"));
2777
- identityBody = [identity.body.trim(), rendered.trim(), ...docsRouting ? [docsRouting.body.trim()] : []].join(
2822
+ const rendered2 = selfAwareness.body.replace("{CLIO_DOCS_PATH}", join3(packageRoot, "docs")).replace("{CLIO_SRC_PATH}", join3(packageRoot, "src")).replace("{CLIO_CODEWIKI_PATH}", join3(packageRoot, "dist", "assets", "codewiki.json"));
2823
+ identityBody = [identity.body.trim(), rendered2.trim(), ...docsRouting ? [docsRouting.body.trim()] : []].join(
2778
2824
  "\n\n"
2779
2825
  );
2780
2826
  }
2781
2827
  const delegation = sessionCanDispatch(session) ? table.byId.get("operating.delegation") : void 0;
2782
2828
  const skills = sessionHasContext(session) ? table.byId.get("operating.skills") : void 0;
2783
- push("identity", identityBody);
2784
- push("operating-contract", operatingContract.body);
2785
- if (delegation) push("delegation", delegation.body);
2786
- if (skills) push("skills", skills.body);
2787
- push("safety", renderSafetySection(safety, autonomyLevel));
2788
- push("runtime", renderRuntimeBlock(session));
2789
- push("tool-contract", renderToolContractBlock(session));
2790
- push("fleet", renderFleetBlock(session));
2791
- push("retrieval-hints", renderRetrievalHintsBlock(session));
2792
- push("memory", renderMemoryBlock(session.memorySection));
2793
- push("project-context", renderProjectBlock(session.contextFiles));
2829
+ const legacy = inputs.sectionOrder === "legacy-0.3.8";
2830
+ const rendered = /* @__PURE__ */ new Map([
2831
+ ["identity", identityBody],
2832
+ ["operating-contract", operatingContract.body],
2833
+ ["delegation", delegation?.body ?? ""],
2834
+ ["skills", skills?.body ?? ""],
2835
+ ["safety", renderSafetySection(safety, autonomyLevel)],
2836
+ ["runtime", renderRuntimeBlock(session)],
2837
+ ["tool-contract", renderToolContractBlock(session)],
2838
+ ["fleet", renderFleetBlock(session)],
2839
+ ["retrieval-hints", renderRetrievalHintsBlock(session)],
2840
+ ["memory", renderMemoryBlock(session.memorySection, legacy)],
2841
+ ["project-context", renderProjectBlock(session.contextFiles)]
2842
+ ]);
2843
+ const order = legacy ? LEGACY_SESSION_PROMPT_SECTION_ORDER : SESSION_PROMPT_SECTION_ORDER;
2844
+ for (const id of order) push(id, rendered.get(id) ?? "");
2794
2845
  for (const fragment of inputs.additionalFragments ?? []) {
2795
2846
  push(fragment.id, fragment.body);
2796
2847
  }
@@ -3355,6 +3406,9 @@ init_esm_shims();
3355
3406
  import { randomBytes as randomBytes2 } from "node:crypto";
3356
3407
  var MAX_RESERVATION_RECORDS = 500;
3357
3408
  var DEFAULT_RESERVATION_TTL_MS = 15 * 6e4;
3409
+ function endpointCapacityDenial(input) {
3410
+ return `dispatch: admission denied: endpoint '${endpointLabel(input.endpointKey)}' capacity exceeded (${input.used + input.requested}/${input.limit} slots): ${describeEndpointCapacityHolders(input)}; reduce the same-wave worker count, collect in-flight runs, or point workers at a second server`;
3411
+ }
3358
3412
  function copyRecord(record) {
3359
3413
  return { ...record, members: record.members.map((member) => ({ ...member })) };
3360
3414
  }
@@ -3362,7 +3416,7 @@ function validRecord(value) {
3362
3416
  if (typeof value !== "object" || value === null) return false;
3363
3417
  const record = value;
3364
3418
  return typeof record.ownerId === "string" && typeof record.ownerPid === "number" && Number.isInteger(record.ownerPid) && record.ownerPid > 0 && (record.topology === "parallel" || record.topology === "detached" || record.topology === "sequential" || record.topology === "pipeline" || record.topology === "review" || record.topology === "compete") && (record.status === "active" || record.status === "released" || record.status === "rolled_back" || record.status === "expired") && typeof record.createdAt === "string" && typeof record.expiresAt === "string" && (record.settledAt === null || typeof record.settledAt === "string") && Array.isArray(record.members) && record.members.every(
3365
- (member) => typeof member.memberId === "string" && Number.isInteger(member.wave) && typeof member.nodeId === "string" && typeof member.costUpperBoundUsd === "number" && Number.isFinite(member.costUpperBoundUsd) && member.costUpperBoundUsd >= 0 && (member.status === "held" || member.status === "consumed" || member.status === "released") && (member.consumedAt === null || typeof member.consumedAt === "string") && (member.releasedAt === null || typeof member.releasedAt === "string")
3419
+ (member) => typeof member.memberId === "string" && Number.isInteger(member.wave) && typeof member.nodeId === "string" && (member.endpointKey === void 0 || typeof member.endpointKey === "string") && typeof member.costUpperBoundUsd === "number" && Number.isFinite(member.costUpperBoundUsd) && member.costUpperBoundUsd >= 0 && (member.status === "held" || member.status === "consumed" || member.status === "released") && (member.consumedAt === null || typeof member.consumedAt === "string") && (member.releasedAt === null || typeof member.releasedAt === "string")
3366
3420
  );
3367
3421
  }
3368
3422
  function parseReservations(values) {
@@ -3399,9 +3453,13 @@ function reservationAllocation(tasks) {
3399
3453
  )
3400
3454
  );
3401
3455
  const nodeSlots = peakBy(tasks.map((task) => ({ wave: task.wave, key: task.nodeId })));
3456
+ const endpointSlots = peakBy(
3457
+ tasks.flatMap((task) => task.endpointKey === void 0 ? [] : [{ wave: task.wave, key: task.endpointKey }])
3458
+ );
3402
3459
  return {
3403
3460
  globalSlots,
3404
3461
  nodeSlots,
3462
+ endpointSlots,
3405
3463
  budgetUsd: tasks.reduce((sum, task) => sum + task.costUpperBoundUsd, 0)
3406
3464
  };
3407
3465
  }
@@ -3434,6 +3492,26 @@ function allocateReservation(tasks, existing, capacity) {
3434
3492
  return { ok: false, reason: `node '${nodeId}' capacity exceeded (${used + slots}/${node.limit})` };
3435
3493
  }
3436
3494
  }
3495
+ for (const [endpointKey, slots] of Object.entries(requested.endpointSlots)) {
3496
+ const endpoint = capacity.endpoints[endpointKey];
3497
+ if (!endpoint || !Number.isFinite(endpoint.limit)) continue;
3498
+ const heldSlots = held2.reduce((sum, allocation) => sum + (allocation.endpointSlots[endpointKey] ?? 0), 0);
3499
+ const used = endpoint.active + heldSlots;
3500
+ if (used + slots > endpoint.limit) {
3501
+ return {
3502
+ ok: false,
3503
+ reason: endpointCapacityDenial({
3504
+ endpointKey,
3505
+ limit: endpoint.limit,
3506
+ used,
3507
+ requested: slots,
3508
+ leases: endpoint.leases ?? endpoint.active - (endpoint.foregroundStreams ?? 0),
3509
+ reservations: heldSlots,
3510
+ foregroundStreams: endpoint.foregroundStreams ?? 0
3511
+ })
3512
+ };
3513
+ }
3514
+ }
3437
3515
  const existingBudget = activeRecords.reduce((sum, record) => sum + outstandingBudget(record), 0);
3438
3516
  const projected = capacity.budget.currentUsd + existingBudget + requested.budgetUsd;
3439
3517
  if (projected >= capacity.budget.ceilingUsd) {
@@ -3461,7 +3539,9 @@ function createDispatchReservation(input) {
3461
3539
  if (!planned.ok) {
3462
3540
  replaceReservations(state, records);
3463
3541
  writeCapacityStateUnsafe(state);
3464
- throw new Error(`dispatch: reservation denied: ${planned.reason}`);
3542
+ throw new Error(
3543
+ planned.reason.startsWith("dispatch:") ? planned.reason : `dispatch: reservation denied: ${planned.reason}`
3544
+ );
3465
3545
  }
3466
3546
  const createdAt = new Date(nowMs).toISOString();
3467
3547
  const record = {
@@ -3484,6 +3564,7 @@ function transferDispatchReservationToLease(input) {
3484
3564
  return acquireCapacityLease({
3485
3565
  assignmentId: input.assignmentId,
3486
3566
  nodeId: input.nodeId,
3567
+ ...input.endpointKey !== void 0 ? { endpointKey: input.endpointKey } : {},
3487
3568
  limits: input.limits,
3488
3569
  nowMs,
3489
3570
  ...input.ttlMs !== void 0 ? { ttlMs: input.ttlMs } : {},
@@ -3511,10 +3592,37 @@ function rebindDispatchReservationMember(input) {
3511
3592
  if (member.status === "released") {
3512
3593
  throw new Error(`dispatch: reservation member '${input.memberId}' was already released`);
3513
3594
  }
3514
- if (member.nodeId === input.nodeId && member.costUpperBoundUsd === input.costUpperBoundUsd) {
3595
+ if (member.nodeId === input.nodeId && member.endpointKey === input.endpointKey && member.costUpperBoundUsd === input.costUpperBoundUsd) {
3515
3596
  return copyRecord(record);
3516
3597
  }
3517
3598
  const others = records.filter((entry) => entry.status === "active" && entry.ownerId !== input.ownerId);
3599
+ if (member.endpointKey !== input.endpointKey && input.endpointKey !== void 0) {
3600
+ const endpointKey = input.endpointKey;
3601
+ const endpoint = input.capacity.endpoints[endpointKey];
3602
+ if (endpoint !== void 0 && Number.isFinite(endpoint.limit)) {
3603
+ const siblingSlots = record.members.filter(
3604
+ (entry) => entry !== member && entry.status !== "released" && entry.endpointKey === endpointKey
3605
+ ).length;
3606
+ const otherHeld = others.reduce(
3607
+ (sum, entry) => sum + (reservationAllocation(outstandingTasks(entry)).endpointSlots[endpointKey] ?? 0),
3608
+ 0
3609
+ );
3610
+ const used = endpoint.active + otherHeld + siblingSlots;
3611
+ if (used + 1 > endpoint.limit) {
3612
+ throw new Error(
3613
+ endpointCapacityDenial({
3614
+ endpointKey,
3615
+ limit: endpoint.limit,
3616
+ used,
3617
+ requested: 1,
3618
+ leases: endpoint.leases ?? endpoint.active - (endpoint.foregroundStreams ?? 0),
3619
+ reservations: otherHeld + siblingSlots,
3620
+ foregroundStreams: endpoint.foregroundStreams ?? 0
3621
+ })
3622
+ );
3623
+ }
3624
+ }
3625
+ }
3518
3626
  if (member.nodeId !== input.nodeId) {
3519
3627
  const node = input.capacity.nodes[input.nodeId];
3520
3628
  if (node !== void 0 && Number.isFinite(node.limit)) {
@@ -3542,6 +3650,8 @@ function rebindDispatchReservationMember(input) {
3542
3650
  );
3543
3651
  }
3544
3652
  member.nodeId = input.nodeId;
3653
+ if (input.endpointKey === void 0) delete member.endpointKey;
3654
+ else member.endpointKey = input.endpointKey;
3545
3655
  member.costUpperBoundUsd = Math.max(0, input.costUpperBoundUsd);
3546
3656
  writeStore2(records);
3547
3657
  return copyRecord(record);
@@ -3564,6 +3674,24 @@ function releaseDispatchReservationMember(ownerId, memberId, nowMs = Date.now())
3564
3674
  return copyRecord(record);
3565
3675
  });
3566
3676
  }
3677
+ function releaseDispatchReservation(ownerId, nowMs = Date.now()) {
3678
+ return withStateFileLockSync(capacityStateLockPath(), () => {
3679
+ const records = readStore2();
3680
+ const record = records.find((entry) => entry.ownerId === ownerId);
3681
+ if (!record) return null;
3682
+ if (record.status !== "active") return copyRecord(record);
3683
+ const settledAt = new Date(nowMs).toISOString();
3684
+ for (const member of record.members) {
3685
+ if (member.status === "released") continue;
3686
+ member.status = "released";
3687
+ member.releasedAt = settledAt;
3688
+ }
3689
+ record.status = "released";
3690
+ record.settledAt = settledAt;
3691
+ writeStore2(records);
3692
+ return copyRecord(record);
3693
+ });
3694
+ }
3567
3695
  function rollbackDispatchReservation(ownerId, nowMs = Date.now()) {
3568
3696
  return withStateFileLockSync(capacityStateLockPath(), () => {
3569
3697
  const records = readStore2();
@@ -3668,6 +3796,15 @@ var PUMP_MIN_MS = 10;
3668
3796
  var PUMP_MAX_MS = 500;
3669
3797
  function describeAdmissionFailure(input) {
3670
3798
  if (input.state === "canceled") return "dispatch: admission canceled before a capacity slot opened";
3799
+ if (input.endpointKey !== void 0) {
3800
+ const endpointLimit = input.limits.endpoints[input.endpointKey];
3801
+ const endpointActive = input.usage.endpoints[input.endpointKey] ?? 0;
3802
+ if (endpointLimit !== void 0 && endpointActive >= endpointLimit) {
3803
+ const holders = input.usage.endpointHolders?.[input.endpointKey];
3804
+ const occupancy = holders === void 0 ? "the supplied capacity snapshot does not attribute the occupied slots" : describeEndpointCapacityHolders(holders);
3805
+ return `dispatch: admission denied: endpoint '${endpointLabel(input.endpointKey)}' capacity reached (${endpointActive}/${endpointLimit} slots): ${occupancy}; collect in-flight runs or point workers at a second server`;
3806
+ }
3807
+ }
3671
3808
  const nodeLimit = input.limits.nodes[input.nodeId];
3672
3809
  const nodeActive = input.usage.nodes[input.nodeId] ?? 0;
3673
3810
  const where = nodeLimit === void 0 ? `${input.usage.global}/${input.limits.global} worker slots in use` : `${nodeActive}/${nodeLimit} worker slots in use on '${input.nodeId}', ${input.usage.global}/${input.limits.global} globally`;
@@ -3709,6 +3846,10 @@ function createCapacityAdmissionController(options) {
3709
3846
  admittedLease = request.value();
3710
3847
  return true;
3711
3848
  } catch (error) {
3849
+ if (error instanceof Error && /endpoint '.*' capacity reached/u.test(error.message)) {
3850
+ queue.fail(request.requestId, error);
3851
+ return false;
3852
+ }
3712
3853
  if (error instanceof Error && /capacity reached/.test(error.message)) return false;
3713
3854
  queue.fail(request.requestId, error instanceof Error ? error : new Error(String(error)));
3714
3855
  return false;
@@ -3759,11 +3900,13 @@ function createCapacityAdmissionController(options) {
3759
3900
  memberId: input.reservation.memberId,
3760
3901
  assignmentId: input.assignmentId,
3761
3902
  nodeId: input.nodeId,
3903
+ ...input.endpointKey !== void 0 ? { endpointKey: input.endpointKey } : {},
3762
3904
  limits: options.limits(),
3763
3905
  nowMs: now()
3764
3906
  }) : acquireCapacityLease({
3765
3907
  assignmentId: input.assignmentId,
3766
3908
  nodeId: input.nodeId,
3909
+ ...input.endpointKey !== void 0 ? { endpointKey: input.endpointKey } : {},
3767
3910
  limits: options.limits(),
3768
3911
  nowMs: now()
3769
3912
  })
@@ -3775,6 +3918,7 @@ function createCapacityAdmissionController(options) {
3775
3918
  describeAdmissionFailure({
3776
3919
  state: outcome.state,
3777
3920
  nodeId: input.nodeId,
3921
+ ...input.endpointKey !== void 0 ? { endpointKey: input.endpointKey } : {},
3778
3922
  waitedMs: now() - queuedAt,
3779
3923
  overdueAtQueueMs: queuedAt - input.deadlineAt,
3780
3924
  queueDepth: queue.size(),
@@ -4344,7 +4488,7 @@ function assessCapabilityMismatch(input) {
4344
4488
 
4345
4489
  // src/domains/dispatch/checkout-writer-lease.ts
4346
4490
  init_esm_shims();
4347
- import { createHash as createHash3 } from "node:crypto";
4491
+ import { createHash as createHash2 } from "node:crypto";
4348
4492
  import { existsSync as existsSync5, mkdirSync, readFileSync as readFileSync5, realpathSync, unlinkSync } from "node:fs";
4349
4493
  import { dirname, join as join6 } from "node:path";
4350
4494
  var held = /* @__PURE__ */ new Map();
@@ -4354,7 +4498,7 @@ function canonicalCheckout(checkout) {
4354
4498
  }
4355
4499
  function checkoutWriterLeasePath(checkout) {
4356
4500
  const canonical = canonicalCheckout(checkout);
4357
- const key = createHash3("sha256").update(canonical, "utf8").digest("hex");
4501
+ const key = createHash2("sha256").update(canonical, "utf8").digest("hex");
4358
4502
  return join6(clioStateDir(), "checkout-writer-leases", `${key}.json`);
4359
4503
  }
4360
4504
  function validRecord3(value) {
@@ -4554,8 +4698,11 @@ function isInfrastructureFailure(failureClass) {
4554
4698
  // src/domains/dispatch/heartbeat.ts
4555
4699
  init_esm_shims();
4556
4700
  var DEFAULT_HEARTBEAT_SPEC = { windowMs: 5e3, graceMs: 1e4 };
4557
- function classifyHeartbeat(heartbeatAt, now, spec) {
4558
- const age = now - heartbeatAt;
4701
+ function heartbeatMonotonicAt(heartbeat) {
4702
+ return heartbeat.monotonic ?? heartbeat.current;
4703
+ }
4704
+ function classifyHeartbeat(heartbeatMonotonicAt2, monotonicNow, spec) {
4705
+ const age = monotonicNow - heartbeatMonotonicAt2;
4559
4706
  if (age <= spec.windowMs) return "alive";
4560
4707
  if (age <= spec.windowMs + spec.graceMs) return "stale";
4561
4708
  return "dead";
@@ -4564,14 +4711,14 @@ function classifyHeartbeat(heartbeatAt, now, spec) {
4564
4711
  // src/domains/dispatch/host-verification.ts
4565
4712
  init_esm_shims();
4566
4713
  import { execFileSync as execFileSync2 } from "node:child_process";
4567
- import { createHash as createHash5, randomUUID } from "node:crypto";
4714
+ import { createHash as createHash4, randomUUID } from "node:crypto";
4568
4715
  import { existsSync as existsSync6, mkdirSync as mkdirSync3, readFileSync as readFileSync6, renameSync, writeFileSync as writeFileSync2 } from "node:fs";
4569
4716
  import { dirname as dirname2, join as join8, resolve as resolve3 } from "node:path";
4570
4717
 
4571
4718
  // src/domains/dispatch/code-step.ts
4572
4719
  init_esm_shims();
4573
4720
  import { execFileSync, spawn as spawn2 } from "node:child_process";
4574
- import { createHash as createHash4 } from "node:crypto";
4721
+ import { createHash as createHash3 } from "node:crypto";
4575
4722
  import { mkdirSync as mkdirSync2, writeFileSync } from "node:fs";
4576
4723
  import { isAbsolute, join as join7, resolve as resolve2 } from "node:path";
4577
4724
  var CODE_STEP_CAPTURE_MAX_BYTES = 1048576;
@@ -4591,10 +4738,10 @@ function canonicalCodeReport(report) {
4591
4738
  });
4592
4739
  }
4593
4740
  function codeReportDigest(report) {
4594
- return createHash4("sha256").update(canonicalCodeReport(report), "utf8").digest("hex");
4741
+ return createHash3("sha256").update(canonicalCodeReport(report), "utf8").digest("hex");
4595
4742
  }
4596
4743
  function sha2562(value) {
4597
- return createHash4("sha256").update(value, "utf8").digest("hex");
4744
+ return createHash3("sha256").update(value, "utf8").digest("hex");
4598
4745
  }
4599
4746
  function tailUtf8(value, limit, marker) {
4600
4747
  if (value.length <= limit) return { text: value.toString("utf8"), truncated: false };
@@ -4644,7 +4791,7 @@ function workspaceHasChanges(root) {
4644
4791
  return status.trim().length > 0;
4645
4792
  }
4646
4793
  function newCodeRunId() {
4647
- return `code-${createHash4("sha256").update(`${process.pid}:${Date.now()}:${Math.random()}`).digest("hex").slice(0, 12)}`;
4794
+ return `code-${createHash3("sha256").update(`${process.pid}:${Date.now()}:${Math.random()}`).digest("hex").slice(0, 12)}`;
4648
4795
  }
4649
4796
  async function spawnCommand(input, cwd, argv) {
4650
4797
  const command = input.command;
@@ -4808,7 +4955,7 @@ ${spawned.spawnError}
4808
4955
  var OUTPUT_TAIL_BYTES = 2048;
4809
4956
  var MEMO_VERSION = 1;
4810
4957
  function sha2563(value) {
4811
- return createHash5("sha256").update(value, "utf8").digest("hex");
4958
+ return createHash4("sha256").update(value, "utf8").digest("hex");
4812
4959
  }
4813
4960
  function outputTail(value) {
4814
4961
  const bytes = Buffer.from(value, "utf8");
@@ -5577,7 +5724,7 @@ function selectApprovedRecoveryCandidates(input) {
5577
5724
  // src/domains/dispatch/reproducibility.ts
5578
5725
  init_esm_shims();
5579
5726
  import { spawnSync } from "node:child_process";
5580
- import { createHash as createHash6 } from "node:crypto";
5727
+ import { createHash as createHash5 } from "node:crypto";
5581
5728
  function collectReproducibilityMetadata(cwd, safety) {
5582
5729
  const branch = git(cwd, ["rev-parse", "--abbrev-ref", "HEAD"]);
5583
5730
  const commit = git(cwd, ["rev-parse", "HEAD"]);
@@ -5614,7 +5761,7 @@ function git(cwd, args) {
5614
5761
  return trimmed.length > 0 ? trimmed : null;
5615
5762
  }
5616
5763
  function sha2564(input) {
5617
- return createHash6("sha256").update(input, "utf8").digest("hex");
5764
+ return createHash5("sha256").update(input, "utf8").digest("hex");
5618
5765
  }
5619
5766
 
5620
5767
  // src/domains/dispatch/route-observer.ts
@@ -5624,7 +5771,7 @@ import { join as join12 } from "node:path";
5624
5771
 
5625
5772
  // src/domains/dispatch/gate-decisions.ts
5626
5773
  init_esm_shims();
5627
- import { createHash as createHash7, randomBytes as randomBytes4 } from "node:crypto";
5774
+ import { createHash as createHash6, randomBytes as randomBytes4 } from "node:crypto";
5628
5775
  import { closeSync, existsSync as existsSync8, fsyncSync, mkdirSync as mkdirSync4, openSync, readdirSync as readdirSync2, readFileSync as readFileSync8, rmSync } from "node:fs";
5629
5776
  import { dirname as dirname3, join as join10, resolve as resolve4 } from "node:path";
5630
5777
  function parseReviewGateResult(output) {
@@ -5814,7 +5961,7 @@ function decisionPayload(decision) {
5814
5961
  };
5815
5962
  }
5816
5963
  function decisionDigest(decision) {
5817
- return createHash7("sha256").update(JSON.stringify(decisionPayload(decision)), "utf8").digest("hex");
5964
+ return createHash6("sha256").update(JSON.stringify(decisionPayload(decision)), "utf8").digest("hex");
5818
5965
  }
5819
5966
  function artifactWithoutIntegrity(artifact) {
5820
5967
  const result = {
@@ -5950,7 +6097,7 @@ function pendingRecordPayload(record) {
5950
6097
  };
5951
6098
  }
5952
6099
  function pendingRecordDigest(record) {
5953
- return createHash7("sha256").update(JSON.stringify(pendingRecordPayload(record)), "utf8").digest("hex");
6100
+ return createHash6("sha256").update(JSON.stringify(pendingRecordPayload(record)), "utf8").digest("hex");
5954
6101
  }
5955
6102
  function pendingRecordWithoutIntegrity(record) {
5956
6103
  if (record.kind === "output") {
@@ -6441,7 +6588,7 @@ function isPhaseTiming(value) {
6441
6588
 
6442
6589
  // src/domains/dispatch/route-quality.ts
6443
6590
  init_esm_shims();
6444
- import { createHash as createHash8 } from "node:crypto";
6591
+ import { createHash as createHash7 } from "node:crypto";
6445
6592
  function compareStrings(left, right) {
6446
6593
  return left < right ? -1 : left > right ? 1 : 0;
6447
6594
  }
@@ -6556,19 +6703,19 @@ function reduceRouteQuality(input) {
6556
6703
  return { label, checks, correlatedGates, sourceDigests: [...sourceDigests].sort(compareStrings) };
6557
6704
  }
6558
6705
  function routeQualityEvalDigest(artifact) {
6559
- return createHash8("sha256").update(canonicalJson3(artifact), "utf8").digest("hex");
6706
+ return createHash7("sha256").update(canonicalJson2(artifact), "utf8").digest("hex");
6560
6707
  }
6561
- function canonicalJson3(value) {
6708
+ function canonicalJson2(value) {
6562
6709
  if (value === null) return "null";
6563
6710
  if (typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
6564
6711
  if (typeof value === "number") {
6565
6712
  if (!Number.isFinite(value)) throw new Error("route quality eval digest requires finite numbers");
6566
6713
  return JSON.stringify(value);
6567
6714
  }
6568
- if (Array.isArray(value)) return `[${value.map(canonicalJson3).join(",")}]`;
6715
+ if (Array.isArray(value)) return `[${value.map(canonicalJson2).join(",")}]`;
6569
6716
  if (typeof value === "object") {
6570
6717
  const record = value;
6571
- return `{${Object.keys(record).sort(compareStrings).map((key) => `${JSON.stringify(key)}:${canonicalJson3(record[key])}`).join(",")}}`;
6718
+ return `{${Object.keys(record).sort(compareStrings).map((key) => `${JSON.stringify(key)}:${canonicalJson2(record[key])}`).join(",")}}`;
6572
6719
  }
6573
6720
  throw new Error(`route quality eval digest cannot represent ${typeof value}`);
6574
6721
  }
@@ -7274,7 +7421,7 @@ function requestOriginFor(req) {
7274
7421
  return req.requestOrigin ?? "agent";
7275
7422
  }
7276
7423
  function sha2565(input) {
7277
- return createHash9("sha256").update(input, "utf8").digest("hex");
7424
+ return createHash8("sha256").update(input, "utf8").digest("hex");
7278
7425
  }
7279
7426
  function promptHash(systemPrompt) {
7280
7427
  return systemPrompt.length > 0 ? sha2565(systemPrompt) : null;
@@ -8496,19 +8643,20 @@ function createDispatchBundle(context, options) {
8496
8643
  return DEFAULT_RESILIENCE_COOLDOWN_MS;
8497
8644
  };
8498
8645
  const now = options?.now ?? (() => Date.now());
8646
+ const monotonicNow = options?.monotonicNow ?? (() => performance5.now());
8499
8647
  const routeObserver = options?.routeObserver ?? createRouteObserver({});
8500
8648
  let ledger = null;
8501
8649
  let heartbeatTimer = null;
8502
8650
  const active = /* @__PURE__ */ new Map();
8503
8651
  const targetCooldowns = /* @__PURE__ */ new Map();
8504
8652
  const ownedReservations = /* @__PURE__ */ new Set();
8505
- const runWriteTargets = /* @__PURE__ */ new Map();
8506
- const recordRunWriteTargets = (runId, paths) => {
8507
- runWriteTargets.set(runId, paths);
8508
- while (runWriteTargets.size > RUN_WRITE_TARGET_HISTORY) {
8509
- const oldest = runWriteTargets.keys().next();
8653
+ const runWriteAttributions = /* @__PURE__ */ new Map();
8654
+ const recordRunWriteAttribution = (runId, attribution) => {
8655
+ runWriteAttributions.set(runId, attribution);
8656
+ while (runWriteAttributions.size > RUN_WRITE_TARGET_HISTORY) {
8657
+ const oldest = runWriteAttributions.keys().next();
8510
8658
  if (oldest.done === true) break;
8511
- runWriteTargets.delete(oldest.value);
8659
+ runWriteAttributions.delete(oldest.value);
8512
8660
  }
8513
8661
  };
8514
8662
  const capacityAdmission = createCapacityAdmissionController({
@@ -8516,7 +8664,7 @@ function createDispatchBundle(context, options) {
8516
8664
  const settings = getEffectiveSettings();
8517
8665
  const nodes = { local: configuredGlobalCapacity(settings) };
8518
8666
  for (const node of settings?.fleet?.nodes ?? []) nodes[node.id] = node.maxWorkers;
8519
- return { global: configuredGlobalCapacity(settings), nodes };
8667
+ return { global: configuredGlobalCapacity(settings), nodes, endpoints: configuredEndpointLimits() };
8520
8668
  },
8521
8669
  now,
8522
8670
  reservedPlanPeak: (planId) => reservedPlanPeakSlots(planId, (error) => reportDispatchDiagnostic("read reserved plan peak", error))
@@ -8527,6 +8675,19 @@ function createDispatchBundle(context, options) {
8527
8675
  onError: (error) => reportDispatchDiagnostic("read capacity lease usage", error)
8528
8676
  })
8529
8677
  );
8678
+ function configuredEndpointLimits() {
8679
+ return Object.fromEntries(
8680
+ Object.entries(endpointCapacitiesForStatuses(providers.list())).map(([key, value]) => [key, value.limit])
8681
+ );
8682
+ }
8683
+ function endpointCapacityForTarget(targetId) {
8684
+ const status = providers.list().find((entry) => entry.target.id === targetId);
8685
+ if (status === void 0) return null;
8686
+ const endpoint = endpointCapacityForStatus(status);
8687
+ if (endpoint === null) return null;
8688
+ const configured = endpointCapacitiesForStatuses(providers.list())[endpoint.key];
8689
+ return configured ?? endpoint;
8690
+ }
8530
8691
  function reservationCapacitySnapshot(settings) {
8531
8692
  const preflight = scheduling.preflight();
8532
8693
  const usage = capacityLeaseUsage();
@@ -8535,9 +8696,21 @@ function createDispatchBundle(context, options) {
8535
8696
  };
8536
8697
  for (const node of settings?.fleet?.nodes ?? [])
8537
8698
  nodes[node.id] = { active: usage.nodes[node.id] ?? 0, limit: node.maxWorkers };
8699
+ const endpoints = Object.fromEntries(
8700
+ Object.entries(configuredEndpointLimits()).map(([key, limit]) => [
8701
+ key,
8702
+ {
8703
+ active: usage.endpoints[key] ?? 0,
8704
+ limit,
8705
+ leases: usage.endpointHolders[key]?.leases ?? 0,
8706
+ foregroundStreams: usage.endpointHolders[key]?.foregroundStreams ?? 0
8707
+ }
8708
+ ])
8709
+ );
8538
8710
  return {
8539
8711
  global: { active: usage.global, limit: configuredGlobalCapacity(settings) },
8540
8712
  nodes,
8713
+ endpoints,
8541
8714
  budget: { currentUsd: preflight.currentUsd, ceilingUsd: preflight.ceilingUsd }
8542
8715
  };
8543
8716
  }
@@ -8548,6 +8721,7 @@ function createDispatchBundle(context, options) {
8548
8721
  memberId: task.memberId,
8549
8722
  wave: task.wave,
8550
8723
  nodeId: task.resolution.node.id,
8724
+ ...task.resolution.endpoint !== void 0 ? { endpointKey: task.resolution.endpoint.key } : {},
8551
8725
  costUpperBoundUsd: task.resolution.routeApproval?.totalCostUpperBoundUsd ?? task.resolution.costUpperBoundUsd
8552
8726
  })),
8553
8727
  capacity: reservationCapacitySnapshot(getEffectiveSettings()),
@@ -8589,7 +8763,7 @@ function createDispatchBundle(context, options) {
8589
8763
  const configured = settings?.budget.concurrency;
8590
8764
  return scheduling.maxWorkers?.() ?? (configured === "auto" || configured === void 0 ? 4 : Math.max(1, configured));
8591
8765
  }
8592
- async function admitAssignmentCapacity(req, nodeId, timing) {
8766
+ async function admitAssignmentCapacity(req, nodeId, timing, endpoint) {
8593
8767
  const queuedAt = now();
8594
8768
  timing.queuedAt = new Date(queuedAt).toISOString();
8595
8769
  const assignmentId = req.lineage?.rootRunId ?? `pending-${queuedAt.toString(36)}-${randomBytes6(6).toString("hex")}`;
@@ -8605,9 +8779,14 @@ function createDispatchBundle(context, options) {
8605
8779
  const admitted = await capacityAdmission.admit({
8606
8780
  assignmentId,
8607
8781
  nodeId,
8782
+ ...endpoint !== null && endpoint !== void 0 ? { endpointKey: endpoint.key } : {},
8608
8783
  deadlineAt,
8609
8784
  ...plan,
8610
- ...req.reservation !== void 0 && req.lineage === void 0 ? { reservation: req.reservation } : {}
8785
+ // A fleet's first attempt carries lineage and still owns the held
8786
+ // reservation member that admission must transfer into its lease.
8787
+ // Retries carry the same reservation identity after that member was
8788
+ // consumed, so they reacquire/rebind the assignment lease normally.
8789
+ ...req.reservation !== void 0 && (req.lineage === void 0 || req.lineage.attempt === 0) ? { reservation: req.reservation } : {}
8611
8790
  });
8612
8791
  timing.admittedAt = new Date(admitted.admittedAt).toISOString();
8613
8792
  return admitted.lease;
@@ -8619,12 +8798,13 @@ function createDispatchBundle(context, options) {
8619
8798
  throw error;
8620
8799
  }
8621
8800
  }
8622
- function rebindReservationSlot(req, nodeId, costUsd, settings) {
8801
+ function rebindReservationSlot(req, nodeId, endpoint, costUsd, settings) {
8623
8802
  if (req.reservation === void 0 || req.lineage === void 0) return;
8624
8803
  const capacity = reservationCapacitySnapshot(settings);
8625
8804
  const rebind = {
8626
8805
  ...req.reservation,
8627
8806
  nodeId,
8807
+ ...endpoint !== null ? { endpointKey: endpoint.key } : {},
8628
8808
  costUpperBoundUsd: req.routeApproval?.totalCostUpperBoundUsd ?? costUsd,
8629
8809
  capacity,
8630
8810
  nowMs: now()
@@ -8691,10 +8871,23 @@ function createDispatchBundle(context, options) {
8691
8871
  persistAssignment(settleStoredAssignment(rootRunId, attemptRunId, "failed"), `${rootRunId}:finalize-error`);
8692
8872
  capacityAdmission.releaseAssignment(rootRunId);
8693
8873
  }
8874
+ function retryChainIsLive(run) {
8875
+ if (run.aborted) return false;
8876
+ const reservation = run.req.reservation;
8877
+ if (reservation === void 0) return assignments.get(run.lineage.rootRunId)?.status === "running";
8878
+ try {
8879
+ const record = getDispatchReservation(reservation.ownerId);
8880
+ const member = record?.members.find((entry) => entry.memberId === reservation.memberId);
8881
+ return record?.status === "active" && member !== void 0 && member.status !== "released";
8882
+ } catch (error) {
8883
+ reportDispatchDiagnostic(`read retry liveness for reservation member ${reservation.memberId}`, error);
8884
+ return false;
8885
+ }
8886
+ }
8694
8887
  function maybeScheduleRetry(run, outcome, detail, receipt, failureClass) {
8695
8888
  if (draining) return { scheduled: false };
8696
8889
  const rootRunId = run.lineage.rootRunId;
8697
- if (assignments.get(rootRunId)?.status !== "running") return { scheduled: false };
8890
+ if (!retryChainIsLive(run)) return { scheduled: false };
8698
8891
  if (!RETRYABLE_OUTCOMES.has(outcome)) {
8699
8892
  retryBackoff.delete(rootRunId);
8700
8893
  return { scheduled: false };
@@ -8803,7 +8996,7 @@ function createDispatchBundle(context, options) {
8803
8996
  });
8804
8997
  }
8805
8998
  async function executeRetry(run, attempt, reason = "retry", decision = decideRetry("internal", run.lineage.attempt, assignmentPolicyFor(run.req).maxRetries)) {
8806
- if (draining || assignments.get(run.lineage.rootRunId)?.status !== "running") return;
8999
+ if (draining || !retryChainIsLive(run)) return;
8807
9000
  const excludesNode = decision.excludedRouteParts.includes("node");
8808
9001
  const rerouteHops = excludesNode && run.node !== null ? [...run.req.reroutes ?? [], { attempt, fromNode: run.node.id, toNode: "", reason }] : run.req.reroutes;
8809
9002
  const retryReq = {
@@ -8959,8 +9152,8 @@ function createDispatchBundle(context, options) {
8959
9152
  fleetRegistry.recordChannelSuccess(run.node.id);
8960
9153
  }
8961
9154
  }
8962
- function heartbeatIso(heartbeatMs) {
8963
- return new Date(heartbeatMs).toISOString();
9155
+ function heartbeatIso(heartbeat) {
9156
+ return new Date(heartbeat.current).toISOString();
8964
9157
  }
8965
9158
  function heartbeatRunStatus(status) {
8966
9159
  return status === "alive" ? "running" : status;
@@ -8979,22 +9172,22 @@ function createDispatchBundle(context, options) {
8979
9172
  event: {
8980
9173
  type: "heartbeat_status",
8981
9174
  status,
8982
- heartbeatAt: run.heartbeatAt ? heartbeatIso(run.heartbeatAt.current) : null
9175
+ heartbeatAt: run.heartbeatAt ? heartbeatIso(run.heartbeatAt) : null
8983
9176
  }
8984
9177
  });
8985
9178
  }
8986
9179
  function checkActiveHeartbeats() {
8987
9180
  if (!ledger) return;
8988
- const tickNow = now();
9181
+ const tickMonotonic = monotonicNow();
8989
9182
  for (const run of active.values()) {
8990
9183
  if (run.aborted || run.stallKilled || !run.heartbeatAt) continue;
8991
- const heartbeatMs = run.heartbeatAt.current;
8992
- if (!Number.isFinite(heartbeatMs)) continue;
9184
+ const heartbeatMonotonic = heartbeatMonotonicAt(run.heartbeatAt);
9185
+ if (!Number.isFinite(heartbeatMonotonic) || !Number.isFinite(run.heartbeatAt.current)) continue;
8993
9186
  if (run.runtimeKind === "acp-delegation") {
8994
- ledger.update(run.runId, { heartbeatAt: heartbeatIso(heartbeatMs) });
9187
+ ledger.update(run.runId, { heartbeatAt: heartbeatIso(run.heartbeatAt) });
8995
9188
  const stallMs = run.stallTimeoutMs;
8996
9189
  if (stallMs === null || stallMs <= 0) continue;
8997
- if (tickNow - heartbeatMs <= stallMs) continue;
9190
+ if (tickMonotonic - heartbeatMonotonic <= stallMs) continue;
8998
9191
  run.stallKilled = true;
8999
9192
  run.heartbeatStatus = "dead";
9000
9193
  emitHeartbeatStatus(run, "dead");
@@ -9004,10 +9197,10 @@ function createDispatchBundle(context, options) {
9004
9197
  }
9005
9198
  continue;
9006
9199
  }
9007
- const status = classifyHeartbeat(heartbeatMs, tickNow, heartbeatSpec);
9200
+ const status = classifyHeartbeat(heartbeatMonotonic, tickMonotonic, heartbeatSpec);
9008
9201
  const patch = {
9009
9202
  status: heartbeatRunStatus(status),
9010
- heartbeatAt: heartbeatIso(heartbeatMs)
9203
+ heartbeatAt: heartbeatIso(run.heartbeatAt)
9011
9204
  };
9012
9205
  ledger.update(run.runId, patch);
9013
9206
  if (status === "alive" && run.node !== null && run.node.kind === "ssh") {
@@ -9343,7 +9536,7 @@ function createDispatchBundle(context, options) {
9343
9536
  const wireModelId = lifecycle.agentConfig.id;
9344
9537
  assertTargetNotCoolingDown(req, targetId, runtimeId, wireModelId);
9345
9538
  assertBudgetAdmitsRoute(req, { rates: null, provenance: "unknown" }, settings);
9346
- const capacityLease = await admitAssignmentCapacity(req, "local", timing);
9539
+ const capacityLease = await admitAssignmentCapacity(req, "local", timing, null);
9347
9540
  const leaseSlot = createLeaseSlotGuard(capacityAdmission, capacityLease.leaseId, req.lineage !== void 0);
9348
9541
  const ledgerRef = (() => {
9349
9542
  try {
@@ -9365,7 +9558,9 @@ function createDispatchBundle(context, options) {
9365
9558
  cwd: lifecycle.cwd,
9366
9559
  safety,
9367
9560
  autonomy: lifecycle.autonomy,
9368
- clientVersion: readClioVersion()
9561
+ clientVersion: readClioVersion(),
9562
+ now,
9563
+ monotonicNow
9369
9564
  });
9370
9565
  } catch (error) {
9371
9566
  leaseSlot.release();
@@ -9518,7 +9713,7 @@ function createDispatchBundle(context, options) {
9518
9713
  ledgerRef.update(envelope.id, {
9519
9714
  status: "running",
9520
9715
  pid: acp.pid,
9521
- heartbeatAt: heartbeatIso(acp.heartbeatAt.current),
9716
+ heartbeatAt: heartbeatIso(acp.heartbeatAt),
9522
9717
  lineage,
9523
9718
  identity,
9524
9719
  node: LOCAL_RUN_NODE,
@@ -9878,7 +10073,7 @@ function createDispatchBundle(context, options) {
9878
10073
  cacheReadTokenCount: receiptDraft.cacheReadTokenCount ?? 0,
9879
10074
  cacheWriteTokenCount: receiptDraft.cacheWriteTokenCount ?? 0,
9880
10075
  reasoningTokenCount: receiptDraft.reasoningTokenCount ?? 0,
9881
- heartbeatAt: heartbeatIso(acp.heartbeatAt.current)
10076
+ heartbeatAt: heartbeatIso(acp.heartbeatAt)
9882
10077
  };
9883
10078
  ledgerRef.update(envelope.id, ledgerPatch);
9884
10079
  const receipt = ledgerRef.recordReceipt(envelope.id, sealRouteDecision(receiptDraft, routeDecision));
@@ -10015,7 +10210,7 @@ function createDispatchBundle(context, options) {
10015
10210
  "dispatch: writeRoots cannot be enforced on an ACP delegation target; the external agent runs its own tool surface. Dispatch to a native or claude-sdk worker."
10016
10211
  );
10017
10212
  }
10018
- rebindReservationSlot(req, "local", UNKNOWN_PRICING_ADMISSION_ESTIMATE_USD, settings);
10213
+ rebindReservationSlot(req, "local", null, UNKNOWN_PRICING_ADMISSION_ESTIMATE_USD, settings);
10019
10214
  routeObservation = observeShadowRoute(req, void 0, settings);
10020
10215
  return attachRouteObservation({
10021
10216
  ...await dispatchAcpDelegation(req, settings, timing, routeObservation.decision, observer),
@@ -10046,10 +10241,12 @@ function createDispatchBundle(context, options) {
10046
10241
  model: lifecycle.target.wireModelId,
10047
10242
  node: placement?.node?.id ?? "local"
10048
10243
  };
10244
+ const endpoint = endpointCapacityForTarget(lifecycle.target.target.id);
10049
10245
  assertRouteWithinApprovedEnvelope(req, effectiveRoute);
10050
10246
  rebindReservationSlot(
10051
10247
  req,
10052
10248
  effectiveRoute.node,
10249
+ endpoint,
10053
10250
  conservativeRouteAdmissionEstimateUsd(lifecycle.target.effectivePricing, admissionMaxOutputTokens(settings)),
10054
10251
  settings
10055
10252
  );
@@ -10067,7 +10264,7 @@ function createDispatchBundle(context, options) {
10067
10264
  },
10068
10265
  shadow: () => observeShadowRoute(req, placed, settings)
10069
10266
  });
10070
- const capacityLease = await admitAssignmentCapacity(req, placement?.node.id ?? "local", timing);
10267
+ const capacityLease = await admitAssignmentCapacity(req, placement?.node.id ?? "local", timing, endpoint);
10071
10268
  const leaseSlot = createLeaseSlotGuard(capacityAdmission, capacityLease.leaseId, req.lineage !== void 0);
10072
10269
  const ledgerRef = (() => {
10073
10270
  try {
@@ -10125,6 +10322,8 @@ function createDispatchBundle(context, options) {
10125
10322
  try {
10126
10323
  worker = (placement?.spawn ?? spawnWorker)(spec, {
10127
10324
  cwd: lifecycle.cwd,
10325
+ now,
10326
+ monotonicNow,
10128
10327
  ...agentLedgerId !== null ? { onLedgerPost } : {}
10129
10328
  });
10130
10329
  } catch (error) {
@@ -10174,7 +10373,18 @@ function createDispatchBundle(context, options) {
10174
10373
  const upstreamResponses = [];
10175
10374
  const skillActivations = [];
10176
10375
  const finishContractEntries = [];
10177
- const runEffects = createRunEffectsRecorder(lifecycle.cwd);
10376
+ let runIdForPermissionAudit = null;
10377
+ const runEffects = createRunEffectsRecorder(lifecycle.cwd, {
10378
+ onWriteRecordDowngraded(downgrade) {
10379
+ const runId = runIdForPermissionAudit;
10380
+ if (runId === null) return;
10381
+ context.bus.emit(BusChannels.DispatchProgress, {
10382
+ runId,
10383
+ agentId: req.agentId,
10384
+ event: { type: "clio_write_record_downgraded", payload: downgrade }
10385
+ });
10386
+ }
10387
+ });
10178
10388
  let finishContractAssistantText = "";
10179
10389
  let finishContractAssistantTurnId = null;
10180
10390
  let failureMessage;
@@ -10182,7 +10392,6 @@ function createDispatchBundle(context, options) {
10182
10392
  const trustedOutcomeCodes = /* @__PURE__ */ new Set();
10183
10393
  let reportedUntrustedOutcome = false;
10184
10394
  const acceptsOutcomeCodeEvents = lifecycle.runtimeKind === "http" || lifecycle.runtimeKind === "sdk" && lifecycle.target.runtime.id === "claude-sdk";
10185
- let runIdForPermissionAudit = null;
10186
10395
  let workerPolicyPermissionCounter = 0;
10187
10396
  const outputCapture = createWorkerOutputCapture();
10188
10397
  const markObservedPhase = (field) => {
@@ -10395,7 +10604,7 @@ function createDispatchBundle(context, options) {
10395
10604
  ...req.council !== void 0 ? { council: req.council } : {},
10396
10605
  ...req.plan !== void 0 ? { plan: req.plan } : {},
10397
10606
  ...lifecycle.personaOverride ? { personaOverride: lifecycle.personaOverride } : {},
10398
- ...heartbeatAt ? { heartbeatAt: heartbeatIso(heartbeatAt.current) } : {}
10607
+ ...heartbeatAt ? { heartbeatAt: heartbeatIso(heartbeatAt) } : {}
10399
10608
  });
10400
10609
  observer?.onAdmitted({
10401
10610
  runId: envelope.id,
@@ -10405,6 +10614,7 @@ function createDispatchBundle(context, options) {
10405
10614
  await ledgerRef.persist();
10406
10615
  const fleetIdentity = {
10407
10616
  budget: lifecycle.budgetEnvelope,
10617
+ ...endpoint !== null ? { endpoint: { key: endpoint.key, label: endpoint.label, limit: endpoint.limit } } : {},
10408
10618
  ...placement !== void 0 && placement !== null ? { node: placement.node.id } : {},
10409
10619
  ...req.gate !== void 0 ? { gate: { role: req.gate.role, cycle: req.gate.cycle } } : {},
10410
10620
  ...req.council !== void 0 ? { council: req.council } : {},
@@ -10528,9 +10738,9 @@ function createDispatchBundle(context, options) {
10528
10738
  if (req.fleetGateReceipt === void 0) return null;
10529
10739
  try {
10530
10740
  const content = readFileSync12(resolvePath(lifecycle.cwd, req.fleetGateReceipt.path));
10531
- return { path: req.fleetGateReceipt.path, pathHash: createHash9("sha256").update(content).digest("hex") };
10741
+ return { path: req.fleetGateReceipt.path, pathHash: createHash8("sha256").update(content).digest("hex") };
10532
10742
  } catch {
10533
- return { path: req.fleetGateReceipt.path, pathHash: createHash9("sha256").update("").digest("hex") };
10743
+ return { path: req.fleetGateReceipt.path, pathHash: createHash8("sha256").update("").digest("hex") };
10534
10744
  }
10535
10745
  })();
10536
10746
  const ledgerContribution = (() => {
@@ -10887,15 +11097,35 @@ function createDispatchBundle(context, options) {
10887
11097
  dynamicHash: receiptDraft.dynamicHash ?? null,
10888
11098
  ...receiptDraft.cacheReadTokenCount !== void 0 ? { cacheReadTokenCount: receiptDraft.cacheReadTokenCount } : {},
10889
11099
  ...receiptDraft.cacheWriteTokenCount !== void 0 ? { cacheWriteTokenCount: receiptDraft.cacheWriteTokenCount } : {},
10890
- ...activeRun.heartbeatAt ? { heartbeatAt: heartbeatIso(activeRun.heartbeatAt.current) } : {}
11100
+ ...activeRun.heartbeatAt ? { heartbeatAt: heartbeatIso(activeRun.heartbeatAt) } : {}
10891
11101
  };
10892
11102
  if (receiptDraft.reasoningTokenCount !== void 0) {
10893
11103
  ledgerPatch.reasoningTokenCount = receiptDraft.reasoningTokenCount;
10894
11104
  }
10895
11105
  ledgerRef.update(envelope.id, ledgerPatch);
10896
11106
  const receipt = ledgerRef.recordReceipt(envelope.id, sealRouteDecision(receiptDraft, routeObservation.decision));
10897
- const writeRecordUsable = receipt.safety?.toolTelemetry?.coverage === "complete" && observedRunEffects.writeRecordComplete;
10898
- recordRunWriteTargets(envelope.id, writeRecordUsable ? [...observedRunEffects.mutatedPaths] : null);
11107
+ const toolTelemetryComplete = receipt.safety?.toolTelemetry?.coverage === "complete";
11108
+ const downgrades = observedRunEffects.writeRecordDowngrades.map((entry) => ({
11109
+ reason: entry.reason,
11110
+ tool: entry.tool,
11111
+ toolCallId: entry.toolCallId,
11112
+ runId: envelope.id,
11113
+ stepId: null
11114
+ }));
11115
+ if (!toolTelemetryComplete) {
11116
+ downgrades.push({
11117
+ reason: "incomplete_tool_telemetry",
11118
+ tool: null,
11119
+ toolCallId: null,
11120
+ runId: envelope.id,
11121
+ stepId: null
11122
+ });
11123
+ }
11124
+ recordRunWriteAttribution(envelope.id, {
11125
+ recorded: [...observedRunEffects.mutatedPaths],
11126
+ complete: toolTelemetryComplete && observedRunEffects.writeRecordComplete,
11127
+ downgrades
11128
+ });
10899
11129
  await ledgerRef.persist();
10900
11130
  if (worktreeReceipt?.applied === true && req.taskWorktree !== void 0) {
10901
11131
  try {
@@ -11136,12 +11366,14 @@ function createDispatchBundle(context, options) {
11136
11366
  allowedTools: effectiveTools,
11137
11367
  settings
11138
11368
  });
11369
+ const endpoint = endpointCapacityForTarget(target.target.id);
11139
11370
  return {
11140
11371
  agentId: req.agentId,
11141
11372
  specFingerprint: agentSpecFingerprint(agentSpec),
11142
11373
  targetId: target.target.id,
11143
11374
  wireModelId: target.wireModelId,
11144
11375
  runtimeId: target.runtime.id,
11376
+ ...endpoint !== null ? { endpoint: { key: endpoint.key, label: endpoint.label, limit: endpoint.limit } } : {},
11145
11377
  node: previewNode(req).node,
11146
11378
  thinkingLevel: target.thinkingLevel,
11147
11379
  toolSignature: toolSignature(effectiveTools),
@@ -11552,19 +11784,21 @@ function createDispatchBundle(context, options) {
11552
11784
  }
11553
11785
  function snapshot() {
11554
11786
  const tickNow = now();
11787
+ const tickMonotonic = monotonicNow();
11555
11788
  const running = [];
11556
11789
  const totals = { ...finalizedTotals };
11557
11790
  const costAmounts = [...finalizedCosts];
11558
11791
  for (const run of active.values()) {
11559
11792
  let heartbeat = "n/a";
11560
- if (run.heartbeatAt && Number.isFinite(run.heartbeatAt.current)) {
11793
+ if (run.heartbeatAt && Number.isFinite(heartbeatMonotonicAt(run.heartbeatAt))) {
11794
+ const heartbeatMonotonic = heartbeatMonotonicAt(run.heartbeatAt);
11561
11795
  if (run.runtimeKind === "acp-delegation") {
11562
11796
  const stallMs = run.stallTimeoutMs;
11563
11797
  if (stallMs !== null && stallMs > 0) {
11564
- heartbeat = tickNow - run.heartbeatAt.current > stallMs ? "dead" : "alive";
11798
+ heartbeat = tickMonotonic - heartbeatMonotonic > stallMs ? "dead" : "alive";
11565
11799
  }
11566
11800
  } else {
11567
- heartbeat = classifyHeartbeat(run.heartbeatAt.current, tickNow, heartbeatSpec);
11801
+ heartbeat = classifyHeartbeat(heartbeatMonotonic, tickMonotonic, heartbeatSpec);
11568
11802
  }
11569
11803
  }
11570
11804
  const meter = run.meter;
@@ -11678,6 +11912,7 @@ function createDispatchBundle(context, options) {
11678
11912
  routeCandidates,
11679
11913
  reservations: {
11680
11914
  prepare: prepareReservation,
11915
+ release: (ownerId) => releaseDispatchReservation(ownerId, now()),
11681
11916
  rollback: (ownerId) => rollbackDispatchReservation(ownerId, now()),
11682
11917
  rollbackUnconsumed: (ownerId) => rollbackUnconsumedDispatchReservation(ownerId, now()),
11683
11918
  get: getDispatchReservation
@@ -11696,7 +11931,17 @@ function createDispatchBundle(context, options) {
11696
11931
  return ledger.get(runId);
11697
11932
  },
11698
11933
  observedRunWrites(runId) {
11699
- return runWriteTargets.get(runId) ?? null;
11934
+ const attribution = runWriteAttributions.get(runId);
11935
+ return attribution?.complete === true ? [...attribution.recorded] : null;
11936
+ },
11937
+ observedRunWriteAttribution(runId) {
11938
+ const attribution = runWriteAttributions.get(runId);
11939
+ if (attribution === void 0) return null;
11940
+ return {
11941
+ recorded: [...attribution.recorded],
11942
+ complete: attribution.complete,
11943
+ downgrades: attribution.downgrades?.map((entry) => ({ ...entry })) ?? []
11944
+ };
11700
11945
  },
11701
11946
  assignments: {
11702
11947
  get: (id) => assignments.get(id),
@@ -11823,7 +12068,7 @@ async function writeCodeStepRecord(rootId, record) {
11823
12068
 
11824
12069
  // src/domains/dispatch/delegation-plan.ts
11825
12070
  init_esm_shims();
11826
- import { createHash as createHash10 } from "node:crypto";
12071
+ import { createHash as createHash9 } from "node:crypto";
11827
12072
  var DELEGATION_PROPOSAL_BRIEFING_MAX_BYTES = 12e3;
11828
12073
  function buildDelegationProposalBriefing(proposals) {
11829
12074
  const value = proposals.map((proposal) => `PROPOSAL ${proposal.agent}
@@ -11931,7 +12176,7 @@ function validateDelegationPlan(input) {
11931
12176
  }
11932
12177
  }
11933
12178
  const plan = { tasks };
11934
- return { ok: true, plan, hash: createHash10("sha256").update(JSON.stringify(plan)).digest("hex") };
12179
+ return { ok: true, plan, hash: createHash9("sha256").update(JSON.stringify(plan)).digest("hex") };
11935
12180
  }
11936
12181
 
11937
12182
  // src/domains/dispatch/execution-scheduler.ts
@@ -12359,7 +12604,7 @@ function gateFailureLines(output) {
12359
12604
 
12360
12605
  // src/domains/dispatch/fleet-run.ts
12361
12606
  init_esm_shims();
12362
- import { createHash as createHash11 } from "node:crypto";
12607
+ import { createHash as createHash10 } from "node:crypto";
12363
12608
  import { readFileSync as readFileSync13 } from "node:fs";
12364
12609
  import { join as join15 } from "node:path";
12365
12610
 
@@ -12490,10 +12735,29 @@ async function executeFleetRun(input) {
12490
12735
  boundaryFor: (stepId) => livePlan.steps.find((step) => step.id === stepId)?.writes,
12491
12736
  recordedWritesFor: (stepId) => {
12492
12737
  const step = livePlan.steps.find((entry) => entry.id === stepId);
12493
- if (step === void 0 || step.kind !== "agent") return null;
12738
+ if (step === void 0) return null;
12739
+ if (step.kind !== "agent") {
12740
+ return {
12741
+ recorded: [],
12742
+ complete: false,
12743
+ downgrades: [
12744
+ {
12745
+ reason: "code_step_untracked",
12746
+ tool: null,
12747
+ toolCallId: null,
12748
+ runId: null,
12749
+ stepId
12750
+ }
12751
+ ]
12752
+ };
12753
+ }
12494
12754
  const receipt = receiptsByStep.get(stepId);
12495
12755
  if (receipt === void 0) return null;
12496
- return dispatch.observedRunWrites?.(receipt.runId) ?? null;
12756
+ if (dispatch.observedRunWriteAttribution !== void 0) {
12757
+ return dispatch.observedRunWriteAttribution(receipt.runId);
12758
+ }
12759
+ const recorded = dispatch.observedRunWrites?.(receipt.runId) ?? null;
12760
+ return recorded === null ? null : { recorded, complete: true, downgrades: [] };
12497
12761
  },
12498
12762
  onVerdict(verdict, path2) {
12499
12763
  if (verdict.detail === null) return;
@@ -12691,7 +12955,7 @@ async function executeFleetRun(input) {
12691
12955
  } catch {
12692
12956
  gateBytes = "";
12693
12957
  }
12694
- gatePathHash = createHash11("sha256").update(gateBytes).digest("hex");
12958
+ gatePathHash = createHash10("sha256").update(gateBytes).digest("hex");
12695
12959
  const command = input.commands?.commands.get(step.gate.commandId);
12696
12960
  if (gateBytes.length === 0 || command === void 0) {
12697
12961
  stepSucceeded = false;
@@ -12864,7 +13128,7 @@ async function executeFleetRun(input) {
12864
13128
  cancel: (assignmentId) => dispatch.abort(assignmentId),
12865
13129
  release: (ownerId) => {
12866
13130
  if (ownerId === NO_WORKER_RESERVATION) return;
12867
- dispatch.reservations?.rollbackUnconsumed(ownerId);
13131
+ dispatch.reservations?.release(ownerId);
12868
13132
  },
12869
13133
  releaseUnconsumed: (ownerId) => {
12870
13134
  if (ownerId === NO_WORKER_RESERVATION) return;
@@ -12977,6 +13241,36 @@ function attributeEvidenceFailure(facts) {
12977
13241
  return "unknown";
12978
13242
  }
12979
13243
 
13244
+ // src/domains/evidence/findings-markdown.ts
13245
+ init_esm_shims();
13246
+ function renderEvidenceFindingsMarkdown(findings, trustStatus) {
13247
+ const lines = ["# Findings", "", "## Canonical trust", ""];
13248
+ if (trustStatus.runs.length === 0) {
13249
+ lines.push("No linked run trust status.");
13250
+ } else {
13251
+ for (const run of trustStatus.runs) {
13252
+ lines.push(
13253
+ `- run=${run.runId}`,
13254
+ ` tier: ${trustVerdict(run.status)}`,
13255
+ ` summary: ${formatTrustSummary(run.status)}`,
13256
+ ` axes: ${formatTrustAxes(run.status)}`
13257
+ );
13258
+ }
13259
+ }
13260
+ lines.push("", "## Finding records", "");
13261
+ if (findings.length === 0) {
13262
+ lines.push("No findings.");
13263
+ } else {
13264
+ for (const item of findings) {
13265
+ const run = item.runId === null ? "" : ` run=${item.runId}`;
13266
+ lines.push(`- ${item.id} [${item.severity}] ${item.tag}${run}: ${item.message}`);
13267
+ }
13268
+ }
13269
+ lines.push("");
13270
+ return `${lines.join("\n")}
13271
+ `;
13272
+ }
13273
+
12980
13274
  // src/domains/evidence/provenance.ts
12981
13275
  init_esm_shims();
12982
13276
  var PERSONA_HASH_PREFIX_CHARS = 12;
@@ -13148,7 +13442,6 @@ function buildEvidenceTrustStatusFile(input) {
13148
13442
  evidenceId: input.evidenceId,
13149
13443
  source,
13150
13444
  gateDecisions: input.gateDecisions,
13151
- auditRows: input.auditRows,
13152
13445
  validationEvidence: input.validationEvidence?.get(source.envelope.id) ?? []
13153
13446
  })
13154
13447
  }))
@@ -13156,7 +13449,6 @@ function buildEvidenceTrustStatusFile(input) {
13156
13449
  }
13157
13450
  function composeEvidenceRunTrustStatus(input) {
13158
13451
  const inspection = inspectRunReceiptTrustStatus(input.source.receipt, input.source.envelope);
13159
- const receiptRejected = inspection.status.artifactIntegrity.state === "failed";
13160
13452
  let status = inspection.status;
13161
13453
  const grounded = input.validationEvidence.filter((artifact) => isTrustStatusIdentifier(artifact.id));
13162
13454
  if (grounded.length > 0 && (status.validationGrounding.state === "absent" || status.validationGrounding.state === "unknown")) {
@@ -13181,21 +13473,6 @@ function composeEvidenceRunTrustStatus(input) {
13181
13473
  independentReview: adaptGateDecisionReviewStatus(gate, input.source.envelope.id, verification)
13182
13474
  });
13183
13475
  }
13184
- const finish = latestFinishContractForRun(input.auditRows, input.source.envelope.id);
13185
- if (finish !== null) {
13186
- const completion = adaptFinishContractCompletionStatus(finish.assessment, {
13187
- sourceId: finish.sourceId,
13188
- artifacts: finish.artifacts
13189
- });
13190
- status = composeTrustStatus(status, {
13191
- completionEvidence: receiptRejected && completion.state === "evidenced" ? {
13192
- state: "unknown",
13193
- source: { kind: "finish_contract", id: finish.sourceId },
13194
- authority: { kind: "clio", id: "finish-contract" },
13195
- artifacts: finish.artifacts
13196
- } : completion
13197
- });
13198
- }
13199
13476
  return status;
13200
13477
  }
13201
13478
  function latestGateDecisionForRun(decisions, runId) {
@@ -13203,55 +13480,6 @@ function latestGateDecisionForRun(decisions, runId) {
13203
13480
  (left, right) => compareCodepoints(left.createdAt, right.createdAt) || left.cycle - right.cycle || compareCodepoints(left.id, right.id)
13204
13481
  ).at(-1) ?? null;
13205
13482
  }
13206
- function latestFinishContractForRun(rows, runId) {
13207
- const candidates = rows.filter((row) => row.auditKind === "completion_contract" && row.runId === runId && row.confidence === "exact").flatMap((row) => {
13208
- const assessment = finishContractAssessmentFromAudit(row.row);
13209
- if (assessment === null) return [];
13210
- const correlationId = readOptionalString(row.row.correlationId) ?? `${runId}:completion-contract`;
13211
- if (!isTrustStatusIdentifier(correlationId)) return [];
13212
- const turnId = readOptionalString(row.row.turnId);
13213
- const artifacts = [
13214
- { kind: "finish_contract_evidence", id: correlationId },
13215
- ...turnId === null || !isTrustStatusIdentifier(turnId) ? [] : [{ kind: "session_entry", id: turnId }]
13216
- ];
13217
- return [{ sourceId: correlationId, assessment, artifacts, timestamp: row.ts ?? "" }];
13218
- }).sort(
13219
- (left, right) => compareCodepoints(left.timestamp, right.timestamp) || compareCodepoints(left.sourceId, right.sourceId)
13220
- );
13221
- const latest2 = candidates.at(-1);
13222
- return latest2 === void 0 ? null : { sourceId: latest2.sourceId, assessment: latest2.assessment, artifacts: latest2.artifacts };
13223
- }
13224
- function finishContractAssessmentFromAudit(row) {
13225
- const reason = readOptionalString(row.reason);
13226
- const decision = readOptionalString(row.decision);
13227
- const mutatedPaths = Array.isArray(row.mutatedPaths) ? row.mutatedPaths.filter((entry) => typeof entry === "string") : [];
13228
- const turnId = readOptionalString(row.turnId);
13229
- const evidenceKinds = Array.isArray(row.evidenceKinds) ? row.evidenceKinds.filter(isFinishContractEvidenceKind) : [];
13230
- const evidence = evidenceKinds.map((kind) => ({
13231
- kind,
13232
- summary: "recorded by the finish contract",
13233
- ...turnId === null ? {} : { turnId }
13234
- }));
13235
- if (decision === "ok" && reason === "no_mutation") {
13236
- return { kind: "ok", reason, evidence: [], mutatedPaths };
13237
- }
13238
- if (decision === "ok" && reason === "validation_evidence") {
13239
- return { kind: "ok", reason, evidence, mutatedPaths };
13240
- }
13241
- if (decision === "ok" && reason === "explicit_limitation") {
13242
- return { kind: "ok", reason, evidence: [], mutatedPaths };
13243
- }
13244
- if (decision === "engage" && reason === "unvalidated_mutation") {
13245
- return { kind: "engage", reason, message: "finish contract engaged", evidence: [], mutatedPaths };
13246
- }
13247
- return null;
13248
- }
13249
- function isFinishContractEvidenceKind(value) {
13250
- return value === "validation_command" || value === "protected_artifact" || value === "dispatch_receipt";
13251
- }
13252
- function readOptionalString(value) {
13253
- return typeof value === "string" && value.trim().length > 0 ? value : null;
13254
- }
13255
13483
 
13256
13484
  // src/domains/evidence/store.ts
13257
13485
  init_esm_shims();
@@ -13564,7 +13792,6 @@ async function buildEvidence(options) {
13564
13792
  evidenceId,
13565
13793
  runSources,
13566
13794
  gateDecisions: gateDecisions.decisions,
13567
- auditRows: auditLinks.rows,
13568
13795
  validationEvidence
13569
13796
  });
13570
13797
  const findings = buildFindings(runSources, trustStatusRaw, sessionLinks, auditLinks, protectedArtifactsRaw);
@@ -13887,15 +14114,15 @@ function validationToolCallSummary(toolName, args) {
13887
14114
  const parsed = parseMaybeJson(args);
13888
14115
  const argRecord = isRecord11(parsed) ? parsed : null;
13889
14116
  if (toolName === "bash") {
13890
- const command = readOptionalString2(argRecord?.command);
14117
+ const command = readOptionalString(argRecord?.command);
13891
14118
  if (command === null) return null;
13892
14119
  const detected = detectValidationCommand(command);
13893
14120
  return detected.kind === "validation" ? detected.matched : null;
13894
14121
  }
13895
14122
  if (toolName === "verify") {
13896
- const check = readOptionalString2(argRecord?.check);
14123
+ const check = readOptionalString(argRecord?.check);
13897
14124
  if (check === "frontend") {
13898
- const target = readOptionalString2(argRecord?.path) ?? "artifact";
14125
+ const target = readOptionalString(argRecord?.path) ?? "artifact";
13899
14126
  return `verify frontend ${target}`;
13900
14127
  }
13901
14128
  if (check === null) return null;
@@ -13937,7 +14164,7 @@ async function writeEvidenceFiles(directory, overview, runSources, findings, ses
13937
14164
  await writeJson(join17(directory, "trust-status.json"), trustStatus);
13938
14165
  await writeJson(join17(directory, "protected-artifacts.json"), protectedArtifacts);
13939
14166
  await writeJson(join17(directory, "findings.json"), findingsFile(overview.evidenceId, [...findings]));
13940
- await writeFile(join17(directory, "findings.md"), renderFindings(findings), "utf8");
14167
+ await writeFile(join17(directory, "findings.md"), renderEvidenceFindingsMarkdown(findings, trustStatus), "utf8");
13941
14168
  }
13942
14169
  function rawTraceRows(runSources) {
13943
14170
  const rows = [];
@@ -14082,12 +14309,12 @@ function attributionWindows(ledger, runSources, sessionIds) {
14082
14309
  const linkedSessions = new Set(sessionIds);
14083
14310
  for (const row of ledger.rows) {
14084
14311
  if (!isRecord11(row)) continue;
14085
- const id = readOptionalString2(row.id);
14086
- const startedAt = readOptionalString2(row.startedAt);
14087
- const sessionId = readOptionalString2(row.sessionId);
14312
+ const id = readOptionalString(row.id);
14313
+ const startedAt = readOptionalString(row.startedAt);
14314
+ const sessionId = readOptionalString(row.sessionId);
14088
14315
  if (id === null || startedAt === null || sessionId === null) continue;
14089
14316
  if (windows.has(id) || !linkedSessions.has(sessionId)) continue;
14090
- windows.set(id, { runId: id, startedAt, endedAt: readOptionalString2(row.endedAt) });
14317
+ windows.set(id, { runId: id, startedAt, endedAt: readOptionalString(row.endedAt) });
14091
14318
  }
14092
14319
  return [...windows.values()].sort((left, right) => compareCodepoints(left.runId, right.runId));
14093
14320
  }
@@ -14202,16 +14429,16 @@ function extractSessionToolCall(entry, linked) {
14202
14429
  const payload = payloadObject(entry.payload);
14203
14430
  const block = firstContentBlock(entry.payload, "toolCall");
14204
14431
  const fn = payloadObject(payload?.function);
14205
- const id = readOptionalString2(payload?.id) ?? readOptionalString2(payload?.toolCallId) ?? readOptionalString2(payload?.tool_call_id) ?? readOptionalString2(block?.id) ?? entry.turnId;
14206
- const tool = readOptionalString2(payload?.name) ?? readOptionalString2(payload?.toolName) ?? readOptionalString2(payload?.tool) ?? readOptionalString2(fn?.name) ?? readOptionalString2(block?.name) ?? "tool";
14432
+ const id = readOptionalString(payload?.id) ?? readOptionalString(payload?.toolCallId) ?? readOptionalString(payload?.tool_call_id) ?? readOptionalString(block?.id) ?? entry.turnId;
14433
+ const tool = readOptionalString(payload?.name) ?? readOptionalString(payload?.toolName) ?? readOptionalString(payload?.tool) ?? readOptionalString(fn?.name) ?? readOptionalString(block?.name) ?? "tool";
14207
14434
  const args = payload?.arguments ?? payload?.args ?? payload?.input ?? parseMaybeJson(fn?.arguments) ?? block?.arguments ?? block?.args ?? void 0;
14208
14435
  return { id, tool, args, timestamp: entry.timestamp, link: linked.link, sessionId: linked.sessionId };
14209
14436
  }
14210
14437
  function extractSessionToolResult(entry, linked) {
14211
14438
  const payload = payloadObject(entry.payload);
14212
14439
  const contentText = extractTextFromPayload(entry.payload);
14213
- const id = readOptionalString2(payload?.toolCallId) ?? readOptionalString2(payload?.tool_call_id) ?? readOptionalString2(payload?.id) ?? null;
14214
- const tool = readOptionalString2(payload?.toolName) ?? readOptionalString2(payload?.name) ?? readOptionalString2(payload?.tool) ?? "tool";
14440
+ const id = readOptionalString(payload?.toolCallId) ?? readOptionalString(payload?.tool_call_id) ?? readOptionalString(payload?.id) ?? null;
14441
+ const tool = readOptionalString(payload?.toolName) ?? readOptionalString(payload?.name) ?? readOptionalString(payload?.tool) ?? "tool";
14215
14442
  const result = payload?.result ?? payload?.output ?? payload?.out ?? payload?.content ?? (contentText.length > 0 ? contentText : entry.payload);
14216
14443
  return {
14217
14444
  id,
@@ -14238,12 +14465,12 @@ async function linkAuditRows(stateDir, source, runSources, sessionLinks) {
14238
14465
  runSources.map((item) => [item.envelope.id, item.envelope.sessionId ?? item.receipt?.sessionId ?? null])
14239
14466
  );
14240
14467
  for (const audit of auditRows.rows) {
14241
- const directRunId = readOptionalString2(audit.row.runId);
14468
+ const directRunId = readOptionalString(audit.row.runId);
14242
14469
  if (directRunId !== null && runIds.has(directRunId)) {
14243
14470
  rows.push(
14244
14471
  auditLinkedRow(audit, {
14245
14472
  runId: directRunId,
14246
- sessionId: readOptionalString2(audit.row.sessionId) ?? runSessionIds.get(directRunId) ?? null,
14473
+ sessionId: readOptionalString(audit.row.sessionId) ?? runSessionIds.get(directRunId) ?? null,
14247
14474
  linkKind: "run-id",
14248
14475
  confidence: "exact",
14249
14476
  reasons: ["audit runId matched run ledger"]
@@ -14251,7 +14478,7 @@ async function linkAuditRows(stateDir, source, runSources, sessionLinks) {
14251
14478
  );
14252
14479
  continue;
14253
14480
  }
14254
- const directSessionId = readOptionalString2(audit.row.sessionId);
14481
+ const directSessionId = readOptionalString(audit.row.sessionId);
14255
14482
  if (directSessionId !== null && sessionIds.has(directSessionId)) {
14256
14483
  rows.push(
14257
14484
  auditLinkedRow(audit, {
@@ -14286,7 +14513,7 @@ function auditLinkedRow(audit, fields) {
14286
14513
  }
14287
14514
  function bestEffortAuditLink(audit, source, runSources, sessionIds) {
14288
14515
  if (audit.auditKind !== "tool_call") return null;
14289
- const tool = readOptionalString2(audit.row.tool);
14516
+ const tool = readOptionalString(audit.row.tool);
14290
14517
  if (tool === null || audit.ts === null) return null;
14291
14518
  const candidates = runSources.filter((item) => {
14292
14519
  if (!timestampInRunWindow(audit.ts ?? "", item.envelope)) return false;
@@ -14350,9 +14577,9 @@ function auditToolEvents(rows) {
14350
14577
  const events = [];
14351
14578
  for (const row of rows) {
14352
14579
  if (row.auditKind !== "tool_call") continue;
14353
- const tool = readOptionalString2(row.row.tool);
14580
+ const tool = readOptionalString(row.row.tool);
14354
14581
  if (tool === null) continue;
14355
- const decision = readOptionalString2(row.row.decision);
14582
+ const decision = readOptionalString(row.row.decision);
14356
14583
  if (decision === "classified") continue;
14357
14584
  const event = {
14358
14585
  source: "audit-row",
@@ -14369,7 +14596,7 @@ function auditToolEvents(rows) {
14369
14596
  };
14370
14597
  if (row.ts !== null) event.timestamp = row.ts;
14371
14598
  if (decision !== null) event.decision = decision;
14372
- const actionClass = readOptionalString2(row.row.actionClass);
14599
+ const actionClass = readOptionalString(row.row.actionClass);
14373
14600
  if (actionClass !== null) event.actionClass = actionClass;
14374
14601
  events.push(event);
14375
14602
  }
@@ -14380,8 +14607,8 @@ function compareAuditLinkedRows(a, b) {
14380
14607
  if (byTs !== 0) return byTs;
14381
14608
  const byKind = compareCodepoints(a.auditKind, b.auditKind);
14382
14609
  if (byKind !== 0) return byKind;
14383
- const aCorrelation = readOptionalString2(a.row.correlationId) ?? "";
14384
- const bCorrelation = readOptionalString2(b.row.correlationId) ?? "";
14610
+ const aCorrelation = readOptionalString(a.row.correlationId) ?? "";
14611
+ const bCorrelation = readOptionalString(b.row.correlationId) ?? "";
14385
14612
  if (aCorrelation !== bCorrelation) return compareCodepoints(aCorrelation, bCorrelation);
14386
14613
  return compareCodepoints(JSON.stringify(a.row), JSON.stringify(b.row));
14387
14614
  }
@@ -14614,17 +14841,6 @@ function axisFindings(offset, source, status) {
14614
14841
  }
14615
14842
  return out;
14616
14843
  }
14617
- function renderFindings(findings) {
14618
- if (findings.length === 0) return "# Findings\n\nNo findings.\n";
14619
- const lines = ["# Findings", ""];
14620
- for (const item of findings) {
14621
- const run = item.runId === null ? "" : ` run=${item.runId}`;
14622
- lines.push(`- ${item.id} [${item.severity}] ${item.tag}${run}: ${item.message}`);
14623
- }
14624
- lines.push("");
14625
- return `${lines.join("\n")}
14626
- `;
14627
- }
14628
14844
  async function readRunLedger(stateDir) {
14629
14845
  const target = join17(stateDir, "runs.json");
14630
14846
  let raw;
@@ -14713,7 +14929,7 @@ function parseRunReceipt(value, source) {
14713
14929
  const integrity = value.integrity;
14714
14930
  if (!isRecord11(integrity)) throw new Error(`${source}.integrity: expected object`);
14715
14931
  const reasoningTokenCount = readOptionalNumber2(value, source, "reasoningTokenCount");
14716
- const failureMessage = readOptionalString2(value.failureMessage);
14932
+ const failureMessage = readOptionalString(value.failureMessage);
14717
14933
  return {
14718
14934
  ...value,
14719
14935
  runId: readString2(value, source, "runId"),
@@ -14805,7 +15021,7 @@ function readNullableNumber(record, source, field) {
14805
15021
  throw new Error(`${source}.${field}: expected number or null`);
14806
15022
  return value;
14807
15023
  }
14808
- function readOptionalString2(value) {
15024
+ function readOptionalString(value) {
14809
15025
  return typeof value === "string" && value.length > 0 ? value : null;
14810
15026
  }
14811
15027
  function parseJson2(raw, source) {
@@ -14947,9 +15163,6 @@ init_esm_shims();
14947
15163
  // src/domains/eval/report.ts
14948
15164
  init_esm_shims();
14949
15165
 
14950
- // src/domains/eval/run-compare.ts
14951
- init_esm_shims();
14952
-
14953
15166
  // src/domains/eval/runner.ts
14954
15167
  init_esm_shims();
14955
15168
  function summarizeEvalResults(records) {
@@ -15018,8 +15231,7 @@ async function buildEvalEvidence(options) {
15018
15231
  const trustStatus = buildEvidenceTrustStatusFile({
15019
15232
  evidenceId,
15020
15233
  runSources: linkedRuns.runSources,
15021
- gateDecisions: gateDecisions.decisions,
15022
- auditRows: linkedRuns.auditRows
15234
+ gateDecisions: gateDecisions.decisions
15023
15235
  });
15024
15236
  await writeEvalEvidenceFiles(
15025
15237
  directory,
@@ -15153,7 +15365,7 @@ async function writeEvalEvidenceFiles(directory, artifact, overview, findings, t
15153
15365
  await writeJson2(join18(directory, "protected-artifacts.json"), emptyProtected);
15154
15366
  await writeJson2(join18(directory, "eval-result.json"), redactedArtifact);
15155
15367
  await writeJson2(join18(directory, "findings.json"), findingsFile(overview.evidenceId, [...findings]));
15156
- await writeFile2(join18(directory, "findings.md"), renderFindings2(findings), "utf8");
15368
+ await writeFile2(join18(directory, "findings.md"), renderEvidenceFindingsMarkdown(findings, trustStatus), "utf8");
15157
15369
  }
15158
15370
  function rawEvalTraceRows(artifact) {
15159
15371
  return artifact.results.map((result) => ({
@@ -15243,16 +15455,6 @@ function renderEvalTranscript(artifact, overview) {
15243
15455
  return `${lines.join("\n")}
15244
15456
  `;
15245
15457
  }
15246
- function renderFindings2(findings) {
15247
- if (findings.length === 0) return "No findings.\n";
15248
- const lines = ["# Findings", ""];
15249
- for (const finding2 of findings) {
15250
- lines.push(`- ${finding2.id} [${finding2.severity}] ${finding2.tag}: ${finding2.message}`);
15251
- }
15252
- lines.push("");
15253
- return `${lines.join("\n")}
15254
- `;
15255
- }
15256
15458
  async function writeJson2(path2, value) {
15257
15459
  await writeFile2(path2, `${JSON.stringify(value, null, 2)}
15258
15460
  `, "utf8");
@@ -15464,30 +15666,30 @@ init_esm_shims();
15464
15666
  function lower(value) {
15465
15667
  return (value ?? "").toLowerCase();
15466
15668
  }
15467
- function canonicalJson4(value) {
15669
+ function canonicalJson3(value) {
15468
15670
  if (value === null) return "null";
15469
15671
  if (typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
15470
15672
  if (typeof value === "number") {
15471
15673
  if (!Number.isFinite(value)) throw new Error("response schema digest requires finite numbers");
15472
15674
  return JSON.stringify(value);
15473
15675
  }
15474
- if (Array.isArray(value)) return `[${value.map(canonicalJson4).join(",")}]`;
15676
+ if (Array.isArray(value)) return `[${value.map(canonicalJson3).join(",")}]`;
15475
15677
  if (typeof value === "object") {
15476
15678
  const record = value;
15477
15679
  return `{${Object.keys(record).sort().map((key) => {
15478
15680
  if (record[key] === void 0) throw new Error("response schema digest cannot contain undefined");
15479
- return `${JSON.stringify(key)}:${canonicalJson4(record[key])}`;
15681
+ return `${JSON.stringify(key)}:${canonicalJson3(record[key])}`;
15480
15682
  }).join(",")}}`;
15481
15683
  }
15482
15684
  throw new Error(`response schema digest cannot represent ${typeof value}`);
15483
15685
  }
15484
15686
  function canonicalResponseSchemaDigest(schema) {
15485
- return createHash12("sha256").update(canonicalJson4(schema), "utf8").digest("hex");
15687
+ return createHash11("sha256").update(canonicalJson3(schema), "utf8").digest("hex");
15486
15688
  }
15487
15689
  function typedValidationFactsFromToolStats(toolStats) {
15488
15690
  return toolStats.filter((stat) => stat.tool === "verify" && stat.count > 0).map((stat) => ({
15489
15691
  sourceId: "tool:verify",
15490
- validatorDigest: createHash12("sha256").update(canonicalJson4(stat), "utf8").digest("hex"),
15692
+ validatorDigest: createHash11("sha256").update(canonicalJson3(stat), "utf8").digest("hex"),
15491
15693
  passed: stat.ok === stat.count && stat.errors === 0 && stat.blocked === 0
15492
15694
  }));
15493
15695
  }
@@ -15614,14 +15816,13 @@ export {
15614
15816
  ACP_MAX_RAW_RECORD_BYTES,
15615
15817
  ACP_MAX_CHUNK_BYTES,
15616
15818
  ACP_MAX_TOOL_CALL_ID_BYTES,
15617
- sha256,
15618
- canonicalJson2 as canonicalJson,
15619
15819
  compile,
15620
15820
  compileWorker,
15621
15821
  WORKER_OUTPUT_MAX_BYTES,
15622
15822
  durableAssistantTextFromEvent,
15623
15823
  setCapacityDraining,
15624
15824
  capacityDrain,
15825
+ capacityLeaseUsage,
15625
15826
  openAgentLedger,
15626
15827
  renderAgentLedgerBoard,
15627
15828
  closeAgentLedger,
@@ -15659,4 +15860,4 @@ export {
15659
15860
  summarizeEvalResults,
15660
15861
  buildEvalEvidence
15661
15862
  };
15662
- //# sourceMappingURL=chunk-TLQJPP24.js.map
15863
+ //# sourceMappingURL=chunk-TEO2TLVN.js.map