@phren/cli 0.3.65 → 0.3.67

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.
Files changed (37) hide show
  1. package/dist/bridge/account-choice.d.ts +12 -3
  2. package/dist/bridge/account-choice.js +133 -19
  3. package/dist/bridge/account-last-known.d.ts +27 -0
  4. package/dist/bridge/account-last-known.js +124 -0
  5. package/dist/bridge/changes.d.ts +22 -0
  6. package/dist/bridge/changes.js +323 -82
  7. package/dist/bridge/claude-accounts.d.ts +27 -0
  8. package/dist/bridge/claude-accounts.js +63 -8
  9. package/dist/bridge/dispatch-returns.d.ts +8 -0
  10. package/dist/bridge/dispatch-returns.js +20 -2
  11. package/dist/bridge/files.d.ts +1 -1
  12. package/dist/bridge/harnesses.js +8 -2
  13. package/dist/bridge/helper.d.ts +3 -2
  14. package/dist/bridge/helper.js +5 -4
  15. package/dist/bridge/machine-health-alerts.d.ts +20 -0
  16. package/dist/bridge/machine-health-alerts.js +47 -0
  17. package/dist/bridge/machine-health.d.ts +42 -0
  18. package/dist/bridge/machine-health.js +124 -0
  19. package/dist/bridge/machine-probes.d.ts +58 -0
  20. package/dist/bridge/machine-probes.js +306 -0
  21. package/dist/bridge/push.d.ts +10 -0
  22. package/dist/bridge/push.js +15 -0
  23. package/dist/bridge/resources.d.ts +5 -0
  24. package/dist/bridge/resources.js +16 -2
  25. package/dist/bridge/schedule-launch.js +2 -2
  26. package/dist/bridge/server-launch.js +3 -1
  27. package/dist/bridge/server.js +5 -1
  28. package/dist/bridge-hook.mjs +29235 -28083
  29. package/dist/computers/read.d.ts +18 -0
  30. package/dist/computers/read.js +18 -0
  31. package/dist/governance/policy.js +4 -3
  32. package/dist/governance/scores.js +2 -1
  33. package/dist/modules/registry.js +1 -1
  34. package/dist/tools/dispatch.js +16 -0
  35. package/dist/tools/helper.js +1 -1
  36. package/package.json +1 -1
  37. package/starter/global/skills/conductor/SKILL.md +6 -0
