@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/src/records.ts ADDED
@@ -0,0 +1,180 @@
1
+ /**
2
+ * The records of the watch plugin, and the typed references of its actions.
3
+ *
4
+ * A subject is something that works and can stop working: a session or a run, named
5
+ * `session:<harness> <native id>` or `run:<id>`. The watch writes only two facts about a subject,
6
+ * that it is stuck and that it is not any more; what to do about it is a workflow subscribed to
7
+ * those records.
8
+ */
9
+
10
+ import { z } from "zod";
11
+
12
+ import { actionRef, queryOf, record } from "@niwa-labs/core";
13
+ import type { TypeQuery } from "@niwa-labs/core";
14
+
15
+ /** What a subject is doing, as the journal shows it. */
16
+ export const WatchState = z.enum([
17
+ /** Making progress: a turn or a step is going on and signs of life keep coming. */
18
+ "working",
19
+ /** Waiting for a person: a question is open, or a run is paused for a decision. */
20
+ "waiting-human",
21
+ /** Waiting for something to happen: a run is suspended on a record or on another run's work. */
22
+ "waiting-event",
23
+ /** Waiting for a moment: a timer will wake it. */
24
+ "sleeping",
25
+ /** Nothing to do: a session between turns, a run not yet started. */
26
+ "idle",
27
+ /** Working, but repeating itself without anything changing. */
28
+ "looping",
29
+ /** Should be working and is not, or was told to stop and does not. */
30
+ "stuck",
31
+ /** The journal does not say: a watch began, or a turn ended with no known outcome. */
32
+ "unknown",
33
+ ]);
34
+ export type WatchState = z.infer<typeof WatchState>;
35
+
36
+ /**
37
+ * Why a subject counts as stuck:
38
+ *
39
+ * - `silent` — it is working and has given no sign of life for too long;
40
+ * - `looping` — it repeats the same thing and nothing changes;
41
+ * - `shielded-cancel` — the run was cancelled and a shielded scope inside it still goes on.
42
+ */
43
+ export const StuckKind = z.enum(["silent", "looping", "shielded-cancel"]);
44
+ export type StuckKind = z.infer<typeof StuckKind>;
45
+
46
+ /** What a subject names: a run by its id, or a session by its harness and the id the harness gave it. */
47
+ type SubjectParts = { readonly kind: "run"; readonly id: string } | { readonly kind: "session"; readonly harness: string; readonly native: string };
48
+
49
+ /** The one reading of a subject's text: a run is `run:<id>`, a session `session:<harness> <id>` with a harness that holds no space. */
50
+ function partsOf(text: string): SubjectParts | undefined {
51
+ const run = /^run:(\S.*)$/.exec(text);
52
+ if (run?.[1] !== undefined) return { kind: "run", id: run[1] };
53
+ const session = /^session:(\S+) (\S.*)$/.exec(text);
54
+ if (session?.[1] !== undefined && session[2] !== undefined) return { kind: "session", harness: session[1], native: session[2] };
55
+ return undefined;
56
+ }
57
+
58
+ /** A session or a run: `session:<harness> <native id>`, `run:<id>`. */
59
+ export const Subject = z
60
+ .string()
61
+ .refine((text) => partsOf(text) !== undefined, "a subject is session:<harness> <id> or run:<id>")
62
+ .brand<"WatchSubject">();
63
+ export type Subject = z.infer<typeof Subject>;
64
+
65
+ /** The subject of a session, when the harness and the id name one: neither empty, and no space in the harness. */
66
+ export function trySessionSubject(harness: string, native: string): Subject | undefined {
67
+ const parsed = Subject.safeParse(`session:${harness} ${native}`);
68
+ const parts = parsed.success ? partsOf(parsed.data) : undefined;
69
+ // The text is read back, so that two pairs cannot give one subject.
70
+ return parts?.kind === "session" && parts.harness === harness && parts.native === native ? parsed.data : undefined;
71
+ }
72
+
73
+ /** The subject of a run, when the id names one: it is not empty and does not start with a space. */
74
+ export function tryRunSubject(run: string): Subject | undefined {
75
+ const parsed = Subject.safeParse(`run:${run}`);
76
+ return parsed.success ? parsed.data : undefined;
77
+ }
78
+
79
+ /** The subject of a session, from the harness and the id the harness gave it. */
80
+ export function sessionSubject(harness: string, native: string): Subject {
81
+ const subject = trySessionSubject(harness, native);
82
+ if (subject === undefined) throw new TypeError(`not a session: harness ${JSON.stringify(harness)}, id ${JSON.stringify(native)}`);
83
+ return subject;
84
+ }
85
+
86
+ /** The subject of a run. */
87
+ export function runSubject(run: string): Subject {
88
+ const subject = tryRunSubject(run);
89
+ if (subject === undefined) throw new TypeError(`not a run: ${JSON.stringify(run)}`);
90
+ return subject;
91
+ }
92
+
93
+ /**
94
+ * A subject is stuck.
95
+ *
96
+ * `since` is when the condition began (for silence: the end of the time it was allowed to be
97
+ * quiet), `last` is the moment of its last sign of life. Both are milliseconds since the epoch.
98
+ * A subject is flagged once for one condition: another record follows only after `watch.recovered`.
99
+ */
100
+ export const WatchStuck = record(
101
+ "watch.stuck",
102
+ z.object({
103
+ subject: Subject,
104
+ since: z.number().int().nonnegative(),
105
+ last: z.number().int().nonnegative(),
106
+ kind: StuckKind,
107
+ }),
108
+ );
109
+ export type WatchStuckData = z.infer<typeof WatchStuck.schema>;
110
+
111
+ /**
112
+ * The condition of a `watch.stuck` is over: the subject gave a sign of life, stopped repeating
113
+ * itself, ended, or its shielded scope closed. It names the record it closes by `subject`, `kind`
114
+ * and `since`.
115
+ */
116
+ export const WatchRecovered = record(
117
+ "watch.recovered",
118
+ z.object({
119
+ subject: Subject,
120
+ since: z.number().int().nonnegative(),
121
+ kind: StuckKind,
122
+ }),
123
+ );
124
+ export type WatchRecoveredData = z.infer<typeof WatchRecovered.schema>;
125
+
126
+ /**
127
+ * The stuck records of one subject, as a script waits for or reads them with their data typed:
128
+ * `await wait(watchStuck(subject), { timeout: "1h" })`. With `kind`, only that condition. A text that
129
+ * is not a subject is refused here.
130
+ */
131
+ export function watchStuck(subject: string, kind?: StuckKind): TypeQuery<WatchStuckData> {
132
+ return queryOf(WatchStuck, { subject: Subject.parse(subject), ...(kind === undefined ? {} : { kind: StuckKind.parse(kind) }) });
133
+ }
134
+
135
+ /** The recoveries of one subject, or of one condition of it: what ends a `watch.stuck`. */
136
+ export function watchRecovered(subject: string, kind?: StuckKind): TypeQuery<WatchRecoveredData> {
137
+ return queryOf(WatchRecovered, { subject: Subject.parse(subject), ...(kind === undefined ? {} : { kind: StuckKind.parse(kind) }) });
138
+ }
139
+
140
+ /** The record types the watch plugin declares. */
141
+ export const WATCH_TYPES = [WatchStuck, WatchRecovered] as const;
142
+
143
+ /** One subject as the watch reads it now. */
144
+ export const Reading = z.object({
145
+ subject: Subject,
146
+ state: WatchState,
147
+ /** When the subject entered this state, in milliseconds since the epoch. */
148
+ since: z.number().int().nonnegative(),
149
+ /** Its last sign of life. */
150
+ last: z.number().int().nonnegative(),
151
+ /** Why it is stuck or looping; present exactly for those two states. */
152
+ kind: StuckKind.optional(),
153
+ });
154
+ export type Reading = z.infer<typeof Reading>;
155
+
156
+ /**
157
+ * What a grant's `@target` names a subject by: `session/<harness>/<id>` or `run/<id>`, each segment
158
+ * encoded so that no text can add a wildcard or a separator (`watch.get@session/claude/*`).
159
+ */
160
+ export function subjectTarget(subject: Subject): string {
161
+ const encoded = (text: string): string => encodeURIComponent(text).replace(/\*/g, "%2A");
162
+ const parts = partsOf(subject);
163
+ if (parts === undefined) throw new TypeError(`not a subject: ${JSON.stringify(subject)}`);
164
+ if (parts.kind === "run") return `run/${encoded(parts.id)}`;
165
+ return `session/${encoded(parts.harness)}/${encoded(parts.native)}`;
166
+ }
167
+
168
+ export const watchGet = actionRef("watch.get", {
169
+ description: "Read the state of a session or a run from the journal: what it is doing, since when, and its last sign of life.",
170
+ input: z.object({ subject: Subject }),
171
+ output: Reading,
172
+ target: (input) => subjectTarget(input.subject),
173
+ });
174
+
175
+ export const watchList = actionRef("watch.list", {
176
+ description:
177
+ "List the sessions and runs the watch follows, each with its state. `state` keeps those in one state, such as `stuck`.",
178
+ input: z.object({ state: WatchState.optional() }),
179
+ output: z.object({ subjects: z.array(Reading) }),
180
+ });
@@ -0,0 +1,29 @@
1
+ // The copy of the watch actions the cockpit module keeps reads what the host answers, and the host lists the module.
2
+
3
+ import { expect, test } from "bun:test";
4
+ import { actionName } from "@niwa-labs/core";
5
+ import { createNiwa, tempHome, unreadable, unsendable } from "@niwa-labs/testing";
6
+
7
+ import { watch } from "../src/index.ts";
8
+ import { watchList } from "../src/records.ts";
9
+ import { listAction } from "../src/cockpit/actions.ts";
10
+
11
+ test("the subjects are read from what the host answers", () => {
12
+ expect(String(listAction.name)).toBe(String(watchList.name));
13
+ expect(unsendable(listAction.input, watchList.input)).toEqual([]);
14
+ expect(unreadable(listAction.output, watchList.output)).toEqual([]);
15
+ });
16
+
17
+ test("the plugin offers its page to the cockpit", async () => {
18
+ const home = await tempHome();
19
+ const niwa = createNiwa({ home: home.path });
20
+ try {
21
+ niwa.use(watch());
22
+ await niwa.serve();
23
+ const catalog = (await niwa.call(actionName("niwa.cockpit.catalog"), {})) as { modules: Array<{ id: string; plugin: string }> };
24
+ expect(catalog.modules).toContainEqual(expect.objectContaining({ id: "watch", plugin: "watch" }));
25
+ } finally {
26
+ await niwa.close();
27
+ await home.cleanup();
28
+ }
29
+ });
@@ -0,0 +1,89 @@
1
+ // The watch page: the order of the subjects, what a subject is called, and the incidents the flags make.
2
+
3
+ import { expect, test } from "bun:test";
4
+
5
+ import { decisionText } from "../src/cockpit/decisions.ts";
6
+ import { matchRecord } from "@niwa-labs/cockpit-sdk";
7
+
8
+ import type { Reading, WatchState } from "../src/cockpit/actions.ts";
9
+ import { REFRESH_ON, agoText, countByState, incidents, ordered, subjectName, subjectText } from "../src/cockpit/subjects.ts";
10
+
11
+ function reading(subject: string, state: WatchState, since = 0): Reading {
12
+ return { subject, state, since, last: since };
13
+ }
14
+
15
+ test("troubles come first, then subjects that wait for a person, and the longest in a state first", () => {
16
+ const list = ordered([
17
+ reading("run:idle", "idle"),
18
+ reading("run:late", "working", 500),
19
+ reading("run:early", "working", 100),
20
+ reading("session:claude a", "waiting-human"),
21
+ reading("run:loop", "looping"),
22
+ reading("run:stuck", "stuck"),
23
+ ]);
24
+ expect(list.map((one) => one.subject)).toEqual(["run:stuck", "run:loop", "session:claude a", "run:early", "run:late", "run:idle"]);
25
+ });
26
+
27
+ test("states are counted in the order of the page and the empty ones are left out", () => {
28
+ expect(countByState([reading("run:a", "idle"), reading("run:b", "stuck"), reading("run:c", "idle")])).toEqual([
29
+ { state: "stuck", count: 1 },
30
+ { state: "idle", count: 2 },
31
+ ]);
32
+ expect(countByState([])).toEqual([]);
33
+ });
34
+
35
+ test("a subject is a run or a session with its harness", () => {
36
+ expect(subjectName("run:run-7")).toEqual({ kind: "run", id: "run-7" });
37
+ expect(subjectName("session:claude 4f9 a")).toEqual({ kind: "session", harness: "claude", id: "4f9 a" });
38
+ expect(subjectText("run:run-7")).toBe("run run-7");
39
+ expect(subjectText("session:codex abc")).toBe("session codex/abc");
40
+ });
41
+
42
+ test("a moment is told as how long ago it was", () => {
43
+ const now = 10_000_000;
44
+ expect(agoText(now + 5_000, now)).toBe("только что");
45
+ expect(agoText(now - 30_000, now)).toBe("30 с назад");
46
+ expect(agoText(now - 10 * 60_000, now)).toBe("10 мин назад");
47
+ expect(agoText(now - 3 * 3_600_000, now)).toBe("3 ч назад");
48
+ expect(agoText(now - 5 * 86_400_000, now)).toBe("5 дн назад");
49
+ });
50
+
51
+ const stuck = (subject: string, kind: string, since: number, last = since - 1) => ({ type: "watch.stuck", at: since + 1, data: { subject, kind, since, last } });
52
+ const recovered = (subject: string, kind: string, since: number, at: number) => ({ type: "watch.recovered", at, data: { subject, kind, since } });
53
+
54
+ test("a recovery closes the flag it names by subject, kind and since", () => {
55
+ const found = incidents([stuck("run:a", "silent", 100), stuck("run:a", "looping", 150), recovered("run:a", "silent", 100, 400)]);
56
+ expect(found.map((one) => [one.kind, one.recoveredAt])).toEqual([
57
+ ["looping", undefined],
58
+ ["silent", 400],
59
+ ]);
60
+ });
61
+
62
+ test("a subject flagged again after it recovered is a second incident", () => {
63
+ const found = incidents([stuck("run:a", "silent", 100), recovered("run:a", "silent", 100, 200), stuck("run:a", "silent", 300)]);
64
+ expect(found.map((one) => [one.since, one.recoveredAt])).toEqual([
65
+ [300, undefined],
66
+ [100, 200],
67
+ ]);
68
+ });
69
+
70
+ test("a recovery whose flag is not held is no incident, and a record that is no flag is ignored", () => {
71
+ expect(incidents([recovered("run:a", "silent", 100, 400), { type: "watch.stuck", at: 1, data: { subject: "run:a" } }, { type: "watch.stuck", at: 1, data: null }])).toEqual([]);
72
+ });
73
+
74
+ test("the list is read again after a record that moves a session or a run between states, and not after its activity", () => {
75
+ const at = (type: string) => ({ id: "r", seq: 1, type, stream: "s", at: 0, data: {} }) as unknown as Parameters<typeof matchRecord>[1];
76
+ for (const type of ["watch.stuck", "watch.recovered", "session.started", "session.turn-started", "session.turn-ended", "session.ended", "workflow.run.finished", "request.created", "request.answered", "timer.slept"]) {
77
+ expect([type, matchRecord(REFRESH_ON, at(type))]).toEqual([type, true]);
78
+ }
79
+ expect(matchRecord(REFRESH_ON, at("session.activity"))).toBe(false);
80
+ });
81
+
82
+ test("a merge claim and a refused write identify the affected entity in the watch", () => {
83
+ expect(decisionText({ type: "forge.pr.merge.started", data: {
84
+ operation: "op1", pr: { repo: { host: "git.example", path: "work/project" }, number: 2 },
85
+ } })).toBe("Запрошено слияние · git.example/work/project!2");
86
+ expect(decisionText({ type: "niwa.record.refused", actor: { kind: "client", id: "planner" }, data: {
87
+ recordType: "plan.revised", entity: "work", reason: "revision changed",
88
+ } })).toBe("planner · plan.revised · work · revision changed");
89
+ });
@@ -0,0 +1,27 @@
1
+ // The query builders of the watch records: what a script waits for when it watches a subject.
2
+
3
+ import { expect, test } from "bun:test";
4
+
5
+ import { resolveQuery } from "@niwa-labs/core";
6
+
7
+ import { WatchRecovered, WatchStuck, sessionSubject, watchRecovered, watchStuck } from "../src/records.ts";
8
+
9
+ const me = sessionSubject("claude", "abc");
10
+
11
+ test("the stuck and recovered records of a subject are queries of their type, filtered on it", () => {
12
+ expect(watchStuck(me)).toEqual({ types: [WatchStuck], filter: { subject: me } });
13
+ expect(watchRecovered(me)).toEqual({ types: [WatchRecovered], filter: { subject: me } });
14
+ expect(resolveQuery(watchStuck(me)).types?.map(String)).toEqual(["watch.stuck"]);
15
+ });
16
+
17
+ test("a condition narrows the query, and the filter paths are fields of the record", () => {
18
+ expect(watchStuck(me, "looping").filter).toEqual({ subject: me, kind: "looping" });
19
+ expect(watchRecovered(me, "silent").filter).toEqual({ subject: me, kind: "silent" });
20
+ const data = WatchStuck.schema.parse({ subject: me, since: 1, last: 0, kind: "looping" });
21
+ for (const [path, value] of Object.entries(watchStuck(me, "looping").filter ?? {})) expect((data as Record<string, unknown>)[path]).toBe(value);
22
+ });
23
+
24
+ test("a text that is not a subject, or a condition, is refused when the query is made", () => {
25
+ expect(() => watchStuck("claude abc")).toThrow();
26
+ expect(() => watchStuck(me, "tired" as never)).toThrow();
27
+ });