@niwa-labs/watch 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.
- package/LICENSE +21 -0
- package/README.md +75 -2
- package/package.json +29 -4
- package/src/cockpit/actions.ts +29 -0
- package/src/cockpit/decisions.ts +35 -0
- package/src/cockpit/index.tsx +19 -0
- package/src/cockpit/page.tsx +116 -0
- package/src/cockpit/subjects.ts +138 -0
- package/src/index.ts +160 -0
- package/src/readings.ts +709 -0
- package/src/records.ts +180 -0
- package/test/cockpit-actions.test.ts +29 -0
- package/test/cockpit-subjects.test.ts +89 -0
- package/test/queries.test.ts +27 -0
- package/test/readings.test.ts +579 -0
- package/test/watch.test.ts +287 -0
- package/tsconfig.json +15 -0
package/src/readings.ts
ADDED
|
@@ -0,0 +1,709 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the watch knows, folded from the journal records it reads.
|
|
3
|
+
*
|
|
4
|
+
* The model is fed record by record (`Model.apply`) and asked, at a moment, what every subject is
|
|
5
|
+
* doing (`Model.readings`). It reads records by type name and parses only the fields it needs, so a
|
|
6
|
+
* record it cannot read is passed over and a plugin it does not know of is not required. Time is
|
|
7
|
+
* given, never read: the same records and the same moment always give the same readings.
|
|
8
|
+
*
|
|
9
|
+
* The sources are: the turns, activity and progress of sessions, the pauses, log, phases, scopes and steps of
|
|
10
|
+
* runs, the requests and sleeps that hold either, a head that moved, and the watch's own flags.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { z } from "zod";
|
|
14
|
+
|
|
15
|
+
import { keyUnder, stableJson } from "@niwa-labs/core";
|
|
16
|
+
import type { StoredRecord } from "@niwa-labs/core";
|
|
17
|
+
|
|
18
|
+
import { Subject, runSubject, sessionSubject, tryRunSubject, trySessionSubject } from "./records.ts";
|
|
19
|
+
import type { Reading, StuckKind, WatchRecoveredData, WatchStuckData } from "./records.ts";
|
|
20
|
+
|
|
21
|
+
/** The record types, and families, the model reads. */
|
|
22
|
+
export const SOURCES: readonly string[] = [
|
|
23
|
+
"session.*",
|
|
24
|
+
"history.session.*",
|
|
25
|
+
"request.*",
|
|
26
|
+
"timer.sleep.requested",
|
|
27
|
+
"timer.slept",
|
|
28
|
+
"git.head.moved",
|
|
29
|
+
"workflow.run.*",
|
|
30
|
+
"workflow.scope.*",
|
|
31
|
+
"workflow.phase.*",
|
|
32
|
+
"niwa.invocation.resolved",
|
|
33
|
+
"niwa.step.intent",
|
|
34
|
+
"niwa.step.outcome",
|
|
35
|
+
"niwa.step.cancelled",
|
|
36
|
+
"niwa.invocation.state",
|
|
37
|
+
"watch.*",
|
|
38
|
+
];
|
|
39
|
+
|
|
40
|
+
/** The limits that decide when a subject is stuck. All durations are milliseconds. */
|
|
41
|
+
export interface Settings {
|
|
42
|
+
/** How long a subject that is working may give no sign of life. A session that says its own `stuckAfter` is held to that. */
|
|
43
|
+
readonly silentAfter: number;
|
|
44
|
+
/** How many identical steps in a row make a run loop. */
|
|
45
|
+
readonly loopRepeats: number;
|
|
46
|
+
/** How many identical activities, with no progress between them, make a session loop. */
|
|
47
|
+
readonly sessionLoopRepeats: number;
|
|
48
|
+
/** How long after a cancel a shielded scope may keep a run going. */
|
|
49
|
+
readonly shieldGrace: number;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export const DEFAULT_SETTINGS: Settings = {
|
|
53
|
+
silentAfter: 10 * 60_000,
|
|
54
|
+
loopRepeats: 6,
|
|
55
|
+
sessionLoopRepeats: 25,
|
|
56
|
+
shieldGrace: 60_000,
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
// What is read of each record. A field the model does not use is not named.
|
|
60
|
+
const Text = z.string().min(1);
|
|
61
|
+
/** The id of a run as a record names it, when it can name a subject. */
|
|
62
|
+
const RunName = Text.refine((run) => tryRunSubject(run) !== undefined, "not the id of a run");
|
|
63
|
+
const SessionObject = z
|
|
64
|
+
.object({ harness: Text, native: Text })
|
|
65
|
+
.refine((named) => trySessionSubject(named.harness, named.native) !== undefined, "not a session");
|
|
66
|
+
/** A session as records name it, when it can name a subject: the pair as one text (niwa's own), or as an object (the history's). */
|
|
67
|
+
const SessionNamed = z.union([Text.refine((named) => Subject.safeParse(`session:${named}`).success, "not a session"), SessionObject]);
|
|
68
|
+
|
|
69
|
+
const OfSession = z.object({ session: SessionNamed });
|
|
70
|
+
const Started = z.object({
|
|
71
|
+
session: SessionNamed,
|
|
72
|
+
// A limit that is no whole number of milliseconds is not one a flag can be dated by: the session is followed under the default.
|
|
73
|
+
stuckAfter: z.number().int().positive().optional().catch(undefined),
|
|
74
|
+
});
|
|
75
|
+
const TurnEnded = z.object({ session: SessionNamed, how: z.string().optional() });
|
|
76
|
+
const HistoryEnded = z.object({ session: SessionNamed, certainty: z.string().optional() });
|
|
77
|
+
const Activity = z.object({ session: SessionNamed, tool: z.string().optional(), permission: z.unknown().optional() });
|
|
78
|
+
const OfRun = z.object({ run: RunName });
|
|
79
|
+
const Scope = z.object({ run: RunName, scope: Text, shield: z.boolean().optional() });
|
|
80
|
+
const OfInvocation = z.object({ invocation: Text });
|
|
81
|
+
const Cancelled = z.object({ invocation: Text, prefixes: z.array(z.string()).optional(), except: z.array(z.string()).optional() });
|
|
82
|
+
const Outcome = z.object({ invocation: Text, key: z.string() });
|
|
83
|
+
const Intent = z.object({ invocation: Text, key: z.string(), action: z.string(), input: z.unknown() });
|
|
84
|
+
/** The keys of the steps the workflow bridge writes beside the step of a call: `<key>~auth`, `~now`, `~mark`, `~arm`, `~ended`. */
|
|
85
|
+
const ASIDE = /~(auth|now|mark|arm|ended)$/;
|
|
86
|
+
/** The action a sleep records as its step. */
|
|
87
|
+
const WAIT_ACTION = "niwa.wait";
|
|
88
|
+
/** The action a wait of a script for a record, with or without a timeout, records as its step. */
|
|
89
|
+
const SCRIPT_WAIT_ACTION = "workflow.script.wait";
|
|
90
|
+
const InvocationState = z.object({ invocation: Text, state: z.string() });
|
|
91
|
+
const Paused = z.object({ run: RunName, choices: z.array(z.string()).optional() });
|
|
92
|
+
const PauseRequested = z.object({ run: RunName, kind: z.string().optional() });
|
|
93
|
+
const Continued = z.object({ run: RunName, pause: z.string() });
|
|
94
|
+
const RequestMade = z.object({
|
|
95
|
+
id: Text,
|
|
96
|
+
to: z.object({ kind: z.string() }),
|
|
97
|
+
from: z.object({ kind: z.string(), harness: z.string().optional(), id: z.string().optional() }).optional(),
|
|
98
|
+
});
|
|
99
|
+
const OfRequest = z.object({ id: Text });
|
|
100
|
+
const OfKey = z.object({ key: Text });
|
|
101
|
+
const HeadMoved = z.object({ session: SessionNamed.optional() });
|
|
102
|
+
const Flag = z.object({ subject: Subject, since: z.number(), kind: z.string() });
|
|
103
|
+
const Stuck = Flag.extend({ last: z.number() });
|
|
104
|
+
|
|
105
|
+
/** How a session is written as a subject, from either form of its name. */
|
|
106
|
+
function sessionSubjectOf(named: z.infer<typeof SessionNamed>): Subject {
|
|
107
|
+
if (typeof named !== "string") return sessionSubject(named.harness, named.native);
|
|
108
|
+
return Subject.parse(`session:${named}`);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
type Base = "idle" | "working" | "unknown";
|
|
112
|
+
|
|
113
|
+
interface Streak {
|
|
114
|
+
readonly signature: string;
|
|
115
|
+
readonly count: number;
|
|
116
|
+
/** When the first of the identical records was written. */
|
|
117
|
+
readonly from: number;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
interface Track {
|
|
121
|
+
readonly subject: Subject;
|
|
122
|
+
readonly kind: "session" | "run";
|
|
123
|
+
base: Base;
|
|
124
|
+
/** What the subject was last found doing, held or not; `since` is the moment that changed. */
|
|
125
|
+
shown: Reading["state"];
|
|
126
|
+
/** Whether niwa runs the session and says its turns itself; a session only the history follows is not. */
|
|
127
|
+
managed: boolean;
|
|
128
|
+
since: number;
|
|
129
|
+
last: number;
|
|
130
|
+
stuckAfter?: number;
|
|
131
|
+
streak?: Streak;
|
|
132
|
+
// A run only.
|
|
133
|
+
invocation?: string;
|
|
134
|
+
started: boolean;
|
|
135
|
+
invocationState?: string;
|
|
136
|
+
/** The pause of an error or of a script that cannot go on, until it is answered. */
|
|
137
|
+
pause?: { readonly cancelOnly: boolean };
|
|
138
|
+
/** The pause someone asked for, or the deadline that was reached, until the continue that names it. */
|
|
139
|
+
manual?: { readonly id: string; readonly deadline: boolean };
|
|
140
|
+
/** The requests the subject asked that are open, each with whether it is put to the owner. */
|
|
141
|
+
asked: Map<string, boolean>;
|
|
142
|
+
/** The steps of the run's invocation that have begun and not ended, by key, with the action each calls. */
|
|
143
|
+
steps: Map<string, string>;
|
|
144
|
+
/** The keys of the wakes the run's invocation has asked for and not had. */
|
|
145
|
+
timers: Set<string>;
|
|
146
|
+
/** The shielded scopes that are open, each with the moment a cancel spared it, once one has. */
|
|
147
|
+
shields: Map<string, number | undefined>;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** A flag the watch wrote and has not closed. */
|
|
151
|
+
export interface OpenFlag {
|
|
152
|
+
readonly since: number;
|
|
153
|
+
readonly last: number;
|
|
154
|
+
readonly kind: StuckKind;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** A record the watch should write to bring the journal in line with what it reads. */
|
|
158
|
+
export type Transition =
|
|
159
|
+
| { readonly type: "stuck"; readonly data: WatchStuckData }
|
|
160
|
+
| { readonly type: "recovered"; readonly data: WatchRecoveredData };
|
|
161
|
+
|
|
162
|
+
function isKind(value: string): value is StuckKind {
|
|
163
|
+
return value === "silent" || value === "looping" || value === "shielded-cancel";
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** The model: every subject the records have named, and what holds each one. */
|
|
167
|
+
export class Model {
|
|
168
|
+
private readonly tracks = new Map<Subject, Track>();
|
|
169
|
+
/** The subjects that ended; a sign of life from one is not a reason to follow it again. */
|
|
170
|
+
private readonly gone = new Set<Subject>();
|
|
171
|
+
private readonly byInvocation = new Map<string, Subject>();
|
|
172
|
+
private readonly requests = new Map<string, Subject>();
|
|
173
|
+
private readonly sleeps = new Map<string, Subject>();
|
|
174
|
+
private readonly open = new Map<Subject, OpenFlag>();
|
|
175
|
+
/** The position of the last record applied: a record at or before it was seen already. */
|
|
176
|
+
private seen = 0;
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* @param floor Silence is counted from the later of a subject's last sign and this moment: the
|
|
180
|
+
* watch cannot say what happened while it was not looking.
|
|
181
|
+
*/
|
|
182
|
+
constructor(private floor = 0) {}
|
|
183
|
+
|
|
184
|
+
/** From now on, silence is counted from this moment at the earliest. */
|
|
185
|
+
startedAt(moment: number): void {
|
|
186
|
+
this.floor = Math.max(this.floor, moment);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** The flags the watch has written and not closed, as its own records say. */
|
|
190
|
+
flags(): ReadonlyMap<Subject, OpenFlag> {
|
|
191
|
+
return this.open;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Fold one record. Records are applied in the order they were committed; one seen before is passed over. */
|
|
195
|
+
apply(row: StoredRecord): void {
|
|
196
|
+
if (row.seq <= this.seen) return;
|
|
197
|
+
this.seen = row.seq;
|
|
198
|
+
const at = row.at as number;
|
|
199
|
+
this.fold(row, at);
|
|
200
|
+
// A subject that is now in another state has been in it since this record.
|
|
201
|
+
for (const track of this.tracks.values()) {
|
|
202
|
+
const state = this.heldState(track) ?? track.base;
|
|
203
|
+
if (state !== track.shown) {
|
|
204
|
+
track.shown = state;
|
|
205
|
+
track.since = at;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
private fold(row: StoredRecord, at: number): void {
|
|
211
|
+
switch (row.type as string) {
|
|
212
|
+
case "session.started": {
|
|
213
|
+
const data = Started.safeParse(row.data);
|
|
214
|
+
if (!data.success) return;
|
|
215
|
+
const track = this.revive(sessionSubjectOf(data.data.session), "session", at);
|
|
216
|
+
track.managed = true;
|
|
217
|
+
track.base = "idle";
|
|
218
|
+
track.last = at;
|
|
219
|
+
if (data.data.stuckAfter !== undefined) track.stuckAfter = data.data.stuckAfter;
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
case "session.turn-started": {
|
|
223
|
+
const data = OfSession.safeParse(row.data);
|
|
224
|
+
if (!data.success) return;
|
|
225
|
+
const track = this.revive(sessionSubjectOf(data.data.session), "session", at);
|
|
226
|
+
track.managed = true;
|
|
227
|
+
this.become(track, "working", at);
|
|
228
|
+
track.streak = undefined;
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
case "session.turn-ended": {
|
|
232
|
+
const data = TurnEnded.safeParse(row.data);
|
|
233
|
+
if (!data.success) return;
|
|
234
|
+
const track = this.known(sessionSubjectOf(data.data.session));
|
|
235
|
+
if (track === undefined) return;
|
|
236
|
+
this.become(track, data.data.how === "unknown" ? "unknown" : "idle", at);
|
|
237
|
+
track.streak = undefined;
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
case "session.activity": {
|
|
241
|
+
const data = Activity.safeParse(row.data);
|
|
242
|
+
if (!data.success) return;
|
|
243
|
+
const track = this.known(sessionSubjectOf(data.data.session)) ?? this.create(sessionSubjectOf(data.data.session), "session", at);
|
|
244
|
+
if (track === undefined) return;
|
|
245
|
+
if (track.base !== "working") this.become(track, "working", at);
|
|
246
|
+
track.last = at;
|
|
247
|
+
// Only a call of a tool names an operation that can repeat; any other sign of life is just that.
|
|
248
|
+
if (data.data.tool !== undefined || data.data.permission !== undefined) {
|
|
249
|
+
this.repeat(track, stableJson([data.data.tool ?? null, data.data.permission ?? null]), at);
|
|
250
|
+
}
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
case "session.progress": {
|
|
254
|
+
const data = OfSession.safeParse(row.data);
|
|
255
|
+
if (!data.success) return;
|
|
256
|
+
const subject = sessionSubjectOf(data.data.session);
|
|
257
|
+
const track = this.known(subject) ?? this.create(subject, "session", at);
|
|
258
|
+
if (track === undefined) return;
|
|
259
|
+
if (track.base !== "working") this.become(track, "working", at);
|
|
260
|
+
track.last = at;
|
|
261
|
+
track.streak = undefined;
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
case "session.ended": {
|
|
265
|
+
const data = OfSession.safeParse(row.data);
|
|
266
|
+
if (data.success) this.end(sessionSubjectOf(data.data.session));
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
case "history.session.ended": {
|
|
270
|
+
const data = HistoryEnded.safeParse(row.data);
|
|
271
|
+
if (!data.success) return;
|
|
272
|
+
const subject = sessionSubjectOf(data.data.session);
|
|
273
|
+
// A quiet transcript only suggests that a session niwa runs is over: it says so itself.
|
|
274
|
+
if (this.tracks.get(subject)?.managed === true && data.data.certainty !== "exact") return;
|
|
275
|
+
this.end(subject);
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
case "history.session.unwatched": {
|
|
279
|
+
const data = OfSession.safeParse(row.data);
|
|
280
|
+
if (!data.success) return;
|
|
281
|
+
const subject = sessionSubjectOf(data.data.session);
|
|
282
|
+
// The history was the only source of a session niwa does not run: with it gone there is nothing to measure.
|
|
283
|
+
// A session niwa runs goes on being read from its own records.
|
|
284
|
+
if (this.tracks.get(subject)?.managed === false) this.end(subject);
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
case "history.session.seen": {
|
|
288
|
+
const data = OfSession.safeParse(row.data);
|
|
289
|
+
if (!data.success) return;
|
|
290
|
+
const subject = sessionSubjectOf(data.data.session);
|
|
291
|
+
if (this.tracks.has(subject)) return;
|
|
292
|
+
this.revive(subject, "session", at).base = "unknown";
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
case "history.session.paused": {
|
|
296
|
+
const data = OfSession.safeParse(row.data);
|
|
297
|
+
if (!data.success) return;
|
|
298
|
+
const track = this.known(sessionSubjectOf(data.data.session));
|
|
299
|
+
// A quiet transcript says nothing of a turn niwa runs: the turn is open until it ends.
|
|
300
|
+
if (track === undefined || track.managed) return;
|
|
301
|
+
this.become(track, "idle", at);
|
|
302
|
+
track.streak = undefined;
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
case "git.head.moved": {
|
|
306
|
+
const data = HeadMoved.safeParse(row.data);
|
|
307
|
+
// A moved head is progress for whoever it can be attributed to: the session it names, or
|
|
308
|
+
// the run whose handler wrote it.
|
|
309
|
+
const track =
|
|
310
|
+
data.success && data.data.session !== undefined
|
|
311
|
+
? this.known(sessionSubjectOf(data.data.session))
|
|
312
|
+
: this.ofActor(row);
|
|
313
|
+
if (track === undefined) return;
|
|
314
|
+
track.last = at;
|
|
315
|
+
track.streak = undefined;
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
case "workflow.run.requested": {
|
|
319
|
+
const data = OfRun.safeParse(row.data);
|
|
320
|
+
if (!data.success) return;
|
|
321
|
+
const track = this.revive(runSubject(data.data.run), "run", at);
|
|
322
|
+
// An attempt at the script begins: nothing of the one before holds.
|
|
323
|
+
this.release(track);
|
|
324
|
+
track.base = "idle";
|
|
325
|
+
track.started = false;
|
|
326
|
+
track.pause = undefined;
|
|
327
|
+
track.manual = undefined;
|
|
328
|
+
track.streak = undefined;
|
|
329
|
+
track.shields.clear();
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
case "workflow.run.started": {
|
|
333
|
+
const data = OfRun.safeParse(row.data);
|
|
334
|
+
if (!data.success) return;
|
|
335
|
+
const track = this.revive(runSubject(data.data.run), "run", at);
|
|
336
|
+
track.started = true;
|
|
337
|
+
this.become(track, "working", at);
|
|
338
|
+
if (row.actor.kind === "handler" && track.invocation !== (row.actor.invocation as string)) {
|
|
339
|
+
this.release(track);
|
|
340
|
+
track.invocation = row.actor.invocation as string;
|
|
341
|
+
this.byInvocation.set(track.invocation, track.subject);
|
|
342
|
+
}
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
case "workflow.run.finished": {
|
|
346
|
+
const data = OfRun.safeParse(row.data);
|
|
347
|
+
if (data.success) this.end(runSubject(data.data.run));
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
case "workflow.run.paused": {
|
|
351
|
+
const data = Paused.safeParse(row.data);
|
|
352
|
+
const track = data.success ? this.attemptOf(row, data.data.run) : undefined;
|
|
353
|
+
if (track === undefined || !data.success) return;
|
|
354
|
+
track.pause = { cancelOnly: data.data.choices?.join() === "cancel" };
|
|
355
|
+
track.last = at;
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
case "workflow.run.pause-requested": {
|
|
359
|
+
const data = PauseRequested.safeParse(row.data);
|
|
360
|
+
const track = data.success ? this.tracks.get(runSubject(data.data.run)) : undefined;
|
|
361
|
+
if (track === undefined || !data.success) return;
|
|
362
|
+
track.manual = { id: String(row.id), deadline: data.data.kind === "deadline" };
|
|
363
|
+
track.last = at;
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
case "workflow.run.continued": {
|
|
367
|
+
const data = Continued.safeParse(row.data);
|
|
368
|
+
const track = data.success ? this.tracks.get(runSubject(data.data.run)) : undefined;
|
|
369
|
+
if (track === undefined || !data.success) return;
|
|
370
|
+
// It frees the pause it names: a hold shares the record, and a later pause is not the one that was released.
|
|
371
|
+
if (track.manual?.id === data.data.pause) track.manual = undefined;
|
|
372
|
+
track.last = at;
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
case "workflow.run.log": {
|
|
376
|
+
const data = OfRun.safeParse(row.data);
|
|
377
|
+
const track = data.success ? this.attemptOf(row, data.data.run) : undefined;
|
|
378
|
+
if (track !== undefined) track.last = at;
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
case "workflow.phase.entered":
|
|
382
|
+
case "workflow.phase.left": {
|
|
383
|
+
const data = OfRun.safeParse(row.data);
|
|
384
|
+
const track = data.success ? this.attemptOf(row, data.data.run) : undefined;
|
|
385
|
+
if (track === undefined) return;
|
|
386
|
+
// A script that moves to another phase is getting somewhere: what it repeated before is not a loop.
|
|
387
|
+
track.last = at;
|
|
388
|
+
track.streak = undefined;
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
case "workflow.scope.opened": {
|
|
392
|
+
const data = Scope.safeParse(row.data);
|
|
393
|
+
if (!data.success) return;
|
|
394
|
+
const track = this.known(runSubject(data.data.run));
|
|
395
|
+
if (track === undefined) return;
|
|
396
|
+
if (data.data.shield === true && !track.shields.has(data.data.scope)) track.shields.set(data.data.scope, undefined);
|
|
397
|
+
track.last = at;
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
case "workflow.scope.closed": {
|
|
401
|
+
const data = Scope.safeParse(row.data);
|
|
402
|
+
if (!data.success) return;
|
|
403
|
+
const track = this.known(runSubject(data.data.run));
|
|
404
|
+
if (track === undefined) return;
|
|
405
|
+
track.shields.delete(data.data.scope);
|
|
406
|
+
track.last = at;
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
case "niwa.step.intent": {
|
|
410
|
+
const data = Intent.safeParse(row.data);
|
|
411
|
+
if (!data.success) return;
|
|
412
|
+
const track = this.ofInvocation(data.data.invocation);
|
|
413
|
+
if (track === undefined) return;
|
|
414
|
+
track.last = at;
|
|
415
|
+
track.steps.set(data.data.key, data.data.action);
|
|
416
|
+
// The steps the bridge adds around a call (its permission, the clock, the arming of a wake) and the
|
|
417
|
+
// sleep itself are signs of life: they are not the script repeating a call.
|
|
418
|
+
if (!ASIDE.test(data.data.key) && data.data.action !== WAIT_ACTION) this.repeat(track, stableJson([data.data.action, data.data.input]), at);
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
case "niwa.step.outcome": {
|
|
422
|
+
const data = Outcome.safeParse(row.data);
|
|
423
|
+
const track = data.success ? this.ofInvocation(data.data.invocation) : undefined;
|
|
424
|
+
if (track === undefined || !data.success) return;
|
|
425
|
+
track.steps.delete(data.data.key);
|
|
426
|
+
track.last = at;
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
case "niwa.step.cancelled": {
|
|
430
|
+
const data = Cancelled.safeParse(row.data);
|
|
431
|
+
const track = data.success ? this.ofInvocation(data.data.invocation) : undefined;
|
|
432
|
+
if (track === undefined || !data.success) return;
|
|
433
|
+
// The steps it holds are over, whether or not an outcome is ever written for them.
|
|
434
|
+
const { prefixes = [], except = [] } = data.data;
|
|
435
|
+
for (const key of [...track.steps.keys()]) {
|
|
436
|
+
if (prefixes.some((prefix) => keyUnder(key, prefix)) && !except.some((spared) => keyUnder(key, spared))) track.steps.delete(key);
|
|
437
|
+
}
|
|
438
|
+
// A cancel names the open shields it spares in `except`: those are the scopes that go on past it.
|
|
439
|
+
for (const scope of data.data.except ?? []) {
|
|
440
|
+
if (track.shields.has(scope) && track.shields.get(scope) === undefined) track.shields.set(scope, at);
|
|
441
|
+
}
|
|
442
|
+
track.last = at;
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
case "niwa.invocation.state": {
|
|
446
|
+
const data = InvocationState.safeParse(row.data);
|
|
447
|
+
const track = data.success ? this.ofInvocation(data.data.invocation) : undefined;
|
|
448
|
+
if (track === undefined || !data.success) return;
|
|
449
|
+
track.invocationState = data.data.state;
|
|
450
|
+
track.last = at;
|
|
451
|
+
if (data.data.state === "running") track.pause = undefined;
|
|
452
|
+
// An invocation that is done is the end of the run, unless the run waits for its script to be revised.
|
|
453
|
+
if (data.data.state === "done" && track.pause?.cancelOnly !== true) this.end(track.subject);
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
case "niwa.invocation.resolved": {
|
|
457
|
+
const data = OfInvocation.safeParse(row.data);
|
|
458
|
+
const track = data.success ? this.ofInvocation(data.data.invocation) : undefined;
|
|
459
|
+
if (track === undefined) return;
|
|
460
|
+
// A retry, a skip or a cancel answers the pause of the invocation.
|
|
461
|
+
track.pause = undefined;
|
|
462
|
+
track.last = at;
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
case "request.created": {
|
|
466
|
+
const data = RequestMade.safeParse(row.data);
|
|
467
|
+
if (!data.success) return;
|
|
468
|
+
const from = data.data.from;
|
|
469
|
+
const subject =
|
|
470
|
+
from?.kind === "session" && from.harness !== undefined && from.id !== undefined
|
|
471
|
+
? trySessionSubject(from.harness, from.id)
|
|
472
|
+
: this.ofActor(row)?.subject;
|
|
473
|
+
const track = subject === undefined ? undefined : this.tracks.get(subject);
|
|
474
|
+
if (subject === undefined) return;
|
|
475
|
+
this.requests.set(data.data.id, subject);
|
|
476
|
+
// Only a question to the owner waits for a person; one to a session or another address waits for what answers it.
|
|
477
|
+
track?.asked.set(data.data.id, data.data.to.kind === "owner");
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
case "request.answered":
|
|
481
|
+
case "request.cancelled":
|
|
482
|
+
case "request.expired": {
|
|
483
|
+
const data = OfRequest.safeParse(row.data);
|
|
484
|
+
if (!data.success) return;
|
|
485
|
+
const subject = this.requests.get(data.data.id);
|
|
486
|
+
this.requests.delete(data.data.id);
|
|
487
|
+
const track = subject === undefined ? undefined : this.tracks.get(subject);
|
|
488
|
+
if (track === undefined) return;
|
|
489
|
+
track.asked.delete(data.data.id);
|
|
490
|
+
track.last = at;
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
case "timer.sleep.requested": {
|
|
494
|
+
const data = OfKey.safeParse(row.data);
|
|
495
|
+
if (!data.success) return;
|
|
496
|
+
// The key of a sleep is the invocation and the sleeping place: `<invocation>:<place>`.
|
|
497
|
+
const invocation = row.actor.kind === "handler" ? (row.actor.invocation as string) : data.data.key.split(":")[0];
|
|
498
|
+
const track = invocation === undefined ? undefined : this.ofInvocation(invocation);
|
|
499
|
+
if (track === undefined) return;
|
|
500
|
+
this.sleeps.set(data.data.key, track.subject);
|
|
501
|
+
track.timers.add(data.data.key);
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
case "timer.slept": {
|
|
505
|
+
const data = OfKey.safeParse(row.data);
|
|
506
|
+
if (!data.success) return;
|
|
507
|
+
const subject = this.sleeps.get(data.data.key);
|
|
508
|
+
this.sleeps.delete(data.data.key);
|
|
509
|
+
const track = subject === undefined ? undefined : this.tracks.get(subject);
|
|
510
|
+
if (track === undefined) return;
|
|
511
|
+
track.timers.delete(data.data.key);
|
|
512
|
+
track.last = at;
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
case "watch.stuck": {
|
|
516
|
+
const data = Stuck.safeParse(row.data);
|
|
517
|
+
if (data.success && isKind(data.data.kind)) {
|
|
518
|
+
this.open.set(data.data.subject, { since: data.data.since, last: data.data.last, kind: data.data.kind });
|
|
519
|
+
}
|
|
520
|
+
return;
|
|
521
|
+
}
|
|
522
|
+
case "watch.recovered": {
|
|
523
|
+
const data = Flag.safeParse(row.data);
|
|
524
|
+
if (!data.success) return;
|
|
525
|
+
const flag = this.open.get(data.data.subject);
|
|
526
|
+
// It closes the flag it names, not a newer one for the same subject.
|
|
527
|
+
if (flag !== undefined && flag.since === data.data.since && flag.kind === data.data.kind) {
|
|
528
|
+
this.open.delete(data.data.subject);
|
|
529
|
+
}
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
default:
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/** What every followed subject is doing at `now`, by subject. */
|
|
538
|
+
readings(now: number, settings: Settings = DEFAULT_SETTINGS): Reading[] {
|
|
539
|
+
const readings: Reading[] = [];
|
|
540
|
+
for (const track of this.tracks.values()) readings.push(this.reading(track, now, settings));
|
|
541
|
+
return readings.sort((a, b) => (a.subject < b.subject ? -1 : a.subject > b.subject ? 1 : 0));
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/** What one subject is doing at `now`; undefined for a subject the model does not follow. */
|
|
545
|
+
readingOf(subject: Subject, now: number, settings: Settings = DEFAULT_SETTINGS): Reading | undefined {
|
|
546
|
+
const track = this.tracks.get(subject);
|
|
547
|
+
return track === undefined ? undefined : this.reading(track, now, settings);
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
private reading(track: Track, now: number, settings: Settings): Reading {
|
|
551
|
+
const shape = (state: Reading["state"], since: number, kind?: StuckKind): Reading => ({
|
|
552
|
+
subject: track.subject,
|
|
553
|
+
state,
|
|
554
|
+
since,
|
|
555
|
+
last: track.last,
|
|
556
|
+
...(kind === undefined ? {} : { kind }),
|
|
557
|
+
});
|
|
558
|
+
|
|
559
|
+
// A run whose cancel spared a shielded scope that is still open past the grace is not stopping.
|
|
560
|
+
const spared = [...track.shields.values()].filter((at): at is number => at !== undefined && now - at >= settings.shieldGrace);
|
|
561
|
+
if (spared.length > 0) return shape("stuck", Math.min(...spared), "shielded-cancel");
|
|
562
|
+
|
|
563
|
+
const held = this.heldState(track);
|
|
564
|
+
if (held !== undefined) return shape(held, track.since);
|
|
565
|
+
if (track.base !== "working") return shape(track.base, track.since);
|
|
566
|
+
|
|
567
|
+
const repeats = track.kind === "run" ? settings.loopRepeats : settings.sessionLoopRepeats;
|
|
568
|
+
if (track.streak !== undefined && track.streak.count >= repeats) return shape("looping", track.streak.from, "looping");
|
|
569
|
+
|
|
570
|
+
const quiet = settings.silentAfter;
|
|
571
|
+
const allowed = track.stuckAfter ?? quiet;
|
|
572
|
+
// A silence the watch flagged lasts until a sign of life: it is not counted again from a later floor.
|
|
573
|
+
const flagged = this.open.get(track.subject);
|
|
574
|
+
if (flagged?.kind === "silent" && flagged.last === track.last) return shape("stuck", flagged.since, "silent");
|
|
575
|
+
// Time the watch was not looking does not count as quiet.
|
|
576
|
+
const lastSign = Math.max(track.last, this.floor);
|
|
577
|
+
if (now - lastSign >= allowed) return shape("stuck", lastSign + allowed, "silent");
|
|
578
|
+
return shape("working", track.since);
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/** What holds a subject that would otherwise be working: a question to a person, a paused run, a sleep, a wait. */
|
|
582
|
+
private heldState(track: Track): Reading["state"] | undefined {
|
|
583
|
+
const asked = track.asked.size > 0;
|
|
584
|
+
const person = [...track.asked.values()].includes(true);
|
|
585
|
+
if (track.kind === "session") {
|
|
586
|
+
if (!asked || track.base === "unknown") return undefined;
|
|
587
|
+
return person ? "waiting-human" : "waiting-event";
|
|
588
|
+
}
|
|
589
|
+
if (!track.started) return track.base === "idle" ? "idle" : undefined;
|
|
590
|
+
// A deadline that was reached pauses the run from that moment; a pause someone asked for, when the run reaches a boundary.
|
|
591
|
+
if (track.manual?.deadline === true) return "waiting-human";
|
|
592
|
+
if (track.pause !== undefined || track.invocationState === "paused") return "waiting-human";
|
|
593
|
+
if (track.manual !== undefined && track.invocationState === "waiting") return "waiting-human";
|
|
594
|
+
if (track.invocationState !== "waiting") return undefined;
|
|
595
|
+
if (person) return "waiting-human";
|
|
596
|
+
return this.sleeping(track) ? "sleeping" : "waiting-event";
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* Whether the run waits for a moment: a sleep of its own is open with its wake not yet come, and no wait for a record
|
|
601
|
+
* is. A wait with a timeout arms the same wake as a sleep, but a record can end it, and a wake left over from a wait
|
|
602
|
+
* that a record ended is not what a later wait waits for.
|
|
603
|
+
*/
|
|
604
|
+
private sleeping(track: Track): boolean {
|
|
605
|
+
let asleep = false;
|
|
606
|
+
for (const [key, action] of track.steps) {
|
|
607
|
+
if (action === SCRIPT_WAIT_ACTION) return false;
|
|
608
|
+
if (action === WAIT_ACTION && track.invocation !== undefined && track.timers.has(`${track.invocation}:${key}`)) asleep = true;
|
|
609
|
+
}
|
|
610
|
+
return asleep;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
private create(subject: Subject, kind: Track["kind"], at: number): Track | undefined {
|
|
614
|
+
if (this.gone.has(subject)) return undefined;
|
|
615
|
+
const track: Track = { subject, kind, base: "idle", managed: false, shown: "idle", since: at, last: at, started: kind === "session", asked: new Map(), steps: new Map(), timers: new Set(), shields: new Map() };
|
|
616
|
+
this.tracks.set(subject, track);
|
|
617
|
+
return track;
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
/** The track of a subject that begins or begins again: a start or a new turn is a reason to follow it. */
|
|
621
|
+
private revive(subject: Subject, kind: Track["kind"], at: number): Track {
|
|
622
|
+
this.gone.delete(subject);
|
|
623
|
+
const track = this.tracks.get(subject) ?? this.create(subject, kind, at);
|
|
624
|
+
if (track === undefined) throw new Error(`the subject ${subject} could not be followed`);
|
|
625
|
+
track.last = Math.max(track.last, at);
|
|
626
|
+
return track;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
private known(subject: Subject): Track | undefined {
|
|
630
|
+
return this.tracks.get(subject);
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/** The track of the run a record is about, unless an invocation other than the run's current one wrote it. */
|
|
634
|
+
private attemptOf(row: StoredRecord, run: string): Track | undefined {
|
|
635
|
+
const track = this.tracks.get(runSubject(run));
|
|
636
|
+
if (track === undefined) return undefined;
|
|
637
|
+
if (row.actor.kind === "handler" && track.invocation !== undefined && (row.actor.invocation as string) !== track.invocation) return undefined;
|
|
638
|
+
return track;
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
private ofInvocation(invocation: string): Track | undefined {
|
|
642
|
+
const subject = this.byInvocation.get(invocation);
|
|
643
|
+
const track = subject === undefined ? undefined : this.tracks.get(subject);
|
|
644
|
+
return track?.invocation === invocation ? track : undefined;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/** The invocation a run was in is over for it: what it said is not read for the run any more. */
|
|
648
|
+
private release(track: Track): void {
|
|
649
|
+
if (track.invocation !== undefined) this.byInvocation.delete(track.invocation);
|
|
650
|
+
track.invocation = undefined;
|
|
651
|
+
track.invocationState = undefined;
|
|
652
|
+
track.steps.clear();
|
|
653
|
+
track.timers.clear();
|
|
654
|
+
for (const [key, owner] of this.sleeps) if (owner === track.subject) this.sleeps.delete(key);
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/** The run whose handler wrote a record, when one did. */
|
|
658
|
+
private ofActor(row: StoredRecord): Track | undefined {
|
|
659
|
+
return row.actor.kind === "handler" ? this.ofInvocation(row.actor.invocation as string) : undefined;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
private become(track: Track, base: Base, at: number): void {
|
|
663
|
+
track.base = base;
|
|
664
|
+
track.last = at;
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
private repeat(track: Track, signature: string, at: number): void {
|
|
668
|
+
const streak = track.streak;
|
|
669
|
+
track.streak =
|
|
670
|
+
streak !== undefined && streak.signature === signature
|
|
671
|
+
? { signature, count: streak.count + 1, from: streak.from }
|
|
672
|
+
: { signature, count: 1, from: at };
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
private end(subject: Subject): void {
|
|
676
|
+
const track = this.tracks.get(subject);
|
|
677
|
+
this.tracks.delete(subject);
|
|
678
|
+
this.gone.add(subject);
|
|
679
|
+
if (track?.invocation !== undefined) this.byInvocation.delete(track.invocation);
|
|
680
|
+
for (const [key, owner] of this.requests) if (owner === subject) this.requests.delete(key);
|
|
681
|
+
for (const [key, owner] of this.sleeps) if (owner === subject) this.sleeps.delete(key);
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/**
|
|
686
|
+
* The records to write so that the flags in the journal say what the readings say: close a flag whose
|
|
687
|
+
* condition is over or changed, open one for a subject that is stuck or looping and has none.
|
|
688
|
+
*/
|
|
689
|
+
export function transitions(flags: ReadonlyMap<Subject, OpenFlag>, readings: readonly Reading[]): Transition[] {
|
|
690
|
+
const wanted = new Map<Subject, Reading & { kind: StuckKind }>();
|
|
691
|
+
for (const reading of readings) if (reading.kind !== undefined) wanted.set(reading.subject, { ...reading, kind: reading.kind });
|
|
692
|
+
|
|
693
|
+
const closing: Transition[] = [];
|
|
694
|
+
for (const [subject, flag] of flags) {
|
|
695
|
+
const now = wanted.get(subject);
|
|
696
|
+
if (now === undefined || now.kind !== flag.kind || now.since !== flag.since) {
|
|
697
|
+
closing.push({ type: "recovered", data: { subject, since: flag.since, kind: flag.kind } });
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
const opening: Transition[] = [];
|
|
702
|
+
for (const [subject, reading] of wanted) {
|
|
703
|
+
const flag = flags.get(subject);
|
|
704
|
+
if (flag === undefined || flag.kind !== reading.kind || flag.since !== reading.since) {
|
|
705
|
+
opening.push({ type: "stuck", data: { subject, since: reading.since, last: reading.last, kind: reading.kind } });
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
return [...closing, ...opening];
|
|
709
|
+
}
|