@@ -0,0 +1,306 @@
1
+ import { execFile } from "node:child_process";
2
+ import { readdir, readFile, stat } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { findPhrenPath } from "../phren-paths.js";
5
+ import { homeDir } from "../home-paths.js";
6
+ import { bridgeRoot } from "./protocol.js";
7
+ /**
8
+ * The slow half of machine health: platform probes that each cost a command or
9
+ * a directory walk, run in the background every few minutes (OS updates every
10
+ * few hours) and served from cache on each resource read. A probe whose tool
11
+ * is missing or fails reports nothing; it never fails the read.
12
+ *
13
+ * macOS: launchd agents in a restart loop, Time Machine age, pending updates,
14
+ * crash and jetsam reports. Linux: systemd NRestarts and failed units, OOM
15
+ * kills, core dumps, journal size, pending updates, NVIDIA GPU errors. Both:
16
+ * phren lock files whose owner process is gone.
17
+ */
18
+ const HOUR = 3_600_000, DAY = 24 * HOUR, MIN = 60_000;
19
+ const GB = 1024 ** 3;
20
+ export const PROBE_EVERY_MS = 5 * MIN;
21
+ export const UPDATES_EVERY_MS = 6 * HOUR;
22
+ const finding = (check, subject, severity, title, detail, fix) => ({ id: subject ? `${check}:${subject}` : check, check, severity, title, detail, fix });
23
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
24
+ const ago = (ms) => ms >= DAY ? `${Math.floor(ms / DAY)}d` : `${Math.max(1, Math.floor(ms / HOUR))}h`;
25
+ // ── launchd / systemd restart loops ─────────────────────────────────────────
26
+ /** `launchctl print gui/<uid>/<label>`: restart count, unless the job is meant to run repeatedly. */
27
+ export function parseLaunchdService(label, text) {
28
+ const runs = Number(/^\s*runs = (\d+)/m.exec(text)?.[1] ?? 0);
29
+ // Interval, calendar and path-watching jobs run often by design.
30
+ if (/run interval =|start calendar interval|event triggers|path state/i.test(text) && !/keepalive/i.test(text))
31
+ return undefined;
32
+ if (runs < 100)
33
+ return undefined;
34
+ const exit = /last exit code = ([^\n]+)/.exec(text)?.[1]?.trim();
35
+ return finding("restart-loop", label, runs >= 1000 ? "high" : "warn", `${label} restarted ${runs.toLocaleString("en-US")} times`, `launchd keeps relaunching it${exit ? `; last exit: ${exit}` : ""}.`, `Read its log, fix the cause, or unload it: launchctl bootout gui/$(id -u)/${label}`);
36
+ }
37
+ /** `launchctl list`: non-Apple labels, which are the ones worth printing. */
38
+ export function launchdLabels(text) {
39
+ return text.split("\n").slice(1).map(line => line.trim().split(/\s+/)[2]).filter((l) => !!l && !l.startsWith("com.apple.")).slice(0, 80);
40
+ }
41
+ /** `systemctl show -p Id -p NRestarts <units>`: blocks separated by blank lines. */
42
+ export function parseSystemdRestarts(text, scope) {
43
+ const out = [];
44
+ for (const block of text.split(/\n\s*\n/)) {
45
+ const id = /^Id=(.+)$/m.exec(block)?.[1]?.trim();
46
+ const restarts = Number(/^NRestarts=(\d+)$/m.exec(block)?.[1] ?? 0);
47
+ if (!id || restarts < 20)
48
+ continue;
49
+ const flag = scope === "user" ? "--user " : "";
50
+ out.push(finding("restart-loop", id, restarts >= 200 ? "high" : "warn", `${id} restarted ${restarts.toLocaleString("en-US")} times`, "systemd keeps restarting it.", `journalctl ${flag}-u ${id} -n 50, fix the cause, then systemctl ${flag}reset-failed ${id}.`));
51
+ }
52
+ return out;
53
+ }
54
+ /** `systemctl --failed --no-legend --plain`. */
55
+ export function parseFailedUnits(text, scope) {
56
+ const units = text.split("\n").map(l => l.trim().replace(/^●\s*/, "").split(/\s+/)[0]).filter(Boolean);
57
+ if (!units.length)
58
+ return [];
59
+ const flag = scope === "user" ? "--user " : "";
60
+ return [finding("failed-units", scope, "warn", `${plural(units.length, `failed ${scope} unit`)}`, units.slice(0, 6).join(", "), `systemctl ${flag}status ${units[0]} for the reason; systemctl ${flag}reset-failed once fixed.`)];
61
+ }
62
+ // ── backups and updates ─────────────────────────────────────────────────────
63
+ /** `tmutil latestbackup`: the newest backup's timestamp in its path. */
64
+ export function parseTimeMachine(latest, now) {
65
+ const m = /(\d{4})-(\d{2})-(\d{2})-(\d{2})(\d{2})(\d{2})/.exec(latest);
66
+ if (!m)
67
+ return undefined;
68
+ const at = new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]).getTime();
69
+ const age = now - at;
70
+ if (age < 3 * DAY)
71
+ return undefined;
72
+ return finding("backup", "time-machine", age >= 14 * DAY ? "high" : "warn", `Last Time Machine backup ${ago(age)} ago`, "Work since then is not backed up.", "Connect the backup disk, or run tmutil startbackup and check System Settings > Time Machine.");
73
+ }
74
+ /** `softwareupdate -l`, `checkupdates` or `apt list --upgradable`. */
75
+ export function parseUpdates(text, tool) {
76
+ const lines = text.split("\n");
77
+ const names = tool === "softwareupdate" ? lines.filter(l => /^\s*\* Label:/.test(l)).map(l => l.replace(/^\s*\* Label:\s*/, "").trim())
78
+ : tool === "apt" ? lines.filter(l => l.includes("[upgradable")).map(l => l.split("/")[0])
79
+ : lines.map(l => l.trim().split(/\s+/)[0]).filter(Boolean);
80
+ if (!names.length)
81
+ return undefined;
82
+ const restart = tool === "softwareupdate" && /Action: restart/i.test(text);
83
+ const fix = tool === "softwareupdate" ? "Install from System Settings > General > Software Update." : tool === "apt" ? "sudo apt upgrade" : "sudo pacman -Syu";
84
+ return finding("os-updates", "", restart ? "warn" : "info", `${plural(names.length, "pending update")}`, `${names.slice(0, 4).join(", ")}${names.length > 4 ? ", …" : ""}${restart ? " (needs a restart)" : ""}.`, fix);
85
+ }
86
+ // ── crashes and out-of-memory kills ─────────────────────────────────────────
87
+ /** Report file names from DiagnosticReports changed in the last day. */
88
+ export function parseDiagnosticReports(names) {
89
+ const out = [];
90
+ const jetsam = names.filter(n => n.startsWith("JetsamEvent")).length;
91
+ const panics = names.filter(n => /\.panic$|^panic-/.test(n)).length;
92
+ const crashes = new Map();
93
+ for (const n of names) {
94
+ if (!/\.(ips|crash)$/.test(n) || n.startsWith("JetsamEvent"))
95
+ continue;
96
+ const program = n.split(/[-_.]\d{4}-\d{2}-\d{2}/)[0];
97
+ crashes.set(program, (crashes.get(program) ?? 0) + 1);
98
+ }
99
+ if (panics)
100
+ out.push(finding("crashes", "kernel", "high", `${plural(panics, "kernel panic")} in the last day`, "The machine restarted on a panic.", "Open the panic report in Console; recurring panics point at hardware or a kernel extension."));
101
+ if (jetsam)
102
+ out.push(finding("oom", "", jetsam >= 5 ? "high" : "warn", `${plural(jetsam, "jetsam event")} in the last day`, "macOS killed processes to recover memory.", "Find what fills memory (memory-hog findings, Activity Monitor) and restart it."));
103
+ for (const [program, count] of crashes) {
104
+ if (count < 3)
105
+ continue;
106
+ out.push(finding("crashes", program, count >= 20 ? "high" : "warn", `${program} crashed ${count} times in the last day`, "Repeated crash reports in DiagnosticReports.", `Open the latest ${program} report in Console; update or reinstall it.`));
107
+ }
108
+ return out;
109
+ }
110
+ /** `journalctl -k --grep 'Out of memory: Killed process'` lines. */
111
+ export function parseOomKills(text) {
112
+ const lines = text.split("\n").filter(l => /Killed process/.test(l));
113
+ if (!lines.length)
114
+ return undefined;
115
+ const victims = [...new Set(lines.map(l => /\(([^)]+)\)/.exec(l)?.[1]).filter(Boolean))];
116
+ return finding("oom", "", lines.length >= 5 ? "high" : "warn", `${plural(lines.length, "OOM kill")} in the last day`, `The kernel killed ${victims.slice(0, 4).join(", ") || "processes"} to free memory.`, "Find what fills memory and cap or restart it; add swap if there is none.");
117
+ }
118
+ /** `coredumpctl list --json=short`: crashes by executable. */
119
+ export function parseCoredumps(json) {
120
+ let rows;
121
+ try {
122
+ rows = JSON.parse(json);
123
+ }
124
+ catch {
125
+ return [];
126
+ }
127
+ if (!Array.isArray(rows))
128
+ return [];
129
+ const counts = new Map();
130
+ for (const r of rows)
131
+ if (r.exe)
132
+ counts.set(path.basename(r.exe), (counts.get(path.basename(r.exe)) ?? 0) + 1);
133
+ return [...counts].filter(([, n]) => n >= 3).map(([exe, n]) => finding("crashes", exe, n >= 20 ? "high" : "warn", `${exe} crashed ${n} times in the last day`, "Repeated core dumps.", `coredumpctl info ${exe} for the backtrace.`));
134
+ }
135
+ /** `journalctl --disk-usage`. */
136
+ export function parseJournalSize(text) {
137
+ const m = /take up ([\d.]+)([KMGT])/.exec(text);
138
+ if (!m)
139
+ return undefined;
140
+ const bytes = Number(m[1]) * 1024 ** "KMGT".indexOf(m[2]) * 1024;
141
+ if (bytes < 4 * GB)
142
+ return undefined;
143
+ return finding("journal", "", bytes >= 16 * GB ? "high" : "warn", `System journal at ${m[1]}${m[2]}`, "Logs are taking disk space.", "sudo journalctl --vacuum-size=1G, and set SystemMaxUse in journald.conf.");
144
+ }
145
+ // ── GPU ─────────────────────────────────────────────────────────────────────
146
+ /** `nvidia-smi --query-gpu=index,name,ecc.errors.uncorrected.volatile.total,temperature.gpu --format=csv,noheader,nounits` plus Xid lines. */
147
+ export function parseNvidia(query, xid) {
148
+ const out = [];
149
+ for (const line of query.split("\n").filter(l => l.trim())) {
150
+ const [index, name, ecc, temp] = line.split(",").map(s => s.trim());
151
+ if (Number(ecc) > 0)
152
+ out.push(finding("gpu", `ecc-${index}`, "high", `GPU ${index} has ${ecc} uncorrectable memory errors`, name, "Drain its jobs and reset it (nvidia-smi -r -i " + index + "); replace it if they recur."));
153
+ if (Number(temp) >= 90)
154
+ out.push(finding("gpu", `temp-${index}`, "warn", `GPU ${index} at ${temp}°C`, name, "Check fans and airflow; lower its power limit."));
155
+ }
156
+ const xids = xid.split("\n").map(l => /Xid \([^)]*\): (\d+)/.exec(l)?.[1]).filter((x) => !!x);
157
+ if (xids.length) {
158
+ const fatal = xids.some(x => ["48", "79", "92", "94", "95"].includes(x));
159
+ out.push(finding("gpu", "xid", fatal || xids.length >= 10 ? "high" : "warn", `${plural(xids.length, "NVIDIA Xid error")} in the last day`, `Codes ${[...new Set(xids)].join(", ")}.`, fatal ? "The GPU fell off the bus or hit a double-bit error: reboot, then check power and seating." : "Look up the Xid codes; often a driver or application fault."));
160
+ }
161
+ return out;
162
+ }
163
+ export async function nvidiaFindings(deps) {
164
+ let query;
165
+ try {
166
+ query = await deps.run("nvidia-smi", ["--query-gpu=index,name,ecc.errors.uncorrected.volatile.total,temperature.gpu", "--format=csv,noheader,nounits"], 15_000);
167
+ }
168
+ catch (err) {
169
+ if (err.code === "ENOENT")
170
+ return [];
171
+ const message = String(err.stderr || err.message).split("\n")[0].slice(0, 160);
172
+ return [finding("gpu", "smi", "high", "nvidia-smi fails", message, "The driver is not talking to the GPU: check for a driver/kernel mismatch and reboot.")];
173
+ }
174
+ const xid = await deps.run("journalctl", ["-k", "--since=-24h", "--no-pager", "-q", "-o", "cat", "--grep", "NVRM: Xid"], 15_000).catch(() => "");
175
+ return parseNvidia(query, xid);
176
+ }
177
+ // ── stale locks ─────────────────────────────────────────────────────────────
178
+ /** A lock written as `<pid>\n<ms>` whose process is gone and that is older than 30 minutes. */
179
+ export async function staleLocks(deps) {
180
+ const stale = [];
181
+ const walk = async (dir, depth) => {
182
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
183
+ for (const e of entries) {
184
+ const full = path.join(dir, e.name);
185
+ if (e.isDirectory() && depth > 0 && !e.name.startsWith(".git") && e.name !== "node_modules")
186
+ await walk(full, depth - 1);
187
+ else if (e.isFile() && e.name.endsWith(".lock")) {
188
+ const info = await stat(full).catch(() => undefined);
189
+ if (!info || deps.now() - info.mtimeMs < 30 * MIN)
190
+ continue;
191
+ const pid = Number((await readFile(full, "utf8").catch(() => "")).split("\n")[0]);
192
+ if (Number.isInteger(pid) && pid > 0 && !deps.alive(pid))
193
+ stale.push(full);
194
+ }
195
+ }
196
+ };
197
+ for (const dir of deps.lockDirs)
198
+ await walk(dir, 2);
199
+ if (!stale.length)
200
+ return undefined;
201
+ return finding("stale-lock", "", "warn", `${plural(stale.length, "stale lock")}`, `Held by processes that have exited: ${stale.slice(0, 4).map(p => path.basename(p)).join(", ")}.`, `Remove them: rm ${stale.slice(0, 4).map(p => JSON.stringify(p)).join(" ")}`);
202
+ }
203
+ // ── the probes ──────────────────────────────────────────────────────────────
204
+ const since24h = ["--since=-24h", "--no-pager", "-q", "-o", "cat"];
205
+ const defined = (xs) => xs.filter((x) => x !== undefined);
206
+ const PROBES = [
207
+ { name: "launchd", everyMs: PROBE_EVERY_MS, platforms: ["darwin"], run: async (d) => {
208
+ const labels = launchdLabels(await d.run("/bin/launchctl", ["list"]));
209
+ const printed = await Promise.all(labels.map(l => d.run("/bin/launchctl", ["print", `gui/${d.uid}/${l}`]).then(t => parseLaunchdService(l, t), () => undefined)));
210
+ return defined(printed);
211
+ } },
212
+ { name: "systemd", everyMs: PROBE_EVERY_MS, platforms: ["linux"], run: async (d) => {
213
+ const out = [];
214
+ for (const scope of ["system", "user"]) {
215
+ const flag = scope === "user" ? ["--user"] : [];
216
+ const units = (await d.run("systemctl", [...flag, "list-units", "--type=service", "--all", "--no-legend", "--plain"]).catch(() => ""))
217
+ .split("\n").map(l => l.trim().split(/\s+/)[0]).filter(u => u.endsWith(".service"));
218
+ if (units.length)
219
+ out.push(...parseSystemdRestarts(await d.run("systemctl", [...flag, "show", "-p", "Id", "-p", "NRestarts", ...units]).catch(() => ""), scope));
220
+ out.push(...parseFailedUnits(await d.run("systemctl", [...flag, "--failed", "--no-legend", "--plain"]).catch(() => ""), scope));
221
+ }
222
+ return out;
223
+ } },
224
+ { name: "time-machine", everyMs: PROBE_EVERY_MS, platforms: ["darwin"], run: async (d) => defined([parseTimeMachine(await d.run("/usr/bin/tmutil", ["latestbackup"], 20_000), d.now())]) },
225
+ { name: "updates", everyMs: UPDATES_EVERY_MS, platforms: ["darwin", "linux"], run: async (d) => {
226
+ if (d.platform === "darwin")
227
+ return defined([parseUpdates(await d.run("/usr/sbin/softwareupdate", ["-l"], 120_000), "softwareupdate")]);
228
+ const pacman = await d.run("checkupdates", [], 120_000).then(t => parseUpdates(t, "checkupdates"), (e) => e.code === "ENOENT" ? null : undefined);
229
+ if (pacman !== null)
230
+ return defined([pacman]);
231
+ return defined([parseUpdates(await d.run("apt", ["list", "--upgradable"], 60_000), "apt")]);
232
+ } },
233
+ { name: "crashes", everyMs: PROBE_EVERY_MS, platforms: ["darwin"], run: async (d) => {
234
+ const recent = [];
235
+ for (const dir of [path.join(d.home, "Library/Logs/DiagnosticReports"), "/Library/Logs/DiagnosticReports"]) {
236
+ for (const n of await readdir(dir).catch(() => [])) {
237
+ const info = await stat(path.join(dir, n)).catch(() => undefined);
238
+ if (info?.isFile() && d.now() - info.mtimeMs < DAY)
239
+ recent.push(n);
240
+ }
241
+ }
242
+ return parseDiagnosticReports(recent);
243
+ } },
244
+ { name: "oom", everyMs: PROBE_EVERY_MS, platforms: ["linux"], run: async (d) => defined([
245
+ parseOomKills(await d.run("journalctl", ["-k", ...since24h, "--grep", "Out of memory: Killed process"], 15_000).catch(() => "")),
246
+ parseJournalSize(await d.run("journalctl", ["--disk-usage"]).catch(() => "")),
247
+ ...parseCoredumps(await d.run("coredumpctl", ["list", "--since=-24h", "--no-legend", "--json=short"], 15_000).catch(() => "[]")),
248
+ ]) },
249
+ { name: "gpu", everyMs: PROBE_EVERY_MS, platforms: ["linux", "win32"], run: nvidiaFindings },
250
+ { name: "locks", everyMs: PROBE_EVERY_MS, platforms: ["darwin", "linux"], run: async (d) => defined([await staleLocks(d)]) },
251
+ ];
252
+ function defaultDeps() {
253
+ const store = (() => { try {
254
+ return findPhrenPath();
255
+ }
256
+ catch {
257
+ return null;
258
+ } })();
259
+ return {
260
+ platform: process.platform, now: Date.now, home: homeDir(), uid: process.getuid?.() ?? 0,
261
+ run: (file, args, timeoutMs = 10_000) => new Promise((resolve, reject) => {
262
+ execFile(file, args, { timeout: timeoutMs, maxBuffer: 8 * 1024 * 1024, env: { ...process.env, LC_ALL: "C" } }, (err, stdout, stderr) => err ? reject(Object.assign(err, { stderr })) : resolve(stdout));
263
+ }),
264
+ lockDirs: [bridgeRoot(), ...(store ? [store] : [])],
265
+ alive: pid => { try {
266
+ process.kill(pid, 0);
267
+ return true;
268
+ }
269
+ catch (e) {
270
+ return e.code === "EPERM";
271
+ } },
272
+ };
273
+ }
274
+ /** Runs the due probes in the background and serves the last results. */
275
+ export class PlatformProbes {
276
+ probes;
277
+ results = new Map();
278
+ ranAt = new Map();
279
+ running;
280
+ deps;
281
+ constructor(deps = {}, probes = PROBES) {
282
+ this.probes = probes;
283
+ this.deps = { ...defaultDeps(), ...deps };
284
+ }
285
+ /** The cached findings; starts a refresh when a probe is due. */
286
+ current() {
287
+ void this.refresh();
288
+ return [...this.results.values()].flat();
289
+ }
290
+ refresh() {
291
+ if (this.running)
292
+ return this.running;
293
+ const now = this.deps.now();
294
+ const due = this.probes.filter(p => p.platforms.includes(this.deps.platform) && now - (this.ranAt.get(p.name) ?? -Infinity) >= p.everyMs);
295
+ if (!due.length)
296
+ return Promise.resolve();
297
+ for (const p of due)
298
+ this.ranAt.set(p.name, now);
299
+ // One at a time: these are background checks and should not compete with the work they watch.
300
+ this.running = (async () => {
301
+ for (const p of due)
302
+ this.results.set(p.name, await p.run(this.deps).catch(() => []));
303
+ })().finally(() => { this.running = undefined; });
304
+ return this.running;
305
+ }
306
+ }
@@ -43,6 +43,13 @@ export interface ApprovalPush {
43
43
  request?: string;
44
44
  requestKind?: RequestKind;
45
45
  }
