@phren/cli 0.3.66 → 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.
- package/dist/bridge/account-choice.d.ts +12 -3
- package/dist/bridge/account-choice.js +133 -19
- package/dist/bridge/account-last-known.d.ts +27 -0
- package/dist/bridge/account-last-known.js +124 -0
- package/dist/bridge/claude-accounts.d.ts +27 -0
- package/dist/bridge/claude-accounts.js +63 -8
- package/dist/bridge/dispatch-returns.d.ts +8 -0
- package/dist/bridge/dispatch-returns.js +20 -2
- package/dist/bridge/files.d.ts +1 -1
- package/dist/bridge/harnesses.js +8 -2
- package/dist/bridge/helper.d.ts +3 -2
- package/dist/bridge/helper.js +5 -4
- package/dist/bridge/machine-health-alerts.d.ts +20 -0
- package/dist/bridge/machine-health-alerts.js +47 -0
- package/dist/bridge/machine-health.d.ts +42 -0
- package/dist/bridge/machine-health.js +124 -0
- package/dist/bridge/machine-probes.d.ts +58 -0
- package/dist/bridge/machine-probes.js +306 -0
- package/dist/bridge/push.d.ts +10 -0
- package/dist/bridge/push.js +15 -0
- package/dist/bridge/resources.d.ts +5 -0
- package/dist/bridge/resources.js +16 -2
- package/dist/bridge/schedule-launch.js +2 -2
- package/dist/bridge/server-launch.js +3 -1
- package/dist/bridge/server.js +5 -1
- package/dist/bridge-hook.mjs +29054 -28107
- package/dist/computers/read.d.ts +18 -0
- package/dist/computers/read.js +18 -0
- package/dist/modules/registry.js +1 -1
- package/dist/tools/dispatch.js +16 -0
- package/dist/tools/helper.js +1 -1
- package/package.json +1 -1
- package/starter/global/skills/conductor/SKILL.md +6 -0
package/dist/bridge/helper.js
CHANGED
|
@@ -30,8 +30,9 @@ const PANE_ENV = (name) => name.startsWith("HERDR_") || name === "TMUX" || name
|
|
|
30
30
|
/** Without allowEdits: tools that change files or run commands, refused even if a settings file allows them. */
|
|
31
31
|
const WRITE_TOOLS = "Bash,Edit,MultiEdit,Write,NotebookEdit";
|
|
32
32
|
/**
|
|
33
|
-
* The project's helper account and model, checked: configured, an account on this computer
|
|
34
|
-
*
|
|
33
|
+
* The project's helper account and model, checked: configured, an account on this computer with role `helpers`
|
|
34
|
+
* (a team store's phren.project.yaml can name any of the owner's local accounts), and in the project's and this
|
|
35
|
+
* computer's allowed pools. Throws with what to change otherwise.
|
|
35
36
|
*/
|
|
36
37
|
export function helperFor(phrenPath, project, env = process.env) {
|
|
37
38
|
const raw = readProjectConfig(phrenPath, project).helper;
|
|
@@ -52,8 +53,8 @@ export function helperFor(phrenPath, project, env = process.env) {
|
|
|
52
53
|
// Read strictly: an accounts.yaml that can't be read must not turn the refusals off.
|
|
53
54
|
const policy = accountPolicy();
|
|
54
55
|
const { pool, role } = policy.settings[account] ?? {};
|
|
55
|
-
if (role
|
|
56
|
-
throw new Error(`Claude account ${account}'s role is
|
|
56
|
+
if (role !== "helpers")
|
|
57
|
+
throw new Error(`Claude account ${account}'s role is ${role ?? "not set"}: a helper runs only under an account with role helpers (phren bridge accounts role ${account} helpers).`);
|
|
57
58
|
const where = pool ? `pool ${pool}` : "no pool";
|
|
58
59
|
const forProject = projectAllowedPools(phrenPath, project);
|
|
59
60
|
if (!poolAllowed(forProject, pool))
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { HealthFinding } from "./machine-health.js";
|
|
2
|
+
/**
|
|
3
|
+
* Turns the stream of health reads into phone pushes: one push when a `high`
|
|
4
|
+
* finding id first appears, nothing while it stays, and again only if it
|
|
5
|
+
* clears and comes back after `REPEAT_AFTER_MS`. At most `MAX_PER_HOUR`
|
|
6
|
+
* pushes an hour across all ids, so a bad morning is a few alerts, not a
|
|
7
|
+
* storm. State is in memory: a Hook restart may repeat a standing alert once.
|
|
8
|
+
*/
|
|
9
|
+
export declare const REPEAT_AFTER_MS: number;
|
|
10
|
+
export declare const MAX_PER_HOUR = 3;
|
|
11
|
+
export declare const ALERT_CHECK_MS: number;
|
|
12
|
+
export declare class HealthAlerts {
|
|
13
|
+
private readonly notify;
|
|
14
|
+
private active;
|
|
15
|
+
private lastPushed;
|
|
16
|
+
private sent;
|
|
17
|
+
constructor(notify: (finding: HealthFinding) => Promise<unknown>);
|
|
18
|
+
/** The findings that were pushed for this read. */
|
|
19
|
+
observe(findings: readonly HealthFinding[] | undefined, now: number): HealthFinding[];
|
|
20
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turns the stream of health reads into phone pushes: one push when a `high`
|
|
3
|
+
* finding id first appears, nothing while it stays, and again only if it
|
|
4
|
+
* clears and comes back after `REPEAT_AFTER_MS`. At most `MAX_PER_HOUR`
|
|
5
|
+
* pushes an hour across all ids, so a bad morning is a few alerts, not a
|
|
6
|
+
* storm. State is in memory: a Hook restart may repeat a standing alert once.
|
|
7
|
+
*/
|
|
8
|
+
export const REPEAT_AFTER_MS = 6 * 3_600_000;
|
|
9
|
+
export const MAX_PER_HOUR = 3;
|
|
10
|
+
export const ALERT_CHECK_MS = 5 * 60_000;
|
|
11
|
+
export class HealthAlerts {
|
|
12
|
+
notify;
|
|
13
|
+
active = new Set();
|
|
14
|
+
lastPushed = new Map();
|
|
15
|
+
sent = [];
|
|
16
|
+
constructor(notify) {
|
|
17
|
+
this.notify = notify;
|
|
18
|
+
}
|
|
19
|
+
/** The findings that were pushed for this read. */
|
|
20
|
+
observe(findings, now) {
|
|
21
|
+
const high = (findings ?? []).filter(f => f.severity === "high");
|
|
22
|
+
const ids = new Set(high.map(f => f.id));
|
|
23
|
+
for (const id of this.active)
|
|
24
|
+
if (!ids.has(id))
|
|
25
|
+
this.active.delete(id);
|
|
26
|
+
this.sent = this.sent.filter(at => now - at < 3_600_000);
|
|
27
|
+
const pushed = [];
|
|
28
|
+
for (const finding of high) {
|
|
29
|
+
if (this.active.has(finding.id))
|
|
30
|
+
continue;
|
|
31
|
+
const last = this.lastPushed.get(finding.id);
|
|
32
|
+
if (last !== undefined && now - last < REPEAT_AFTER_MS) {
|
|
33
|
+
this.active.add(finding.id);
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
// Over the hourly cap the finding stays new, so the next read retries it.
|
|
37
|
+
if (this.sent.length >= MAX_PER_HOUR)
|
|
38
|
+
continue;
|
|
39
|
+
this.active.add(finding.id);
|
|
40
|
+
this.lastPushed.set(finding.id, now);
|
|
41
|
+
this.sent.push(now);
|
|
42
|
+
pushed.push(finding);
|
|
43
|
+
void this.notify(finding).catch(() => { });
|
|
44
|
+
}
|
|
45
|
+
return pushed;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { ComputerResources, ProcessRow } from "./resources.js";
|
|
2
|
+
/**
|
|
3
|
+
* Named machine health findings from numbers the resource monitor already
|
|
4
|
+
* reads (load, memory, swap, disk, the process table): no extra scans. Each
|
|
5
|
+
* finding has a stable `id` (check plus subject) so clients and the conductor
|
|
6
|
+
* can track it across reads, a severity, and a suggested fix in plain words.
|
|
7
|
+
* Trends come from a short in-memory history of samples, one per
|
|
8
|
+
* `SAMPLE_EVERY_MS`, so a leak or a filling disk shows before the threshold.
|
|
9
|
+
*/
|
|
10
|
+
export type HealthSeverity = "info" | "warn" | "high";
|
|
11
|
+
export type HealthCheck = "swap" | "disk" | "load" | "memory-hog" | "memory-leak" | "orphan" | "simulator-clones" | "uptime" | "restart-loop" | "failed-units" | "backup" | "os-updates" | "crashes" | "oom" | "journal" | "gpu" | "stale-lock";
|
|
12
|
+
export interface HealthFinding {
|
|
13
|
+
id: string;
|
|
14
|
+
check: HealthCheck;
|
|
15
|
+
severity: HealthSeverity;
|
|
16
|
+
title: string;
|
|
17
|
+
detail: string;
|
|
18
|
+
fix: string;
|
|
19
|
+
}
|
|
20
|
+
export interface HealthSample {
|
|
21
|
+
at: number;
|
|
22
|
+
swapUsedBytes?: number;
|
|
23
|
+
diskFreeBytes?: number;
|
|
24
|
+
/** Resident bytes of the largest processes, by program name. */
|
|
25
|
+
rss: Record<string, number>;
|
|
26
|
+
}
|
|
27
|
+
export declare const SAMPLE_EVERY_MS: number;
|
|
28
|
+
/** Two hours of samples. */
|
|
29
|
+
export declare const HISTORY_SAMPLES = 24;
|
|
30
|
+
/** One sample from a resource read, keeping the eight largest resident programs. */
|
|
31
|
+
export declare function healthSample(value: ComputerResources, rows: readonly ProcessRow[], at: number): HealthSample;
|
|
32
|
+
/** The findings for one read, worst first. `history` is oldest first and may be empty. */
|
|
33
|
+
export declare function assessHealth(value: ComputerResources, rows: readonly ProcessRow[], history: readonly HealthSample[], now: number): HealthFinding[];
|
|
34
|
+
/** Keeps the sample history and assesses each read, adding the slow probes' cached findings. */
|
|
35
|
+
export declare class MachineHealth {
|
|
36
|
+
private readonly probes?;
|
|
37
|
+
private history;
|
|
38
|
+
constructor(probes?: {
|
|
39
|
+
current(): HealthFinding[];
|
|
40
|
+
} | undefined);
|
|
41
|
+
assess(value: ComputerResources, rows: readonly ProcessRow[], now: number): HealthFinding[];
|
|
42
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
const GB = 1024 ** 3;
|
|
3
|
+
const HOUR = 3_600_000;
|
|
4
|
+
export const SAMPLE_EVERY_MS = 5 * 60_000;
|
|
5
|
+
/** Two hours of samples. */
|
|
6
|
+
export const HISTORY_SAMPLES = 24;
|
|
7
|
+
const gb = (bytes) => `${(bytes / GB).toFixed(bytes < 10 * GB ? 1 : 0)} GB`;
|
|
8
|
+
const age = (ms) => ms >= 86_400_000 ? `${Math.floor(ms / 86_400_000)}d` : `${Math.max(1, Math.floor(ms / HOUR))}h`;
|
|
9
|
+
const name = (row) => path.basename(row.command) || row.command;
|
|
10
|
+
const rank = { high: 0, warn: 1, info: 2 };
|
|
11
|
+
/** Processes the OS or an app spawns many of; per-process RSS on these is not a leak signal. */
|
|
12
|
+
const NOT_A_DAEMON = /^(launchd_sim|Simulator|qemu-system|java|node|Electron|Google Chrome Helper.*)$/;
|
|
13
|
+
/** Patterns of programs that should never outlive whoever started them. */
|
|
14
|
+
const ORPHANS = [
|
|
15
|
+
{ subject: "simctl-record", match: r => /simctl\b.*\brecordVideo\b/.test(r.args), minAgeMs: HOUR,
|
|
16
|
+
fix: "End it: pkill -f 'simctl.*recordVideo'." },
|
|
17
|
+
{ subject: "desktop-reh", match: r => /desktop-reh|reh-server|server-main\.js/.test(r.args) && /phren|desktop/.test(r.args), minAgeMs: 6 * HOUR,
|
|
18
|
+
fix: "End the stray editor servers: pkill -f desktop-reh." },
|
|
19
|
+
{ subject: "test-postgres", match: r => name(r) === "postgres" && /(\/tmp\/|\/var\/folders\/|test|pglite|embedded)/i.test(r.args), minAgeMs: 6 * HOUR,
|
|
20
|
+
fix: "Stop the leftover test database (pg_ctl stop -D <dir>, or kill the postmaster)." },
|
|
21
|
+
{ subject: "test-runner", match: r => /\b(vitest|jest|playwright|xctest)\b/i.test(r.args), minAgeMs: 6 * HOUR,
|
|
22
|
+
fix: "End the leftover test run; nothing is waiting on it." },
|
|
23
|
+
];
|
|
24
|
+
/** One sample from a resource read, keeping the eight largest resident programs. */
|
|
25
|
+
export function healthSample(value, rows, at) {
|
|
26
|
+
const byName = new Map();
|
|
27
|
+
for (const row of rows) {
|
|
28
|
+
const key = name(row);
|
|
29
|
+
if (NOT_A_DAEMON.test(key))
|
|
30
|
+
continue;
|
|
31
|
+
byName.set(key, Math.max(byName.get(key) ?? 0, row.rssKB * 1024));
|
|
32
|
+
}
|
|
33
|
+
const rss = Object.fromEntries([...byName].sort((a, b) => b[1] - a[1]).slice(0, 8));
|
|
34
|
+
return { at, ...(value.memory.swapUsedBytes !== undefined ? { swapUsedBytes: value.memory.swapUsedBytes } : {}),
|
|
35
|
+
...(value.disk ? { diskFreeBytes: value.disk.freeBytes } : {}), rss };
|
|
36
|
+
}
|
|
37
|
+
/** The findings for one read, worst first. `history` is oldest first and may be empty. */
|
|
38
|
+
export function assessHealth(value, rows, history, now) {
|
|
39
|
+
const out = [];
|
|
40
|
+
const add = (check, subject, severity, title, detail, fix) => out.push({ id: subject ? `${check}:${subject}` : check, check, severity, title, detail, fix });
|
|
41
|
+
const oldest = history.find(s => now - s.at >= 30 * 60_000);
|
|
42
|
+
const hours = oldest ? (now - oldest.at) / HOUR : 0;
|
|
43
|
+
const swap = value.memory.swapUsedBytes;
|
|
44
|
+
if (swap !== undefined) {
|
|
45
|
+
const grew = oldest?.swapUsedBytes !== undefined ? swap - oldest.swapUsedBytes : 0;
|
|
46
|
+
if (swap >= 20 * GB)
|
|
47
|
+
add("swap", "", "high", `Swap at ${gb(swap)}`, "The system is paging heavily; everything slows and the disk fills.", "Find the process holding the most memory and restart it.");
|
|
48
|
+
else if (swap >= 8 * GB)
|
|
49
|
+
add("swap", "", "warn", `Swap at ${gb(swap)}`, "Memory is overcommitted.", "Close or restart the largest memory users.");
|
|
50
|
+
else if (grew >= 4 * GB)
|
|
51
|
+
add("swap", "", "warn", `Swap grew ${gb(grew)} in ${age(now - oldest.at)}`, `Now ${gb(swap)}.`, "Look for a process whose memory keeps climbing.");
|
|
52
|
+
}
|
|
53
|
+
const free = value.disk?.freeBytes;
|
|
54
|
+
if (free !== undefined) {
|
|
55
|
+
const rate = oldest?.diskFreeBytes !== undefined && hours > 0 ? (oldest.diskFreeBytes - free) / hours : 0;
|
|
56
|
+
const fix = "Free space: clear simulator clones (xcrun simctl delete unavailable), DerivedData, caches and old swap.";
|
|
57
|
+
if (free < 10 * GB)
|
|
58
|
+
add("disk", "", "high", `${gb(free)} free on the home volume`, "Builds, swap and the store will start failing.", fix);
|
|
59
|
+
else if (free < 20 * GB)
|
|
60
|
+
add("disk", "", "warn", `${gb(free)} free on the home volume`, "Getting close to the 10 GB floor.", fix);
|
|
61
|
+
else if (rate >= 2 * GB)
|
|
62
|
+
add("disk", "", "warn", `Disk filling at ${gb(rate)}/h`, `${gb(free)} free, about ${Math.round(free / rate)}h left at this rate.`, "Find what is writing: swap growth, logs, or a runaway build.");
|
|
63
|
+
}
|
|
64
|
+
const { cores, loadPerCore, load1 } = value.cpu;
|
|
65
|
+
if (loadPerCore > 2 && rows.length) {
|
|
66
|
+
const busyCores = rows.reduce((sum, r) => sum + r.cpu, 0) / 100;
|
|
67
|
+
if (busyCores < cores * 0.5)
|
|
68
|
+
add("load", "pileup", "warn", `Load ${load1} with CPU ${Math.round(busyCores / cores * 100)}% busy`, "Load far above CPU use means threads waiting on disk I/O or locks, not real work (often many parallel simulators or tests).", "Cut parallelism (fewer simulators or test workers) and check for a process stuck on I/O.");
|
|
69
|
+
else
|
|
70
|
+
add("load", "cpu", loadPerCore > 4 ? "high" : "warn", `Load ${load1} on ${cores} cores`, "The CPU is saturated.", "Pause or stop the heaviest jobs listed under Heavy.");
|
|
71
|
+
}
|
|
72
|
+
const total = value.memory.totalBytes;
|
|
73
|
+
const biggest = new Map();
|
|
74
|
+
for (const row of rows) {
|
|
75
|
+
const key = name(row);
|
|
76
|
+
if (NOT_A_DAEMON.test(key))
|
|
77
|
+
continue;
|
|
78
|
+
if ((biggest.get(key)?.rssKB ?? 0) < row.rssKB)
|
|
79
|
+
biggest.set(key, row);
|
|
80
|
+
}
|
|
81
|
+
for (const [key, row] of biggest) {
|
|
82
|
+
const bytes = row.rssKB * 1024;
|
|
83
|
+
const before = oldest?.rss[key];
|
|
84
|
+
if (total && bytes >= Math.max(8 * GB, total * 0.25)) {
|
|
85
|
+
add("memory-hog", key, bytes >= total * 0.5 ? "high" : "warn", `${key} holds ${gb(bytes)}`, `pid ${row.pid}, ${Math.round(bytes / total * 100)}% of memory.`, `Restart it (kill ${row.pid}; launchd or systemd brings system daemons back).`);
|
|
86
|
+
}
|
|
87
|
+
else if (before !== undefined && bytes - before >= 2 * GB) {
|
|
88
|
+
add("memory-leak", key, "warn", `${key} grew ${gb(bytes - before)} in ${age(now - oldest.at)}`, `pid ${row.pid}, now ${gb(bytes)}.`, `Likely a leak; restart it before it pushes the system into swap (kill ${row.pid}).`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
for (const pattern of ORPHANS) {
|
|
92
|
+
const stale = rows.filter(r => r.ppid === 1 && pattern.match(r) && r.startedAt !== undefined && now - r.startedAt >= pattern.minAgeMs);
|
|
93
|
+
if (!stale.length)
|
|
94
|
+
continue;
|
|
95
|
+
const oldestStart = Math.min(...stale.map(r => r.startedAt));
|
|
96
|
+
add("orphan", pattern.subject, stale.length >= 10 || now - oldestStart >= 7 * 86_400_000 ? "high" : "warn", `${stale.length} orphaned ${pattern.subject} process${stale.length === 1 ? "" : "es"}`, `Oldest running ${age(now - oldestStart)} with no parent (pid ${stale.slice(0, 5).map(r => r.pid).join(", ")}).`, pattern.fix);
|
|
97
|
+
}
|
|
98
|
+
const clones = rows.filter(r => name(r) === "launchd_sim" && /XCTestDevices/.test(r.args)).length;
|
|
99
|
+
if (clones >= 8)
|
|
100
|
+
add("simulator-clones", "", clones >= 30 ? "high" : "warn", `${clones} simulator test clones running`, "Parallel UI testing left clones booted; each holds memory and threads.", "xcrun simctl --set testing shutdown all && xcrun simctl --set testing delete all");
|
|
101
|
+
const days = value.uptimeSeconds / 86_400;
|
|
102
|
+
if (days >= 30)
|
|
103
|
+
add("uptime", "", "info", `Up ${Math.floor(days)} days`, "Long uptimes accumulate leaks and defer OS updates.", "Restart at a convenient time.");
|
|
104
|
+
return out.sort((a, b) => rank[a.severity] - rank[b.severity]);
|
|
105
|
+
}
|
|
106
|
+
/** Keeps the sample history and assesses each read, adding the slow probes' cached findings. */
|
|
107
|
+
export class MachineHealth {
|
|
108
|
+
probes;
|
|
109
|
+
history = [];
|
|
110
|
+
constructor(probes) {
|
|
111
|
+
this.probes = probes;
|
|
112
|
+
}
|
|
113
|
+
assess(value, rows, now) {
|
|
114
|
+
const findings = [...assessHealth(value, rows, this.history, now), ...(this.probes?.current() ?? [])]
|
|
115
|
+
.sort((a, b) => rank[a.severity] - rank[b.severity]);
|
|
116
|
+
const last = this.history.at(-1);
|
|
117
|
+
if (!last || now - last.at >= SAMPLE_EVERY_MS) {
|
|
118
|
+
this.history.push(healthSample(value, rows, now));
|
|
119
|
+
if (this.history.length > HISTORY_SAMPLES)
|
|
120
|
+
this.history.shift();
|
|
121
|
+
}
|
|
122
|
+
return findings;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { HealthFinding } from "./machine-health.js";
|
|
2
|
+
export declare const PROBE_EVERY_MS: number;
|
|
3
|
+
export declare const UPDATES_EVERY_MS: number;
|
|
4
|
+
export interface ProbeDeps {
|
|
5
|
+
platform: string;
|
|
6
|
+
now: () => number;
|
|
7
|
+
home: string;
|
|
8
|
+
uid: number;
|
|
9
|
+
/** stdout of a command; rejects when it is missing, fails or times out. */
|
|
10
|
+
run: (file: string, args: string[], timeoutMs?: number) => Promise<string>;
|
|
11
|
+
/** Directories searched (two levels) for `*.lock` files. */
|
|
12
|
+
lockDirs: string[];
|
|
13
|
+
alive: (pid: number) => boolean;
|
|
14
|
+
}
|
|
15
|
+
type Probe = {
|
|
16
|
+
name: string;
|
|
17
|
+
everyMs: number;
|
|
18
|
+
platforms: string[];
|
|
19
|
+
run: (deps: ProbeDeps) => Promise<HealthFinding[]>;
|
|
20
|
+
};
|
|
21
|
+
/** `launchctl print gui/<uid>/<label>`: restart count, unless the job is meant to run repeatedly. */
|
|
22
|
+
export declare function parseLaunchdService(label: string, text: string): HealthFinding | undefined;
|
|
23
|
+
/** `launchctl list`: non-Apple labels, which are the ones worth printing. */
|
|
24
|
+
export declare function launchdLabels(text: string): string[];
|
|
25
|
+
/** `systemctl show -p Id -p NRestarts <units>`: blocks separated by blank lines. */
|
|
26
|
+
export declare function parseSystemdRestarts(text: string, scope: "system" | "user"): HealthFinding[];
|
|
27
|
+
/** `systemctl --failed --no-legend --plain`. */
|
|
28
|
+
export declare function parseFailedUnits(text: string, scope: "system" | "user"): HealthFinding[];
|
|
29
|
+
/** `tmutil latestbackup`: the newest backup's timestamp in its path. */
|
|
30
|
+
export declare function parseTimeMachine(latest: string, now: number): HealthFinding | undefined;
|
|
31
|
+
/** `softwareupdate -l`, `checkupdates` or `apt list --upgradable`. */
|
|
32
|
+
export declare function parseUpdates(text: string, tool: "softwareupdate" | "checkupdates" | "apt"): HealthFinding | undefined;
|
|
33
|
+
/** Report file names from DiagnosticReports changed in the last day. */
|
|
34
|
+
export declare function parseDiagnosticReports(names: readonly string[]): HealthFinding[];
|
|
35
|
+
/** `journalctl -k --grep 'Out of memory: Killed process'` lines. */
|
|
36
|
+
export declare function parseOomKills(text: string): HealthFinding | undefined;
|
|
37
|
+
/** `coredumpctl list --json=short`: crashes by executable. */
|
|
38
|
+
export declare function parseCoredumps(json: string): HealthFinding[];
|
|
39
|
+
/** `journalctl --disk-usage`. */
|
|
40
|
+
export declare function parseJournalSize(text: string): HealthFinding | undefined;
|
|
41
|
+
/** `nvidia-smi --query-gpu=index,name,ecc.errors.uncorrected.volatile.total,temperature.gpu --format=csv,noheader,nounits` plus Xid lines. */
|
|
42
|
+
export declare function parseNvidia(query: string, xid: string): HealthFinding[];
|
|
43
|
+
export declare function nvidiaFindings(deps: Pick<ProbeDeps, "run">): Promise<HealthFinding[]>;
|
|
44
|
+
/** A lock written as `<pid>\n<ms>` whose process is gone and that is older than 30 minutes. */
|
|
45
|
+
export declare function staleLocks(deps: Pick<ProbeDeps, "lockDirs" | "alive" | "now">): Promise<HealthFinding | undefined>;
|
|
46
|
+
/** Runs the due probes in the background and serves the last results. */
|
|
47
|
+
export declare class PlatformProbes {
|
|
48
|
+
private readonly probes;
|
|
49
|
+
private results;
|
|
50
|
+
private ranAt;
|
|
51
|
+
private running?;
|
|
52
|
+
private readonly deps;
|
|
53
|
+
constructor(deps?: Partial<ProbeDeps>, probes?: Probe[]);
|
|
54
|
+
/** The cached findings; starts a refresh when a probe is due. */
|
|
55
|
+
current(): HealthFinding[];
|
|
56
|
+
refresh(): Promise<void>;
|
|
57
|
+
}
|
|
58
|
+
export {};
|
|
@@ -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
|
+
}
|