@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.
@@ -0,0 +1,287 @@
1
+ import { expect, test } from "bun:test";
2
+ import { z } from "zod";
3
+
4
+ import { isCallTarget, record } from "@niwa-labs/core";
5
+ import type { Action, StoredRecord } from "@niwa-labs/core";
6
+ import { plugin } from "@niwa-labs/plugin";
7
+ import type { Plugin, PluginApi } from "@niwa-labs/plugin";
8
+ import { createNiwa, eventually, tempHome, testClock } from "@niwa-labs/testing";
9
+ import type { TestClock } from "@niwa-labs/testing";
10
+
11
+ import { watch } from "../src/index.ts";
12
+ import { Subject, WatchRecovered, WatchStuck, runSubject, sessionSubject, subjectTarget, watchGet, watchList } from "../src/records.ts";
13
+
14
+ const MINUTE = 60_000;
15
+ const START = 1_000_000;
16
+ const ME = "claude abc";
17
+ const me = sessionSubject("claude", "abc");
18
+
19
+ // The records of the sessions, as the sessions plugin writes them, declared here so that a host
20
+ // without that plugin can carry them. Only the fields the watch reads are given.
21
+ const Started = record("session.started", z.object({ session: z.string(), id: z.string() }));
22
+ const TurnStarted = record("session.turn-started", z.object({ session: z.string(), turn: z.number() }));
23
+ const TurnEnded = record("session.turn-ended", z.object({ session: z.string(), turn: z.number() }));
24
+ const Activity = record("session.activity", z.object({ session: z.string(), tool: z.string().optional() }));
25
+ const Asked = record(
26
+ "request.created",
27
+ z.object({ id: z.string(), to: z.object({ kind: z.string() }), from: z.object({ kind: z.string(), harness: z.string(), id: z.string() }) }),
28
+ );
29
+ const Answered = record("request.answered", z.object({ id: z.string(), answer: z.object({}) }));
30
+ const sessionRecords = plugin("fixture", (api) => api.declare(Started, TurnStarted, TurnEnded, Activity, Asked, Answered));
31
+
32
+ interface Rig {
33
+ readonly niwa: ReturnType<typeof createNiwa>;
34
+ readonly clock: TestClock;
35
+ }
36
+
37
+ async function rig(use: Plugin[], run: (rig: Rig) => Promise<void>, opts: { home?: string; start?: number } = {}): Promise<void> {
38
+ const home = opts.home === undefined ? await tempHome() : undefined;
39
+ const clock = testClock(opts.start ?? START);
40
+ const niwa = createNiwa({ home: opts.home ?? home!.path, clock });
41
+ try {
42
+ niwa.use(sessionRecords, ...use);
43
+ await niwa.serve();
44
+ await run({ niwa, clock });
45
+ // Work the watch does on the clock must not fail quietly.
46
+ expect(clock.failures()).toEqual([]);
47
+ } finally {
48
+ await niwa.close();
49
+ await home?.cleanup();
50
+ }
51
+ }
52
+
53
+ const flagsOf = async (niwa: Rig["niwa"]): Promise<StoredRecord[]> =>
54
+ (await niwa.records.read()).filter((row) => row.type === "watch.stuck" || row.type === "watch.recovered");
55
+
56
+ const typesOf = (rows: StoredRecord[]): string[] => rows.map((row) => row.type as string);
57
+
58
+ async function beginTurn(niwa: Rig["niwa"]): Promise<void> {
59
+ await niwa.emit(Started, { session: ME, id: "s-1" });
60
+ await niwa.emit(TurnStarted, { session: ME, turn: 1 });
61
+ }
62
+
63
+ test("a session that goes quiet is flagged once, when its time runs out", async () => {
64
+ await rig([watch()], async ({ niwa, clock }) => {
65
+ await beginTurn(niwa);
66
+ await clock.advance(9 * MINUTE);
67
+ expect(await flagsOf(niwa)).toEqual([]);
68
+
69
+ await clock.advance(2 * MINUTE);
70
+ const flags = await flagsOf(niwa);
71
+ expect(flags).toHaveLength(1);
72
+ expect(flags[0]).toMatchObject({ type: "watch.stuck", data: { subject: me, kind: "silent", last: START, since: START + 10 * MINUTE } });
73
+
74
+ await clock.advance(30 * MINUTE);
75
+ expect(await flagsOf(niwa)).toHaveLength(1);
76
+ expect(await niwa.call(watchGet, { subject: me })).toMatchObject({ state: "stuck", kind: "silent" });
77
+ });
78
+ });
79
+
80
+ test("a sign of life from a flagged session is recorded as a recovery, and a new silence is a new flag", async () => {
81
+ await rig([watch()], async ({ niwa, clock }) => {
82
+ await beginTurn(niwa);
83
+ await clock.advance(11 * MINUTE);
84
+ await niwa.emit(Activity, { session: ME, tool: "Bash" });
85
+ await clock.advance(MINUTE);
86
+
87
+ const flags = await flagsOf(niwa);
88
+ expect(typesOf(flags)).toEqual(["watch.stuck", "watch.recovered"]);
89
+ expect(flags[1]?.data).toEqual({ subject: me, kind: "silent", since: START + 10 * MINUTE });
90
+ expect(await niwa.call(watchGet, { subject: me })).toMatchObject({ state: "working" });
91
+
92
+ await clock.advance(12 * MINUTE);
93
+ expect(typesOf(await flagsOf(niwa))).toEqual(["watch.stuck", "watch.recovered", "watch.stuck"]);
94
+ });
95
+ });
96
+
97
+ test("a session that ends while flagged has its flag closed", async () => {
98
+ await rig([watch()], async ({ niwa, clock }) => {
99
+ await beginTurn(niwa);
100
+ await clock.advance(11 * MINUTE);
101
+ await niwa.emit(TurnEnded, { session: ME, turn: 1 });
102
+ await clock.advance(MINUTE);
103
+ expect(typesOf(await flagsOf(niwa))).toEqual(["watch.stuck", "watch.recovered"]);
104
+ expect(await niwa.call(watchGet, { subject: me })).toMatchObject({ state: "idle" });
105
+ });
106
+ });
107
+
108
+ test("a flag survives a restart without a second record, and a sign of life after it still recovers", async () => {
109
+ const home = await tempHome();
110
+ try {
111
+ await rig([watch()], async ({ niwa, clock }) => {
112
+ await beginTurn(niwa);
113
+ await clock.advance(11 * MINUTE);
114
+ expect(await flagsOf(niwa)).toHaveLength(1);
115
+ }, { home: home.path });
116
+
117
+ await rig([watch()], async ({ niwa, clock }) => {
118
+ await clock.advance(5 * MINUTE);
119
+ expect(typesOf(await flagsOf(niwa))).toEqual(["watch.stuck"]);
120
+ expect(await niwa.call(watchGet, { subject: me })).toMatchObject({ state: "stuck", kind: "silent", since: START + 10 * MINUTE });
121
+
122
+ await niwa.emit(Activity, { session: ME });
123
+ await clock.advance(MINUTE);
124
+ expect(typesOf(await flagsOf(niwa))).toEqual(["watch.stuck", "watch.recovered"]);
125
+ }, { home: home.path, start: START + 3 * 60 * MINUTE });
126
+ } finally {
127
+ await home.cleanup();
128
+ }
129
+ });
130
+
131
+ test("time the host was down is not counted as silence", async () => {
132
+ const home = await tempHome();
133
+ try {
134
+ await rig([watch()], async ({ niwa }) => {
135
+ await beginTurn(niwa);
136
+ }, { home: home.path });
137
+
138
+ await rig([watch()], async ({ niwa, clock }) => {
139
+ await clock.advance(9 * MINUTE);
140
+ expect(await flagsOf(niwa)).toEqual([]);
141
+ await clock.advance(2 * MINUTE);
142
+ expect(await flagsOf(niwa)).toHaveLength(1);
143
+ }, { home: home.path, start: START + 5 * 60 * MINUTE });
144
+ } finally {
145
+ await home.cleanup();
146
+ }
147
+ });
148
+
149
+ test("a workflow-like subscriber is woken by the records it filters for, and by no others", async () => {
150
+ const silent: string[] = [];
151
+ const looping: string[] = [];
152
+ const reactions = plugin("react", (api) => {
153
+ api.on(WatchStuck, { id: "poke", filter: { kind: "silent" } }, (data) => void silent.push(data.subject));
154
+ api.on(WatchStuck, { id: "kill", filter: { kind: "looping" } }, (data) => void looping.push(data.subject));
155
+ api.on(WatchRecovered, { id: "relax" }, () => undefined);
156
+ });
157
+ await rig([watch(), reactions], async ({ niwa, clock }) => {
158
+ await beginTurn(niwa);
159
+ await clock.advance(11 * MINUTE);
160
+ await eventually(() => silent.length === 1);
161
+ expect(silent).toEqual([me]);
162
+ expect(looping).toEqual([]);
163
+ });
164
+ });
165
+
166
+ test("a session looping on the same activity is flagged as looping", async () => {
167
+ await rig([watch({ sessionLoopRepeats: 3 })], async ({ niwa, clock }) => {
168
+ await beginTurn(niwa);
169
+ for (let n = 0; n < 3; n += 1) {
170
+ await clock.advance(1000);
171
+ await niwa.emit(Activity, { session: ME, tool: "Edit" });
172
+ }
173
+ await clock.advance(20_000);
174
+ const flags = await flagsOf(niwa);
175
+ expect(flags).toHaveLength(1);
176
+ expect(flags[0]).toMatchObject({ type: "watch.stuck", data: { subject: me, kind: "looping" } });
177
+ });
178
+ });
179
+
180
+ test("a condition that comes back after a recovery is flagged again, though nothing about its start changed", async () => {
181
+ await rig([watch({ sessionLoopRepeats: 3 })], async ({ niwa, clock }) => {
182
+ await beginTurn(niwa);
183
+ for (let n = 0; n < 3; n += 1) {
184
+ await clock.advance(1000);
185
+ await niwa.emit(Activity, { session: ME, tool: "Edit" });
186
+ }
187
+ await clock.advance(20_000);
188
+ expect(typesOf(await flagsOf(niwa))).toEqual(["watch.stuck"]);
189
+
190
+ // A question to a person is not a loop; the answer puts the same loop back, from the same start.
191
+ await niwa.emit(Asked, { id: "req-1", to: { kind: "owner" }, from: { kind: "session", harness: "claude", id: "abc" } });
192
+ await clock.advance(20_000);
193
+ expect(typesOf(await flagsOf(niwa))).toEqual(["watch.stuck", "watch.recovered"]);
194
+ await niwa.emit(Answered, { id: "req-1", answer: {} });
195
+ await clock.advance(20_000);
196
+
197
+ const flags = await flagsOf(niwa);
198
+ expect(typesOf(flags)).toEqual(["watch.stuck", "watch.recovered", "watch.stuck"]);
199
+ expect(flags[0]?.data).toMatchObject({ kind: "looping", since: flags[2]?.data && (flags[2].data as { since: number }).since });
200
+ expect((flags[2]?.data as { last: number }).last).toBeGreaterThan((flags[0]?.data as { last: number }).last);
201
+ });
202
+ });
203
+
204
+ test("watch.get and watch.list read the states now, with records written since the last look", async () => {
205
+ await rig([watch({ silentAfter: 5 * MINUTE })], async ({ niwa, clock }) => {
206
+ await beginTurn(niwa);
207
+ expect((await niwa.call(watchList, {})).subjects).toEqual([{ subject: me, state: "working", since: START, last: START }]);
208
+
209
+ await niwa.emit(Started, { session: "claude other", id: "s-2" });
210
+ const other = sessionSubject("claude", "other");
211
+ expect(await niwa.call(watchGet, { subject: other })).toEqual({ subject: other, state: "idle", since: START, last: START });
212
+ expect((await niwa.call(watchList, {})).subjects.map((one) => [one.subject, one.state])).toEqual([
213
+ [me, "working"],
214
+ [other, "idle"],
215
+ ]);
216
+
217
+ await clock.advance(6 * MINUTE);
218
+ expect((await niwa.call(watchList, { state: "stuck" })).subjects.map((one) => one.subject)).toEqual([me]);
219
+ await expect(niwa.call(watchGet, { subject: sessionSubject("claude", "nobody") })).rejects.toThrow(/does not follow/);
220
+ });
221
+ });
222
+
223
+ test("a record is counted once however many looks read past it", async () => {
224
+ await rig([watch({ sessionLoopRepeats: 3 })], async ({ niwa, clock }) => {
225
+ await beginTurn(niwa);
226
+ await niwa.emit(Activity, { session: ME, tool: "Edit" });
227
+ await niwa.emit(Activity, { session: ME, tool: "Edit" });
228
+ // Many looks pass over the two records; two repeats are not three.
229
+ await clock.advance(5 * MINUTE);
230
+ expect(await flagsOf(niwa)).toEqual([]);
231
+ expect(await niwa.call(watchGet, { subject: me })).toMatchObject({ state: "working" });
232
+ });
233
+ });
234
+
235
+ test("the limits must be positive numbers", () => {
236
+ expect(() => watch({ silentAfter: 0 })).toThrow(/silentAfter/);
237
+ expect(() => watch({ tick: -1 })).toThrow(/tick/);
238
+ expect(() => watch({ loopRepeats: Number.NaN })).toThrow(/loopRepeats/);
239
+ expect(() => watch({ silentAfter: undefined })).not.toThrow();
240
+ });
241
+
242
+ test("the limits must be whole numbers of milliseconds and of repeats", () => {
243
+ expect(() => watch({ silentAfter: 1.5 })).toThrow(/silentAfter/);
244
+ expect(() => watch({ shieldGrace: 0.5 })).toThrow(/shieldGrace/);
245
+ expect(() => watch({ tick: 2.5 })).toThrow(/tick/);
246
+ expect(() => watch({ loopRepeats: 2.5 })).toThrow(/loopRepeats/);
247
+ expect(() => watch({ sessionLoopRepeats: Number.MAX_SAFE_INTEGER + 2 })).toThrow(/sessionLoopRepeats/);
248
+ expect(() => watch({ silentAfter: 90_000, loopRepeats: 3 })).not.toThrow();
249
+ });
250
+
251
+ /** The actions a plugin registers, read by running its setup against a recording api. */
252
+ function actionsOf(source: Plugin): Map<string, Action<any, any, any>> {
253
+ const found = new Map<string, Action<any, any, any>>();
254
+ const api = new Proxy({} as PluginApi, {
255
+ get: (_target, name) => (name === "action" ? (one: Action<any, any, any>) => void found.set(one.name, one) : () => undefined),
256
+ });
257
+ source.setup(api);
258
+ return found;
259
+ }
260
+
261
+ test("the watch only reads: its actions are reads of niwa's own state", () => {
262
+ const actions = actionsOf(watch());
263
+ expect([...actions.keys()].sort()).toEqual(["watch.get", "watch.list"]);
264
+ for (const one of actions.values()) expect(one).toMatchObject({ effect: "read", world: "niwa", recovery: "repeat" });
265
+ expect(actions.get("watch.get")?.target?.({ subject: me })).toBe("session/claude/abc");
266
+ expect(actions.get("watch.get")?.target?.({ subject: runSubject("run-1") })).toBe("run/run-1");
267
+ });
268
+
269
+ test("a subject names a harness and an id for a session, and an id for a run", () => {
270
+ for (const text of ["session:claude", "session:claude ", "session: abc", "session:a b", "run:", "run: x", "thing:x"]) {
271
+ expect(Subject.safeParse(text).success, text).toBe(false);
272
+ }
273
+ for (const text of ["session:claude abc", "session:pi a b/c", "run:run-1", "run:a b"]) {
274
+ expect(Subject.safeParse(text).success, text).toBe(true);
275
+ }
276
+ // Two pairs never give one subject, so never one target.
277
+ expect(() => sessionSubject("a b", "c")).toThrow(TypeError);
278
+ expect(() => sessionSubject("a", "")).toThrow(TypeError);
279
+ expect(subjectTarget(sessionSubject("a", "b c"))).toBe("session/a/b%20c");
280
+ });
281
+
282
+ test("the target of a call to read a subject is one a grant can name, whatever the id holds", () => {
283
+ for (const subject of [me, sessionSubject("pi", "a b/c*{x}@y:z"), runSubject("run/1 *")]) {
284
+ expect(isCallTarget(subjectTarget(subject))).toBe(true);
285
+ }
286
+ expect(subjectTarget(sessionSubject("pi", "a/*"))).toBe("session/pi/a%2F%2A");
287
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "lib": [
5
+ "ESNext",
6
+ "DOM",
7
+ "DOM.Iterable",
8
+ "DOM.AsyncIterable"
9
+ ],
10
+ "jsx": "react-jsx"
11
+ },
12
+ "include": [
13
+ "src"
14
+ ]
15
+ }