@milaboratories/pl-middle-layer 2.1.2 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/middle_layer/block_status_fold.cjs +382 -0
  2. package/dist/middle_layer/block_status_fold.cjs.map +1 -0
  3. package/dist/middle_layer/block_status_fold.js +373 -0
  4. package/dist/middle_layer/block_status_fold.js.map +1 -0
  5. package/dist/middle_layer/block_status_tree.cjs +287 -0
  6. package/dist/middle_layer/block_status_tree.cjs.map +1 -0
  7. package/dist/middle_layer/block_status_tree.js +283 -0
  8. package/dist/middle_layer/block_status_tree.js.map +1 -0
  9. package/dist/middle_layer/build_stamp.cjs +1 -1
  10. package/dist/middle_layer/build_stamp.js +1 -1
  11. package/dist/middle_layer/instance_stats.cjs +2 -2
  12. package/dist/middle_layer/instance_stats.cjs.map +1 -1
  13. package/dist/middle_layer/instance_stats.js +2 -2
  14. package/dist/middle_layer/instance_stats.js.map +1 -1
  15. package/dist/middle_layer/project.cjs +73 -2
  16. package/dist/middle_layer/project.cjs.map +1 -1
  17. package/dist/middle_layer/project.d.ts +22 -1
  18. package/dist/middle_layer/project.d.ts.map +1 -1
  19. package/dist/middle_layer/project.js +74 -3
  20. package/dist/middle_layer/project.js.map +1 -1
  21. package/dist/model/project_model.cjs +27 -0
  22. package/dist/model/project_model.cjs.map +1 -1
  23. package/dist/model/project_model.js +25 -1
  24. package/dist/model/project_model.js.map +1 -1
  25. package/dist/mutator/project.cjs +2 -1
  26. package/dist/mutator/project.cjs.map +1 -1
  27. package/dist/mutator/project.d.ts.map +1 -1
  28. package/dist/mutator/project.js +3 -2
  29. package/dist/mutator/project.js.map +1 -1
  30. package/dist/mutator/template/render_block.cjs +24 -0
  31. package/dist/mutator/template/render_block.cjs.map +1 -1
  32. package/dist/mutator/template/render_block.js +23 -2
  33. package/dist/mutator/template/render_block.js.map +1 -1
  34. package/package.json +14 -14
  35. package/src/middle_layer/block_status_bench.test.ts +197 -0
  36. package/src/middle_layer/block_status_fold.test.ts +694 -0
  37. package/src/middle_layer/block_status_fold.ts +563 -0
  38. package/src/middle_layer/block_status_tree.test.ts +253 -0
  39. package/src/middle_layer/block_status_tree.ts +391 -0
  40. package/src/middle_layer/instance_stats.test.ts +7 -9
  41. package/src/middle_layer/instance_stats.ts +2 -2
  42. package/src/middle_layer/project.ts +111 -2
  43. package/src/middle_layer/project_pruning.test.ts +59 -0
  44. package/src/model/project_model.ts +30 -0
  45. package/src/mutator/project.ts +7 -1
  46. package/src/mutator/project_action_context.test.ts +13 -3
  47. package/src/mutator/template/render_block.ts +32 -2
