@niwa-labs/workflow 0.0.0-stage → 0.0.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 (114) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +13 -2
  3. package/package.json +55 -4
  4. package/src/actions.ts +408 -0
  5. package/src/agent.ts +211 -0
  6. package/src/ask.ts +84 -0
  7. package/src/bridge.ts +710 -0
  8. package/src/catalogue.ts +74 -0
  9. package/src/check.ts +880 -0
  10. package/src/child.ts +1378 -0
  11. package/src/cockpit/actions.ts +128 -0
  12. package/src/cockpit/catalogue-actions.ts +97 -0
  13. package/src/cockpit/dashboard.tsx +134 -0
  14. package/src/cockpit/groups.ts +45 -0
  15. package/src/cockpit/index.tsx +50 -0
  16. package/src/cockpit/launch.tsx +136 -0
  17. package/src/cockpit/plan.ts +101 -0
  18. package/src/cockpit/run-commands.tsx +102 -0
  19. package/src/cockpit/run-page.tsx +140 -0
  20. package/src/cockpit/run-summary.ts +16 -0
  21. package/src/cockpit/runs.tsx +73 -0
  22. package/src/cockpit/statistics.tsx +176 -0
  23. package/src/cockpit/track.tsx +159 -0
  24. package/src/cockpit/workflows.tsx +383 -0
  25. package/src/describe-cache.ts +122 -0
  26. package/src/describe.ts +174 -0
  27. package/src/guide.ts +213 -0
  28. package/src/index.ts +2813 -0
  29. package/src/inspect.ts +235 -0
  30. package/src/installation.ts +90 -0
  31. package/src/language.ts +217 -0
  32. package/src/records-entry.ts +63 -0
  33. package/src/records.ts +574 -0
  34. package/src/registry.ts +250 -0
  35. package/src/revise.ts +89 -0
  36. package/src/runner.ts +339 -0
  37. package/src/script-types.ts +549 -0
  38. package/src/stats.ts +460 -0
  39. package/src/status.ts +512 -0
  40. package/src/store.ts +259 -0
  41. package/src/subscriptions.ts +102 -0
  42. package/src/waiting.ts +61 -0
  43. package/test/cockpit-actions.test.ts +20 -0
  44. package/test/cockpit-groups.test.ts +42 -0
  45. package/test/cockpit-plan.test.ts +118 -0
  46. package/test/fixtures/branches-host.ts +58 -0
  47. package/test/fixtures/branches-script.js +23 -0
  48. package/test/fixtures/bridge-host.ts +23 -0
  49. package/test/fixtures/bridge-keys-script.js +15 -0
  50. package/test/fixtures/bridge-wait-script.js +8 -0
  51. package/test/fixtures/cancel-host.ts +58 -0
  52. package/test/fixtures/cancel-script.js +12 -0
  53. package/test/fixtures/crash-host.ts +61 -0
  54. package/test/fixtures/crash-script.js +14 -0
  55. package/test/fixtures/ping-records.ts +20 -0
  56. package/test/fixtures/revision-host.ts +57 -0
  57. package/test/fixtures/revision-script.js +11 -0
  58. package/test/fixtures/running-host.ts +61 -0
  59. package/test/fixtures/running-script.js +12 -0
  60. package/test/fixtures/with-data/flow.ts +2 -0
  61. package/test/fixtures/with-data/table.json +1 -0
  62. package/test/git-repo.ts +45 -0
  63. package/test/git-worktree.test.ts +413 -0
  64. package/test/question-format.test.ts +279 -0
  65. package/test/workflow-agent-caps.test.ts +91 -0
  66. package/test/workflow-agent-lifetime.test.ts +93 -0
  67. package/test/workflow-agent-options.test.ts +216 -0
  68. package/test/workflow-agent-schema.test.ts +386 -0
  69. package/test/workflow-agent-typings.test.ts +241 -0
  70. package/test/workflow-ask-resume.test.ts +145 -0
  71. package/test/workflow-branch-keys.test.ts +133 -0
  72. package/test/workflow-bridge-inproc.test.ts +230 -0
  73. package/test/workflow-bridge.test.ts +141 -0
  74. package/test/workflow-builtin-candidate.test.ts +230 -0
  75. package/test/workflow-builtin.test.ts +197 -0
  76. package/test/workflow-cancel-agent.test.ts +144 -0
  77. package/test/workflow-cancel.test.ts +166 -0
  78. package/test/workflow-chain.test.ts +84 -0
  79. package/test/workflow-check-options.test.ts +144 -0
  80. package/test/workflow-check-uses.test.ts +148 -0
  81. package/test/workflow-check.test.ts +282 -0
  82. package/test/workflow-contract.test.ts +295 -0
  83. package/test/workflow-crash-resume.test.ts +141 -0
  84. package/test/workflow-deadline.test.ts +102 -0
  85. package/test/workflow-describe-cache.test.ts +240 -0
  86. package/test/workflow-directory.test.ts +73 -0
  87. package/test/workflow-emits.test.ts +261 -0
  88. package/test/workflow-group-keys.test.ts +72 -0
  89. package/test/workflow-harnesses.test.ts +262 -0
  90. package/test/workflow-inspect.test.ts +152 -0
  91. package/test/workflow-language-types.test.ts +148 -0
  92. package/test/workflow-manifest.test.ts +93 -0
  93. package/test/workflow-manual-pause.test.ts +116 -0
  94. package/test/workflow-owners.test.ts +154 -0
  95. package/test/workflow-pause.test.ts +200 -0
  96. package/test/workflow-phases.test.ts +445 -0
  97. package/test/workflow-plugin-entries.test.ts +59 -0
  98. package/test/workflow-record-refs.test.ts +310 -0
  99. package/test/workflow-replay.test.ts +206 -0
  100. package/test/workflow-resume-once.test.ts +188 -0
  101. package/test/workflow-revision.test.ts +216 -0
  102. package/test/workflow-scope.test.ts +505 -0
  103. package/test/workflow-script-defaults.test.ts +119 -0
  104. package/test/workflow-script-error.test.ts +228 -0
  105. package/test/workflow-script-libraries.test.ts +88 -0
  106. package/test/workflow-script-packages.test.ts +119 -0
  107. package/test/workflow-stdout.test.ts +89 -0
  108. package/test/workflow-stop.test.ts +299 -0
  109. package/test/workflow-store.test.ts +220 -0
  110. package/test/workflow-visible.test.ts +136 -0
  111. package/test/workflow-wait-version.test.ts +54 -0
  112. package/test/workflow-wait.test.ts +224 -0
  113. package/test/workflow-waiting-agent.test.ts +64 -0
  114. package/tsconfig.json +15 -0
