@phren/cli 0.3.79 → 0.3.80

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/dispatch.js +17 -3
  2. package/dist/bridge/housekeeping/command.d.ts +5 -0
  3. package/dist/bridge/housekeeping/command.js +106 -0
  4. package/dist/bridge/housekeeping/housekeeper.d.ts +123 -0
  5. package/dist/bridge/housekeeping/housekeeper.js +459 -0
  6. package/dist/bridge/housekeeping/inventory.d.ts +145 -0
  7. package/dist/bridge/housekeeping/inventory.js +276 -0
  8. package/dist/bridge/housekeeping/report.d.ts +672 -0
  9. package/dist/bridge/housekeeping/report.js +168 -0
  10. package/dist/bridge/housekeeping/safety.d.ts +177 -0
  11. package/dist/bridge/housekeeping/safety.js +466 -0
  12. package/dist/bridge/owner-proof.js +1 -0
  13. package/dist/bridge/push.js +3 -1
  14. package/dist/bridge/resources.d.ts +8 -0
  15. package/dist/bridge/resources.js +18 -5
  16. package/dist/bridge/server-pane-routes.d.ts +6 -0
  17. package/dist/bridge/server-pane-routes.js +1 -1
  18. package/dist/bridge/server-routes.d.ts +5 -0
  19. package/dist/bridge/server-routes.js +44 -3
  20. package/dist/bridge/server.js +44 -8
  21. package/dist/bridge-hook.mjs +2980 -1226
  22. package/dist/cli-registry.js +18 -1
  23. package/dist/fanout/command.js +42 -15
  24. package/dist/heavy/budget-status.d.ts +26 -0
  25. package/dist/heavy/budget-status.js +26 -0
  26. package/dist/heavy/budget.d.ts +39 -0
  27. package/dist/heavy/budget.js +57 -0
  28. package/dist/heavy/command.d.ts +15 -0
  29. package/dist/heavy/command.js +119 -0
  30. package/dist/heavy/reap.d.ts +70 -0
  31. package/dist/heavy/reap.js +211 -0
  32. package/dist/heavy/slots.d.ts +58 -0
  33. package/dist/heavy/slots.js +142 -0
  34. package/dist/modules/registry.js +4 -3
  35. package/package.json +1 -1
  36. package/starter/global/skills/conductor/SKILL.md +10 -0
  37. package/starter/global/skills/fanout/SKILL.md +30 -0
@@ -198,6 +198,17 @@ export const REGISTRY = [
198
198
  summary: "Run sudo -A with Phren Hook's askpass: your phone shows the command and asks for the password, for `!` commands and agents with no terminal",
199
199
  run: async (args) => (await import("./bridge/sudo.js")).runSudo(args),
200
200
  },