46
+ export interface MachineHealthPush {
47
+ computer: string;
48
+ id: string;
49
+ title: string;
50
+ detail: string;
51
+ fix: string;
52
+ }
46
53
  export interface FanoutBlockedPush {
47
54
  job: string;
48
55
  label: string;
@@ -72,6 +79,7 @@ export declare function approvalPushPayload(value: ApprovalPush, host?: string):
72
79
  * notification action. */
73
80
  export declare function sudoPushPayload(value: SudoRequestView, host?: string): Record<string, unknown>;
74
81
  export declare function fanoutBlockedPushPayload(value: FanoutBlockedPush): Record<string, unknown>;
82
+ export declare function machineHealthPushPayload(value: MachineHealthPush, host?: string): Record<string, unknown>;
75
83
  export declare function schedulePushPayload(value: SchedulePush): Record<string, unknown>;
76
84
  /** What `phren bridge doctor` prints when the Hook has no APNs sender. */
77
85
  export declare function apnsSetupSteps(configFile?: string): string;
@@ -139,6 +147,8 @@ export declare class ApprovalPushService {
139
147
  * phones already accept agent alerts; the payload carries the reason so the
140
148
  * notification is actionable on its own. */
141
149
  notifyFanoutBlocked(value: FanoutBlockedPush): Promise<boolean>;
150
+ /** A new high-severity machine health finding (machine-health-alerts.ts dedupes). */
151
+ notifyMachineHealth(value: MachineHealthPush): Promise<boolean>;
142
152
  notifySchedule(value: SchedulePush): Promise<SchedulePushResult>;
143
153
  }
144
154
  export {};
@@ -64,6 +64,12 @@ export function fanoutBlockedPushPayload(value) {
64
64
  phren: { kind: "fanoutBlocked", job: value.job, provider: value.provider, label: value.label, reason: value.reason },
65
65
  };
66
66
  }