@@ -0,0 +1,563 @@
1
+ /**
2
+ * Folds a block's action-context tree into the {@link BlockStatusSummary} the Desktop App shows.
3
+ *
4
+ * The fold runs bottom up: {@link foldContext} reads one context on its own, and
5
+ * {@link mergeSubtree} merges it with the folds of its children. Over a synchronized tree each
6
+ * context gets its own computable (see `block_status_tree.ts`), so a report re-reads only the
7
+ * context it landed in and re-merges the contexts above it; the rest of the tree is not read
8
+ * again.
9
+ *
10
+ * The fold attaches no meaning to the states the reporters write, beyond the lifecycle the backend
11
+ * fixes: a context ends in `Completed` or `Terminated`, and a command's `Running` is work on a
12
+ * machine. Jobs are counted per state as reported, so a state added on the backend reaches the
13
+ * Desktop App without a middle layer release.
14
+ */
15
+
16
+ import type {
17
+ BlockStatusJobGroup,
18
+ BlockStatusJobs,
19
+ BlockStatusSummary,
20
+ } from "@milaboratories/pl-model-middle-layer";
21
+ import {
22
+ blockStatusStatesRecord,
23
+ isTerminalBlockStatusState,
24
+ } from "@milaboratories/pl-model-middle-layer";
25
+
26
+ /**
27
+ * A key-value written as a JSON object, with its fields unchecked; undefined for anything else.
28
+ * A reporter may write any JSON, so `null` or a bare number must not reach a field read.
29
+ */
30
+ function parseJsonObject(value: string): Record<string, unknown> | undefined {
31
+ let parsed: unknown;
32
+ try {
33
+ parsed = JSON.parse(value);
34
+ } catch {
35
+ return undefined;
36
+ }
37
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return undefined;
38
+ return Object.fromEntries(Object.entries(parsed));
39
+ }
40
+
41
+ /** The part of an action context a fold reads. A tree node accessor satisfies it. */
42
+ export interface ActionContextNode {
43
+ /** Stable identity of the context, for deduplicating a walk. */
44
+ readonly id: string;
45
+ /** The context's baggage: `name`, `block-pack`, `block-id`, `run-id`. */
46
+ getData(): Record<string, unknown> | undefined;
47
+ /** KV entries under a prefix, values as text. */
48
+ listKeyValuesAsString(prefix: string): { key: string; value: string }[];
49
+ /** Field names, whatever their type: the children are `child/<render>`. */
50
+ listFields(): string[];
51
+ /** The context a field points at, or undefined while the field is unset. */
52
+ traverse(field: string): ActionContextNode | undefined;
53
+ }
54
+
55
+ /**
56
+ * How deep the fold follows `child/<render>`.
57
+ *
58
+ * A stack guard, not a correctness device: a context already on the path is skipped, and the depth
59
+ * of a real tree is the nesting depth of the templates, far below this.
60
+ */
61
+ export const MaxDepth = 256;
62
+
63
+ /** Prefix of the field names holding child contexts. */
64
+ const ChildFieldPrefix = "child/";
65
+
66
+ /** Prefix of the transition keys: `transition/<namespace>/<resource>/<ns>`. */
67
+ const TransitionPrefix = "transition/";
68
+
69
+ /** Prefix of the reading keys: `reading/<namespace>/<resource>/<key>`. */
70
+ const ReadingPrefix = "reading/";
71
+
72
+ /** The namespace the workflow controller reports a render's own lifecycle under. */
73
+ const RenderNamespace = "render";
74
+
75
+ /**
76
+ * The namespace the creator of a context reports under. The middle layer records `Terminated` here
77
+ * on the root when the user stops the run, see `recordBlockRunCancelled`.
78
+ */
79
+ const CreatorNamespace = "core";
80
+
81
+ /** The namespace a command reports under; its `Running` means a job executing on a machine. */
82
+ const ExecNamespace = "exec";
83
+
84
+ /** The namespace a job's work folder reports under. */
85
+ const WorkdirNamespace = "workdir";
86
+
87
+ /** One transition, as stored under `transition/<namespace>/<resource>/<ns>`. */
88
+ export type Transition = {
89
+ namespace: string;
90
+ /** The resource that reported: the render itself, or a command or work dir it created. */
91
+ reporter: string;
92
+ /** The reporter's clock in nanoseconds, as the decimal string the key carries. */
93
+ ns: string;
94
+ /** As the reporter wrote it, whether or not this build knows the name. */
95
+ state: string;
96
+ detail: string;
97
+ reason: string;
98
+ };
99
+
100
+ /** What one context reported. */
101
+ export type ContextReports = {
102
+ /** Every transition whose key and value parse. */
103
+ all: Transition[];
104
+ /** The earliest and latest timestamp of any transition key, even one whose value does not
105
+ * parse: a report arriving is evidence the run moved whatever it says. */
106
+ firstNs?: string;
107
+ lastNs?: string;
108
+ };
109
+
110
+ /** A node of the tree, reduced to what the summary needs. */
111
+ export type FoldedNode = {
112
+ /** True when the render of this context has ended and nothing it started is still running. */
113
+ terminal: boolean;
114
+ /** The reason, set when the render itself ended in a termination rather than a completion. */
115
+ failure?: string;
116
+ /** The transition holding this node, undefined when it is terminal or has not reported. */
117
+ holding?: Transition;
118
+ /** True when {@link FoldedNode.holding} is `Running` reported by a command. */
119
+ onMachine: boolean;
120
+ };
121
+
122
+ /** Compares non-negative decimal integers given as strings, shorter is smaller. */
123
+ export function compareNs(a: string, b: string): number {
124
+ return a.length !== b.length ? a.length - b.length : a < b ? -1 : a > b ? 1 : 0;
125
+ }
126
+
127
+ /** Nanoseconds since the epoch, as the key carries them, to milliseconds. */
128
+ export function nsToMs(ns: string): number {
129
+ return Number(BigInt(ns) / 1_000_000n);
130
+ }
131
+
132
+ function earlier(a: string | undefined, b: string | undefined): string | undefined {
133
+ return a === undefined || (b !== undefined && compareNs(b, a) < 0) ? b : a;
134
+ }
135
+
136
+ function later(a: string | undefined, b: string | undefined): string | undefined {
137
+ return a === undefined || (b !== undefined && compareNs(b, a) > 0) ? b : a;
138
+ }
139
+
140
+ /**
141
+ * How strongly a report claims to be what holds a node.
142
+ *
143
+ * The render's own `Running` means only that template code is being evaluated, and the workflow
144
+ * controller records it again on every evaluation, so it routinely carries a newer timestamp than
145
+ * the wait that actually holds the node. Anything else outranks it however old it is, including a
146
+ * command's `Running`, which is real work. Recency decides only between equal ranks.
147
+ */
148
+ function rank(t: Transition): number {
149
+ return t.state === blockStatusStatesRecord.Running && t.namespace === RenderNamespace ? 0 : 1;
150
+ }
151
+
152
+ /**
153
+ * The transitions of one context.
154
+ *
155
+ * A value that is not the JSON the reporters write is left out: a report is diagnostic, and a
156
+ * malformed one must not break the surface. Its timestamp still counts.
157
+ */
158
+ export function readTransitions(node: ActionContextNode): ContextReports {
159
+ const out: ContextReports = { all: [] };
160
+
161
+ for (const { key, value } of node.listKeyValuesAsString(TransitionPrefix)) {
162
+ const parts = key.split("/");
163
+ if (parts.length !== 4) continue;
164
+ const [, namespace, reporter, ns] = parts;
165
+ // Leading zeros would break the length-first comparison, and no reporter writes them.
166
+ if (!/^(0|[1-9]\d*)$/.test(ns)) continue;
167
+
168
+ out.firstNs = earlier(out.firstNs, ns);
169
+ out.lastNs = later(out.lastNs, ns);
170
+
171
+ const parsed = parseJsonObject(value);
172
+ if (parsed === undefined) continue;
173
+ const state = parsed.state;
174
+ if (typeof state !== "string") continue;
175
+ const detail = typeof parsed.detail === "string" ? parsed.detail : "";
176
+ const reason = typeof parsed.reason === "string" ? parsed.reason : "";
177
+ out.all.push({ namespace, reporter, ns, state, detail, reason });
178
+ }
179
+
180
+ return out;
181
+ }
182
+
183
+ /**
184
+ * Reduces one context to {@link FoldedNode}.
185
+ *
186
+ * A context carries the reports of several reporters: the render reports under `render`, and the
187
+ * commands and work dirs it created report under `exec` and `workdir`. The latest transition of
188
+ * each reporter is that reporter's current state, and the state holding the node is the strongest
189
+ * of those a reporter has not left, see {@link rank}.
190
+ *
191
+ * The node has ended when the render has reported its own end (`Completed` once its outputs are
192
+ * set, `Terminated` with its error, or `Completed` with detail `deduplicated`) and every other
193
+ * reporter in the context has ended too: the render's outputs being set does not stop a command it
194
+ * started, and that command's report must stay visible.
195
+ */
196
+ export function foldNode(transitions: readonly Transition[]): FoldedNode {
197
+ const latestPerReporter = new Map<string, Transition>();
198
+ for (const t of transitions) {
199
+ const reporterKey = `${t.namespace}/${t.reporter}`;
200
+ const previous = latestPerReporter.get(reporterKey);
201
+ if (previous === undefined || compareNs(t.ns, previous.ns) > 0)
202
+ latestPerReporter.set(reporterKey, t);
203
+ }
204
+
205
+ let render: Transition | undefined;
206
+ let holding: Transition | undefined;
207
+ let everyReporterEnded = true;
208
+ for (const t of latestPerReporter.values()) {
209
+ if (t.namespace === RenderNamespace) render = t;
210
+ if (isTerminalBlockStatusState(t.state)) continue;
211
+ everyReporterEnded = false;
212
+ if (holding === undefined) {
213
+ holding = t;
214
+ continue;
215
+ }
216
+ const byRank = rank(t) - rank(holding);
217
+ if (byRank > 0 || (byRank === 0 && compareNs(t.ns, holding.ns) > 0)) holding = t;
218
+ }
219
+
220
+ if (render !== undefined && isTerminalBlockStatusState(render.state) && everyReporterEnded)
221
+ return {
222
+ terminal: true,
223
+ onMachine: false,
224
+ failure: render.state === blockStatusStatesRecord.Terminated ? render.reason : undefined,
225
+ };
226
+
227
+ return {
228
+ terminal: false,
229
+ holding,
230
+ onMachine:
231
+ holding?.state === blockStatusStatesRecord.Running && holding.namespace === ExecNamespace,
232
+ };
233
+ }
234
+
235
+ /** The render's own latest transition in a context. */
236
+ export function latestRender(transitions: readonly Transition[]): Transition | undefined {
237
+ let latest: Transition | undefined;
238
+ for (const t of transitions)
239
+ if (t.namespace === RenderNamespace && (latest === undefined || compareNs(t.ns, latest.ns) > 0))
240
+ latest = t;
241
+ return latest;
242
+ }
243
+
244
+ /** One reading, as stored under `reading/<namespace>/<resource>/<key>`. */
245
+ export type Reading = { namespace: string; resource: string; key: string; value: string };
246
+
247
+ /** One context read on its own, before its children are merged in. */
248
+ export type ContextFold = {
249
+ readonly id: string;
250
+ /** The baggage: `name`, `block-pack`, `block-id`, `run-id`. */
251
+ readonly data: Record<string, unknown> | undefined;
252
+ readonly reports: ContextReports;
253
+ readonly readings: readonly Reading[];
254
+ readonly folded: FoldedNode;
255
+ /** True for a context a command or its work folder reports in: one job. */
256
+ readonly job: boolean;
257
+ /** The render's own latest transition, when it is a termination. */
258
+ readonly terminated?: { readonly reason: string; readonly ns: string };
259
+ };
260
+
261
+ function readReadings(node: ActionContextNode): Reading[] {
262
+ const out: Reading[] = [];
263
+ for (const { key, value } of node.listKeyValuesAsString(ReadingPrefix)) {
264
+ const parts = key.split("/");
265
+ if (parts.length !== 4) continue;
266
+ out.push({ namespace: parts[1], resource: parts[2], key: parts[3], value });
267
+ }
268
+ return out;
269
+ }
270
+
271
+ /** Reads one context: its transitions, its readings, and the state holding it. */
272
+ export function foldContext(node: ActionContextNode): ContextFold {
273
+ const reports = readTransitions(node);
274
+ const render = latestRender(reports.all);
275
+ return {
276
+ id: node.id,
277
+ data: node.getData(),
278
+ reports,
279
+ readings: readReadings(node),
280
+ folded: foldNode(reports.all),
281
+ job: reports.all.some((t) => t.namespace === ExecNamespace || t.namespace === WorkdirNamespace),
282
+ terminated:
283
+ render?.state === blockStatusStatesRecord.Terminated
284
+ ? { reason: render.reason, ns: render.ns }
285
+ : undefined,
286
+ };
287
+ }
288
+
289
+ /** {@link BlockStatusJobGroup} being accumulated, its timestamp still in nanoseconds. */
290
+ type JobGroupTally = {
291
+ readonly namespace: string;
292
+ readonly state: string;
293
+ readonly count: number;
294
+ readonly sinceNs?: string;
295
+ readonly files?: { readonly done: number; readonly total: number };
296
+ };
297
+
298
+ /**
299
+ * {@link BlockStatusJobs} being accumulated over a subtree. Plain data throughout, no `Map`: it is
300
+ * the value of a computable, which the computable types map over field by field.
301
+ */
302
+ export type JobTally = {
303
+ readonly total: number;
304
+ readonly done: number;
305
+ readonly failed: number;
306
+ /** Jobs not ended, by `<namespace>/<state>` of the transition holding each. */
307
+ readonly groups: Readonly<Record<string, JobGroupTally>>;
308
+ };
309
+
310
+ const EmptyJobTally: JobTally = { total: 0, done: 0, failed: 0, groups: {} };
311
+
312
+ /** A context and everything under it, folded. */
313
+ export type SubtreeFold = {
314
+ readonly own: ContextFold;
315
+ readonly children: readonly SubtreeFold[];
316
+ /** This context and every context under it. */
317
+ readonly contexts: number;
318
+ /** Contexts in the subtree that have not ended. */
319
+ readonly activeContexts: number;
320
+ readonly firstNs?: string;
321
+ readonly lastNs?: string;
322
+ /** The earliest render in the subtree whose latest report is a termination. */
323
+ readonly failure?: { readonly reason: string; readonly ns: string };
324
+ readonly jobs: JobTally;
325
+ };
326
+
327
+ /** Files done of all, summed over the work folders' progress readings of one context. */
328
+ function workdirProgress(readings: readonly Reading[]): JobGroupTally["files"] {
329
+ let progress: JobGroupTally["files"];
330
+ for (const r of readings) {
331
+ if (r.namespace !== WorkdirNamespace || r.key !== "progress") continue;
332
+ const parsed = parseJsonObject(r.value);
333
+ if (typeof parsed?.done !== "number" || typeof parsed.total !== "number") continue;
334
+ progress = addFiles(progress, { done: parsed.done, total: parsed.total });
335
+ }
336
+ return progress;
337
+ }
338
+
339
+ function addFiles(a: JobGroupTally["files"], b: JobGroupTally["files"]): JobGroupTally["files"] {
340
+ if (a === undefined) return b;
341
+ if (b === undefined) return a;
342
+ return { done: a.done + b.done, total: a.total + b.total };
343
+ }
344
+
345
+ function groupKey(group: Pick<JobGroupTally, "namespace" | "state">): string {
346
+ return `${group.namespace}/${group.state}`;
347
+ }
348
+
349
+ function mergeGroup(
350
+ groups: Record<string, JobGroupTally>,
351
+ key: string,
352
+ group: JobGroupTally,
353
+ ): void {
354
+ const previous = groups[key];
355
+ groups[key] =
356
+ previous === undefined
357
+ ? group
358
+ : {
359
+ namespace: group.namespace,
360
+ state: group.state,
361
+ count: previous.count + group.count,
362
+ sinceNs: earlier(previous.sinceNs, group.sinceNs),
363
+ files: addFiles(previous.files, group.files),
364
+ };
365
+ }
366
+
367
+ /** The job a context is, counted where it is now; empty when it is not one. */
368
+ function ownJobs(own: ContextFold): JobTally {
369
+ if (!own.job) return EmptyJobTally;
370
+ const { terminal, failure, holding } = own.folded;
371
+ if (terminal)
372
+ return failure === undefined
373
+ ? { ...EmptyJobTally, total: 1, done: 1 }
374
+ : { ...EmptyJobTally, total: 1, failed: 1 };
375
+ if (holding === undefined) return { ...EmptyJobTally, total: 1 };
376
+ const group: JobGroupTally = {
377
+ namespace: holding.namespace,
378
+ state: holding.state,
379
+ count: 1,
380
+ sinceNs: holding.ns,
381
+ files: workdirProgress(own.readings),
382
+ };
383
+ return { ...EmptyJobTally, total: 1, groups: { [groupKey(group)]: group } };
384
+ }
385
+
386
+ /**
387
+ * Merges a context with the folds of its children. One pass over the direct children, so a report
388
+ * re-merges each context on its path to the root and nothing else.
389
+ */
390
+ export function mergeSubtree(own: ContextFold, children: readonly SubtreeFold[]): SubtreeFold {
391
+ let contexts = 1;
392
+ let activeContexts = own.folded.terminal ? 0 : 1;
393
+ let firstNs = own.reports.firstNs;
394
+ let lastNs = own.reports.lastNs;
395
+ let failure = own.terminated;
396
+ let failedBelow = false;
397
+
398
+ const self = ownJobs(own);
399
+ let { total, done, failed } = self;
400
+ const groups: Record<string, JobGroupTally> = { ...self.groups };
401
+
402
+ for (const child of children) {
403
+ contexts += child.contexts;
404
+ activeContexts += child.activeContexts;
405
+ firstNs = earlier(firstNs, child.firstNs);
406
+ lastNs = later(lastNs, child.lastNs);
407
+ if (child.failure !== undefined) {
408
+ failedBelow = true;
409
+ if (failure === undefined || compareNs(child.failure.ns, failure.ns) < 0)
410
+ failure = child.failure;
411
+ }
412
+ total += child.jobs.total;
413
+ done += child.jobs.done;
414
+ failed += child.jobs.failed;
415
+ for (const [key, group] of Object.entries(child.jobs.groups)) mergeGroup(groups, key, group);
416
+ }
417
+
418
+ // A render that failed on its own, e.g. one whose command could not start, is a failed job too;
419
+ // one that only passes up the failure under it is not counted again.
420
+ if (own.terminated !== undefined && !failedBelow && !own.job) {
421
+ total++;
422
+ failed++;
423
+ }
424
+
425
+ return {
426
+ own,
427
+ children,
428
+ contexts,
429
+ activeContexts,
430
+ firstNs,
431
+ lastNs,
432
+ failure,
433
+ jobs: { total, done, failed, groups },
434
+ };
435
+ }
436
+
437
+ /**
438
+ * The child contexts a fold follows: each once, and none already on the path from the root, so a
439
+ * context linked twice or a cycle cannot count a subtree again.
440
+ */
441
+ export function childContexts<T extends { readonly id: unknown }>(
442
+ fields: readonly string[],
443
+ traverse: (field: string) => T | undefined,
444
+ path: ReadonlySet<string>,
445
+ ): T[] {
446
+ if (path.size > MaxDepth) return [];
447
+ const out: T[] = [];
448
+ const seen = new Set<string>();
449
+ for (const field of fields) {
450
+ if (!field.startsWith(ChildFieldPrefix)) continue;
451
+ const child = traverse(field);
452
+ if (child === undefined) continue;
453
+ const id = String(child.id);
454
+ if (path.has(id) || seen.has(id)) continue;
455
+ seen.add(id);
456
+ out.push(child);
457
+ }
458
+ return out;
459
+ }
460
+
461
+ /**
462
+ * Folds a context and everything under it in one walk: what the per-context computables compute,
463
+ * for a tree that is read once.
464
+ */
465
+ export function foldSubtree(
466
+ node: ActionContextNode,
467
+ path: ReadonlySet<string> = new Set(),
468
+ ): SubtreeFold {
469
+ const below = new Set(path).add(node.id);
470
+ const children = childContexts(node.listFields(), (f) => node.traverse(f), below);
471
+ return mergeSubtree(
472
+ foldContext(node),
473
+ children.map((child) => foldSubtree(child, below)),
474
+ );
475
+ }
476
+
477
+ /** Where the backend nests the error of an input inside the error of what consumes it. */
478
+ const InputErrorMarker = "has input errors:";
479
+
480
+ /** Wrappers the workflow controller puts in front of a template's own error. */
481
+ const TemplateErrorPrefix = /^(cannot eval code: |cannot eval template: |tengo template error: )+/;
482
+
483
+ /** Longest headline, in characters. */
484
+ const MaxHeadlineLength = 200;
485
+
486
+ /**
487
+ * The innermost message of a termination reason, for a title: the backend wraps the error of each
488
+ * input in the error of its consumer, and tengo appends stack frames, so a reason can run to pages.
489
+ */
490
+ export function failureHeadline(reason: string): string {
491
+ const marker = reason.lastIndexOf(InputErrorMarker);
492
+ const lines = reason
493
+ .slice(marker < 0 ? 0 : marker + InputErrorMarker.length)
494
+ .split("\n")
495
+ .map((line) => line.trim())
496
+ // Stack frames: `@platforma-sdk/workflow-tengo:tpl.base:595:5`.
497
+ .filter((line) => line !== "" && !/^@\S+:\d+:\d+$/.test(line));
498
+
499
+ const text = lines.join(" ");
500
+ // A command that failed: `Command ID: … Command name: "python" … Error: docker is not set`.
501
+ const command = /Command name: "([^"]*)".*\bError: (.+)$/.exec(text);
502
+ const headline =
503
+ command !== null
504
+ ? `${command[1]} failed: ${command[2]}`
505
+ : text.replace(TemplateErrorPrefix, "");
506
+ return headline.length > MaxHeadlineLength
507
+ ? `${headline.slice(0, MaxHeadlineLength - 1)}…`
508
+ : headline;
509
+ }
510
+
511
+ function finishJobs(jobs: JobTally): BlockStatusJobs {
512
+ const byState = Object.values(jobs.groups)
513
+ .map((g): BlockStatusJobGroup => ({
514
+ namespace: g.namespace,
515
+ state: g.state,
516
+ count: g.count,
517
+ since: g.sinceNs === undefined ? undefined : nsToMs(g.sinceNs),
518
+ files: g.files,
519
+ }))
520
+ .sort((a, b) => b.count - a.count || groupKey(a).localeCompare(groupKey(b)));
521
+ return { total: jobs.total, done: jobs.done, failed: jobs.failed, byState };
522
+ }
523
+
524
+ /** The summary of a block run, from the fold of its root action context. */
525
+ export function summarize(root: SubtreeFold): BlockStatusSummary {
526
+ const runId = root.own.data?.["run-id"];
527
+ const jobs = finishJobs(root.jobs);
528
+ const summary = {
529
+ availability: "read" as const,
530
+ runId: typeof runId === "string" ? runId : undefined,
531
+ activeContexts: root.activeContexts,
532
+ totalContexts: root.contexts,
533
+ jobs,
534
+ startedAt: root.firstNs === undefined ? undefined : nsToMs(root.firstNs),
535
+ };
536
+
537
+ // A stopped run: its render is gone and reports nothing more, so the tree is frozen where it
538
+ // stopped. The counters stay, to say where each node was; the run itself is over.
539
+ let cancelledNs: string | undefined;
540
+ for (const t of root.own.reports.all)
541
+ if (t.namespace === CreatorNamespace && t.state === blockStatusStatesRecord.Terminated)
542
+ cancelledNs = later(cancelledNs, t.ns);
543
+ if (cancelledNs !== undefined)
544
+ return { ...summary, lastChangeAt: nsToMs(cancelledNs), done: true, cancelled: true };
545
+
546
+ // A terminated render fails the run. Renders waiting on its outputs never report again, so once
547
+ // no job is held by its command or work folder the run is over, though they still look active.
548
+ const working = jobs.byState.some((g) => g.namespace !== RenderNamespace);
549
+ return {
550
+ ...summary,
551
+ lastChangeAt: root.lastNs === undefined ? undefined : nsToMs(root.lastNs),
552
+ // The root's outputs can be set while work it started still runs, so done needs both.
553
+ done:
554
+ (root.own.folded.terminal && root.activeContexts === 0) ||
555
+ (root.failure !== undefined && !working),
556
+ failure: root.failure === undefined ? undefined : failureHeadline(root.failure.reason),
557
+ };
558
+ }
559
+
560
+ /** The summary of a block run, from the root action context of its render. */
561
+ export function foldBlockStatus(root: ActionContextNode): BlockStatusSummary {
562
+ return summarize(foldSubtree(root));
563
+ }