201
+ {
202
+ name: "heavy", topic: "core", standalone: true,
203
+ usage: "phren heavy [--priority release|normal|low] [--slots N] [--pool NAME] [--label TEXT] [--timeout MINUTES] -- <command...> | phren heavy status [--json]",
204
+ summary: "Run a heavy job (full test run, native build) once this computer has a slot: N at once, release work first, waiting while memory or load is over budget",
205
+ run: async (args) => (await import("./heavy/command.js")).runHeavy(args),
206
+ },
207
+ {
208
+ name: "reap", topic: "core", standalone: true, usage: "phren reap [--all] [--json]",
209
+ summary: "List dev servers, build daemons, test watchers, wait loops and test database clones agents left running, with age, idle time, memory and the command that stops each; stops nothing itself",
210
+ run: async (args) => (await import("./heavy/reap.js")).runReap(args),
211
+ },
201
212
  {
202
213
  name: "secret-exec", topic: "core", standalone: true, usage: "phren secret-exec [--prompt <text>] [--plist <key> [--field K=V]...] -- <command...>",
203
214
  summary: "Run a command with a secret typed on your phone on its stdin (a line, or a plist field); the phone shows the exact command and the secret never reaches the agent",
@@ -216,6 +227,12 @@ export const REGISTRY = [
216
227
  summary: "Agent usage per harness (limits, resets, spend) across computers from Phren Hook, without Phren memory",
217
228
  run: async (args) => (await import("./computers/command.js")).runUsage(args),
218
229
  },
230
+ {
231
+ name: "housekeeping", topic: "core", standalone: true,
232
+ usage: "phren housekeeping [--dry-run] [--local] [--json] | --scan | --apply <action ids>",
233
+ summary: "The Hook's housekeeping report and inventory (worktrees, space, panes) for this and every linked computer; --apply removes or closes what you name, after a safety re-check",
234
+ run: async (args) => (await import("./bridge/housekeeping/command.js")).runHousekeeping(args),
235
+ },
219
236
  {
220
237
  name: "owner-inbox", topic: "core", usage: "phren owner-inbox [list [--all] | add <title> [--project <slug>] [--id <uuid>] | resolve <id> [--computer <name>] [--resolution <text>]]",
221
238
  summary: "List, add and resolve what waits on the owner",
@@ -583,7 +600,7 @@ export const REGISTRY = [
583
600
  {
584
601
  name: "fanout",
585
602
  topic: "config",
586
- usage: "phren fanout run|usage|resume|review|list|archive",
603
+ usage: "phren fanout run|usage|resume|review|list|archive [--priority release|normal|low] [--wait MINUTES]",
587
604
  summary: "Launch and manage usage-aware agent workers",
588
605
  run: async (args, ctx) => (await import("./fanout/command.js")).runFanout(args, ctx),
589
606
  },
@@ -6,6 +6,8 @@ import { archiveFinishedFanouts } from "../bridge/fanouts.js";
6
6
  import { defaultPolicy, policySchema, pick } from "./picker.js";
7
7
  import { readUsage, recentProviderErrors } from "./usage.js";
8
8
  import { createJob, jobsRoot, launch, listJobs, readJob, swiftBuildCount } from "./launcher.js";
9
+ import { readBudget, readPressure } from "../heavy/budget.js";
10
+ import { acquire, PRIORITIES, QueueTimeout } from "../heavy/slots.js";
9
11
  export async function runFanout(args, ctx) {
10
12
  const [action, ...rest] = args, store = ctx.phrenPath();
11
13
  if (action === "usage") {
@@ -35,7 +37,7 @@ export async function runFanout(args, ctx) {
35
37
  const flags = {}, extra = [];
36
38
  while (rest.length) {
37
39
  const key = rest.shift(), value = rest.shift();
38
- if (!["--tier", "--provider", "--model", "--label", "--worktree", "--variant", "--extra"].includes(key) || !value)
40
+ if (!["--tier", "--provider", "--model", "--label", "--worktree", "--variant", "--extra", "--priority", "--wait"].includes(key) || !value)
39
41
  throw new Error(`Invalid fan-out option ${key}`);
40
42
  if (key === "--extra")
41
43
  extra.push(value);
@@ -61,18 +63,43 @@ export async function runFanout(args, ctx) {
61
63
  throw new Error("Provide a brief on stdin.");
62
64
  const file = path.join(store, ".config", "fanout.yaml");
63
65
  const policy = fs.existsSync(file) ? policySchema.parse(yaml.load(fs.readFileSync(file, "utf8"), { schema: yaml.CORE_SCHEMA })) : defaultPolicy;
64
- const usage = await readUsage(), errors = recentProviderErrors(), needsSwift = /\b(swift|xcodebuild|ios)\b/i.test(prompt);
65
- fs.mkdirSync(jobsRoot(store), { recursive: true, mode: 0o700 });
66
- const reserved = withFileLock(path.join(jobsRoot(store), "launch"), () => {
67
- const running = listJobs(store).filter(job => !fs.existsSync(path.join(jobsRoot(store), job.id, "exit.txt")));
68
- const chosen = pick({ policy, tier: tier, usage, errors, running, swiftBuilds: needsSwift ? swiftBuildCount() : 0, needsSwift,
69
- override: { provider: (flags.provider ?? previous?.provider), model: flags.model ?? previous?.model } });
70
- // An OpenCode worker is driven over HTTP; there is no command line to extend.
71
- if (chosen.provider === "opencode" && extra.length)
72
- throw new Error("OpenCode workers take no --extra arguments.");
73
- console.log(chosen.reason);
74
- const options = { ...chosen, store, label, worktree, prompt, review: tier === "review", resume: previous?.session, variant: flags.variant, extra };
75
- return { options, reservation: createJob(options) };
76
- });
77
- return launch(reserved.options, reserved.reservation);
66
+ // Wait for this computer's worker budget rather than start a worker it has
67
+ // no memory or CPU for (heavy/budget.ts; see `phren heavy status`).
68
+ if (flags.priority && !(flags.priority in PRIORITIES))
69
+ throw new Error("Choose priority release, normal or low.");
70
+ const waitMinutes = flags.wait === undefined ? 120 : Number(flags.wait);
71
+ if (!Number.isFinite(waitMinutes) || waitMinutes < 0)
72
+ throw new Error("--wait takes minutes (0 to fail at once when the computer is full).");
73
+ const budget = readBudget((await readPressure()).totalBytes), slots = Math.min(budget.workers, policy.computerCap);
74
+ let held;
75
+ try {
76
+ held = await acquire({ pool: "workers", slots, priority: PRIORITIES[(flags.priority ?? "normal")], label, budget,
77
+ pressure: () => readPressure(), timeoutMs: waitMinutes * 60_000, report: message => console.error(`phren fanout: ${message} (worker budget ${slots} on this computer)`) });
78
+ }
79
+ catch (error) {
80
+ if (error instanceof QueueTimeout) {
81
+ console.error(`phren fanout: not started, ${error.message}`);
82
+ return 75;
83
+ }
84
+ throw error;
85
+ }
86
+ try {
87
+ const usage = await readUsage(), errors = recentProviderErrors(), needsSwift = /\b(swift|xcodebuild|ios)\b/i.test(prompt);
88
+ fs.mkdirSync(jobsRoot(store), { recursive: true, mode: 0o700 });
89
+ const reserved = withFileLock(path.join(jobsRoot(store), "launch"), () => {
90
+ const running = listJobs(store).filter(job => !fs.existsSync(path.join(jobsRoot(store), job.id, "exit.txt")));
91
+ const chosen = pick({ policy, tier: tier, usage, errors, running, swiftBuilds: needsSwift ? swiftBuildCount() : 0, needsSwift,
92
+ override: { provider: (flags.provider ?? previous?.provider), model: flags.model ?? previous?.model } });
93
+ // An OpenCode worker is driven over HTTP; there is no command line to extend.
94
+ if (chosen.provider === "opencode" && extra.length)
95
+ throw new Error("OpenCode workers take no --extra arguments.");
96
+ console.log(chosen.reason);
97
+ const options = { ...chosen, store, label, worktree, prompt, review: tier === "review", resume: previous?.session, variant: flags.variant, extra };
98
+ return { options, reservation: createJob(options) };
99
+ });
100
+ return await launch(reserved.options, reserved.reservation);
101
+ }
102
+ finally {
103
+ held.release();
104
+ }
78
105
  }
@@ -0,0 +1,26 @@
1
+ import { type Pressure } from "./budget.js";
2
+ /** One pool as the phone shows it: its slots, what runs and what waits, oldest first. */
3
+ export interface PoolView {
4
+ slots: number;
5
+ running: number;
6
+ waiting: number;
7
+ jobs: Array<{
8
+ label: string;
9
+ state: "running" | "waiting";
10
+ priority: "release" | "normal" | "low";
11
+ sinceSeconds: number;
12
+ }>;
13
+ }
14
+ /**
15
+ * This computer's budget for agent work (`phren fanout run`, `phren heavy`) as
16
+ * it stands now: the two pools and, when memory or load is past the budget,
17
+ * why nothing new should start. Served on the resources reading.
18
+ */
19
+ export interface AgentBudget {
20
+ workers: PoolView;
21
+ heavy: PoolView;
22
+ minFreeBytes: number;
23
+ maxLoadPerCore: number;
24
+ overBudget?: string;
25
+ }
26
+ export declare function agentBudget(pressure: Pressure, now?: number, root?: string, env?: NodeJS.ProcessEnv): AgentBudget;
@@ -0,0 +1,26 @@
1
+ import { pressureReason, readBudget } from "./budget.js";
2
+ import { poolStatus, priorityName, slotsRoot } from "./slots.js";
3
+ const MAX_JOBS = 8;
4
+ function view(tickets, slots, now) {
5
+ const running = tickets.filter(t => t.state === "running").length;
6
+ return {
7
+ slots, running, waiting: tickets.length - running,
8
+ jobs: tickets.slice(0, MAX_JOBS).map(t => ({
9
+ label: (t.label || "job").replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 80),
10
+ state: t.state,
11
+ priority: priorityName(t.priority),
12
+ sinceSeconds: Math.max(0, Math.round((now - (t.state === "running" ? t.startedAt ?? t.createdAt : t.createdAt)) / 1000)),
13
+ })),
14
+ };
15
+ }
16
+ export function agentBudget(pressure, now = Date.now(), root = slotsRoot(), env = process.env) {
17
+ const budget = readBudget(pressure.totalBytes, env);
18
+ const overBudget = pressureReason(pressure, budget);
19
+ return {
20
+ workers: view(poolStatus("workers", root), budget.workers, now),
21
+ heavy: view(poolStatus("heavy", root), budget.heavySlots, now),
22
+ minFreeBytes: budget.minFreeBytes,
23
+ maxLoadPerCore: budget.maxLoadPerCore,
24
+ ...(overBudget ? { overBudget } : {}),
25
+ };
26
+ }
@@ -0,0 +1,39 @@
1
+ /** What this computer can take right now. */
2
+ export interface Pressure {
3
+ totalBytes: number;
4
+ availableBytes?: number;
5
+ load1: number;
6
+ cores: number;
7
+ }
8
+ /**
9
+ * The per-machine budget for agent work. Measured on a 31 GB Linux box
10
+ * (2026-11-15): a worker with its full vitest run takes 2 to 8 GB and an app
11
+ * stack 0.6 to 1 GB, so about one worker per 7 GB and one heavy job (a full
12
+ * test run, a native build) per 12 GB keep it out of swap.
13
+ */
14
+ export interface Budget {
15
+ /** Agent workers started through `phren fanout run` at once. */
16
+ workers: number;
17
+ /** Jobs run through `phren heavy` at once. */
18
+ heavySlots: number;
19
+ /** Below this much available memory nothing new starts while another holds a slot. */
20
+ minFreeBytes: number;
21
+ /** Above this one-minute load per core nothing new starts while another holds a slot. */
22
+ maxLoadPerCore: number;
23
+ }
24
+ export declare const budgetKeys: {
25
+ readonly workers: "PHREN_FANOUT_WORKERS";
26
+ readonly heavySlots: "PHREN_HEAVY_SLOTS";
27
+ readonly minFreeGB: "PHREN_MIN_FREE_GB";
28
+ readonly maxLoadPerCore: "PHREN_MAX_LOAD_PER_CORE";
29
+ };
30
+ /** `$XDG_CONFIG_HOME/phren/budget.yaml`: this computer's own budget, never synced with the store. */
31
+ export declare function budgetFile(env?: NodeJS.ProcessEnv): string;
32
+ export declare function defaultBudget(totalBytes: number): Budget;
33
+ /** Defaults from the memory size, then budget.yaml, then the environment. Invalid values are ignored. */
34
+ export declare function readBudget(totalBytes: number, env?: NodeJS.ProcessEnv, file?: string): Budget;
35
+ /** Memory comes from the resources gauge's reader (bridge/resources.ts), so the budget and the Hook's gauge agree. */
36
+ export declare function readPressure(platform?: NodeJS.Platform): Promise<Pressure>;
37
+ /** Why nothing new should start now, or undefined when the computer has room. */
38
+ export declare function pressureReason(pressure: Pressure, budget: Budget): string | undefined;
39
+ export declare function describePressure(pressure: Pressure): string;
@@ -0,0 +1,57 @@
1
+ import * as fs from "node:fs";
2
+ import { cpus, freemem, homedir, loadavg, totalmem } from "node:os";
3
+ import * as path from "node:path";
4
+ import * as yaml from "js-yaml";
5
+ const GB = 1024 ** 3;
6
+ export const budgetKeys = { workers: "PHREN_FANOUT_WORKERS", heavySlots: "PHREN_HEAVY_SLOTS", minFreeGB: "PHREN_MIN_FREE_GB", maxLoadPerCore: "PHREN_MAX_LOAD_PER_CORE" };
7
+ /** `$XDG_CONFIG_HOME/phren/budget.yaml`: this computer's own budget, never synced with the store. */
8
+ export function budgetFile(env = process.env) {
9
+ return path.join(env.XDG_CONFIG_HOME || path.join(homedir(), ".config"), "phren", "budget.yaml");
10
+ }
11
+ export function defaultBudget(totalBytes) {
12
+ const gb = totalBytes / GB;
13
+ return { workers: Math.max(1, Math.floor(gb / 7)), heavySlots: Math.max(1, Math.floor(gb / 12)),
14
+ minFreeBytes: Math.max(2, Math.round(gb * 0.1)) * GB, maxLoadPerCore: 1.5 };
15
+ }
16
+ /** Defaults from the memory size, then budget.yaml, then the environment. Invalid values are ignored. */
17
+ export function readBudget(totalBytes, env = process.env, file = budgetFile(env)) {
18
+ const budget = defaultBudget(totalBytes);
19
+ let config = {};
20
+ try {
21
+ const parsed = yaml.load(fs.readFileSync(file, "utf8"), { schema: yaml.CORE_SCHEMA });
22
+ if (parsed && typeof parsed === "object")
23
+ config = parsed;
24
+ }
25
+ catch { /* No file or unreadable: defaults. */ }
26
+ const value = (key) => {
27
+ const raw = env[budgetKeys[key]] ?? config[key];
28
+ const n = typeof raw === "number" ? raw : typeof raw === "string" && raw.trim() ? Number(raw) : NaN;
29
+ return Number.isFinite(n) && n > 0 ? n : undefined;
30
+ };
31
+ const workers = value("workers"), heavySlots = value("heavySlots"), minFree = value("minFreeGB"), load = value("maxLoadPerCore");
32
+ return { workers: workers ? Math.floor(workers) : budget.workers, heavySlots: heavySlots ? Math.floor(heavySlots) : budget.heavySlots,
33
+ minFreeBytes: minFree ? minFree * GB : budget.minFreeBytes, maxLoadPerCore: load ?? budget.maxLoadPerCore };
34
+ }
35
+ /** Memory comes from the resources gauge's reader (bridge/resources.ts), so the budget and the Hook's gauge agree. */
36
+ export async function readPressure(platform = process.platform) {
37
+ const { readMemory } = await import("../bridge/resources.js");
38
+ const memory = await readMemory(platform).catch(() => ({ totalBytes: totalmem(), availablePercent: undefined }));
39
+ const totalBytes = memory.totalBytes || totalmem();
40
+ return { totalBytes, availableBytes: memory.availablePercent === undefined ? freemem() : Math.round(totalBytes * memory.availablePercent / 100),
41
+ load1: loadavg()[0], cores: cpus().length || 1 };
42
+ }
43
+ const gb = (bytes) => `${(bytes / GB).toFixed(1)} GB`;
44
+ /** Why nothing new should start now, or undefined when the computer has room. */
45
+ export function pressureReason(pressure, budget) {
46
+ const reasons = [];
47
+ if (pressure.availableBytes !== undefined && pressure.availableBytes < budget.minFreeBytes) {
48
+ reasons.push(`${gb(pressure.availableBytes)} of ${gb(pressure.totalBytes)} memory available, under the ${gb(budget.minFreeBytes)} floor`);
49
+ }
50
+ const perCore = pressure.load1 / pressure.cores;
51
+ if (perCore > budget.maxLoadPerCore)
52
+ reasons.push(`load ${pressure.load1.toFixed(1)} on ${pressure.cores} cores, over ${budget.maxLoadPerCore} per core`);
53
+ return reasons.length ? reasons.join("; ") : undefined;
54
+ }
55
+ export function describePressure(pressure) {
56
+ return `${pressure.availableBytes === undefined ? "memory unknown" : `${gb(pressure.availableBytes)} of ${gb(pressure.totalBytes)} memory available`}, load ${pressure.load1.toFixed(1)} on ${pressure.cores} cores`;
57
+ }
@@ -0,0 +1,15 @@
1
+ import type { ComputerReport } from "../computers/read.js";
2
+ /**
3
+ * `phren heavy -- pnpm test`: run one heavy job (a full test run, a native
4
+ * build) once this computer has a slot for it. Up to the budget's
5
+ * `heavySlots` run at once; waiting jobs start release work first, then in
6
+ * arrival order. The command's own exit code is returned; 75 when it never
7
+ * started (timeout). Messages go to stderr so the command's stdout is untouched.
8
+ */
9
+ export declare function runHeavy(args: string[]): Promise<number>;
10
+ /**
11
+ * Where this job could run instead. Phren cannot move a command yet, only an
12
+ * agent: a dispatched worker in a fresh worktree on that computer runs it and
13
+ * reports back (docs/fanout.md, "Heavy runs on another computer").
14
+ */
15
+ export declare function elsewhereHint(computers: ComputerReport[], label: string): string | undefined;
@@ -0,0 +1,119 @@
1
+ import { spawn } from "node:child_process";
2
+ import { budgetFile, describePressure, readBudget, readPressure } from "./budget.js";
3
+ import { acquire, minutes, poolStatus, pools, PRIORITIES, priorityName, QueueTimeout } from "./slots.js";
4
+ const USAGE = `Usage: phren heavy [--priority release|normal|low] [--slots N] [--pool NAME] [--label TEXT] [--timeout MINUTES] -- <command...>
5
+ phren heavy status [--json]`;
6
+ /**
7
+ * `phren heavy -- pnpm test`: run one heavy job (a full test run, a native
8
+ * build) once this computer has a slot for it. Up to the budget's
9
+ * `heavySlots` run at once; waiting jobs start release work first, then in
10
+ * arrival order. The command's own exit code is returned; 75 when it never
11
+ * started (timeout). Messages go to stderr so the command's stdout is untouched.
12
+ */
13
+ export async function runHeavy(args) {
14
+ if (args[0] === "status")
15
+ return status(args.slice(1));
16
+ const split = args.indexOf("--");
17
+ if (split < 0 || split === args.length - 1)
18
+ throw new Error(USAGE);
19
+ const options = args.slice(0, split), command = args.slice(split + 1);
20
+ const flags = {};
21
+ for (let i = 0; i < options.length; i += 2) {
22
+ const key = options[i], value = options[i + 1];
23
+ if (!["--priority", "--slots", "--pool", "--label", "--timeout"].includes(key) || value === undefined)
24
+ throw new Error(USAGE);
25
+ flags[key.slice(2)] = value;
26
+ }
27
+ const priority = (flags.priority ?? process.env.PHREN_HEAVY_PRIORITY ?? "normal");
28
+ if (!(priority in PRIORITIES))
29
+ throw new Error("Choose priority release, normal or low.");
30
+ const pressure = await readPressure(), budget = readBudget(pressure.totalBytes);
31
+ const pool = flags.pool ?? "heavy";
32
+ const slots = flags.slots ? Number(flags.slots) : pool === "workers" ? budget.workers : budget.heavySlots;
33
+ if (!Number.isInteger(slots) || slots < 1 || slots > 64)
34
+ throw new Error("--slots takes a whole number from 1 to 64.");
35
+ const timeout = flags.timeout === undefined ? undefined : Number(flags.timeout);
36
+ if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0))
37
+ throw new Error("--timeout takes minutes.");
38
+ const label = (flags.label ?? command.join(" ")).replace(/\s+/g, " ").slice(0, 120);
39
+ const say = (message) => process.stderr.write(`phren heavy: ${message}\n`);
40
+ let held, hinted = false;
41
+ const report = (message) => {
42
+ say(`${message} [${pool}: ${slots} slot${slots === 1 ? "" : "s"}, ${priority}]`);
43
+ // Held back by this computer's memory or load: name an enrolled computer with room, once.
44
+ if (hinted || !/^queued: .*(memory available|load \d)/.test(message))
45
+ return;
46
+ hinted = true;
47
+ void import("../computers/read.js").then(read => Promise.race([read.readComputers({ peers: true }),
48
+ new Promise((_, reject) => setTimeout(() => reject(new Error("slow")), 4_000).unref())]))
49
+ .then(({ computers }) => { const hint = elsewhereHint(computers, label); if (hint)
50
+ say(hint); }).catch(() => undefined);
51
+ };
52
+ try {
53
+ held = await acquire({ pool, slots, priority: PRIORITIES[priority], label, budget, pressure: () => readPressure(), report,
54
+ ...(timeout !== undefined ? { timeoutMs: timeout * 60_000 } : {}) });
55
+ }
56
+ catch (error) {
57
+ if (error instanceof QueueTimeout) {
58
+ say(`not started, ${error.message}`);
59
+ return 75;
60
+ }
61
+ throw error;
62
+ }
63
+ try {
64
+ return await new Promise(resolve => {
65
+ const child = spawn(command[0], command.slice(1), { stdio: "inherit", env: { ...process.env, PHREN_HEAVY_POOL: pool } });
66
+ // Pass the person's or agent's interrupt on and keep the slot until the job is gone.
67
+ const forward = (signal) => () => { try {
68
+ child.kill(signal);
69
+ }
70
+ catch { /* Gone. */ } };
71
+ const handlers = ["SIGINT", "SIGTERM", "SIGHUP"].map(signal => [signal, forward(signal)]);
72
+ for (const [signal, handler] of handlers)
73
+ process.on(signal, handler);
74
+ const done = (code) => { for (const [signal, handler] of handlers)
75
+ process.off(signal, handler); resolve(code); };
76
+ child.once("error", error => { say(`${command[0]}: ${error.message}`); done(127); });
77
+ child.once("exit", (code, signal) => done(code ?? (signal ? 128 + ({ SIGINT: 2, SIGTERM: 15, SIGHUP: 1, SIGKILL: 9 }[signal] ?? 1) : 1)));
78
+ });
79
+ }
80
+ finally {
81
+ held.release();
82
+ }
83
+ }
84
+ async function status(args) {
85
+ if (args.some(arg => arg !== "--json"))
86
+ throw new Error(USAGE);
87
+ const pressure = await readPressure(), budget = readBudget(pressure.totalBytes), now = Date.now();
88
+ const report = { pressure, budget, budgetFile: budgetFile(),
89
+ pools: pools().map(pool => ({ pool, tickets: poolStatus(pool) })) };
90
+ if (args.includes("--json")) {
91
+ console.log(JSON.stringify(report, null, 2));
92
+ return 0;
93
+ }
94
+ console.log(`${describePressure(pressure)}`);
95
+ console.log(`Budget: ${budget.workers} workers, ${budget.heavySlots} heavy jobs, at least ${(budget.minFreeBytes / 1024 ** 3).toFixed(1)} GB free, load under ${budget.maxLoadPerCore} per core (${report.budgetFile})`);
96
+ for (const { pool, tickets } of report.pools) {
97
+ if (!tickets.length)
98
+ continue;
99
+ console.log(`\n${pool}`);
100
+ for (const t of tickets)
101
+ console.log(` ${t.state === "running" ? "running" : "waiting"}\t${minutes(now - (t.startedAt ?? t.createdAt))}\t${priorityName(t.priority)}\tpid ${t.pid}\t${t.label}`);
102
+ }
103
+ return 0;
104
+ }
105
+ /**
106
+ * Where this job could run instead. Phren cannot move a command yet, only an
107
+ * agent: a dispatched worker in a fresh worktree on that computer runs it and
108
+ * reports back (docs/fanout.md, "Heavy runs on another computer").
109
+ */
110
+ export function elsewhereHint(computers, label) {
111
+ const other = computers.filter(c => !c.local && c.online && c.resources && c.resources.level !== "stressed")
112
+ .sort((a, b) => a.resources.pressure.overall - b.resources.pressure.overall)[0];
113
+ if (!other)
114
+ return undefined;
115
+ const r = other.resources;
116
+ const free = r.memory.availablePercent === undefined ? "" : `${r.memory.availablePercent}% memory available, `;
117
+ return `${other.name} has room (${free}load ${r.cpu.load1} on ${r.cpu.cores} cores). To run it there instead, push your branch and have an agent dispatch it: ` +
118
+ `phren dispatch ${other.name} <project> --worktree --prompt "Check out <branch>, run ${label.replace(/"/g, "'")}, report the exit code and failures", then phren dispatch wait <id>.`;
119
+ }
@@ -0,0 +1,70 @@
1
+ import { type PaneRef, type ProcessRow } from "../bridge/resources.js";
2
+ /**
3
+ * `phren reap`: what agents left running that nobody stops: dev servers,
4
+ * build daemons, test watchers, headless browsers whose parent is gone, shell
5
+ * wait loops and Postgres test database clones. Read-only: every row carries
6
+ * the exact command that would stop it, and the owner runs the ones they want.
7
+ */
8
+ export type ReapKind = "dev server" | "build daemon" | "test watcher" | "headless browser" | "wait loop";
9
+ /** `ancestors` is the pid chain above the row, nearest first; `pane` the terminal pane whose shell or foreground process is the row or one of them. */
10
+ export interface ReapRow {
11
+ kind: ReapKind;
12
+ name: string;
13
+ pid: number;
14
+ startedAt?: number;
15
+ ancestors: number[];
16
+ pane?: PaneRef;
17
+ ageMs?: number;
18
+ idleMs?: number;
19
+ cpuShare?: number;
20
+ rssBytes: number;
21
+ by: string;
22
+ cwd?: string;
23
+ stop: string;
24
+ }
25
+ export interface ReapDatabase {
26
+ name: string;
27
+ template: string;
28
+ bytes?: number;
29
+ connections: number;
30
+ stop: string;
31
+ }
32
+ /** What a process is, when it is something agents start and forget. */
33
+ export declare function classify(row: ProcessRow, parentGone: boolean): {
34
+ kind: ReapKind;
35
+ name: string;
36
+ } | undefined;
37
+ export interface Sample {
38
+ cpuSeconds: number;
39
+ since: number;
40
+ }
41
+ /**
42
+ * Report rows from a process table. `cpu` is each pid's cumulative CPU
43
+ * seconds; `samples` is what an earlier report saw, so a process whose CPU
44
+ * time has not moved since is idle at least that long. Returns the samples to
45
+ * keep for next time. Without `all`, only work an agent started (or whose
46
+ * parent is gone) is listed.
47
+ */
48
+ export declare function reapRows(rows: ProcessRow[], options: {
49
+ now: number;
50
+ cpu: Map<number, number>;
51
+ samples: Record<string, Sample>;
52
+ all?: boolean;
53
+ env?: (pid: number) => string | undefined;
54
+ cwd?: (pid: number) => string | undefined;
55
+ self?: number;
56
+ /** Pane pids (bridge/resources.ts `paneOwners()`), to name the pane each row runs in. */
57
+ owners?: Map<number, PaneRef>;
58
+ }): {
59
+ rows: ReapRow[];
60
+ samples: Record<string, Sample>;
61
+ };
62
+ /** `ps -o pid=,time=` cumulative CPU: `[[dd-]hh:]mm:ss[.cc]`. */
63
+ export declare function parseCpuTimes(output: string): Map<number, number>;
64
+ /** Databases cloned from a test template (`hub_test_797` beside `hub_test`): name, template, size and open connections. */
65
+ export declare function testClones(rows: Array<{
66
+ name: string;
67
+ bytes?: number;
68
+ connections: number;
69
+ }>): ReapDatabase[];
70
+ export declare function runReap(args: string[]): Promise<number>;