@relayflows/sdk 2.0.30 → 2.0.32

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 (347) hide show
  1. package/dist/agent-artifacts.d.ts.map +1 -1
  2. package/dist/agent-artifacts.js +2 -9
  3. package/dist/agent-artifacts.js.map +1 -1
  4. package/dist/agent-cwd.d.ts +69 -0
  5. package/dist/agent-cwd.d.ts.map +1 -0
  6. package/dist/agent-cwd.js +140 -0
  7. package/dist/agent-cwd.js.map +1 -0
  8. package/dist/artifact-scan-policy.d.ts +35 -0
  9. package/dist/artifact-scan-policy.d.ts.map +1 -0
  10. package/dist/artifact-scan-policy.js +49 -0
  11. package/dist/artifact-scan-policy.js.map +1 -0
  12. package/dist/authored-completion-record.d.ts +35 -0
  13. package/dist/authored-completion-record.d.ts.map +1 -0
  14. package/dist/authored-completion-record.js +92 -0
  15. package/dist/authored-completion-record.js.map +1 -0
  16. package/dist/authored-completion.d.ts +99 -0
  17. package/dist/authored-completion.d.ts.map +1 -0
  18. package/dist/authored-completion.js +184 -0
  19. package/dist/authored-completion.js.map +1 -0
  20. package/dist/authored-flow-error.d.ts +13 -1
  21. package/dist/authored-flow-error.d.ts.map +1 -1
  22. package/dist/authored-flow-error.js +12 -0
  23. package/dist/authored-flow-error.js.map +1 -1
  24. package/dist/authored-flow-executor.d.ts +7 -30
  25. package/dist/authored-flow-executor.d.ts.map +1 -1
  26. package/dist/authored-flow-executor.js +54 -47
  27. package/dist/authored-flow-executor.js.map +1 -1
  28. package/dist/authored-human.d.ts.map +1 -1
  29. package/dist/authored-human.js +1 -3
  30. package/dist/authored-human.js.map +1 -1
  31. package/dist/authored-node-entry.js +4 -1
  32. package/dist/authored-node-entry.js.map +1 -1
  33. package/dist/authored-node-runner.d.ts +9 -1
  34. package/dist/authored-node-runner.d.ts.map +1 -1
  35. package/dist/authored-node-runner.js +92 -17
  36. package/dist/authored-node-runner.js.map +1 -1
  37. package/dist/authored-preflight.d.ts +4 -0
  38. package/dist/authored-preflight.d.ts.map +1 -0
  39. package/dist/authored-preflight.js +50 -0
  40. package/dist/authored-preflight.js.map +1 -0
  41. package/dist/authored-root.d.ts +5 -0
  42. package/dist/authored-root.d.ts.map +1 -1
  43. package/dist/authored-root.js +20 -2
  44. package/dist/authored-root.js.map +1 -1
  45. package/dist/authored-step-output.d.ts +35 -10
  46. package/dist/authored-step-output.d.ts.map +1 -1
  47. package/dist/authored-step-output.js +108 -40
  48. package/dist/authored-step-output.js.map +1 -1
  49. package/dist/authored-verdict.d.ts +28 -0
  50. package/dist/authored-verdict.d.ts.map +1 -0
  51. package/dist/authored-verdict.js +79 -0
  52. package/dist/authored-verdict.js.map +1 -0
  53. package/dist/authored-worker-step.d.ts +5 -2
  54. package/dist/authored-worker-step.d.ts.map +1 -1
  55. package/dist/authored-worker-step.js +51 -13
  56. package/dist/authored-worker-step.js.map +1 -1
  57. package/dist/cli/check-worker-surface.d.ts +27 -0
  58. package/dist/cli/check-worker-surface.d.ts.map +1 -0
  59. package/dist/cli/check-worker-surface.js +63 -0
  60. package/dist/cli/check-worker-surface.js.map +1 -0
  61. package/dist/cli/check.d.ts +28 -3
  62. package/dist/cli/check.d.ts.map +1 -1
  63. package/dist/cli/check.js +27 -140
  64. package/dist/cli/check.js.map +1 -1
  65. package/dist/cli/cli-probe.d.ts +20 -0
  66. package/dist/cli/cli-probe.d.ts.map +1 -0
  67. package/dist/cli/cli-probe.js +166 -0
  68. package/dist/cli/cli-probe.js.map +1 -0
  69. package/dist/cli/cloud-format.d.ts +9 -0
  70. package/dist/cli/cloud-format.d.ts.map +1 -0
  71. package/dist/cli/cloud-format.js +77 -0
  72. package/dist/cli/cloud-format.js.map +1 -0
  73. package/dist/cli/cloud-live.d.ts +39 -0
  74. package/dist/cli/cloud-live.d.ts.map +1 -0
  75. package/dist/cli/cloud-live.js +325 -0
  76. package/dist/cli/cloud-live.js.map +1 -0
  77. package/dist/cli/cloud-mirror-session.d.ts +97 -0
  78. package/dist/cli/cloud-mirror-session.d.ts.map +1 -0
  79. package/dist/cli/cloud-mirror-session.js +264 -0
  80. package/dist/cli/cloud-mirror-session.js.map +1 -0
  81. package/dist/cli/cloud-read.d.ts +3 -7
  82. package/dist/cli/cloud-read.d.ts.map +1 -1
  83. package/dist/cli/cloud-read.js +14 -266
  84. package/dist/cli/cloud-read.js.map +1 -1
  85. package/dist/cli/cloud-refusal.d.ts +39 -0
  86. package/dist/cli/cloud-refusal.d.ts.map +1 -0
  87. package/dist/cli/cloud-refusal.js +95 -0
  88. package/dist/cli/cloud-refusal.js.map +1 -0
  89. package/dist/cli/cloud-status-view.d.ts +7 -0
  90. package/dist/cli/cloud-status-view.d.ts.map +1 -0
  91. package/dist/cli/cloud-status-view.js +214 -0
  92. package/dist/cli/cloud-status-view.js.map +1 -0
  93. package/dist/cli/direct-run.d.ts.map +1 -1
  94. package/dist/cli/direct-run.js +16 -2
  95. package/dist/cli/direct-run.js.map +1 -1
  96. package/dist/cli/hn-monitor.d.ts +0 -13
  97. package/dist/cli/hn-monitor.d.ts.map +1 -1
  98. package/dist/cli/hn-monitor.js +2 -1
  99. package/dist/cli/hn-monitor.js.map +1 -1
  100. package/dist/cli/local-agent-remedy.d.ts +80 -0
  101. package/dist/cli/local-agent-remedy.d.ts.map +1 -0
  102. package/dist/cli/local-agent-remedy.js +116 -0
  103. package/dist/cli/local-agent-remedy.js.map +1 -0
  104. package/dist/cli/observer-session.d.ts +41 -0
  105. package/dist/cli/observer-session.d.ts.map +1 -0
  106. package/dist/cli/observer-session.js +78 -0
  107. package/dist/cli/observer-session.js.map +1 -0
  108. package/dist/cli/run.d.ts +30 -2
  109. package/dist/cli/run.d.ts.map +1 -1
  110. package/dist/cli/run.js +186 -24
  111. package/dist/cli/run.js.map +1 -1
  112. package/dist/cli/status.d.ts +9 -0
  113. package/dist/cli/status.d.ts.map +1 -1
  114. package/dist/cli/status.js +31 -2
  115. package/dist/cli/status.js.map +1 -1
  116. package/dist/cli/step-evidence.d.ts +90 -0
  117. package/dist/cli/step-evidence.d.ts.map +1 -0
  118. package/dist/cli/step-evidence.js +259 -0
  119. package/dist/cli/step-evidence.js.map +1 -0
  120. package/dist/cli/step-failure.d.ts +14 -4
  121. package/dist/cli/step-failure.d.ts.map +1 -1
  122. package/dist/cli/step-failure.js +41 -76
  123. package/dist/cli/step-failure.js.map +1 -1
  124. package/dist/cli-commands.d.ts +12 -0
  125. package/dist/cli-commands.d.ts.map +1 -1
  126. package/dist/cli-commands.js +3 -0
  127. package/dist/cli-commands.js.map +1 -1
  128. package/dist/cli.d.ts +17 -0
  129. package/dist/cli.d.ts.map +1 -1
  130. package/dist/cli.js +134 -57
  131. package/dist/cli.js.map +1 -1
  132. package/dist/cloud-deploy.d.ts +1 -1
  133. package/dist/cloud-deploy.d.ts.map +1 -1
  134. package/dist/cloud-deploy.js +24 -8
  135. package/dist/cloud-deploy.js.map +1 -1
  136. package/dist/cloud-mirror-ledger.d.ts +40 -0
  137. package/dist/cloud-mirror-ledger.d.ts.map +1 -0
  138. package/dist/cloud-mirror-ledger.js +142 -0
  139. package/dist/cloud-mirror-ledger.js.map +1 -0
  140. package/dist/cloud-mirror-step.d.ts +168 -0
  141. package/dist/cloud-mirror-step.d.ts.map +1 -0
  142. package/dist/cloud-mirror-step.js +504 -0
  143. package/dist/cloud-mirror-step.js.map +1 -0
  144. package/dist/cloud-mirror-transport.d.ts +94 -0
  145. package/dist/cloud-mirror-transport.d.ts.map +1 -0
  146. package/dist/cloud-mirror-transport.js +163 -0
  147. package/dist/cloud-mirror-transport.js.map +1 -0
  148. package/dist/cloud-mirror.d.ts +132 -0
  149. package/dist/cloud-mirror.d.ts.map +1 -0
  150. package/dist/cloud-mirror.js +556 -0
  151. package/dist/cloud-mirror.js.map +1 -0
  152. package/dist/cloud-read.d.ts +15 -0
  153. package/dist/cloud-read.d.ts.map +1 -1
  154. package/dist/cloud-read.js +20 -1
  155. package/dist/cloud-read.js.map +1 -1
  156. package/dist/cloud-run-record.d.ts +27 -0
  157. package/dist/cloud-run-record.d.ts.map +1 -0
  158. package/dist/cloud-run-record.js +56 -0
  159. package/dist/cloud-run-record.js.map +1 -0
  160. package/dist/cloud-run.d.ts +2 -9
  161. package/dist/cloud-run.d.ts.map +1 -1
  162. package/dist/cloud-run.js +3 -20
  163. package/dist/cloud-run.js.map +1 -1
  164. package/dist/communication/local.d.ts.map +1 -1
  165. package/dist/communication/local.js +2 -1
  166. package/dist/communication/local.js.map +1 -1
  167. package/dist/communication/worker.d.ts +1 -1
  168. package/dist/communication/worker.d.ts.map +1 -1
  169. package/dist/communication/worker.js +13 -5
  170. package/dist/communication/worker.js.map +1 -1
  171. package/dist/compile.d.ts.map +1 -1
  172. package/dist/compile.js +28 -6
  173. package/dist/compile.js.map +1 -1
  174. package/dist/direct-input.d.ts.map +1 -1
  175. package/dist/direct-input.js +21 -1
  176. package/dist/direct-input.js.map +1 -1
  177. package/dist/failure-kinds.d.ts +96 -6
  178. package/dist/failure-kinds.d.ts.map +1 -1
  179. package/dist/failure-kinds.js +29 -2
  180. package/dist/failure-kinds.js.map +1 -1
  181. package/dist/flow-requirements.d.ts.map +1 -1
  182. package/dist/flow-requirements.js +24 -9
  183. package/dist/flow-requirements.js.map +1 -1
  184. package/dist/gate-contract.d.ts +7 -0
  185. package/dist/gate-contract.d.ts.map +1 -1
  186. package/dist/gate-contract.js +6 -1
  187. package/dist/gate-contract.js.map +1 -1
  188. package/dist/helper-preflight.d.ts.map +1 -1
  189. package/dist/helper-preflight.js +10 -3
  190. package/dist/helper-preflight.js.map +1 -1
  191. package/dist/helper-reference.d.ts +25 -0
  192. package/dist/helper-reference.d.ts.map +1 -0
  193. package/dist/helper-reference.js +129 -0
  194. package/dist/helper-reference.js.map +1 -0
  195. package/dist/hosted-extension-runtime.js +1 -1
  196. package/dist/index.d.ts +1 -1
  197. package/dist/index.d.ts.map +1 -1
  198. package/dist/index.js.map +1 -1
  199. package/dist/journal-client.d.ts +3 -1
  200. package/dist/journal-client.d.ts.map +1 -1
  201. package/dist/journal-client.js +17 -2
  202. package/dist/journal-client.js.map +1 -1
  203. package/dist/journal-projection.d.ts +16 -0
  204. package/dist/journal-projection.d.ts.map +1 -0
  205. package/dist/journal-projection.js +108 -0
  206. package/dist/journal-projection.js.map +1 -0
  207. package/dist/llm-worker.js +1 -1
  208. package/dist/llm-worker.js.map +1 -1
  209. package/dist/local-agent.d.ts +1 -1
  210. package/dist/local-agent.d.ts.map +1 -1
  211. package/dist/local-agent.js +4 -3
  212. package/dist/local-agent.js.map +1 -1
  213. package/dist/named-gate-lowering.js +35 -5
  214. package/dist/named-gate-lowering.js.map +1 -1
  215. package/dist/named-gate-preflight.d.ts +27 -0
  216. package/dist/named-gate-preflight.d.ts.map +1 -0
  217. package/dist/named-gate-preflight.js +47 -0
  218. package/dist/named-gate-preflight.js.map +1 -0
  219. package/dist/named-gates.d.ts +1 -1
  220. package/dist/named-gates.d.ts.map +1 -1
  221. package/dist/named-gates.js +3 -0
  222. package/dist/named-gates.js.map +1 -1
  223. package/dist/observer-link.d.ts +7 -0
  224. package/dist/observer-link.d.ts.map +1 -1
  225. package/dist/observer-link.js +3 -1
  226. package/dist/observer-link.js.map +1 -1
  227. package/dist/package-version.d.ts +10 -0
  228. package/dist/package-version.d.ts.map +1 -0
  229. package/dist/package-version.js +22 -0
  230. package/dist/package-version.js.map +1 -0
  231. package/dist/preflight.d.ts +14 -0
  232. package/dist/preflight.d.ts.map +1 -1
  233. package/dist/preflight.js +25 -3
  234. package/dist/preflight.js.map +1 -1
  235. package/dist/protocol.d.ts +2 -0
  236. package/dist/protocol.d.ts.map +1 -1
  237. package/dist/redact.d.ts +42 -0
  238. package/dist/redact.d.ts.map +1 -1
  239. package/dist/redact.js +128 -0
  240. package/dist/redact.js.map +1 -1
  241. package/dist/relay-cli.d.ts.map +1 -1
  242. package/dist/relay-cli.js +1 -21
  243. package/dist/relay-cli.js.map +1 -1
  244. package/dist/run-projection.d.ts +83 -0
  245. package/dist/run-projection.d.ts.map +1 -0
  246. package/dist/run-projection.js +199 -0
  247. package/dist/run-projection.js.map +1 -0
  248. package/dist/shell-word.d.ts +19 -0
  249. package/dist/shell-word.d.ts.map +1 -0
  250. package/dist/shell-word.js +23 -0
  251. package/dist/shell-word.js.map +1 -0
  252. package/dist/spec.d.ts +52 -3
  253. package/dist/spec.d.ts.map +1 -1
  254. package/dist/spec.js.map +1 -1
  255. package/dist/step-fields.d.ts +1 -1
  256. package/dist/step-fields.js +1 -1
  257. package/dist/step-fields.js.map +1 -1
  258. package/dist/steps-green.d.ts +27 -0
  259. package/dist/steps-green.d.ts.map +1 -0
  260. package/dist/steps-green.js +164 -0
  261. package/dist/steps-green.js.map +1 -0
  262. package/dist/validate.d.ts.map +1 -1
  263. package/dist/validate.js +39 -8
  264. package/dist/validate.js.map +1 -1
  265. package/dist/worker-lease.d.ts +8 -1
  266. package/dist/worker-lease.d.ts.map +1 -1
  267. package/dist/worker-lease.js +34 -4
  268. package/dist/worker-lease.js.map +1 -1
  269. package/dist/worker.d.ts +8 -0
  270. package/dist/worker.d.ts.map +1 -1
  271. package/dist/worker.js +17 -9
  272. package/dist/worker.js.map +1 -1
  273. package/package.json +3 -7
  274. package/src/agent-artifacts.ts +2 -10
  275. package/src/agent-cwd.ts +139 -0
  276. package/src/artifact-scan-policy.ts +51 -0
  277. package/src/authored-completion-record.ts +119 -0
  278. package/src/authored-completion.ts +203 -0
  279. package/src/authored-flow-error.ts +13 -1
  280. package/src/authored-flow-executor.ts +91 -58
  281. package/src/authored-human.ts +1 -4
  282. package/src/authored-node-entry.ts +4 -1
  283. package/src/authored-node-runner.ts +96 -22
  284. package/src/authored-preflight.ts +46 -0
  285. package/src/authored-root.ts +20 -2
  286. package/src/authored-step-output.ts +139 -42
  287. package/src/authored-verdict.ts +87 -0
  288. package/src/authored-worker-step.ts +63 -14
  289. package/src/cli/check-worker-surface.ts +66 -0
  290. package/src/cli/check.ts +59 -166
  291. package/src/cli/cli-probe.ts +194 -0
  292. package/src/cli/cloud-format.ts +82 -0
  293. package/src/cli/cloud-live.ts +366 -0
  294. package/src/cli/cloud-mirror-session.ts +329 -0
  295. package/src/cli/cloud-read.ts +13 -282
  296. package/src/cli/cloud-refusal.ts +113 -0
  297. package/src/cli/cloud-status-view.ts +213 -0
  298. package/src/cli/direct-run.ts +19 -2
  299. package/src/cli/hn-monitor.ts +2 -1
  300. package/src/cli/local-agent-remedy.ts +160 -0
  301. package/src/cli/observer-session.ts +107 -0
  302. package/src/cli/run.ts +233 -28
  303. package/src/cli/status.ts +59 -3
  304. package/src/cli/step-evidence.ts +310 -0
  305. package/src/cli/step-failure.ts +57 -81
  306. package/src/cli-commands.ts +3 -0
  307. package/src/cli.ts +155 -60
  308. package/src/cloud-deploy.ts +26 -8
  309. package/src/cloud-mirror-ledger.ts +161 -0
  310. package/src/cloud-mirror-step.ts +618 -0
  311. package/src/cloud-mirror-transport.ts +261 -0
  312. package/src/cloud-mirror.ts +633 -0
  313. package/src/cloud-read.ts +25 -1
  314. package/src/cloud-run-record.ts +64 -0
  315. package/src/cloud-run.ts +5 -24
  316. package/src/communication/local.ts +2 -1
  317. package/src/communication/worker.ts +13 -5
  318. package/src/compile.ts +28 -6
  319. package/src/direct-input.ts +22 -1
  320. package/src/failure-kinds.ts +104 -2
  321. package/src/flow-requirements.ts +24 -9
  322. package/src/gate-contract.ts +13 -1
  323. package/src/helper-preflight.ts +10 -3
  324. package/src/helper-reference.ts +130 -0
  325. package/src/hosted-extension-runtime.ts +1 -1
  326. package/src/index.ts +2 -0
  327. package/src/journal-client.ts +19 -2
  328. package/src/journal-projection.ts +106 -0
  329. package/src/llm-worker.ts +1 -1
  330. package/src/local-agent.ts +4 -2
  331. package/src/named-gate-lowering.ts +35 -5
  332. package/src/named-gate-preflight.ts +47 -0
  333. package/src/named-gates.ts +3 -0
  334. package/src/observer-link.ts +10 -1
  335. package/src/package-version.ts +23 -0
  336. package/src/preflight.ts +38 -7
  337. package/src/protocol.ts +2 -0
  338. package/src/redact.ts +111 -0
  339. package/src/relay-cli.ts +1 -24
  340. package/src/run-projection.ts +247 -0
  341. package/src/shell-word.ts +24 -0
  342. package/src/spec.ts +54 -3
  343. package/src/step-fields.ts +1 -1
  344. package/src/steps-green.ts +168 -0
  345. package/src/validate.ts +35 -8
  346. package/src/worker-lease.ts +35 -5
  347. package/src/worker.ts +27 -11