67
+ export function machineHealthPushPayload(value, host) {
68
+ return {
69
+ aps: { alert: { title: `${value.computer}: ${value.title}`, body: `${value.detail} ${value.fix}`.trim() }, sound: "default", category: "PHREN_HEALTH" },
70
+ phren: { kind: "machineHealth", ...(host ? { host } : {}), computer: value.computer, id: value.id, title: value.title, detail: value.detail, fix: value.fix, route: "resources" },
71
+ };
72
+ }
67
73
  export function schedulePushPayload(value) {
68
74
  const state = value.kind === "scheduleStarted" ? "started" : value.kind === "scheduleFinished" ? (value.status === "needs-you" ? "needs you" : "finished")
69
75
  : value.kind === "scheduleBlocked" ? "blocked" : "failed";
@@ -309,6 +315,15 @@ export class ApprovalPushService {
309
315
  expiration: "0", collapseId: `fanout-${value.job}`,
310
316
  })))).some(Boolean);
311
317
  }
318
+ /** A new high-severity machine health finding (machine-health-alerts.ts dedupes). */
319
+ async notifyMachineHealth(value) {
320
+ const devices = this.reachable.filter(device => device.kinds.includes("approval"));
321
+ if (!devices.length)
322
+ return false;
323
+ return (await Promise.all(devices.map(device => this.send(device, machineHealthPushPayload(value, device.hostID), {
324
+ expiration: "0", collapseId: `health-${value.id}`.slice(0, 64),
325
+ })))).some(Boolean);
326
+ }
312
327
  async notifySchedule(value) {
313
328
  const reachable = this.reachable;
314
329
  if (!reachable.length)
@@ -1,4 +1,5 @@
1
1
  import { type CleanupReport, type JobSource, type ProcessLike, type TrackedJob } from "./job-registry.js";
2
+ import { type HealthFinding } from "./machine-health.js";
2
3
  /**
3
4
  * This computer's live resources for `GET /v1/resources`, the overview
4
5
  * stream's `resources` frames and the memory-free `phren computers` surface:
@@ -74,6 +75,8 @@ export interface ComputerResources {
74
75
  };
75
76
  level: "ok" | "busy" | "stressed";
76
77
  warnings: Array<"load-high" | "memory-low" | "disk-low" | "battery-low">;
78
+ /** Named health findings with severity and a fix (machine-health.ts), worst first. */
79
+ health?: HealthFinding[];
77
80
  }
