pi-straw-boss 0.75.2 → 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/{chunk-PQZBUOCK.mjs → chunk-7HXSLT4U.mjs} +5 -5
- package/dist/server/cli.mjs +1 -1
- package/dist/server/main.mjs +790 -508
- package/package.json +1 -1
- package/prompts/integrator.md +1 -1
- package/src/boardfill.ts +6 -3
- package/src/boardseed.ts +6 -2
- package/src/branchscan.ts +18 -0
- package/src/exe.mjs +7 -7
- 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/src/trust/intent.ts +3 -2
|
@@ -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));
|
package/src/trust/intent.ts
CHANGED
|
@@ -5,8 +5,9 @@ import { canonical } from "./found.ts";
|
|
|
5
5
|
// trust question is asked as usual instead of being answered "not trusted" at once. The list of such panes is the sb server's, in its memory only: the pane it started, with the folder it
|
|
6
6
|
// started pi in, from before pi starts until the open's start and join have ended, however they end. The pane's pi runs in another process, so it asks the server over the control socket
|
|
7
7
|
// (`open-intent`, with its own pane id, Herdr's, and its own folder) and takes only the server's yes. No server, no answer in time, an older server, or one that started again (its memory is
|
|
8
|
-
// new) is a no, and the question is answered as before.
|
|
9
|
-
// environment variable can add a pane to the list.
|
|
8
|
+
// new) is a no, and the question is answered as before. No listing is written to or read from disk for it (review R156-F001: a file is not proof of who wrote it), and no request field, flag, or
|
|
9
|
+
// environment variable can add a pane to the list. The asker finds the server through its record (`server.json`), as every control request does, so a same-uid process that writes that record and
|
|
10
|
+
// answers the socket can say yes (review R0752-F001); that grants no trust, D3 becomes a question that waits for a person.
|
|
10
11
|
|
|
11
12
|
export interface Intents {
|
|
12
13
|
/** Lists `pane`, whose pi starts in `cwd`; returns the call that takes it off again. */
|