@@ -0,0 +1,618 @@
1
+ // One journal, folded into the two step shapes Cloud stores for a run.
2
+ //
3
+ // A hosted run's steps reach Cloud twice: as a *live snapshot* while it runs
4
+ // (`POST /runs/<id>/steps/snapshot`) and as the *final report* once it is over
5
+ // (`POST /runs/<id>/steps`). The sandbox derives both from `flows status`;
6
+ // this module derives them from the same journal fold `flows status` uses
7
+ // (`run-state.ts`), so a local run and a hosted one put the same facts in the
8
+ // same fields and the dashboard cannot tell which produced a row.
9
+ //
10
+ // Nothing here does I/O or reads a clock: the caller passes the events and
11
+ // `now_ms`, exactly as `foldRunState` does. That is what lets a test fold a
12
+ // hand-built journal and assert the exact bytes a push would carry.
13
+ //
14
+ // ## The bounds are the server's, restated
15
+ //
16
+ // Every cap below is the one Cloud's own parser enforces
17
+ // (`@cloud/core` `storage/step-snapshot.ts` and `storage/step-detail.ts`).
18
+ // They are restated rather than imported because this package cannot depend on
19
+ // the Cloud app — the same reason `cloud-transcript.ts` restates the
20
+ // dashboard's transcript vocabulary. A push that violates one is refused
21
+ // whole, so producing a bounded value here is not politeness: it is the
22
+ // difference between a run that appears on the dashboard and one that does
23
+ // not.
24
+ //
25
+ // ## Redaction
26
+ //
27
+ // Every dynamic string goes through `redact` before it is bounded, never
28
+ // after: clipping first can leave the head of a secret standing where the
29
+ // redactor would have replaced the whole value. Identifier-shaped fields are
30
+ // then normalized into the shape Cloud's parser accepts, because the redactor
31
+ // emits `[redacted:NAME]`, which no identifier pattern admits.
32
+
33
+ import { redact } from './redact.js';
34
+ import { foldRunState, type RunView, type StepView } from './run-state.js';
35
+ import type { JournalEvent } from './journal-reader.js';
36
+ import { AUTHORED_STEP_STREAM, foldAuthoredStepRecords } from './authored-step-index.js';
37
+
38
+ /** Steps one snapshot may carry; a longer run publishes its live tail. */
39
+ export const SNAPSHOT_MAX_STEPS = 64;
40
+ /** Serialized snapshot envelope cap, against the real UTF-8 byte count. */
41
+ export const SNAPSHOT_MAX_BYTES = 64 * 1024;
42
+ /** Artifact paths named per step; the rest are counted. */
43
+ export const SNAPSHOT_ARTIFACTS_MAX = 5;
44
+ export const SNAPSHOT_ARTIFACT_MAX_CHARS = 200;
45
+ /** `stepName`, `journalRunId`, `stepType`, `completionReason`, gate, model. */
46
+ export const IDENTIFIER_MAX_CHARS = 128;
47
+ /** Predecessors one live step lists. */
48
+ export const SNAPSHOT_DEPENDS_ON_MAX = 32;
49
+ /** Predecessors a final row lists. */
50
+ export const DEPENDS_ON_MAX_ENTRIES = 256;
51
+ /** The backing columns are PostgreSQL 32-bit integers. */
52
+ export const MAX_INT32 = 2_147_483_647;
53
+ /** `workflow_steps.display_name`, in code points. */
54
+ export const LABEL_MAX_CHARS = 120;
55
+ /** `workflow_steps.output_summary`. */
56
+ export const OUTPUT_SUMMARY_MAX_CHARS = 1000;
57
+ /** `workflow_steps.error`. */
58
+ export const ERROR_MAX_CHARS = 1024;
59
+ /** Serialized `workflow_steps.detail`. */
60
+ export const DETAIL_MAX_BYTES = 16 * 1024;
61
+ /** Attempt rows kept on `detail.attempts`; older ones are counted, not listed. */
62
+ export const DETAIL_MAX_ATTEMPTS = 20;
63
+ /**
64
+ * The one completion reason the kernel uses for success. Cloud keys a step's
65
+ * status off exactly this value, so the live derivation and the final row
66
+ * agree about what "completed" means.
67
+ */
68
+ export const SUCCESS_COMPLETION_REASON = 'success';
69
+ /** The authored root step spans the whole flow; its children carry the steps. */
70
+ export const AUTHORED_ROOT_STEP = 'authored-root';
71
+
72
+ const IDENTIFIER = /^[A-Za-z0-9_.:/-]+$/u;
73
+ const IDENTIFIER_UNSAFE = /[^A-Za-z0-9_.:/-]+/gu;
74
+
75
+ /** Live kernel states Cloud publishes. A step that has not begun has no honest rendering. */
76
+ export type SnapshotState = 'running' | 'backoff' | 'waiting' | 'needs_human' | 'done';
77
+
78
+ export interface SnapshotStep {
79
+ stepName: string;
80
+ /** Child runs may repeat a step id, so identity is the pair. */
81
+ journalRunId: string;
82
+ stepType: string;
83
+ state: SnapshotState;
84
+ attempt: number;
85
+ elapsedMs: number;
86
+ completionReason?: string;
87
+ gate?: { name: string; verdict: string };
88
+ model?: string;
89
+ turns?: number;
90
+ toolCalls?: number;
91
+ costUsd?: number;
92
+ artifactCount?: number;
93
+ artifacts?: string[];
94
+ label?: string;
95
+ dependsOn?: string[];
96
+ }
97
+
98
+ /** One row of the final report; the field names are `workflow_steps`'s own. */
99
+ export interface FinalStep {
100
+ stepName: string;
101
+ stepType: string;
102
+ agent: string;
103
+ preset: string;
104
+ cli: string;
105
+ sandboxId: string;
106
+ startTime: string;
107
+ endTime: string;
108
+ durationMs: number;
109
+ exitCode: number;
110
+ outputSummary: string;
111
+ status: 'completed' | 'failed';
112
+ completionReason: string;
113
+ retryCount: number;
114
+ model?: string;
115
+ tokensInput?: number;
116
+ tokensOutput?: number;
117
+ costUsd?: number;
118
+ error?: string;
119
+ detail?: Record<string, unknown>;
120
+ detailTruncated?: true;
121
+ label?: string;
122
+ dependsOn?: string[];
123
+ }
124
+
125
+ /** One step's per-attempt transcript files, for the `<stepName>/agent.log` upload. */
126
+ export interface StepTranscriptRef {
127
+ stepName: string;
128
+ attempts: Array<{ attempt: number; path: string }>;
129
+ }
130
+
131
+ /** What one journal contributes, keyed for the caller's cross-journal cache. */
132
+ export interface MirroredJournal {
133
+ runId: string;
134
+ status: RunView['status'];
135
+ terminal: boolean;
136
+ steps: SnapshotStep[];
137
+ finals: FinalStep[];
138
+ transcripts: StepTranscriptRef[];
139
+ /** Child journals this run admitted, from an authored root's step index. */
140
+ children: string[];
141
+ /** Authored graph hints by step id, from an authored root's step index. */
142
+ hints: Map<string, { label?: string; after?: string[] }>;
143
+ }
144
+
145
+ type Payload = Record<string, unknown>;
146
+
147
+ function record(value: unknown): Payload | undefined {
148
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Payload : undefined;
149
+ }
150
+
151
+ function int32(value: unknown, floor = 0): number | undefined {
152
+ if (typeof value !== 'number' || !Number.isFinite(value)) return undefined;
153
+ const rounded = Math.round(value);
154
+ if (rounded < floor) return undefined;
155
+ return Math.min(rounded, MAX_INT32);
156
+ }
157
+
158
+ /**
159
+ * Redact, then normalize, then clip — in that order. Clipping first could
160
+ * leave the head of a secret standing; normalizing first would let a
161
+ * multi-character replacement push the result back over the cap.
162
+ */
163
+ export function identifier(
164
+ value: unknown,
165
+ env: NodeJS.ProcessEnv,
166
+ maxChars: number = IDENTIFIER_MAX_CHARS,
167
+ ): string | undefined {
168
+ if (typeof value !== 'string' || value.length === 0) return undefined;
169
+ const clipped = redact(value, env).replace(IDENTIFIER_UNSAFE, '_').slice(0, Math.max(1, maxChars));
170
+ return IDENTIFIER.test(clipped) ? clipped : undefined;
171
+ }
172
+
173
+ /** Free text, redacted then bounded by code points. Empty becomes undefined. */
174
+ export function text(value: unknown, env: NodeJS.ProcessEnv, maxChars: number): string | undefined {
175
+ if (typeof value !== 'string' || value.length === 0) return undefined;
176
+ const cleaned = redact(value, env);
177
+ const bounded = [...cleaned].slice(0, maxChars).join('');
178
+ return bounded.length === 0 ? undefined : bounded;
179
+ }
180
+
181
+ /**
182
+ * A step label as `workflow_steps.display_name` accepts it: control characters
183
+ * become spaces, whitespace runs collapse, the result is trimmed and clipped.
184
+ */
185
+ export function label(value: unknown, env: NodeJS.ProcessEnv): string | undefined {
186
+ if (typeof value !== 'string') return undefined;
187
+ const normalized = redact(value, env)
188
+ .replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu, ' ')
189
+ .replace(/\s+/gu, ' ')
190
+ .trim();
191
+ if (normalized.length === 0) return undefined;
192
+ return [...normalized].slice(0, LABEL_MAX_CHARS).join('').trimEnd();
193
+ }
194
+
195
+ function snapshotState(state: StepView['state']): SnapshotState | undefined {
196
+ // `pending` and `runnable` are states, but not publishable ones: a step that
197
+ // has not begun is neither completed nor running.
198
+ return state === 'pending' || state === 'runnable' ? undefined : state;
199
+ }
200
+
201
+ /** Cloud's own vocabulary for a live step, derived rather than carried. */
202
+ export function snapshotStepStatus(step: Pick<SnapshotStep, 'state' | 'completionReason'>):
203
+ 'running' | 'completed' | 'failed' {
204
+ if (step.state !== 'done') return 'running';
205
+ return step.completionReason === SUCCESS_COMPLETION_REASON ? 'completed' : 'failed';
206
+ }
207
+
208
+ function snapshotStep(journalRunId: string, step: StepView, env: NodeJS.ProcessEnv): SnapshotStep | undefined {
209
+ const state = snapshotState(step.state);
210
+ if (state === undefined) return undefined;
211
+ const stepName = identifier(step.id, env);
212
+ const journal = identifier(journalRunId, env);
213
+ const stepType = identifier(step.type, env);
214
+ if (stepName === undefined || journal === undefined || stepType === undefined) return undefined;
215
+ const transcript = step.last_attempt?.transcript ?? null;
216
+ const verification = step.last_attempt?.verification ?? null;
217
+ const gateName = verification === null ? undefined : identifier(verification.gate, env);
218
+ const gateVerdict = verification === null ? undefined : identifier(verification.verdict, env);
219
+ const paths = step.artifacts.paths
220
+ .slice(0, SNAPSHOT_ARTIFACTS_MAX)
221
+ .map(path => identifier(path, env, SNAPSHOT_ARTIFACT_MAX_CHARS))
222
+ .filter((path): path is string => path !== undefined);
223
+ const completionReason = identifier(step.completion_reason ?? step.last_attempt?.completion_reason, env);
224
+ const cost = transcript?.total_cost_usd;
225
+ return {
226
+ stepName,
227
+ journalRunId: journal,
228
+ stepType,
229
+ state,
230
+ attempt: int32(step.attempt) ?? 0,
231
+ elapsedMs: int32(step.elapsed_ms) ?? 0,
232
+ ...(completionReason === undefined ? {} : { completionReason }),
233
+ ...(gateName === undefined || gateVerdict === undefined ? {} : { gate: { name: gateName, verdict: gateVerdict } }),
234
+ ...(identifier(transcript?.model, env) === undefined ? {} : { model: identifier(transcript?.model, env)! }),
235
+ ...(int32(transcript?.num_turns) === undefined ? {} : { turns: int32(transcript?.num_turns)! }),
236
+ ...(int32(transcript?.tool_calls) === undefined ? {} : { toolCalls: int32(transcript?.tool_calls)! }),
237
+ ...(typeof cost === 'number' && Number.isFinite(cost) && cost >= 0 ? { costUsd: cost } : {}),
238
+ ...(step.artifacts.journaled ? { artifactCount: int32(step.artifacts.paths.length) ?? 0 } : {}),
239
+ ...(paths.length === 0 ? {} : { artifacts: paths }),
240
+ };
241
+ }
242
+
243
+ function isoAt(ms: number | null | undefined): string {
244
+ if (typeof ms !== 'number' || !Number.isFinite(ms)) return '';
245
+ const at = new Date(ms);
246
+ return Number.isNaN(at.getTime()) ? '' : at.toISOString();
247
+ }
248
+
249
+ /**
250
+ * The bounded `workflow_steps.detail` for one step: the attempt's journaled
251
+ * transcript digest, plus the attempt roster. The digest is already redacted
252
+ * and bounded where the worker wrote it (`agent-transcript.ts`); it is
253
+ * re-bounded here because this process, not that one, is what Cloud's parser
254
+ * will judge.
255
+ */
256
+ function stepDetail(
257
+ attempts: AttemptRecord[],
258
+ env: NodeJS.ProcessEnv,
259
+ ): { detail?: Record<string, unknown>; truncated?: true } {
260
+ const last = attempts.at(-1);
261
+ const digest = record(record(last?.trajectoryTail)?.['transcript']);
262
+ const roster = attempts.slice(-DETAIL_MAX_ATTEMPTS).map(entry => ({
263
+ attempt: entry.attempt,
264
+ atMs: entry.atMs,
265
+ completionReason: identifier(entry.completionReason, env) ?? 'unknown',
266
+ ...(identifier(entry.disposition, env) === undefined ? {} : { disposition: identifier(entry.disposition, env)! }),
267
+ ...(entry.transcriptBytes === undefined ? {} : { transcriptBytes: entry.transcriptBytes }),
268
+ }));
269
+ if (digest === undefined && roster.length <= 1) return {};
270
+ // The digest carries a sandbox-free copy of the transcript's facts. `file`
271
+ // names a path on *this* machine, which is neither useful to a reader of the
272
+ // dashboard nor something to publish; the byte counts beside it are.
273
+ const file = record(digest?.['file']);
274
+ const detail: Record<string, unknown> = {
275
+ ...(digest === undefined ? {} : {
276
+ transcript: {
277
+ ...digest,
278
+ ...(file === undefined ? {} : {
279
+ file: Object.fromEntries(Object.entries(file).filter(([key]) => key !== 'path')),
280
+ }),
281
+ },
282
+ }),
283
+ ...(roster.length === 0 ? {} : { attempts: roster }),
284
+ ...(attempts.length > roster.length ? { attemptsOmitted: attempts.length - roster.length } : {}),
285
+ };
286
+ if (Buffer.byteLength(JSON.stringify(detail), 'utf8') <= DETAIL_MAX_BYTES) return { detail };
287
+ // Over the cap: drop the transcript's free text and its tool roster — the
288
+ // largest fields by far — and say the detail was cut rather than dropping it
289
+ // whole, which would take the attempt history with it.
290
+ const transcript = record(detail['transcript']);
291
+ const reduced: Record<string, unknown> = {
292
+ ...(transcript === undefined ? {} : {
293
+ transcript: Object.fromEntries(
294
+ Object.entries(transcript).filter(([key]) => key === 'attempt' || key === 'exit_code'
295
+ || key === 'file' || key === 'result'),
296
+ ),
297
+ }),
298
+ ...(roster.length === 0 ? {} : { attempts: roster }),
299
+ };
300
+ if (Buffer.byteLength(JSON.stringify(reduced), 'utf8') <= DETAIL_MAX_BYTES) {
301
+ return { detail: reduced, truncated: true };
302
+ }
303
+ return { detail: { attempts: roster.slice(-1) }, truncated: true };
304
+ }
305
+
306
+ interface AttemptRecord {
307
+ attempt: number;
308
+ atMs: number;
309
+ completionReason: string;
310
+ disposition: string;
311
+ trajectoryTail: unknown;
312
+ transcriptBytes?: number;
313
+ transcriptPath?: string;
314
+ tokensIn?: number;
315
+ tokensOut?: number;
316
+ costUsd?: number;
317
+ }
318
+
319
+ /**
320
+ * Every `step.completed` the journal holds, in order, by step id.
321
+ *
322
+ * `foldRunState` keeps only the *last* attempt, because that is what a status
323
+ * view shows. The final report's `detail.attempts` is the whole roster, and
324
+ * its token totals are the sum across attempts, so both need the raw entries.
325
+ */
326
+ function attemptsByStep(events: readonly JournalEvent[]): Map<string, AttemptRecord[]> {
327
+ const byStep = new Map<string, AttemptRecord[]>();
328
+ for (const event of events) {
329
+ if (event.entry_type !== 'step.completed' || event.step_id === null) continue;
330
+ const payload = record(event.payload) ?? {};
331
+ const budget = record(payload['budget']) ?? {};
332
+ const digest = record(record(payload['trajectory_tail'])?.['transcript']);
333
+ const file = record(digest?.['file']);
334
+ const result = record(digest?.['result']);
335
+ const entries = byStep.get(event.step_id) ?? [];
336
+ entries.push({
337
+ attempt: event.attempt ?? entries.length + 1,
338
+ atMs: event.at_ms,
339
+ completionReason: typeof payload['completionReason'] === 'string' ? payload['completionReason'] : 'unknown',
340
+ disposition: typeof payload['disposition'] === 'string' ? payload['disposition'] : 'unknown',
341
+ trajectoryTail: payload['trajectory_tail'],
342
+ ...(int32(file?.['bytes_kept']) === undefined ? {} : { transcriptBytes: int32(file?.['bytes_kept'])! }),
343
+ ...(typeof file?.['path'] === 'string' ? { transcriptPath: file['path'] } : {}),
344
+ ...(int32(budget['tokens_in']) === undefined ? {} : { tokensIn: int32(budget['tokens_in'])! }),
345
+ ...(int32(budget['tokens_out']) === undefined ? {} : { tokensOut: int32(budget['tokens_out'])! }),
346
+ ...(typeof result?.['total_cost_usd'] === 'number' && Number.isFinite(result['total_cost_usd'])
347
+ && result['total_cost_usd'] >= 0
348
+ ? { costUsd: result['total_cost_usd'] as number } : {}),
349
+ });
350
+ byStep.set(event.step_id, entries);
351
+ }
352
+ return byStep;
353
+ }
354
+
355
+ function finalStep(
356
+ step: StepView,
357
+ attempts: AttemptRecord[],
358
+ env: NodeJS.ProcessEnv,
359
+ ): FinalStep | undefined {
360
+ const stepName = identifier(step.id, env);
361
+ const stepType = identifier(step.type, env);
362
+ if (stepName === undefined || stepType === undefined) return undefined;
363
+ const completionReason = step.completion_reason ?? step.last_attempt?.completion_reason ?? 'unknown';
364
+ const succeeded = completionReason === SUCCESS_COMPLETION_REASON;
365
+ const transcript = step.last_attempt?.transcript ?? null;
366
+ const startMs = step.started_at_ms;
367
+ const endMs = step.last_attempt?.ended_at_ms ?? null;
368
+ const duration = startMs !== null && endMs !== null ? Math.max(0, endMs - startMs) : (step.elapsed_ms ?? 0);
369
+ const tokensIn = attempts.reduce((total, entry) => total + (entry.tokensIn ?? 0), 0);
370
+ const tokensOut = attempts.reduce((total, entry) => total + (entry.tokensOut ?? 0), 0);
371
+ const failure = transcript?.failure ?? null;
372
+ // Summed across attempts, exactly as the tokens above are. Taking the last
373
+ // attempt's figure while summing its tokens was inconsistent in itself, and
374
+ // Cloud totals these rows for the run's spend — so a retried agent's earlier
375
+ // charges simply vanished from the run.
376
+ const spentUsd = attempts.reduce((total, entry) => total + (entry.costUsd ?? 0), 0);
377
+ const detail = stepDetail(attempts, env);
378
+ const verification = step.last_attempt?.verification ?? null;
379
+ // What the step said about itself. A gate's verdict detail is the nearest
380
+ // thing a deterministic step has to an agent's final message; an agent step
381
+ // has neither in the status view, so the completion reason stands alone
382
+ // rather than being invented.
383
+ const summary = text(verification?.detail, env, OUTPUT_SUMMARY_MAX_CHARS)
384
+ ?? `step ${succeeded ? 'completed' : 'ended'}: ${identifier(completionReason, env) ?? 'unknown'}`;
385
+ const model = identifier(transcript?.model, env);
386
+ const error = succeeded ? undefined : text(failure?.excerpt, env, ERROR_MAX_CHARS);
387
+ return {
388
+ stepName,
389
+ stepType,
390
+ // Cloud's legacy v1 columns. The kernel has no agent/preset/CLI identity
391
+ // per step, and an empty string is the honest answer the hosted v2
392
+ // executor gives too — never a guess that would render as a real name.
393
+ agent: '',
394
+ preset: '',
395
+ cli: '',
396
+ // Named after the uploaded transcript object once one is written, exactly
397
+ // as the sandbox does; empty until then, never a fabricated sandbox id.
398
+ sandboxId: '',
399
+ startTime: isoAt(startMs),
400
+ endTime: isoAt(endMs),
401
+ durationMs: int32(duration) ?? 0,
402
+ exitCode: succeeded ? 0 : 1,
403
+ outputSummary: summary,
404
+ status: succeeded ? 'completed' : 'failed',
405
+ completionReason: identifier(completionReason, env) ?? 'unknown',
406
+ retryCount: Math.max(0, attempts.length - 1),
407
+ ...(model === undefined ? {} : { model }),
408
+ ...(tokensIn > 0 ? { tokensInput: Math.min(tokensIn, MAX_INT32) } : {}),
409
+ ...(tokensOut > 0 ? { tokensOutput: Math.min(tokensOut, MAX_INT32) } : {}),
410
+ ...(spentUsd > 0 ? { costUsd: spentUsd } : {}),
411
+ ...(error === undefined ? {} : { error }),
412
+ ...(detail.detail === undefined ? {} : { detail: detail.detail }),
413
+ ...(detail.truncated === undefined ? {} : { detailTruncated: detail.truncated }),
414
+ };
415
+ }
416
+
417
+ /** Per-attempt transcript files this step left on disk, in attempt order. */
418
+ function transcriptRef(stepName: string, attempts: AttemptRecord[]): StepTranscriptRef | undefined {
419
+ const files = attempts
420
+ .filter((entry): entry is AttemptRecord & { transcriptPath: string } => entry.transcriptPath !== undefined)
421
+ .map(entry => ({ attempt: entry.attempt, path: entry.transcriptPath }));
422
+ return files.length === 0 ? undefined : { stepName, attempts: files };
423
+ }
424
+
425
+ /**
426
+ * Fold one journal into everything the mirror can say about it.
427
+ *
428
+ * The authored root is deliberately not published as a step: it spans the
429
+ * whole flow, so a snapshot carrying it would show one node called
430
+ * `authored-root` sitting at 100% for the run's entire duration beside the
431
+ * steps that actually did the work. Its journal is still read, for the step
432
+ * index that names the child journals and their graph edges.
433
+ */
434
+ export function mirrorJournal(
435
+ runId: string,
436
+ events: readonly JournalEvent[],
437
+ nowMs: number,
438
+ env: NodeJS.ProcessEnv = process.env,
439
+ ): MirroredJournal {
440
+ const view = foldRunState(events, nowMs);
441
+ const attempts = attemptsByStep(events);
442
+ const steps: SnapshotStep[] = [];
443
+ const finals: FinalStep[] = [];
444
+ const transcripts: StepTranscriptRef[] = [];
445
+ for (const step of view.steps) {
446
+ if (step.id === AUTHORED_ROOT_STEP) continue;
447
+ const live = snapshotStep(runId, step, env);
448
+ if (live !== undefined) steps.push(live);
449
+ const stepAttempts = attempts.get(step.id) ?? [];
450
+ if (step.state === 'done') {
451
+ const row = finalStep(step, stepAttempts, env);
452
+ if (row !== undefined) {
453
+ finals.push(row);
454
+ const ref = transcriptRef(row.stepName, stepAttempts);
455
+ if (ref !== undefined) transcripts.push(ref);
456
+ }
457
+ }
458
+ }
459
+ const index = authoredIndex(events, env);
460
+ // A declarative flow declares its edges in the spec, not in an authored-step
461
+ // stream — so a YAML run had no hints at all and drew every node
462
+ // unconnected. Read them from `run.spawned`, keyed the same way, and let the
463
+ // authored index win where both exist (an authored root's index is the
464
+ // richer record, and carries labels too).
465
+ const declared = declaredEdges(runId, events, env);
466
+ for (const [key, hint] of declared) {
467
+ if (!index.hints.has(key)) index.hints.set(key, hint);
468
+ }
469
+ return {
470
+ runId,
471
+ status: view.status,
472
+ terminal: view.status === 'completed' || view.status === 'failed' || view.status === 'cancelled',
473
+ steps,
474
+ finals,
475
+ transcripts,
476
+ children: index.children,
477
+ hints: index.hints,
478
+ };
479
+ }
480
+
481
+ /**
482
+ * An authored root's step index: which child journal runs each authored step,
483
+ * what the author called it, and what it came after.
484
+ *
485
+ * This is the only place those facts exist. A child journal's own view knows
486
+ * its kernel step ids and nothing about the authored graph above it, so
487
+ * without the root's index a mirrored authored run would show its steps with
488
+ * no names and no edges — which is exactly what the run graph draws from.
489
+ */
490
+ function authoredIndex(
491
+ events: readonly JournalEvent[],
492
+ env: NodeJS.ProcessEnv,
493
+ ): { children: string[]; hints: Map<string, { label?: string; after?: string[] }> } {
494
+ const messages: unknown[] = [];
495
+ for (const event of events) {
496
+ if (event.entry_type !== 'stream.appended') continue;
497
+ const payload = record(event.payload);
498
+ if (payload?.['stream'] === AUTHORED_STEP_STREAM) messages.push(payload['message']);
499
+ }
500
+ const children: string[] = [];
501
+ const hints = new Map<string, { label?: string; after?: string[] }>();
502
+ for (const entry of foldAuthoredStepRecords(messages).values()) {
503
+ if (/^[A-Za-z0-9][A-Za-z0-9_-]*$/u.test(entry.runId)) children.push(entry.runId);
504
+ const name = label(entry.label, env);
505
+ const after = entry.after === undefined
506
+ ? undefined
507
+ : [...entry.after]
508
+ .slice(0, DEPENDS_ON_MAX_ENTRIES)
509
+ .map(value => identifier(value, env))
510
+ .filter((value): value is string => value !== undefined);
511
+ if (name === undefined && after === undefined) continue;
512
+ hints.set(`${entry.runId}/${entry.step}`, {
513
+ ...(name === undefined ? {} : { label: name }),
514
+ ...(after === undefined ? {} : { after }),
515
+ });
516
+ }
517
+ return { children, hints };
518
+ }
519
+
520
+ /**
521
+ * The `depends_on` a declarative spec declares, as graph hints.
522
+ *
523
+ * `foldRunState` reads these to decide readiness but does not surface them on
524
+ * `StepView`, and deliberately: `flows status --json` is a pinned shape. So
525
+ * they are read here, straight off the `run.spawned` payload this fold already
526
+ * has in hand, rather than by widening a view other readers depend on.
527
+ */
528
+ function declaredEdges(
529
+ runId: string,
530
+ events: readonly JournalEvent[],
531
+ env: NodeJS.ProcessEnv,
532
+ ): Map<string, { after?: string[] }> {
533
+ const hints = new Map<string, { after?: string[] }>();
534
+ const spawned = events.find(event => event.entry_type === 'run.spawned');
535
+ const steps = record(spawned?.payload)?.['spec'];
536
+ const declared = record(steps)?.['steps'];
537
+ if (!Array.isArray(declared)) return hints;
538
+ for (const entry of declared) {
539
+ const step = record(entry);
540
+ const id = identifier(step?.['id'], env);
541
+ if (id === undefined) continue;
542
+ const raw = step?.['depends_on'] ?? step?.['dependsOn'];
543
+ if (!Array.isArray(raw)) continue;
544
+ const after = raw
545
+ .slice(0, DEPENDS_ON_MAX_ENTRIES)
546
+ .map(value => identifier(value, env))
547
+ .filter((value): value is string => value !== undefined);
548
+ hints.set(`${runId}/${id}`, { after });
549
+ }
550
+ return hints;
551
+ }
552
+
553
+ /**
554
+ * Build a snapshot envelope that actually fits both bounds.
555
+ *
556
+ * The count cap applies unconditionally — 65 tiny steps are 65 steps. Only
557
+ * then does the byte cap bite: first the artifact *names* go (their count
558
+ * survives), then the `dependsOn` edges, then whole entries from the head of
559
+ * the display order, because the tail is the newest work and that is what a
560
+ * live view exists to show. A capped view announces itself as incomplete;
561
+ * silently showing fewer steps than ran is the one thing it must not do.
562
+ */
563
+ export function fitSnapshot(
564
+ steps: readonly SnapshotStep[],
565
+ envelope: { sequence: number; capturedAt: string; alreadyOmitted?: number },
566
+ ): { sequence: number; capturedAt: string; truncated?: true; omittedStepCount?: number; steps: SnapshotStep[] } {
567
+ let kept = [...steps];
568
+ let omitted = envelope.alreadyOmitted ?? 0;
569
+ let truncated = omitted > 0;
570
+ if (kept.length > SNAPSHOT_MAX_STEPS) {
571
+ omitted += kept.length - SNAPSHOT_MAX_STEPS;
572
+ kept = kept.slice(kept.length - SNAPSHOT_MAX_STEPS);
573
+ truncated = true;
574
+ }
575
+ const build = (): { sequence: number; capturedAt: string; truncated?: true; omittedStepCount?: number; steps: SnapshotStep[] } => ({
576
+ sequence: envelope.sequence,
577
+ capturedAt: envelope.capturedAt,
578
+ ...(truncated ? { truncated: true as const } : {}),
579
+ ...(omitted > 0 ? { omittedStepCount: Math.min(omitted, MAX_INT32) } : {}),
580
+ steps: kept,
581
+ });
582
+ const bytes = (): number => Buffer.byteLength(JSON.stringify(build()), 'utf8');
583
+ if (bytes() <= SNAPSHOT_MAX_BYTES) return build();
584
+ kept = kept.map(({ artifacts: _artifacts, ...step }) => step);
585
+ truncated = true;
586
+ if (bytes() <= SNAPSHOT_MAX_BYTES) return build();
587
+ kept = kept.map(({ dependsOn: _dependsOn, ...step }) => step);
588
+ if (bytes() <= SNAPSHOT_MAX_BYTES) return build();
589
+ while (kept.length > 1 && bytes() > SNAPSHOT_MAX_BYTES) {
590
+ kept = kept.slice(1);
591
+ omitted += 1;
592
+ }
593
+ return build();
594
+ }
595
+
596
+ /** Apply an authored root's graph hints to a step, bounded for the live view. */
597
+ export function withGraphHints<T extends { stepName: string; journalRunId?: string }>(
598
+ step: T,
599
+ hints: Map<string, { label?: string; after?: string[] }>,
600
+ journalRunId: string,
601
+ maxDependsOn: number,
602
+ knownSteps: ReadonlySet<string>,
603
+ ): T & { label?: string; dependsOn?: string[] } {
604
+ const hint = hints.get(`${journalRunId}/${step.stepName}`);
605
+ if (hint === undefined) return step;
606
+ // Only predecessors that are themselves steps of this report: an edge to a
607
+ // node the graph does not contain draws nothing and reads as data loss.
608
+ const after = hint.after
609
+ ?.filter(name => name !== step.stepName && knownSteps.has(name))
610
+ .slice(0, maxDependsOn);
611
+ return {
612
+ ...step,
613
+ ...(hint.label === undefined ? {} : { label: hint.label }),
614
+ ...(after === undefined ? {} : { dependsOn: after }),
615
+ };
616
+ }
617
+
618
+ export type { RunView };