78
81
  /** What the computer is, read once per Hook run: "MacBook Pro", "Apple M1 Max",
79
82
  * 32 GB; on Linux the DMI vendor and product ("Dell XPS 13 9310") and the CPU's
@@ -158,6 +161,8 @@ export interface ResourceDeps {
158
161
  } | undefined>;
159
162
  hardware?: () => Promise<ComputerHardware | undefined>;
160
163
  jobs?: JobSource;
164
+ /** Named findings for this read from the numbers and the process table. */
165
+ health?: (value: ComputerResources, rows: ProcessRow[]) => HealthFinding[];
161
166
  }
162
167
  export declare function collectResources(deps: ResourceDeps): Promise<ComputerResources>;
163
168
  /** One collection at a time, reused for `RESOURCES_MAX_AGE_MS`. */
@@ -8,6 +8,8 @@ import { recentServers, sharedSnapshot } from "./herdr.js";
8
8
  import { JobRegistry, jobPgids, paneKey } from "./job-registry.js";
9
9
  import { intervalFromEnv } from "./limits.js";
10
10
  import { objects } from "./protocol.js";
11
+ import { MachineHealth } from "./machine-health.js";
12
+ import { PlatformProbes } from "./machine-probes.js";
11
13
  const exec = promisify(execFile);
