pi-straw-boss 0.75.3 → 0.76.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/dist/server/main.mjs +789 -507
- package/package.json +1 -1
- package/src/boardfill.ts +6 -3
- package/src/boardseed.ts +6 -2
- package/src/branchscan.ts +18 -0
- package/src/server/main.ts +6 -1
- package/src/server/procs.ts +3 -0
- package/src/server/procsops.ts +3 -1
- package/src/server/runs.ts +5 -4
- package/src/server/stallops.ts +73 -0
- package/src/server/stallwatch.ts +321 -0
- package/src/todo.ts +16 -6
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-straw-boss",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.76.0",
|
|
4
4
|
"description": "Straw Boss coordination for pi in Herdr: sessions join a tab's net by choice, the first joiner is its main agent, a workspace tower opens on demand with a live monitoring dashboard, and boss_broadcast reaches the rest",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
package/src/boardfill.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { join } from "node:path";
|
|
2
2
|
import { ENDED_MS, finished, readEntries, removeEntry, writeEntry } from "./board.ts";
|
|
3
3
|
import { type Derived, deriveBoard } from "./boardauto.ts";
|
|
4
|
-
import { BOARD_ENTRY, seedBoard,
|
|
4
|
+
import { BOARD_ENTRY, seedBoard, withdrawnScan } from "./boardseed.ts";
|
|
5
5
|
import type { Kit } from "./state.ts";
|
|
6
6
|
import { ownsBoard } from "./trainrole.ts";
|
|
7
|
-
import {
|
|
7
|
+
import { todosOf } from "./items.ts";
|
|
8
|
+
import { snapshotScan } from "./todo.ts";
|
|
8
9
|
|
|
9
10
|
// The work board fills itself (docs/specs/2026-10-25-straw-link.md, Work board, Auto-fill): the main's own session turns its todo list and its name into its entry and writes it
|
|
10
11
|
// with `writeEntry`, as `board_set` does, marked `src: "todo"`. The server takes no part. boardauto.ts is the derivation and the scrub.
|
|
@@ -26,7 +27,9 @@ export function createBoardFill({ pi, cfg, s, guiDir, me, role, tell }: Kit): Bo
|
|
|
26
27
|
const name = pi.getSessionName()?.trim() ?? "";
|
|
27
28
|
return name === me() || name === me().slice(0, 8) ? "" : name;
|
|
28
29
|
};
|
|
29
|
-
|
|
30
|
+
// The refresh runs at every tool call and walked the branch from the leaf for the todo snapshot each time (the whole branch in a session that keeps no todo list). That walk is incremental now (branchscan.ts): the snapshot is found once and then looked for only in what was appended; so is the withdrawal, which is read only while seeding and at a session start. pi's own `getBranch()` still walks the history at every call.
|
|
31
|
+
const snapshotOf = snapshotScan(), withdrawnKey = withdrawnScan();
|
|
32
|
+
const derive = () => deriveBoard({ name: named(), todos: todosOf(snapshotOf(branchOf())), root: ctx?.cwd ?? process.cwd() });
|
|
30
33
|
const branchOf = (): readonly unknown[] => {
|
|
31
34
|
try { return ctx?.sessionManager?.getBranch() ?? []; } catch { return []; } // a replaced session's context throws
|
|
32
35
|
};
|
package/src/boardseed.ts
CHANGED
|
@@ -1,17 +1,21 @@
|
|
|
1
1
|
import { type Entry, finished } from "./board.ts";
|
|
2
2
|
import type { Derived } from "./boardauto.ts";
|
|
3
|
+
import { newestOf } from "./branchscan.ts";
|
|
3
4
|
|
|
4
5
|
/** The custom entry a main keeps in its session when it withdraws the line for a derived entry (`board_set { clear }`, or a finished list's 30 minutes): a /reload reads it back, so the line is not written again. */
|
|
5
6
|
export const BOARD_ENTRY = "straw-boss-board";
|
|
6
7
|
|
|
8
|
+
const withdrawnOf = (entry: unknown): string | undefined => { const e = entry as { type?: string; customType?: string; data?: { cleared?: unknown } }; return e.type === "custom" && e.customType === BOARD_ENTRY && typeof e.data?.cleared === "string" ? e.data.cleared : undefined; };
|
|
7
9
|
/** The key of the newest withdrawal the session branch holds. */
|
|
8
10
|
export function withdrawnKey(branch: readonly unknown[]): string | undefined {
|
|
9
11
|
for (let i = branch.length - 1; i >= 0; i--) {
|
|
10
|
-
const
|
|
11
|
-
if (
|
|
12
|
+
const key = withdrawnOf(branch[i]);
|
|
13
|
+
if (key !== undefined) return key;
|
|
12
14
|
}
|
|
13
15
|
return undefined;
|
|
14
16
|
}
|
|
17
|
+
/** `withdrawnKey` for a reader that asks again as its branch grows: each call walks only what was appended since the last (branchscan.ts). */
|
|
18
|
+
export const withdrawnScan = (): ((branch: readonly unknown[]) => string | undefined) => newestOf(withdrawnOf);
|
|
15
19
|
|
|
16
20
|
/** What the auto-fill starts from on its first refresh after a start or /reload: `last` (the key it believes is written or withdrawn) and `doneAt` (when a finished line was written). */
|
|
17
21
|
export interface Seed { last?: string; doneAt?: number }
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// A session branch read again and again (the work board's refresh runs at every tool call): what a reader looks for in it is found once, and the reader's own walk then covers only the entries appended since. That is the reader's walk alone: pi builds the branch from the leaf to the root at every `getBranch()`, so a refresh still costs the length of the history there.
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The newest entry of a branch for which `pick` gives a value, as a full walk from the leaf would find it. The reader remembers the leaf it read last and what it found: a branch that still holds that entry
|
|
5
|
+
* at that place has the same entries before it (an entry has one parent, so the path from the root to it is one), and only what follows it is walked. Any other branch (the leaf moved to another branch of the
|
|
6
|
+
* tree or back to an ancestor, a new session) is walked whole. pi hands a new array at each `getBranch()`, with the same entry objects, so entries are compared by identity.
|
|
7
|
+
*/
|
|
8
|
+
export function newestOf<T>(pick: (entry: unknown) => T | undefined): (branch: readonly unknown[]) => T | undefined {
|
|
9
|
+
let length = 0, leaf: unknown, found: T | undefined;
|
|
10
|
+
return (branch) => {
|
|
11
|
+
const grown = length === 0 || (branch.length >= length && branch[length - 1] === leaf);
|
|
12
|
+
let hit: T | undefined;
|
|
13
|
+
for (let i = branch.length - 1; i >= (grown ? length : 0) && hit === undefined; i--) hit = pick(branch[i]);
|
|
14
|
+
found = hit ?? (grown ? found : undefined);
|
|
15
|
+
[length, leaf] = [branch.length, branch[branch.length - 1]];
|
|
16
|
+
return found;
|
|
17
|
+
};
|
|
18
|
+
}
|
package/src/server/main.ts
CHANGED
|
@@ -29,6 +29,7 @@ import { operateWire, type OperateWire } from "./operatewire.ts";
|
|
|
29
29
|
import { createLog, tailLog } from "./log.ts";
|
|
30
30
|
import { type Cars, carsReply, startCars } from "./carops.ts";
|
|
31
31
|
import { procsReply, startProcs, type StartProcs } from "./procsops.ts";
|
|
32
|
+
import { startStall, type StartStall } from "./stallops.ts";
|
|
32
33
|
import { gateRun, type RunInfo } from "./rungate.ts";
|
|
33
34
|
import type { ServerTools } from "./runtools.ts";
|
|
34
35
|
import {
|
|
@@ -112,6 +113,8 @@ export interface ServerOptions {
|
|
|
112
113
|
towers?: Partial<TowersOptions>;
|
|
113
114
|
/** Replaces the owner registry's seams (the process table, the kill sequence, the tick), for tests. */
|
|
114
115
|
procs?: StartProcs["over"];
|
|
116
|
+
/** The stall watch's seams (stallops.ts), for tests: without them a test run has no watch. */
|
|
117
|
+
stall?: StartStall["over"];
|
|
115
118
|
touchMs?: number;
|
|
116
119
|
brokerMs?: number;
|
|
117
120
|
herdrGoneMs?: number;
|
|
@@ -627,7 +630,9 @@ export async function runServer(o: ServerOptions): Promise<ServerHandle> {
|
|
|
627
630
|
log.line("herdr-takeover");
|
|
628
631
|
void towers?.takeover().catch((error: Error) => recordError("towers", error.message));
|
|
629
632
|
}, () => (log.line("herdr-lost", { at: Date.now() }), towers?.runs.herdrLost())));
|
|
630
|
-
|
|
633
|
+
// The stall watch (stallwatch.ts): a pi that froze is told to its workspace's tower from the registry's tick; it signals nothing.
|
|
634
|
+
const stall = startStall({ dir: slot.dir, stateDir: slot.stateDir, pid, platform, now, log: (event, facts) => log.line(event, facts), run: cfg.run, sessions: () => (client?.isConnected() ? client.listSessions() : Promise.reject(new Error("pi-intercom is not connected"))), towers: () => towers, ...(o.stall ? { over: o.stall } : {}) });
|
|
635
|
+
procs = startProcs({ dir: slot.dir, stateDir: slot.stateDir, env, pid, platform, now, log: (event, facts) => log.line(event, facts), run: cfg.run, events: cfg.events, ...(stall ? { watch: (table) => stall.sample(table) } : {}), ...(o.procs ? { over: o.procs } : {}), stops, timers, leaving: () => Boolean(leaving) || phase === "stopping" || phase === "restarting" });
|
|
631
636
|
let downSince: number | undefined;
|
|
632
637
|
const herdrUp = o.herdrUp ?? (() => herdrListens({ slot, platform }));
|
|
633
638
|
timers.push(setInterval(() => void herdrUp().then((up) => {
|
package/src/server/procs.ts
CHANGED
|
@@ -59,6 +59,8 @@ export interface ProcsDeps {
|
|
|
59
59
|
reap?: (refs: readonly Ref[]) => Promise<KillReport>;
|
|
60
60
|
/** Pids that must outlive any reap: this server. */
|
|
61
61
|
self?: number[];
|
|
62
|
+
/** Gets the table of each tick (the stall watch, stallwatch.ts): it runs behind the tick, which never waits for it. */
|
|
63
|
+
watch?: (table: readonly Proc[]) => Promise<void>;
|
|
62
64
|
ownUid?: number;
|
|
63
65
|
platform?: NodeJS.Platform;
|
|
64
66
|
}
|
|
@@ -278,6 +280,7 @@ export function createProcs(d: ProcsDeps): Procs {
|
|
|
278
280
|
async function takeTick(): Promise<void> {
|
|
279
281
|
const table = await read();
|
|
280
282
|
if (!table) return;
|
|
283
|
+
void d.watch?.(table).catch((error: Error) => d.log("procs-error", { text: `the tick's watch failed: ${String(error?.message).slice(0, 160)}` }));
|
|
281
284
|
await lookAtWorkspaces();
|
|
282
285
|
let changed = false;
|
|
283
286
|
for (const r of [...owners.values()]) {
|
package/src/server/procsops.ts
CHANGED
|
@@ -46,6 +46,8 @@ export interface StartProcs {
|
|
|
46
46
|
log(event: string, facts: Record<string, number | string | boolean>): void;
|
|
47
47
|
run: HerdrRun;
|
|
48
48
|
events: HerdrEvents;
|
|
49
|
+
/** The stall watch (stallops.ts), which samples the table of each tick. */
|
|
50
|
+
watch?: ProcsDeps["watch"];
|
|
49
51
|
/** The seams of a test (the process table, the kill sequence, the tick); the registry reads no table of this machine in a test run unless the test gives one. */
|
|
50
52
|
over?: Partial<ProcsDeps> & { tickMs?: number };
|
|
51
53
|
stops: (() => void)[];
|
|
@@ -66,7 +68,7 @@ export function startProcs(o: StartProcs): Procs {
|
|
|
66
68
|
protect: (table) => protectedSet(table, { run: o.run, stateDir: o.stateDir, agentDir: o.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), self: o.pid }),
|
|
67
69
|
panes: async () => (await herdrPanes(o.run)).map((p) => ({ pane_id: p.pane_id, ...(p.terminal_id ? { terminal_id: p.terminal_id } : {}), ...(p.cwd ? { cwd: p.cwd } : {}), ...(p.workspace_id ? { workspace_id: p.workspace_id } : {}) })),
|
|
68
70
|
workspaces: async () => (await herdrWorkspaces(o.run)).flatMap((w) => (w.worktree?.is_linked_worktree && w.worktree.checkout_path ? [{ workspace_id: w.workspace_id, checkout_path: w.worktree.checkout_path }] : [])),
|
|
69
|
-
...quiet, ...o.over,
|
|
71
|
+
...(o.watch ? { watch: o.watch } : {}), ...quiet, ...o.over,
|
|
70
72
|
});
|
|
71
73
|
if (o.platform === "win32") return procs;
|
|
72
74
|
try {
|
package/src/server/runs.ts
CHANGED
|
@@ -1582,13 +1582,14 @@ export function createRuns(o: RunsOptions) {
|
|
|
1582
1582
|
poke(svc);
|
|
1583
1583
|
return written;
|
|
1584
1584
|
},
|
|
1585
|
-
/** A late outcome of something a run sent after the run ended: a notice event for the next run. */
|
|
1586
|
-
notice(workspace: string, text: string, key: string) {
|
|
1585
|
+
/** A late outcome of something a run sent after the run ended, or a notice the server raises (the stall watch): a notice event for the next run. False when the server stands in for no tower there. */
|
|
1586
|
+
notice(workspace: string, text: string, key: string): boolean {
|
|
1587
1587
|
const svc = services.get(workspace);
|
|
1588
|
-
if (!svc) return;
|
|
1589
|
-
if (waitingOf(svc).some((e) => e.kind === "notice" && e.messageId === key)) return;
|
|
1588
|
+
if (!svc) return false;
|
|
1589
|
+
if (waitingOf(svc).some((e) => e.kind === "notice" && e.messageId === key)) return true;
|
|
1590
1590
|
append(slot, svc.ref.record(), { kind: "notice", text, at: iso(now()), messageId: key });
|
|
1591
1591
|
poke(svc);
|
|
1592
|
+
return true;
|
|
1592
1593
|
},
|
|
1593
1594
|
/** The service is held because the standing pane runs a program of the boss's: it is Retried by itself once the pane is free (standing.ts). */
|
|
1594
1595
|
paneBusy(workspace: string) {
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { statSync } from "node:fs";
|
|
2
|
+
import { openCalls } from "../ask.ts";
|
|
3
|
+
import { type HerdrRun, isSub, panes as herdrPanes, parentOf, type Session, type Workspace, workspaces as herdrWorkspaces } from "../herdr.ts";
|
|
4
|
+
import { createStallWatch, type Flag, readStallWatch, type StallDeps, type StallWatch } from "./stallwatch.ts";
|
|
5
|
+
import { inTestRun } from "./testguard.ts";
|
|
6
|
+
import { towerRunsEnabled } from "./towerruns.ts";
|
|
7
|
+
import type { Towers } from "./towers.ts";
|
|
8
|
+
|
|
9
|
+
// The server's side of the stall watch (stallwatch.ts): what it reads of this machine (pi-intercom's list, Herdr's panes, the session files) and the tower it tells. Kept out of main.ts, which carries a line budget.
|
|
10
|
+
|
|
11
|
+
export interface StartStall {
|
|
12
|
+
/** The slot's folder and the state folder (`config.json`). */
|
|
13
|
+
dir: string;
|
|
14
|
+
stateDir: string;
|
|
15
|
+
pid: number;
|
|
16
|
+
platform: NodeJS.Platform;
|
|
17
|
+
now(): number;
|
|
18
|
+
log(event: string, facts: Record<string, number | string | boolean>): void;
|
|
19
|
+
run: HerdrRun;
|
|
20
|
+
/** pi-intercom's list as the server's own connection sees it; rejects while it is not connected. */
|
|
21
|
+
sessions(): Promise<Session[]>;
|
|
22
|
+
towers(): Pick<Towers, "status" | "head" | "runs"> | undefined;
|
|
23
|
+
/** The seams of a test; in a test run there is no watch without them (it would read the panes of a fake Herdr every minute). */
|
|
24
|
+
over?: Partial<StallDeps>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The workspace whose tower hears of a session in `workspace`: its own when the server stands in for a tower there, its parent's for a sub workspace (which never has a tower), else the head tower's;
|
|
29
|
+
* none when there is neither.
|
|
30
|
+
*/
|
|
31
|
+
export function stallTarget(workspace: string | undefined, all: readonly Workspace[], served: readonly string[], head: string | undefined): string | undefined {
|
|
32
|
+
const asked = all.find((w) => w.workspace_id === workspace), target = asked && isSub(asked) ? parentOf([...all], asked) : asked;
|
|
33
|
+
return target && served.includes(target.workspace_id) ? target.workspace_id : head;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The notice is one event in the tower's queue: a key that is still waiting there is not queued twice. */
|
|
37
|
+
export async function tellTower(flag: Flag, run: HerdrRun, towers: ReturnType<StartStall["towers"]>): Promise<boolean> {
|
|
38
|
+
if (!towers) return false;
|
|
39
|
+
const to = stallTarget(flag.workspace, await herdrWorkspaces(run).catch(() => []), towers.status().map((r) => r.workspace), towers.head.status()?.workspace);
|
|
40
|
+
return to !== undefined && towers.runs.notice(to, flag.text, `stall:${flag.pid}:${flag.started}:${flag.kind}:${flag.told}`);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The watch of this server, or none: on Windows (there is no process table), and in a test run without seams. */
|
|
44
|
+
export function startStall(o: StartStall): StallWatch | undefined {
|
|
45
|
+
if (o.platform === "win32" || (inTestRun() && !o.over)) return undefined;
|
|
46
|
+
let noTower = false;
|
|
47
|
+
return createStallWatch({
|
|
48
|
+
dir: o.dir, now: o.now, log: o.log, self: [o.pid], config: () => readStallWatch(o.stateDir),
|
|
49
|
+
sessions: async () => (await o.sessions()).flatMap((s) => {
|
|
50
|
+
// SAFETY: pi-intercom's list carries each session's pid (its `SessionInfo`); herdr.ts names only the fields the net reads.
|
|
51
|
+
const pid = (s as { pid?: unknown }).pid;
|
|
52
|
+
// The pane is the one the broker found the session in at this list (`current`). A location it could not resolve carries the pane the session was started in, which a move has renamed since: no pane then.
|
|
53
|
+
const at = s.herdrLocation?.status === "current" ? s.herdrLocation : undefined;
|
|
54
|
+
return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 1 ? [{ id: s.id, ...(s.name ? { name: s.name } : {}), pid, ...(at?.paneId ? { pane: at.paneId } : {}), ...(at?.workspace?.id ? { workspace: at.workspace.id } : {}) }] : [];
|
|
55
|
+
}),
|
|
56
|
+
panes: async () => (await herdrPanes(o.run)).map((p) => ({ pane: p.pane_id, ...(p.terminal_id ? { terminal: p.terminal_id } : {}), ...(p.workspace_id ? { workspace: p.workspace_id } : {}), pi: p.agent === "pi", working: p.agent_status === "working", ...(p.agent_session?.value ? { file: p.agent_session.value } : {}), ...(p.tokens?.sb_role ? { role: p.tokens.sb_role } : {}) })),
|
|
57
|
+
paneProcs: async (pane) => {
|
|
58
|
+
const info = (JSON.parse(await o.run(["pane", "process-info", "--pane", pane])) as { result?: { process_info?: { shell_pid?: unknown; foreground_processes?: { pid?: unknown; name?: unknown; argv0?: unknown }[] } } }).result?.process_info;
|
|
59
|
+
if (!info) return undefined;
|
|
60
|
+
const word = (v: unknown) => (typeof v === "string" ? { v } : undefined);
|
|
61
|
+
return { ...(typeof info.shell_pid === "number" ? { shell: info.shell_pid } : {}), foreground: (info.foreground_processes ?? []).flatMap((p) => (typeof p.pid === "number" && p.pid > 1 ? [{ pid: p.pid, ...(word(p.name) ? { name: word(p.name)!.v } : {}), ...(word(p.argv0) ? { argv0: word(p.argv0)!.v } : {}) }] : [])) };
|
|
62
|
+
},
|
|
63
|
+
mtime: (file) => { try { return statSync(file).mtimeMs; } catch { return undefined; } },
|
|
64
|
+
openCalls: async (file) => { const found = await openCalls(file); return found === "cut" ? undefined : found.length; },
|
|
65
|
+
// With `towerRuns.enabled: false` the towers are resident pi sessions and the server stands in for none, so nobody is told: the log says so once, and each incident is in it as `stall-untold`.
|
|
66
|
+
tell: async (flag) => {
|
|
67
|
+
if (towerRunsEnabled(o.stateDir)) return (noTower = false), tellTower(flag, o.run, o.towers());
|
|
68
|
+
if (!noTower) (noTower = true), o.log("stall-no-tower", { text: "towerRuns.enabled is off in config.json, so the server stands in for no tower: the stall watch tells nobody, and its incidents are in this log only" });
|
|
69
|
+
return false;
|
|
70
|
+
},
|
|
71
|
+
...o.over,
|
|
72
|
+
});
|
|
73
|
+
}
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import { basename, join } from "node:path";
|
|
3
|
+
import { baseName, descendants, type Proc } from "../procs/table.ts";
|
|
4
|
+
import { writeJson } from "./record.ts";
|
|
5
|
+
|
|
6
|
+
// The stall watch of the sb server: a pi session that froze is told to its workspace's tower, once per incident. On 2026-11-12 a main's pi pegged its main thread for 40 hours, took no keys, and fell out
|
|
7
|
+
// of pi-intercom's list, and nobody noticed until a tower rescued it by hand. Once a minute the watch reads, from the process table the owner registry's tick already holds (procs.ts), three signals of each
|
|
8
|
+
// pi session that pi-intercom lists in a Herdr pane:
|
|
9
|
+
// cpu its process averaged `cpuPercent` of a core or more over `cpuMinutes` samples in a row, none of them calm (under half of `cpuPercent`), while its session file was not written. The share is
|
|
10
|
+
// averaged because a pegged pi on a loaded machine dips under the threshold for a minute now and then; a calm sample or a write starts the count again, since a thread that spins has no calm
|
|
11
|
+
// minute and a session that still writes its file is working, not frozen. Healthy mains with a long history were measured at 73% and 83% of a core over a minute while they wrote their files, so
|
|
12
|
+
// the write, not the threshold, is what tells work from a freeze;
|
|
13
|
+
// missing its process is alive and pi-intercom has not listed it for `missingMinutes` samples in a row (the broker drops a client whose event loop stopped heartbeating); the sessions known are kept in
|
|
14
|
+
// `<slot dir>/procs/stallwatch.json`, so one that never came back after a server restart is told too;
|
|
15
|
+
// silent its pane says working, its session file was not written for `silentMinutes` samples in a row, and no tool call is open in it: it waits on a model that does not answer (a long tool call, a
|
|
16
|
+
// subagent, or a build is an open call and is never a stall).
|
|
17
|
+
// Streaks count samples, not the wall clock: a sample that comes more than three minutes after the last (the computer slept, the server was stopped) starts every streak again.
|
|
18
|
+
// Not told (SW-F005): a session that froze more than ten minutes before the watch first saw its pane, with a calm process. `missing` counts only for a session known to have registered, and what says so of
|
|
19
|
+
// a process is its place in pi-intercom's list or its pane's `sb_role` token, which the session itself renews and which lapses ten minutes after it stops (herdr.ts). Nothing else on this machine says it of the
|
|
20
|
+
// process: a session file's entries are carried along by a resume or a fork, and the owner registry holds workers only. So it holds for the first sample of a server whose `stallwatch.json` has no row for the
|
|
21
|
+
// pi (the release that brings the watch, a watch turned on, a lost file); afterwards `known` is on file.
|
|
22
|
+
// The watch only tells: it sends no signal and no key to any process. What the tower does with it is the runbook in the message (`stallText`).
|
|
23
|
+
|
|
24
|
+
export const STALL_FILE = "stallwatch.json";
|
|
25
|
+
export const SAMPLE_MS = 60_000, PAUSE_MS = 180_000, CLEAR_SAMPLES = 3, REMIND_MAX_MS = 8 * 3600_000;
|
|
26
|
+
/** A tick that comes a little early still samples: the tick's own timer is 10 or 30 s. */
|
|
27
|
+
const SLACK_MS = 5000;
|
|
28
|
+
/** The most panes one sample asks Herdr about (`pane process-info` starts the CLI, which costs seconds on a loaded machine): after a server start the panes are taken in over a few samples. */
|
|
29
|
+
export const ADMIT_MAX = 8;
|
|
30
|
+
/** A pane whose pi was not found is asked again after 2, 4, 8, 16, then every 32 samples, and is in the log once, at its third ask in a row that found none. */
|
|
31
|
+
const RETRY_MAX = 32, UNRESOLVED_LOG = 3;
|
|
32
|
+
|
|
33
|
+
export interface StallConfig { enabled: boolean; cpuPercent: number; cpuMinutes: number; silentMinutes: number; missingMinutes: number; remindMinutes: number }
|
|
34
|
+
export const STALL_DEFAULTS: StallConfig = { enabled: true, cpuPercent: 75, cpuMinutes: 5, silentMinutes: 30, missingMinutes: 3, remindMinutes: 60 };
|
|
35
|
+
|
|
36
|
+
/** `stallWatch` from `<state dir>/config.json`: a key that is missing or no number of its kind keeps its default, and a file that is missing or cannot be parsed means the defaults. `0` minutes turns that signal (or the reminders) off. */
|
|
37
|
+
export function readStallWatch(stateDir: string): StallConfig {
|
|
38
|
+
let section: unknown;
|
|
39
|
+
try {
|
|
40
|
+
section = (JSON.parse(readFileSync(join(stateDir, "config.json"), "utf8")) as { stallWatch?: unknown }).stallWatch;
|
|
41
|
+
} catch { /* none, or not JSON (the tower service tells the boss of a config that cannot be read): the defaults */ }
|
|
42
|
+
const found = (typeof section === "object" && section !== null ? section : {}) as Record<string, unknown>;
|
|
43
|
+
const minutes = (key: "cpuMinutes" | "silentMinutes" | "missingMinutes" | "remindMinutes") => (Number.isInteger(found[key]) && (found[key] as number) >= 0 && (found[key] as number) <= 10_080 ? (found[key] as number) : STALL_DEFAULTS[key]);
|
|
44
|
+
const percent = typeof found.cpuPercent === "number" && found.cpuPercent >= 10 && found.cpuPercent <= 100 ? found.cpuPercent : STALL_DEFAULTS.cpuPercent;
|
|
45
|
+
return { enabled: found.enabled !== false, cpuPercent: percent, cpuMinutes: minutes("cpuMinutes"), silentMinutes: minutes("silentMinutes"), missingMinutes: minutes("missingMinutes"), remindMinutes: minutes("remindMinutes") };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export type Signal = "cpu" | "missing" | "silent";
|
|
49
|
+
/** A session as pi-intercom lists it. Its pid is the session's own word: it counts only for a process Herdr lists in the pane (`piOf`), and for a watched pi only when the session is in that pi's pane. `pane` is where the broker places it now; none when it could not (not hosted, or Herdr did not answer the broker), and the pid then counts alone. */
|
|
50
|
+
export interface SessionFact { id: string; name?: string; pid: number; pane?: string; workspace?: string }
|
|
51
|
+
export interface PaneFact { pane: string; /** The terminal in the pane: Herdr reuses a pane id, and another terminal under it is another pane. */ terminal?: string; workspace?: string; /** Herdr says a pi runs in it. */ pi: boolean; working: boolean; /** The session file Herdr names for the pane's pi. */ file?: string; /** The pane's `sb_role` token. */ role?: string }
|
|
52
|
+
/** What Herdr lists in a pane: its shell and its foreground. */
|
|
53
|
+
export interface PaneProcs { shell?: number; foreground: { pid: number; name?: string; argv0?: string }[] }
|
|
54
|
+
/** What a tower is told. `flag`: a new incident; `change`: a further signal fired in it; `remind`: it still stands after the backoff; `clear`: its signals are gone while the process lives. */
|
|
55
|
+
export interface Flag {
|
|
56
|
+
kind: "flag" | "change" | "remind" | "clear";
|
|
57
|
+
pid: number; started: string; session: string; name?: string; pane: string; workspace?: string; role?: string;
|
|
58
|
+
signals: Signal[];
|
|
59
|
+
/** The cpu time the process has used so far, in minutes, and its share of a core over the last sample, in percent. */
|
|
60
|
+
cpuMinutes: number; cpuNow?: number;
|
|
61
|
+
/** How many times this incident was told before. */
|
|
62
|
+
told: number;
|
|
63
|
+
text: string;
|
|
64
|
+
}
|
|
65
|
+
export interface StallDeps {
|
|
66
|
+
/** The folder of the slot; the watch keeps its file in `procs/` below it, beside the owner registry's. */
|
|
67
|
+
dir: string;
|
|
68
|
+
now(): number;
|
|
69
|
+
log(event: string, facts: Record<string, number | string | boolean>): void;
|
|
70
|
+
config(): StallConfig;
|
|
71
|
+
/** The sessions pi-intercom lists now; rejects when the list is not known (the server is not connected), which counts for nothing. */
|
|
72
|
+
sessions(): Promise<SessionFact[]>;
|
|
73
|
+
/** The panes Herdr lists now; rejects when they are not known. */
|
|
74
|
+
panes(): Promise<PaneFact[]>;
|
|
75
|
+
/** What Herdr lists in a pane; undefined or a rejection when it is not known. Asked when a pane's pi is first watched, not at each sample. */
|
|
76
|
+
paneProcs(pane: string): Promise<PaneProcs | undefined>;
|
|
77
|
+
/** When a file was last written, in ms; undefined when it cannot be read. */
|
|
78
|
+
mtime(file: string): number | undefined;
|
|
79
|
+
/** How many tool calls the session file's newest assistant message leaves open; undefined when that cannot be told. */
|
|
80
|
+
openCalls(file: string): Promise<number | undefined>;
|
|
81
|
+
/** Tells the tower that serves the flag's workspace. False when nobody could be told: the watch tries again at the next sample. */
|
|
82
|
+
tell(flag: Flag): Promise<boolean>;
|
|
83
|
+
/** Pids that are never a pi session: this server (its tower identities are in pi-intercom's list under its pid). */
|
|
84
|
+
self?: number[];
|
|
85
|
+
}
|
|
86
|
+
export interface StallRow { pid: number; session: string; pane: string; signals: Signal[]; told: number }
|
|
87
|
+
export interface StallWatch {
|
|
88
|
+
/** One look at the table of a tick; it does nothing until a minute has passed since the last sample, or while a sample runs. Never rejects. */
|
|
89
|
+
sample(table: readonly Proc[]): Promise<void>;
|
|
90
|
+
/** The open incidents. */
|
|
91
|
+
list(): StallRow[];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const phrase = (value: unknown, max: number) => (typeof value === "string" ? value.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ").replace(/\s+/g, " ").trim().slice(0, max) : "");
|
|
95
|
+
const SHELLS = new Set(["sh", "bash", "zsh", "fish", "dash", "ksh", "csh", "tcsh"]);
|
|
96
|
+
const nameOf = (p: { name?: string; argv0?: string }) => baseName(p.argv0 ?? p.name ?? "").replace(/^-/, "");
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The pid of a pane's pi. A pid a listed session gives for the pane is taken when Herdr lists it in the pane's foreground or the table has it below the pane's shell; else the foreground process that is pi by its
|
|
100
|
+
* program (`argv0` on macOS, `name` on Linux), else the one process named node. Two candidates and no listed pid: nothing is guessed. The pane's shell and any shell are never a pi.
|
|
101
|
+
*/
|
|
102
|
+
export function piOf(info: PaneProcs, table: readonly Proc[], listed: readonly number[]): number | undefined {
|
|
103
|
+
const front = info.foreground.filter((p) => p.pid !== info.shell && !SHELLS.has(nameOf(p)));
|
|
104
|
+
const below = info.shell === undefined ? new Set<number>() : new Set(descendants(table, [info.shell]).map((p) => p.pid));
|
|
105
|
+
const said = listed.find((pid) => pid !== info.shell && (front.some((p) => p.pid === pid) || below.has(pid)));
|
|
106
|
+
if (said !== undefined) return said;
|
|
107
|
+
const one = (list: typeof front) => (list.length === 1 ? list[0]!.pid : undefined);
|
|
108
|
+
return one(front.filter((p) => p.argv0 === "pi")) ?? one(front.filter((p) => p.name === "pi")) ?? one(front.filter((p) => p.name === "node"));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const minutes = (n: number) => `${n} minute${n === 1 ? "" : "s"}`;
|
|
112
|
+
/** What each signal saw, in the words of the message. */
|
|
113
|
+
const SEEN: Record<Signal, (cfg: StallConfig) => string> = {
|
|
114
|
+
cpu: (cfg) => `its process averaged at or above ${cfg.cpuPercent}% of a core over ${minutes(cfg.cpuMinutes)} while its session file was not written`,
|
|
115
|
+
missing: (cfg) => `its process is alive and pi-intercom has not listed it for ${minutes(cfg.missingMinutes)} (a pi whose event loop stopped falls out of the list)`,
|
|
116
|
+
silent: (cfg) => `its pane says working, its session file was not written for ${minutes(cfg.silentMinutes)}, and no tool call is open`,
|
|
117
|
+
};
|
|
118
|
+
/** The message a tower gets: what was seen, and the runbook. A session's name and id are its own words, so they are cleaned, cut, and quoted; the rest is the server's. */
|
|
119
|
+
export function stallText(f: Omit<Flag, "text">, cfg: StallConfig): string {
|
|
120
|
+
// Every word here that a session wrote (its name and id, its pane's role token) is cleaned, cut, and kept from closing a quote or a code span or opening a header line.
|
|
121
|
+
const word = (value: unknown, max: number) => phrase(value, max).replace(/["`\[\]]/g, "'");
|
|
122
|
+
const name = word(f.name, 60), pane = word(f.pane, 40), started = word(f.started, 40);
|
|
123
|
+
// The id is quoted like the name and keeps an id's characters only: with no space in it, it cannot read as a sentence of the server's beside the runbook (SW-F006).
|
|
124
|
+
const id = String(f.session ?? "").replace(/[^A-Za-z0-9._:-]+/g, "").slice(0, 80) || "unknown";
|
|
125
|
+
const who = `session "${id}"${name ? ` ("${name}")` : ""}${f.role ? `, role ${word(f.role, 20)}` : ""}, pid ${f.pid} (started ${started} UTC)${f.workspace ? `, workspace ${word(f.workspace, 40)}` : ""}`;
|
|
126
|
+
const cpu = `${f.cpuMinutes} min of cpu so far${f.cpuNow === undefined ? "" : `, ${f.cpuNow}% of a core over the last sample`}`;
|
|
127
|
+
const seen = f.signals.map((sig) => SEEN[sig](cfg)).join("; and ");
|
|
128
|
+
if (f.kind === "clear") return `Stall watch: the pi in pane ${pane} recovered. ${who}; ${cpu}. What was seen no longer holds (${seen}). Do not stop it. Drop what you recorded or asked for it.`;
|
|
129
|
+
const head = f.kind === "change" ? "Stall watch, one more signal" : f.kind === "remind" ? `Stall watch, reminder (told ${f.told} time${f.told === 1 ? "" : "s"} before)` : "Stall watch";
|
|
130
|
+
return [
|
|
131
|
+
`${head}: the pi in pane ${pane} looks frozen. ${who}; ${cpu}.`,
|
|
132
|
+
`Seen: ${seen}.`,
|
|
133
|
+
"The sb server sent no signal and no key to it, and never does. The steps need a shell, and a tower run has none: hand them, with this message, to a main of the workspace that is not this session (open one when there is none), or to the boss.",
|
|
134
|
+
`1. Read the pane twice, a few seconds apart: \`herdr pane read ${pane} --lines 40\`. A screen that moves is a session at work: leave it and stop here.`,
|
|
135
|
+
`2. A screen that stands still: \`herdr pane send-keys ${pane} esc\`, then read it again. If it answers, have it write a handoff note and quit.`,
|
|
136
|
+
`3. If it takes no key: only when it left a handoff file, or the boss approves (record a wait for the boss, and wait), check that pid ${f.pid} is still that process (\`TZ=UTC LC_ALL=C ps -o lstart= -p ${f.pid}\` prints ${started}), stop it with \`kill ${f.pid}\`, and start a fresh session in its folder with the handoff.`,
|
|
137
|
+
`This incident is told once. A further signal or a recovery is told${cfg.remindMinutes ? `, and a reminder comes after ${minutes(cfg.remindMinutes)} and then at twice the wait each time` : ""}.`,
|
|
138
|
+
].join("\n");
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
interface Incident { signals: Signal[]; since: number; told: number; reminds: number; toldAt?: number; /** Samples in a row without a symptom of its signals. */ quiet: number; due?: Flag["kind"]; /** `stall-untold` is in the log. */ untold?: true }
|
|
142
|
+
interface Watched {
|
|
143
|
+
pid: number; started: string; pane: string; terminal?: string; workspace?: string; role?: string; file?: string;
|
|
144
|
+
/** The id and name pi-intercom listed it under; `known` once it was listed, or its pane carries a role and a session file (it registered at some time). */
|
|
145
|
+
session?: string; name?: string; known: boolean;
|
|
146
|
+
/** The last sample's readings; none right after a start or a pause. */
|
|
147
|
+
cpu?: number; mtime?: number; pct?: number;
|
|
148
|
+
/** The shares of a core at the last samples in a row that were not calm and had no write, `cpuMinutes` of them at most. */
|
|
149
|
+
heat: number[];
|
|
150
|
+
silent: number; missing: number;
|
|
151
|
+
/** The open calls of the file as it was at `at` (its mtime). */
|
|
152
|
+
open?: { at: number | undefined; calls: number | undefined };
|
|
153
|
+
incident?: Incident;
|
|
154
|
+
}
|
|
155
|
+
const keyOf = (p: { pid: number; started: string }) => `${p.pid}\n${p.started}`;
|
|
156
|
+
const paneKey = (p: { pane: string; terminal?: string }) => `${p.pane}\n${p.terminal ?? ""}`;
|
|
157
|
+
const text = (v: unknown, max: number) => (typeof v === "string" && v.length > 0 && v.length <= max ? v : undefined);
|
|
158
|
+
|
|
159
|
+
export function createStallWatch(d: StallDeps): StallWatch {
|
|
160
|
+
const folder = join(d.dir, "procs"), file = join(folder, STALL_FILE), self = d.self ?? [process.pid];
|
|
161
|
+
const watched = new Map<string, Watched>();
|
|
162
|
+
/** The panes whose pi was not found, by pane and terminal: how many asks in a row found none, and the sample that asks again. */
|
|
163
|
+
const unresolved = new Map<string, { tries: number; again: number }>();
|
|
164
|
+
let lastAt: number | undefined, on = false, busy = false, saved = "", loaded = false, samples = 0, askedLast: string | undefined;
|
|
165
|
+
|
|
166
|
+
const kept = () => JSON.stringify({ v: 1, watched: [...watched.values()].map(({ pid, started, pane, terminal, workspace, role, file: f, session, name, known, incident }) => ({ pid, started, pane, terminal, workspace, role, file: f, session, name, known, incident })) });
|
|
167
|
+
// A write that fails is one log line: the watch goes on in memory, and a restart then tells an open incident once more.
|
|
168
|
+
const save = () => {
|
|
169
|
+
const next = kept();
|
|
170
|
+
if (next === saved) return;
|
|
171
|
+
try {
|
|
172
|
+
mkdirSync(folder, { recursive: true, mode: 0o700 });
|
|
173
|
+
writeJson(file, JSON.parse(next));
|
|
174
|
+
saved = next;
|
|
175
|
+
} catch (error) {
|
|
176
|
+
d.log("stall-error", { text: `${STALL_FILE} was not written (${(error as NodeJS.ErrnoException).code ?? (error as Error).name})` });
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
/** The sessions the last server knew, with their open incidents: the counts start from nothing, so the first samples after a restart are its grace. */
|
|
180
|
+
const load = () => {
|
|
181
|
+
loaded = true;
|
|
182
|
+
try {
|
|
183
|
+
const parsed = JSON.parse(readFileSync(file, "utf8")) as { watched?: unknown };
|
|
184
|
+
for (const r of Array.isArray(parsed.watched) ? parsed.watched : []) {
|
|
185
|
+
const o = r as Partial<Watched>, i = o?.incident as Partial<Incident> | undefined;
|
|
186
|
+
if (!Number.isSafeInteger(o?.pid) || typeof o.started !== "string" || typeof o.pane !== "string") continue;
|
|
187
|
+
const signals = Array.isArray(i?.signals) ? i.signals.filter((x): x is Signal => x === "cpu" || x === "missing" || x === "silent") : [];
|
|
188
|
+
const incident: Incident | undefined = i && signals.length && Number.isSafeInteger(i.told) ? { signals, since: Number(i.since) || d.now(), told: i.told!, reminds: Number.isSafeInteger(i.reminds) ? i.reminds! : 0, ...(typeof i.toldAt === "number" ? { toldAt: i.toldAt } : {}), quiet: 0, ...(i.due === "flag" || i.due === "change" || i.due === "clear" ? { due: i.due } : {}) } : undefined;
|
|
189
|
+
watched.set(keyOf(o as Watched), { pid: o.pid!, started: o.started, pane: o.pane, terminal: text(o.terminal, 200), workspace: text(o.workspace, 200), role: text(o.role, 40), file: text(o.file, 4096), session: text(o.session, 200), name: text(o.name, 200), known: o.known === true, heat: [], silent: 0, missing: 0, ...(incident ? { incident } : {}) });
|
|
190
|
+
}
|
|
191
|
+
} catch { /* none yet, or not readable: the watch starts empty */ }
|
|
192
|
+
saved = kept();
|
|
193
|
+
};
|
|
194
|
+
const flagOf = (w: Watched, kind: Flag["kind"], proc: Proc, cfg: StallConfig): Flag => {
|
|
195
|
+
const bare: Omit<Flag, "text"> = {
|
|
196
|
+
kind, pid: w.pid, started: w.started, session: w.session ?? (w.file ? basename(w.file).replace(/\.jsonl$/, "") : "(unknown)"), ...(w.name ? { name: w.name } : {}), pane: w.pane, ...(w.workspace ? { workspace: w.workspace } : {}), ...(w.role ? { role: w.role } : {}),
|
|
197
|
+
signals: [...w.incident!.signals], cpuMinutes: Math.round(proc.cpu / 60), ...(w.pct !== undefined ? { cpuNow: Math.round(w.pct) } : {}), told: w.incident!.told,
|
|
198
|
+
};
|
|
199
|
+
return { ...bare, text: stallText(bare, cfg) };
|
|
200
|
+
};
|
|
201
|
+
/** The open calls of a session file, read again only when the file was written since. */
|
|
202
|
+
const openOf = async (w: Watched): Promise<number | undefined> => {
|
|
203
|
+
if (!w.file) return undefined;
|
|
204
|
+
if (!w.open || w.open.at !== w.mtime || w.open.calls === undefined) w.open = { at: w.mtime, calls: await d.openCalls(w.file).catch(() => undefined) };
|
|
205
|
+
return w.open.calls;
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
async function take(table: readonly Proc[], cfg: StallConfig, now: number, gap: number | undefined): Promise<void> {
|
|
209
|
+
// A first sample, and one that comes late (the computer slept, the server was stopped), only takes the readings: every count starts again.
|
|
210
|
+
const paused = gap === undefined || gap > PAUSE_MS;
|
|
211
|
+
const [sessions, panes] = await Promise.all([d.sessions().catch(() => undefined), d.panes().catch(() => undefined)]);
|
|
212
|
+
const live = new Map(table.filter((p) => !p.zombie).map((p) => [keyOf(p), p]));
|
|
213
|
+
// A pi that ended, or whose pane closed (its id gone, or reused for another terminal), is no longer watched: its incident goes without a word (whoever stopped it knows).
|
|
214
|
+
const still = (w: Watched) => !panes || panes.some((p) => p.pane === w.pane && (p.terminal === undefined || w.terminal === undefined || p.terminal === w.terminal));
|
|
215
|
+
for (const [key, w] of watched) {
|
|
216
|
+
if (live.has(key) && still(w)) continue;
|
|
217
|
+
if (w.incident) d.log("stall-ended", { pid: w.pid, pane: w.pane, signals: w.incident.signals.join("+"), told: w.incident.told });
|
|
218
|
+
watched.delete(key);
|
|
219
|
+
}
|
|
220
|
+
for (const pane of panes ?? []) {
|
|
221
|
+
const now1 = [...watched.values()].find((w) => w.pane === pane.pane);
|
|
222
|
+
if (!now1) continue;
|
|
223
|
+
[now1.workspace, now1.role] = [pane.workspace ?? now1.workspace, pane.role ?? now1.role];
|
|
224
|
+
if (pane.file && pane.file !== now1.file) [now1.file, now1.mtime, now1.open] = [pane.file, undefined, undefined]; // /new or /resume in the same pi: another file, read from nothing
|
|
225
|
+
}
|
|
226
|
+
// The pi of each pane where Herdr says one runs is watched from now on. The panes are asked in Herdr's order, in turn from behind the one asked last, and a pane whose pi was not found waits longer
|
|
227
|
+
// before each further ask: panes that give nothing neither keep the others from their turn nor start Herdr's CLI every minute (SW-F003).
|
|
228
|
+
samples++;
|
|
229
|
+
const all = panes ?? [], from = all.findIndex((p) => p.pane === askedLast) + 1;
|
|
230
|
+
const open = [...all.slice(from), ...all.slice(0, from)].filter((p) => p.pi && ![...watched.values()].some((w) => w.pane === p.pane));
|
|
231
|
+
for (const key of unresolved.keys()) if (panes && !open.some((p) => paneKey(p) === key)) unresolved.delete(key);
|
|
232
|
+
for (const pane of open.filter((p) => (unresolved.get(paneKey(p))?.again ?? 0) <= samples).slice(0, ADMIT_MAX)) {
|
|
233
|
+
askedLast = pane.pane;
|
|
234
|
+
const info = await d.paneProcs(pane.pane).catch(() => undefined);
|
|
235
|
+
const pid = info && piOf(info, table, (sessions ?? []).filter((s) => s.pane === pane.pane).map((s) => s.pid));
|
|
236
|
+
const proc = pid === undefined || self.includes(pid) ? undefined : table.find((p) => p.pid === pid && !p.zombie);
|
|
237
|
+
if (!proc || watched.has(keyOf(proc))) {
|
|
238
|
+
const tries = (unresolved.get(paneKey(pane))?.tries ?? 0) + 1;
|
|
239
|
+
unresolved.set(paneKey(pane), { tries, again: samples + Math.min(2 ** tries, RETRY_MAX) });
|
|
240
|
+
if (tries === UNRESOLVED_LOG) d.log("stall-unresolved", { pane: pane.pane, tries });
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
unresolved.delete(paneKey(pane));
|
|
244
|
+
watched.set(keyOf(proc), { pid: proc.pid, started: proc.started, pane: pane.pane, ...(pane.terminal ? { terminal: pane.terminal } : {}), ...(pane.workspace ? { workspace: pane.workspace } : {}), ...(pane.role ? { role: pane.role } : {}), ...(pane.file ? { file: pane.file } : {}), known: false, heat: [], silent: 0, missing: 0 });
|
|
245
|
+
}
|
|
246
|
+
for (const w of watched.values()) {
|
|
247
|
+
const proc = live.get(keyOf(w))!, pane = panes?.find((p) => p.pane === w.pane);
|
|
248
|
+
// A session counts for this pi by the pid it reports only when it is in this pi's pane, or the broker could not place it (SW-F004).
|
|
249
|
+
const listed = sessions?.find((s) => s.pid === w.pid && (s.pane === undefined || s.pane === w.pane));
|
|
250
|
+
if (listed) [w.session, w.name, w.known, w.missing] = [listed.id, listed.name, true, 0];
|
|
251
|
+
// A pane that carries a role and a session file registered at some time, though this server never saw it listed: it froze before the watch first saw it, and less than ten minutes before, while its role token still stood (the header's limit).
|
|
252
|
+
if (pane?.role && pane.file) w.known = true;
|
|
253
|
+
const mtime = w.file ? d.mtime(w.file) : undefined, written = w.file !== undefined && mtime !== w.mtime;
|
|
254
|
+
if (paused) [w.heat, w.silent, w.missing, w.pct] = [[], 0, 0, undefined];
|
|
255
|
+
else {
|
|
256
|
+
w.pct = w.cpu === undefined ? undefined : ((proc.cpu - w.cpu) / (gap / 1000)) * 100;
|
|
257
|
+
// One sample under the threshold does not start the count again (a pegged pi dips on a loaded machine); a calm one, under half of it, does, and so does a write (SW-F002).
|
|
258
|
+
w.heat = !cfg.cpuMinutes || w.pct === undefined || w.pct < cfg.cpuPercent / 2 || written ? [] : [...w.heat, w.pct].slice(-cfg.cpuMinutes);
|
|
259
|
+
// Without Herdr's word on the pane the count stands as it is.
|
|
260
|
+
if (pane || panes) w.silent = pane?.working && w.file !== undefined && !written ? w.silent + 1 : 0;
|
|
261
|
+
if (sessions && !listed && w.known) w.missing++;
|
|
262
|
+
}
|
|
263
|
+
[w.cpu, w.mtime] = [proc.cpu, mtime];
|
|
264
|
+
/** The samples in a row that were not calm average the threshold or more: the cpu signal once there are `cpuMinutes` of them, and its symptom from the first. */
|
|
265
|
+
const pegged = w.heat.length > 0 && w.heat.reduce((sum, pct) => sum + pct, 0) / w.heat.length >= cfg.cpuPercent;
|
|
266
|
+
const firing: Signal[] = [];
|
|
267
|
+
if (pegged && w.heat.length >= cfg.cpuMinutes) firing.push("cpu");
|
|
268
|
+
if (cfg.missingMinutes && w.missing >= cfg.missingMinutes) firing.push("missing");
|
|
269
|
+
if (cfg.silentMinutes && w.silent >= cfg.silentMinutes && (await openOf(w)) === 0) firing.push("silent");
|
|
270
|
+
let inc = w.incident;
|
|
271
|
+
if (!inc) {
|
|
272
|
+
if (!firing.length) continue;
|
|
273
|
+
inc = w.incident = { signals: firing, since: now, told: 0, reminds: 0, quiet: 0, due: "flag" };
|
|
274
|
+
} else {
|
|
275
|
+
const more = firing.filter((sig) => !inc!.signals.includes(sig));
|
|
276
|
+
if (more.length) (inc.signals.push(...more), inc.due = inc.due === "flag" ? "flag" : "change");
|
|
277
|
+
// The incident ends when none of its signals showed a symptom for three samples in a row; a symptom in between starts that count again, so a pi that is pegged on and off stays one incident.
|
|
278
|
+
// A silent incident's symptom is the signal's own: a pane that works with a call open (the session answered and runs a build or a subagent) is at work, not silent (SW-F001).
|
|
279
|
+
const symptom = (inc.signals.includes("cpu") && pegged) || (inc.signals.includes("missing") && w.missing > 0) || (inc.signals.includes("silent") && w.silent > 0 && (await openOf(w)) === 0);
|
|
280
|
+
if (!paused) inc.quiet = symptom ? 0 : inc.quiet + 1;
|
|
281
|
+
if (inc.quiet >= CLEAR_SAMPLES) {
|
|
282
|
+
if (!inc.told) { delete w.incident; continue; } // nobody heard of it
|
|
283
|
+
inc.due = "clear";
|
|
284
|
+
} else if (inc.due === "clear") inc.due = undefined;
|
|
285
|
+
const wait = Math.min(cfg.remindMinutes * 60_000 * 2 ** inc.reminds, REMIND_MAX_MS);
|
|
286
|
+
// A reminder says "looks frozen", so it waits while the symptoms are gone: they come back, or the incident clears.
|
|
287
|
+
if (!inc.due && !inc.quiet && cfg.remindMinutes && inc.toldAt !== undefined && now - inc.toldAt >= wait) inc.due = "remind";
|
|
288
|
+
}
|
|
289
|
+
if (!inc.due) continue;
|
|
290
|
+
const flag = flagOf(w, inc.due, proc, cfg);
|
|
291
|
+
if (await d.tell(flag).catch(() => false)) {
|
|
292
|
+
d.log("stall-told", { kind: flag.kind, pid: w.pid, pane: w.pane, session: flag.session, signals: flag.signals.join("+"), cpuMinutes: flag.cpuMinutes, told: inc.told });
|
|
293
|
+
if (flag.kind === "clear") delete w.incident;
|
|
294
|
+
else [inc.told, inc.reminds, inc.toldAt, inc.due, inc.untold] = [inc.told + 1, inc.reminds + (flag.kind === "remind" ? 1 : 0), now, undefined, undefined];
|
|
295
|
+
} else if (!inc.untold) (inc.untold = true, d.log("stall-untold", { kind: flag.kind, pid: w.pid, pane: w.pane, session: flag.session, signals: flag.signals.join("+") }));
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
return {
|
|
300
|
+
async sample(table) {
|
|
301
|
+
if (busy) return;
|
|
302
|
+
busy = true;
|
|
303
|
+
try {
|
|
304
|
+
const now = d.now();
|
|
305
|
+
if (lastAt !== undefined && now - lastAt < SAMPLE_MS - SLACK_MS) return;
|
|
306
|
+
// The settings are read at each sample. A watch that is off takes no reading, so the first sample after it is turned on starts every count.
|
|
307
|
+
const cfg = d.config(), gap = lastAt === undefined || !on ? undefined : now - lastAt;
|
|
308
|
+
[lastAt, on] = [now, cfg.enabled];
|
|
309
|
+
if (!cfg.enabled) return;
|
|
310
|
+
if (!loaded) load();
|
|
311
|
+
await take(table, cfg, now, gap);
|
|
312
|
+
save();
|
|
313
|
+
} catch (error) {
|
|
314
|
+
d.log("stall-error", { text: String((error as Error)?.message ?? error).slice(0, 200) });
|
|
315
|
+
} finally {
|
|
316
|
+
busy = false;
|
|
317
|
+
}
|
|
318
|
+
},
|
|
319
|
+
list: () => [...watched.values()].flatMap((w) => (w.incident ? [{ pid: w.pid, session: w.session ?? "(unknown)", pane: w.pane, signals: [...w.incident.signals], told: w.incident.told }] : [])),
|
|
320
|
+
};
|
|
321
|
+
}
|
package/src/todo.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { GRAPHS, type Graph } from "./duty.ts";
|
|
2
|
+
import { newestOf } from "./branchscan.ts";
|
|
2
3
|
import { type Todo, todosOf } from "./items.ts";
|
|
3
4
|
|
|
4
5
|
// A session's todo list in short, for its card on the map: its bridge reads it from rpiv-todo's snapshots on its branch (bridge.ts) and the hub
|
|
@@ -9,15 +10,24 @@ export interface TodoSum { done: number; total: number; now?: string; steps?: St
|
|
|
9
10
|
export interface StepLine { id: number; kind: string; status: Todo["status"]; name?: string; round?: number; outcome?: "passed" | "failed" | "void" }
|
|
10
11
|
export const TODO_TEXT = 120;
|
|
11
12
|
|
|
13
|
+
type BranchEntry = { type?: string; customType?: string; data?: unknown; message?: { role?: string; toolName?: string; details?: unknown } };
|
|
14
|
+
/** rpiv-todo's state entry, and the details of a `todo` tool result, when they hold a todo list. */
|
|
15
|
+
const stateOf = (entry: unknown): unknown => { const e = entry as BranchEntry; return e.type === "custom" && e.customType === "rpiv-todo-state" && todosOf(e.data) ? e.data : undefined; };
|
|
16
|
+
const resultOf = (entry: unknown): unknown => { const e = entry as BranchEntry; return e.type === "message" && e.message?.role === "toolResult" && e.message.toolName === "todo" && todosOf(e.message.details) ? e.message.details : undefined; };
|
|
12
17
|
/** The snapshot rpiv-todo left last on a branch, oldest first: its state entries win over its tool results (rpiv-todo's own replay rule). Raw, with every task's metadata, for a reader that needs all of it (the train's guard). */
|
|
13
18
|
export function snapshotOfBranch(entries: readonly unknown[]): unknown {
|
|
14
|
-
let
|
|
15
|
-
for (let i = entries.length - 1; i >= 0
|
|
16
|
-
const
|
|
17
|
-
if (
|
|
18
|
-
|
|
19
|
+
let fromResults: unknown;
|
|
20
|
+
for (let i = entries.length - 1; i >= 0; i--) { // from the leaf: the newest state entry wins, so the walk stops there
|
|
21
|
+
const fromEntries = stateOf(entries[i]);
|
|
22
|
+
if (fromEntries !== undefined) return fromEntries;
|
|
23
|
+
fromResults ??= resultOf(entries[i]);
|
|
19
24
|
}
|
|
20
|
-
return
|
|
25
|
+
return fromResults;
|
|
26
|
+
}
|
|
27
|
+
/** `snapshotOfBranch` for a reader that asks again as its branch grows (the work board's refresh at every tool call): each call walks only what was appended since the last (branchscan.ts). */
|
|
28
|
+
export function snapshotScan(): (entries: readonly unknown[]) => unknown {
|
|
29
|
+
const state = newestOf(stateOf), result = newestOf(resultOf);
|
|
30
|
+
return (entries) => state(entries) ?? result(entries);
|
|
21
31
|
}
|
|
22
32
|
/** The todo list from a branch's entries, oldest first. */
|
|
23
33
|
export const todosOfBranch = (entries: readonly unknown[]): Todo[] | undefined => todosOf(snapshotOfBranch(entries));
|