package/src/status.ts ADDED
@@ -0,0 +1,512 @@
1
+ /**
2
+ * What a run is now, read from the journal: the state a caller waits
3
+ * for and the line a list of runs shows. Nothing here is stored: the facts are the records of the
4
+ * run and of its invocation.
5
+ */
6
+
7
+ import { CORE_TYPES, runIdOfPrincipal, offeredChoices, seq, shortRun } from "@niwa-labs/core";
8
+ import type { JournalReader, RecordTypeName, StoredRecord } from "@niwa-labs/core";
9
+ import { RequestAnswered, RequestCancelledRecord, RequestCreated, RequestExpiredRecord, fold } from "@niwa-labs/requests/records";
10
+ import type { Address } from "@niwa-labs/core";
11
+ import type { RequestId } from "@niwa-labs/requests/records";
12
+ import { PendingExternalItemSchema } from "@niwa-labs/plugin";
13
+ import { z } from "zod";
14
+
15
+ import { WorkflowPhase } from "./language.ts";
16
+ import { PhaseEntered, PhaseLeft, RunContinued, RunDeadlineExtended, RunFinished, RunHoldRequested, RunOutcome, RunPaused, RunPauseRequested, RunRequested, RunStarted } from "./records.ts";
17
+ import { waitingFor } from "./waiting.ts";
18
+
19
+ /** What a run is: it goes on, it waits for a decision, or it ended. */
20
+ export const RunState = z.enum(["running", "paused", "finished"]);
21
+ export type RunState = z.infer<typeof RunState>;
22
+
23
+ /** Where a run is in a declared phase: a branch is in it now, it was passed, or it is still to come. */
24
+ export const PhaseState = z.enum(["done", "current", "ahead"]);
25
+ export type PhaseState = z.infer<typeof PhaseState>;
26
+
27
+ /** A declared phase of a run, with where the run is in it: derived from the phases its branches entered, stored nowhere. */
28
+ export const PhaseProgress = WorkflowPhase.extend({ state: PhaseState });
29
+ export type PhaseProgress = z.infer<typeof PhaseProgress>;
30
+
31
+ /** A run, as a caller waiting for it sees it. */
32
+ /** An operation a run began that has not ended: what a hold waits for before it is `held`. */
33
+ export const InFlight = z.object({
34
+ run: z.string(),
35
+ key: z.string(),
36
+ action: z.string(),
37
+ effect: z.enum(["write", "irreversible"]),
38
+ operationId: z.string().optional(),
39
+ });
40
+ export type InFlight = z.infer<typeof InFlight>;
41
+
42
+ /** What one plugin has begun outside niwa and not ended while a run is held, as the plugin lists it. */
43
+ export const PendingOperations = z.object({
44
+ plugin: z.string(),
45
+ /** What the operations are: "armed merges". */
46
+ label: z.string(),
47
+ items: z.array(PendingExternalItemSchema),
48
+ /** Why the plugin could not be asked, when it could not: its operations are then unknown, not none. */
49
+ unavailable: z.string().optional(),
50
+ });
51
+ export type PendingOperations = z.infer<typeof PendingOperations>;
52
+
53
+ /**
54
+ * A hold of a run: `holding` while operations that write are still going, listed in `inFlight`,
55
+ * and `held` once every one of them has ended. New writes are refused in both.
56
+ */
57
+ export const RunHold = z.object({
58
+ id: z.string(),
59
+ state: z.enum(["holding", "held"]),
60
+ /** The hold covers the runs this run started, at any depth. */
61
+ tree: z.boolean(),
62
+ inFlight: z.array(InFlight),
63
+ /**
64
+ * What plugins began outside niwa that is still pending, by plugin (`PENDING_EXTERNAL`): the hold
65
+ * stops the run's writes, not these. Absent when no plugin offers any.
66
+ */
67
+ pending: z.array(PendingOperations).optional(),
68
+ });
69
+ export type RunHold = z.infer<typeof RunHold>;
70
+
71
+ export const RunStatus = z.object({
72
+ run: z.string(),
73
+ state: RunState,
74
+ /** A pause that holds the run at its next boundary: one asked for, or (`kind: "deadline"`) the run's deadline that came. */
75
+ manualPause: z.object({ id: z.string(), state: z.enum(["requested", "paused"]), kind: z.literal("deadline").optional() }).optional(),
76
+ /** The hold of the run, while one stands. */
77
+ hold: RunHold.optional(),
78
+ /** How the run ended, for a run that finished. */
79
+ outcome: RunOutcome.optional(),
80
+ /** Why the run paused. */
81
+ reason: z.string().optional(),
82
+ /**
83
+ * What may be answered to the pause: `niwa.invocation.resolve` with the invocation and one of these; at a deadline,
84
+ * `extend` (`workflow.extend`) or `cancel` (`workflow.cancel`).
85
+ */
86
+ choices: z.array(z.string()).optional(),
87
+ /** The invocation that is paused, the one to resolve. */
88
+ invocation: z.string().optional(),
89
+ /** The questions the run asked that nobody has answered yet. */
90
+ requests: z.array(z.string()),
91
+ /** The phases the run is in now, in the declared order: one per branch that is going, several while branches of a `parallel` are in different ones. Absent when the script declares none. */
92
+ currentPhases: z.array(z.string()).optional(),
93
+ /** The phases the script declares, in order, each done, current or ahead. Absent when it declares none. */
94
+ phases: z.array(PhaseProgress).optional(),
95
+ /** What a run that is going waits for: `sleep nap until 14:30:00`, `ask …label:ship`, `session claude-haiku … turn 1`, `wait <type>`. */
96
+ waiting: z.string().optional(),
97
+ });
98
+ export type RunStatus = z.infer<typeof RunStatus>;
99
+
100
+ /** The state of one invocation, as the core wrote it last. */
101
+ const InvocationState = z.object({
102
+ state: z.string(),
103
+ reason: z.string().optional(),
104
+ choices: z.array(z.string()).optional(),
105
+ /** The step the invocation paused on; absent for a pause on no step (the handler threw). */
106
+ key: z.string().optional(),
107
+ });
108
+
109
+ const REQUEST_RECORDS: RecordTypeName[] = [
110
+ RequestCreated.name,
111
+ RequestAnswered.name,
112
+ RequestCancelledRecord.name,
113
+ RequestExpiredRecord.name,
114
+ ];
115
+
116
+ /** The requests of a run that are still open: the run asked them, and nobody answered, cancelled or let them expire. */
117
+ function openRequestsOf(journal: JournalReader, run: string): string[] {
118
+ const states = fold(journal.since(seq(0), REQUEST_RECORDS));
119
+ return [...states.values()]
120
+ .filter((state) => state.status === "open" && state.created.from?.kind === "client" && state.created.from.id === `run:${run}`)
121
+ .map((state) => state.created.id);
122
+ }
123
+
124
+ /**
125
+ * The requests that invocations created (what a run's script asked, and what its sessions were
126
+ * asked) and that are still open, with the address each was put to: the party that may withdraw it.
127
+ */
128
+ export function openRequestsOfInvocations(journal: JournalReader, invocations: readonly string[]): Array<{ id: RequestId; to: Address }> {
129
+ const mine = new Set(
130
+ journal
131
+ .find({ type: RequestCreated.name })
132
+ .filter((row) => row.actor.kind === "handler" && invocations.includes(String(row.actor.invocation)))
133
+ .map((row) => RequestCreated.schema.parse(row.data).id),
134
+ );
135
+ return [...fold(journal.since(seq(0), REQUEST_RECORDS)).values()]
136
+ .filter((state) => state.status === "open" && mine.has(state.created.id))
137
+ .map((state) => ({ id: state.created.id, to: state.created.to }));
138
+ }
139
+
140
+ /** Was the run ever asked for? */
141
+ export function runExists(journal: JournalReader, run: string): boolean {
142
+ return journal.find({ type: RunRequested.name, field: "run", equals: run }).length > 0;
143
+ }
144
+
145
+ /** Every run, in the order it was first asked for. */
146
+ export function runIds(journal: JournalReader): string[] {
147
+ return [...new Set(journal.find({ type: RunRequested.name }).map((row) => RunRequested.schema.parse(row.data).run))];
148
+ }
149
+
150
+ /**
151
+ * The state of a run: finished once its latest start ended (a run cancelled while paused ends with
152
+ * no result of its own), paused while its invocation waits for a decision, running otherwise.
153
+ */
154
+ export function manualPausesOf(journal: JournalReader, run: string): StoredRecord[] {
155
+ const after = journal.find({ type: RunRequested.name, field: "run", equals: run }).at(-1)?.seq ?? seq(0);
156
+ return journal.find({ type: RunPauseRequested.name, field: "run", equals: run, after });
157
+ }
158
+
159
+ /** The hold of a run that stands: asked for since the run's latest start and not released. */
160
+ export function activeHold(journal: JournalReader, run: string): StoredRecord | undefined {
161
+ const after = journal.find({ type: RunRequested.name, field: "run", equals: run }).at(-1)?.seq ?? seq(0);
162
+ const hold = journal.find({ type: RunHoldRequested.name, field: "run", equals: run, after }).at(-1);
163
+ if (hold === undefined) return undefined;
164
+ return journal.find({ type: RunContinued.name, field: "pause", equals: hold.id, after: hold.seq }).length === 0 ? hold : undefined;
165
+ }
166
+
167
+ /**
168
+ * The runs a run started: those whose request names it as their parent (a workflow it calls),
169
+ * and those whose grant it is the parent of (a run it started with workflow.start).
170
+ */
171
+ export function childRunsOf(journal: JournalReader, run: string): string[] {
172
+ const named = journal
173
+ .find({ type: RunRequested.name })
174
+ .map((row) => RunRequested.schema.parse(row.data))
175
+ .filter((data) => data.parent?.run === run)
176
+ .map((data) => String(data.run));
177
+ const executions = journal.find({ type: RunRequested.name, field: "run", equals: run })
178
+ .map(row => RunRequested.schema.parse(row.data).execution ?? run);
179
+ const granted = [...new Set([run, ...executions])].flatMap(id =>
180
+ journal.find({ type: CORE_TYPES.accessGranted, field: "parent.principal.id", equals: id }).flatMap(row => {
181
+ const data = row.data as { principal?: { kind?: string; id?: string }; parent?: { principal?: { kind?: string } } };
182
+ return data.principal?.kind === "run" && data.parent?.principal?.kind === "run" && data.principal.id !== undefined ? [runIdOfPrincipal(data.principal.id)] : [];
183
+ }));
184
+ return [...new Set([...named, ...granted])];
185
+ }
186
+
187
+ /** The run that started a run, when a run did: the parent its request names, or the run its grant came from. */
188
+ export function parentRunOf(journal: JournalReader, run: string): string | undefined {
189
+ const requested = journal.find({ type: RunRequested.name, field: "run", equals: run }).at(-1);
190
+ const named = requested === undefined ? undefined : RunRequested.schema.parse(requested.data).parent?.run;
191
+ if (named !== undefined) return named;
192
+ for (const row of journal.find({ type: CORE_TYPES.accessGranted, field: "principal.id", equals: run })) {
193
+ const data = row.data as { principal?: { kind?: string }; parent?: { principal?: { kind?: string; id?: string } } };
194
+ if (data.principal?.kind === "run") return data.parent?.principal?.kind === "run" ? runIdOfPrincipal(data.parent.principal.id!) : undefined;
195
+ }
196
+ return undefined;
197
+ }
198
+
199
+ /** The hold that holds a run: its own, or a hold of the tree of a run above it. */
200
+ export function holdOver(journal: JournalReader, run: string): StoredRecord | undefined {
201
+ const own = activeHold(journal, run);
202
+ if (own !== undefined) return own;
203
+ const seen = new Set([run]);
204
+ for (let above = parentRunOf(journal, run); above !== undefined && !seen.has(above); above = parentRunOf(journal, above)) {
205
+ seen.add(above);
206
+ const hold = activeHold(journal, above);
207
+ if (hold !== undefined && RunHoldRequested.schema.parse(hold.data).tree) return hold;
208
+ }
209
+ return undefined;
210
+ }
211
+
212
+ /** The operations that write, begun in the invocations of a run, that have no outcome yet. */
213
+ function inFlightOf(journal: JournalReader, run: string): InFlight[] {
214
+ const invocations = new Set(
215
+ journal.find({ type: RunStarted.name, field: "run", equals: run }).flatMap((row) => (row.actor.kind === "handler" ? [String(row.actor.invocation)] : [])),
216
+ );
217
+ const going = new Map<string, InFlight>();
218
+ for (const invocation of invocations) {
219
+ for (const row of journal.find({ type: CORE_TYPES.stepIntent, field: "invocation", equals: invocation })) {
220
+ const data = row.data as { key: string; action: string; effect?: string; operationId?: string };
221
+ if (data.effect !== "write" && data.effect !== "irreversible") continue;
222
+ going.set(`${invocation}\n${data.key}`, {
223
+ run,
224
+ key: data.key,
225
+ action: data.action,
226
+ effect: data.effect,
227
+ ...(data.operationId === undefined ? {} : { operationId: data.operationId }),
228
+ });
229
+ }
230
+ for (const row of journal.find({ type: CORE_TYPES.stepOutcome, field: "invocation", equals: invocation })) {
231
+ going.delete(`${invocation}\n${(row.data as { key: string }).key}`);
232
+ }
233
+ }
234
+ return [...going.values()];
235
+ }
236
+
237
+ /** The hold of a run as its status shows it: what is still going in it and, for a tree, in the runs below it. */
238
+ function holdStatusOf(journal: JournalReader, run: string): RunHold | undefined {
239
+ const hold = activeHold(journal, run);
240
+ if (hold === undefined) return undefined;
241
+ const { tree } = RunHoldRequested.schema.parse(hold.data);
242
+ const runs = [run];
243
+ for (let at = 0; tree && at < runs.length; at++) {
244
+ for (const child of childRunsOf(journal, runs[at] ?? "")) if (!runs.includes(child)) runs.push(child);
245
+ }
246
+ const inFlight = runs.flatMap((one) => inFlightOf(journal, one));
247
+ return { id: String(hold.id), state: inFlight.length === 0 ? "held" : "holding", tree, inFlight };
248
+ }
249
+
250
+ export function activeManualPause(journal: JournalReader, run: string): StoredRecord | undefined {
251
+ const pause = manualPausesOf(journal, run).at(-1);
252
+ if (pause === undefined) return;
253
+ return journal.find({ type: RunContinued.name, field: "pause", equals: pause.id, after: pause.seq }).length === 0
254
+ ? pause : undefined;
255
+ }
256
+
257
+ /** A run paused at its deadline: only more time or a cancel answers it. */
258
+ function atDeadline(run: string, reached: number, manualPause: NonNullable<RunStatus["manualPause"]>, requests: string[]): RunStatus {
259
+ const reason = `the run reached its deadline at ${new Date(reached).toISOString()}`;
260
+ return { run, state: "paused", reason, choices: ["extend", "cancel"], manualPause, requests };
261
+ }
262
+
263
+ /** The deadline a pause says the run reached, when it is the pause of a deadline. */
264
+ export function deadlineReached(pause: StoredRecord): number | undefined {
265
+ const data = RunPauseRequested.schema.parse(pause.data);
266
+ return data.kind === "deadline" ? data.deadline : undefined;
267
+ }
268
+
269
+ /** The moment the deadline of a run comes now: the latest extension, else the one it started with. Absent when it has none. */
270
+ export function deadlineOf(journal: JournalReader, run: string): number | undefined {
271
+ const requested = journal.find({ type: RunRequested.name, field: "run", equals: run }).at(-1);
272
+ if (requested === undefined) return undefined;
273
+ const extended = journal.find({ type: RunDeadlineExtended.name, field: "run", equals: run, after: requested.seq }).at(-1);
274
+ return extended !== undefined ? RunDeadlineExtended.schema.parse(extended.data).deadline : RunRequested.schema.parse(requested.data).deadline;
275
+ }
276
+
277
+ /** Is `branch` inside `outer`: a branch made (at any depth) by a group `outer` started? `""` is the script itself. */
278
+ const inside = (branch: string, outer: string): boolean => branch !== outer && (outer === "" || branch.startsWith(`${outer}.`));
279
+
280
+ /**
281
+ * The phase plan of a run: the phases declared by the script, all ahead until it starts. Once started, the state of
282
+ * each phase is read from the phases its branches entered (`workflow.phase.entered`) and the branches
283
+ * that ended (`workflow.phase.left`).
284
+ *
285
+ * - A branch (the script itself, or a branch of `parallel`/`pipeline`) is in the phase it entered last. It is going
286
+ * until it ended, and it waits, not goes, while a branch it made is going: the script is not in its own phase while
287
+ * its `parallel` runs, its branches are. Only the latest start of the run counts here: an earlier one was stopped
288
+ * with its branches unfinished.
289
+ * - **current**: the phase of a branch that is going. A run that finished with its result has none.
290
+ * - **done**: a phase some branch entered (in any start of the run), that is not current, and that is declared before
291
+ * every current one; with no current phase, every phase entered is done.
292
+ * - **ahead**: the rest: not entered yet, or entered and left by a branch while another branch has not reached it
293
+ * (it is declared after a current phase).
294
+ *
295
+ * Undefined for a run whose script declares none.
296
+ */
297
+ export function phasesOf(journal: JournalReader, run: string, status: Pick<RunStatus, "state" | "outcome">): PhaseProgress[] | undefined {
298
+ const requested = journal.find({ type: RunRequested.name, field: "run", equals: run }).at(-1);
299
+ const after = requested?.seq ?? seq(0);
300
+ const started = journal.find({ type: RunStarted.name, field: "run", equals: run, after }).at(-1);
301
+ const pinned = requested === undefined ? undefined : RunRequested.schema.parse(requested.data).phases;
302
+ if (started === undefined) return pinned?.map((phase) => ({ ...phase, state: "ahead" }));
303
+ const declared = pinned ?? RunStarted.schema.parse(started.data).phases;
304
+ if (declared === undefined) return undefined;
305
+ const indexOf = (title: string): number => declared.findIndex((phase) => phase.title === title);
306
+ const entered = journal.find({ type: PhaseEntered.name, field: "run", equals: run, after });
307
+ const reached = new Set(entered.map((row) => indexOf(PhaseEntered.schema.parse(row.data).phase)).filter((index) => index >= 0));
308
+ const done = status.state === "finished" && status.outcome?.status === "done";
309
+ const current = new Set<number>();
310
+ const invocation = started.actor.kind === "handler" ? started.actor.invocation : undefined;
311
+ if (!done && invocation !== undefined) {
312
+ const own = (row: StoredRecord): boolean => row.actor.kind === "handler" && row.actor.invocation === invocation;
313
+ // The phase each branch of the latest start is in, and the branches that ended.
314
+ const branches = new Map<string, number>();
315
+ for (const row of entered.filter(own)) {
316
+ const data = PhaseEntered.schema.parse(row.data);
317
+ branches.set(data.branch, indexOf(data.phase));
318
+ }
319
+ for (const row of journal.find({ type: PhaseLeft.name, field: "run", equals: run, after: started.seq }).filter(own)) {
320
+ branches.delete(PhaseLeft.schema.parse(row.data).branch);
321
+ }
322
+ for (const [branch, index] of branches) {
323
+ if (index >= 0 && ![...branches.keys()].some((other) => inside(other, branch))) current.add(index);
324
+ }
325
+ }
326
+ const first = Math.min(...current);
327
+ return declared.map((phase, index): PhaseProgress => ({
328
+ ...phase,
329
+ state: current.has(index) ? "current" : reached.has(index) && index < first ? "done" : "ahead",
330
+ }));
331
+ }
332
+
333
+ /** Project the current invocation outcome and any outstanding manual pause. */
334
+ export function statusOf(journal: JournalReader, run: string): RunStatus {
335
+ const own = stateOf(journal, run);
336
+ const hold = holdStatusOf(journal, run);
337
+ const status = hold === undefined ? own : { ...own, hold };
338
+ const phases = phasesOf(journal, run, status);
339
+ const plan = phases === undefined ? {} : { currentPhases: phases.filter((phase) => phase.state === "current").map((phase) => phase.title), phases };
340
+ if (status.state !== "running") return { ...status, ...plan };
341
+ const waiting = waitingFor(journal, run, status.requests);
342
+ return {
343
+ ...status,
344
+ ...plan,
345
+ ...(waiting === undefined ? {} : { waiting }),
346
+ };
347
+ }
348
+
349
+ function stateOf(journal: JournalReader, run: string): RunStatus {
350
+ const requests = openRequestsOf(journal, run);
351
+ const requested = journal.find({ type: RunRequested.name, field: "run", equals: run }).at(-1);
352
+ const after = requested?.seq ?? seq(0);
353
+ const execution = requested === undefined ? run : RunRequested.schema.parse(requested.data).execution ?? run;
354
+ const finished = journal.find({ type: RunFinished.name, field: "run", equals: run, after })
355
+ .findLast(row => (RunFinished.schema.parse(row.data).execution ?? run) === execution);
356
+ if (finished !== undefined) {
357
+ const data = RunFinished.schema.parse(finished.data);
358
+ return { run, state: "finished", outcome: data.outcome, requests };
359
+ }
360
+ const started = journal.find({ type: RunStarted.name, field: "run", equals: run, after }).at(-1);
361
+ const invocation = started?.actor.kind === "handler" ? String(started.actor.invocation) : undefined;
362
+ const last = invocation === undefined ? undefined : journal.find({ type: CORE_TYPES.invocationState, field: "invocation", equals: invocation }).at(-1);
363
+ const state = last === undefined ? undefined : InvocationState.safeParse(last.data);
364
+ if (state?.success !== true || invocation === undefined) {
365
+ const manual = activeManualPause(journal, run);
366
+ if (manual === undefined) return { run, state: "running", requests };
367
+ const reached = deadlineReached(manual);
368
+ const manualPause = { id: String(manual.id), state: "requested" as const, ...(reached === undefined ? {} : { kind: "deadline" as const }) };
369
+ return reached === undefined ? { run, state: "running", requests, manualPause } : atDeadline(run, reached, manualPause, requests);
370
+ }
371
+ const paused = journal.find({ type: RunPaused.name, field: "run", equals: run, after }).at(-1);
372
+ if (state.data.state === "done") {
373
+ // A pause that offers only `cancel` is not one the invocation waits on (an edited script, a
374
+ // call the revision shows): the run waits for the owner to revise or cancel it, and has not ended.
375
+ const data = paused === undefined ? undefined : RunPaused.schema.parse(paused.data);
376
+ if (data?.choices?.join() === "cancel") return { run, state: "paused", reason: data.reason, choices: ["cancel"], requests };
377
+ return { run, state: "finished", outcome: { status: "cancelled" }, requests };
378
+ }
379
+ const manual = activeManualPause(journal, run);
380
+ const reached = manual === undefined ? undefined : deadlineReached(manual);
381
+ const manualPause =
382
+ manual === undefined ? undefined : {
383
+ id: String(manual.id),
384
+ state: state.data.state === "waiting" || state.data.state === "paused" ? "paused" as const : "requested" as const,
385
+ ...(reached === undefined ? {} : { kind: "deadline" as const }),
386
+ };
387
+ if (state.data.state === "waiting" && manualPause !== undefined) {
388
+ if (reached !== undefined) return atDeadline(run, reached, manualPause, requests);
389
+ return { run, state: "paused", reason: "manually paused", manualPause, requests };
390
+ }
391
+ const control = manualPause === undefined ? {} : { manualPause };
392
+ if (state.data.state !== "paused") {
393
+ // The deadline came: the run is paused from that moment, though a call it had begun may still end.
394
+ if (reached !== undefined && manualPause !== undefined) return atDeadline(run, reached, manualPause, requests);
395
+ return { run, state: "running", requests, ...control };
396
+ }
397
+ // The run says why it paused in its own words when the pause is the one it wrote for this pause (the core only
398
+ // knows that the handler threw: `handler error: …`): written after the state before this one, or, for a retry that
399
+ // failed the same way and wrote no new pause (its key is the reason), the very reason the core gives. A pause of
400
+ // the core of its own (a version that is gone, a replay mismatch) keeps the core's reason.
401
+ const before = journal.find({ type: CORE_TYPES.invocationState, field: "invocation", equals: invocation }).at(-2);
402
+ const written = paused === undefined ? undefined : RunPaused.schema.parse(paused.data);
403
+ const own =
404
+ written !== undefined && ((before === undefined || (paused?.seq ?? 0) > before.seq) || state.data.reason === `handler error: ${written.reason}`)
405
+ ? written
406
+ : undefined;
407
+ const reason = own?.reason ?? state.data.reason ?? (paused === undefined ? undefined : RunPaused.schema.parse(paused.data).reason);
408
+ // What the core accepts for this pause, by the rule it holds an answer to (no skip on no step, only cancel on a wait).
409
+ const choices = offeredChoices(journal, invocation, state.data);
410
+ return { run, state: "paused", ...(reason === undefined ? {} : { reason }), choices, invocation, requests, ...control };
411
+ }
412
+
413
+ const cut = (text: string, width: number): string => {
414
+ const line = text.replace(/\s+/g, " ").trim();
415
+ return line.length <= width ? line : `${line.slice(0, width - 1)}…`;
416
+ };
417
+
418
+ /** The name of a run for a list: its label, else the file it runs without the directory and the extension. */
419
+ export function nameOfRun(journal: JournalReader, run: string): string {
420
+ const requested = journal.find({ type: RunRequested.name, field: "run", equals: run }).at(-1);
421
+ if (requested === undefined) return run;
422
+ const data = RunRequested.schema.parse(requested.data);
423
+ return data.label ?? (data.file.split("/").at(-1) ?? data.file).replace(/\.[^.]+$/, "");
424
+ }
425
+
426
+ /** What a list of runs says of the phases a run is in: each title with its place among the declared phases, `Review (1/3), Fix (2/3)`. */
427
+ function phaseLine(status: RunStatus): string {
428
+ const phases = status.phases ?? [];
429
+ return phases
430
+ .flatMap((phase, index) => (phase.state === "current" ? [`${phase.title} (${String(index + 1)}/${String(phases.length)})`] : []))
431
+ .join(", ");
432
+ }
433
+
434
+ /** What a list of runs says of how a run ended: the result, the error, or that it was cancelled. */
435
+ function outcomeLine(outcome: RunOutcome): string {
436
+ switch (outcome.status) {
437
+ case "done":
438
+ return outcome.result === null ? "" : JSON.stringify(outcome.result);
439
+ case "failed":
440
+ return `failed: ${outcome.error.message}`;
441
+ case "cancelled":
442
+ return "cancelled";
443
+ }
444
+ }
445
+
446
+ /** A few words of what a run is up to or how it ended. */
447
+ function aboutRun(status: RunStatus): string {
448
+ return status.state === "paused" ? (status.reason ?? "") : status.outcome !== undefined ? outcomeLine(status.outcome) : phaseLine(status);
449
+ }
450
+
451
+ /** A run of a list as fields: what a page needs to group and show runs without reading each one. */
452
+ export const RunEntry = z.object({
453
+ run: z.string(),
454
+ name: z.string(),
455
+ state: RunState,
456
+ /** The directory the run was started for; absent for a run started with none. */
457
+ directory: z.string().optional(),
458
+ workflow: z.string().optional(),
459
+ phases: z.array(PhaseProgress).optional(),
460
+ waiting: z.string().optional(),
461
+ manualPause: z.boolean().optional(),
462
+ /** When the run was last asked for: its start, or the resume that began it again. */
463
+ requestedAt: z.iso.datetime(),
464
+ /** A few words of what the run is up to or how it ended. */
465
+ about: z.string(),
466
+ /** The questions the run asked that nobody has answered yet. */
467
+ requests: z.number().int().nonnegative(),
468
+ });
469
+ export type RunEntry = z.infer<typeof RunEntry>;
470
+
471
+ /** One run of the list, as fields. */
472
+ export function runEntry(journal: JournalReader, run: string): RunEntry {
473
+ const status = statusOf(journal, run);
474
+ const requested = journal.find({ type: RunRequested.name, field: "run", equals: run }).at(-1);
475
+ const data = requested === undefined ? undefined : RunRequested.schema.parse(requested.data);
476
+ return {
477
+ run,
478
+ name: nameOfRun(journal, run),
479
+ ...(data?.workflow && { workflow: data.workflow }),
480
+ ...(status.phases && { phases: status.phases }),
481
+ ...(status.waiting && { waiting: status.waiting }),
482
+ ...(status.manualPause && { manualPause: true }),
483
+ state: status.state,
484
+ ...(data?.directory === undefined ? {} : { directory: data.directory }),
485
+ requestedAt: new Date(requested?.at ?? 0).toISOString(),
486
+ about: cut(aboutRun(status), 120),
487
+ requests: status.requests.length,
488
+ };
489
+ }
490
+
491
+ /**
492
+ * One line of a list of runs: the id, the name, the state, a few words of what it is up to or how
493
+ * it ended, the questions it asked, and for a paused run the command that answers its pause.
494
+ */
495
+ export function runLine(journal: JournalReader, run: string): string {
496
+ const status = statusOf(journal, run);
497
+ const short = shortRun(run);
498
+ const about = aboutRun(status);
499
+ const resolve =
500
+ status.state !== "paused"
501
+ ? ""
502
+ : status.manualPause?.kind === "deadline" && status.invocation === undefined
503
+ ? `extend: niwa workflow.extend --run ${short} --by MS | niwa workflow.cancel --run ${short}`
504
+ : status.manualPause !== undefined && status.invocation === undefined
505
+ ? `continue: niwa workflow.continue --run ${short} --pause ${status.manualPause.id}`
506
+ : status.invocation === undefined
507
+ ? `resolve: niwa workflow.revise --run ${short} --file F | niwa workflow.cancel --run ${short}`
508
+ : `resolve: niwa workflow.resume --run ${short} --choice ${(status.choices ?? []).join("|")}`;
509
+ // A run that is going shows its question in what it waits for.
510
+ const open = status.requests.length === 0 || status.state === "running" ? "" : `asks: ${status.requests.join(",")}`;
511
+ return [short, nameOfRun(journal, run), status.state, cut(about, 60), status.waiting ?? "", open, resolve].filter((part) => part !== "").join(" ");
512
+ }