12
14
  /**
13
15
  * This computer's live resources for `GET /v1/resources`, the overview
@@ -420,7 +422,17 @@ export async function collectResources(deps) {
420
422
  memory, ...(disk ? { disk } : {}), ...(battery ? { battery } : {}), ...(hardware ? { hardware } : {}),
421
423
  heavy: owners.size || jobs.length ? heavyProcesses(rows, owners, jobs) : preliminary,
422
424
  };
423
- return { ...value, ...assess(value) };
425
+ const result = { ...value, ...assess(value) };
426
+ const check = deps.health;
427
+ if (!check)
428
+ return result;
429
+ const health = (() => { try {
430
+ return check(result, rows);
431
+ }
432
+ catch {
433
+ return undefined;
434
+ } })();
435
+ return health ? { ...result, health } : result;
424
436
  }
425
437
  /** One collection at a time, reused for `RESOURCES_MAX_AGE_MS`. */
426
438
  export class ResourceMonitor {
@@ -432,7 +444,9 @@ export class ResourceMonitor {
432
444
  constructor(deps = {}, maxAgeMs = RESOURCES_MAX_AGE_MS) {
433
445
  this.maxAgeMs = maxAgeMs;
434
446
  this.registry = deps.jobs ?? new JobRegistry();
435
- this.deps = { platform: process.platform, now: Date.now, home: homeDir, processes: processTable, owners: paneOwners, panes: livePanes, ...deps, jobs: this.registry };
447
+ const health = new MachineHealth(process.env.PHREN_HEALTH_PROBES === "off" ? undefined : new PlatformProbes());
448
+ this.deps = { platform: process.platform, now: Date.now, home: homeDir, processes: processTable, owners: paneOwners, panes: livePanes,
449
+ health: (value, rows) => health.assess(value, rows, this.deps.now()), ...deps, jobs: this.registry };
436
450
  }
437
451
  async read() {
438
452
  if (this.cached && this.deps.now() - this.cached.at < this.maxAgeMs)
@@ -152,7 +152,7 @@ async function launchInHerdr(server, context, launchHerdr, signal) {
152
152
  // The prompt goes with the launch where the harness takes one (Claude,
153
153
  // Codex); otherwise it is typed once the agent is ready.
154
154
  const brief = context.schedule.prompt.trim() ? { brief: { id: context.runId, text: context.schedule.prompt } } : {};
155
- const launched = await launchHerdr(server, { cwd: context.cwd, label: context.schedule.name, kind: context.schedule.harness, model: context.schedule.model, ...(context.schedule.account ? { account: context.schedule.account } : {}), ...brief });
155
+ const launched = await launchHerdr(server, { cwd: context.cwd, label: context.schedule.name, kind: context.schedule.harness, model: context.schedule.model, project: context.project, ...(context.schedule.account ? { account: context.schedule.account } : {}), ...brief });
156
156
  const workspaceId = String(launched.workspaceId), tabId = String(launched.tabId), paneId = String(launched.paneId);
157
157
  if (launched.briefLaunched !== true)
158
158
  await promptWhenReady(server, paneId, context.schedule.prompt, signal);
@@ -202,7 +202,7 @@ export function headlessEnv(schedule, env = process.env) {
202
202
  async function launchHeadless(context, store, started) {
203
203
  // A Claude schedule that names no account runs under the one with the most room, as a Herdr launch does.
204
204
  const choice = context.schedule.harness === "claude" && !context.schedule.account
205
- ? await pickClaudeAccount(`Schedule "${context.schedule.name}"`).catch(() => undefined) : undefined;
205
+ ? await pickClaudeAccount(`Schedule "${context.schedule.name}"`, { project: context.project, cwd: context.cwd }) : undefined;
206
206
  const env = headlessEnv(choice ? { ...context.schedule, account: choice.account } : context.schedule);
207
207
  const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir = path.join(root, context.runId);
208
208
  await mkdir(jobDir, { recursive: true, mode: 0o700 });
@@ -426,7 +426,9 @@ async function startSession(server, data, options) {
426
426
  const timeout = Math.min(120_000, Math.max(3_001, data.timeoutMs === undefined ? 45_000 : z.number().int().parse(data.timeoutMs)));
427
427
  // Checked before anything is created, so a refusal leaves no pane, worktree or brief file behind.
428
428
  // A Claude launch that names no account runs under the signed-in one with the most room left.
429
- const choice = kind === "claude" && named === undefined ? await pickClaudeAccount(`Launch "${label}"`).catch(() => undefined) : undefined;
429
+ // Pools and roles apply as in dispatch: a 409 account_pool when no account may do this project's work.
430
+ const project = typeof data.project === "string" && data.project ? data.project : undefined;
431
+ const choice = kind === "claude" && named === undefined ? await pickClaudeAccount(`Launch "${label}"`, { project, cwd: projectDirectory }) : undefined;
430
432
  const account = named ?? choice?.account;
431
433
  await requireAvailable(kind, account);
432
434
  const home = kind === "claude" && account && account !== DEFAULT_ACCOUNT ? claudeHome(account) : undefined;
@@ -49,6 +49,7 @@ import { PermissionModeSwitcher } from "./permission-mode.js";
49
49
  import { SideQuestions } from "./side-questions.js";
50
50
  import { AccountUsageReader } from "./usage.js";
51
51
  import { ResourceMonitor } from "./resources.js";
52
+ import { ALERT_CHECK_MS, HealthAlerts } from "./machine-health-alerts.js";
52
53
  import { createScheduleLauncher, Scheduler, scheduleRunsFile } from "./schedules.js";
53
54
  import { dailyCanaryDue, runCanary } from "./canary.js";
54
55
  import { defaultPhrenPath } from "../shared.js";
@@ -343,6 +344,9 @@ export async function serve(version, options = {}) {
343
344
  // Every store converges with its remote even when no agent session runs here (store-sync.ts).
344
345
  const storeSync = startStoreSyncLoop(scheduleStore);
345
346
  const canaryTimer = setInterval(() => { countTick("canary"); void dailyCanaryDue().then(due => due ? canary("daily") : undefined).catch(() => { }); }, 10 * 60_000);
347
+ // A new high machine health finding reaches the phone once (machine-health-alerts.ts).
348
+ const healthAlerts = new HealthAlerts(finding => agentHooks.push.notifyMachineHealth({ computer: hostname(), ...finding }));
349
+ const healthTimer = setInterval(() => { countTick("health"); void resources.read().then(value => healthAlerts.observe(value.health, Date.now())).catch(() => { }); }, ALERT_CHECK_MS);
346
350
  let recording = false;
347
351
  const activityTimer = setInterval(() => {
348
352
  countTick("activity");
@@ -391,7 +395,7 @@ export async function serve(version, options = {}) {
391
395
  })().finally(() => { recording = false; }).catch(() => { });
392
396
  }, 5000);
393
397
  await new Promise(resolve => {
394
- const stop = () => { gitboyWebhooks.stop(); storePulls.stop(); storeSync.stop(); fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(canaryTimer); clearInterval(codexAuthTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); codexServers.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
398
+ const stop = () => { gitboyWebhooks.stop(); storePulls.stop(); storeSync.stop(); fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(canaryTimer); clearInterval(healthTimer); clearInterval(codexAuthTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); codexServers.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
395
399
  process.once("SIGTERM", stop);
396
400
  process.once("SIGINT", stop);
397
401
  });