@phren/cli 0.3.78 → 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 (39) hide show
  1. package/dist/bridge/dispatch.js +17 -3
  2. package/dist/bridge/files.d.ts +1 -1
  3. package/dist/bridge/housekeeping/command.d.ts +5 -0
  4. package/dist/bridge/housekeeping/command.js +106 -0
  5. package/dist/bridge/housekeeping/housekeeper.d.ts +123 -0
  6. package/dist/bridge/housekeeping/housekeeper.js +459 -0
  7. package/dist/bridge/housekeeping/inventory.d.ts +145 -0
  8. package/dist/bridge/housekeeping/inventory.js +276 -0
  9. package/dist/bridge/housekeeping/report.d.ts +672 -0
  10. package/dist/bridge/housekeeping/report.js +168 -0
  11. package/dist/bridge/housekeeping/safety.d.ts +177 -0
  12. package/dist/bridge/housekeeping/safety.js +466 -0
  13. package/dist/bridge/owner-proof.d.ts +41 -0
  14. package/dist/bridge/owner-proof.js +119 -0
  15. package/dist/bridge/push.js +3 -1
  16. package/dist/bridge/resources.d.ts +8 -0
  17. package/dist/bridge/resources.js +18 -5
  18. package/dist/bridge/server-pane-routes.d.ts +6 -0
  19. package/dist/bridge/server-pane-routes.js +1 -1
  20. package/dist/bridge/server-routes.d.ts +6 -0
  21. package/dist/bridge/server-routes.js +53 -4
  22. package/dist/bridge/server.js +44 -8
  23. package/dist/bridge-hook.mjs +3093 -1219
  24. package/dist/cli-registry.js +18 -1
  25. package/dist/fanout/command.js +42 -15
  26. package/dist/heavy/budget-status.d.ts +26 -0
  27. package/dist/heavy/budget-status.js +26 -0
  28. package/dist/heavy/budget.d.ts +39 -0
  29. package/dist/heavy/budget.js +57 -0
  30. package/dist/heavy/command.d.ts +15 -0
  31. package/dist/heavy/command.js +119 -0
  32. package/dist/heavy/reap.d.ts +70 -0
  33. package/dist/heavy/reap.js +211 -0
  34. package/dist/heavy/slots.d.ts +58 -0
  35. package/dist/heavy/slots.js +142 -0
  36. package/dist/modules/registry.js +5 -4
  37. package/package.json +1 -1
  38. package/starter/global/skills/conductor/SKILL.md +10 -0
  39. package/starter/global/skills/fanout/SKILL.md +30 -0
@@ -0,0 +1,276 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { lstat, readdir, realpath } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import path from "node:path";
6
+ import { promisify } from "node:util";
7
+ import { cacheRules, deletionDecision, housekeepingGit, inspectCheckout, paneCloseBlock, parseWorktreeList, plainReason, tmpRoots, } from "./safety.js";
8
+ /**
9
+ * The inventory: everything on this computer the owner may want to see and
10
+ * handle, not just what crossed a threshold. Every worktree, the largest space
11
+ * users, and every agent pane, each with an action that says whether it is
12
+ * allowed now and, if not, why in a plain sentence. Scanning sizes is slow, so
13
+ * the Hook runs it in the background (hourly and on request) and serves the
14
+ * last scan; every action re-checks against the disk when approved.
15
+ */
16
+ const exec = promisify(execFile);
17
+ export const LABELS = {
18
+ "remove-worktree": "Remove worktree", "delete-path": "Delete", "close-pane": "Close pane", "end-job": "End job",
19
+ "shutdown-simulator": "Shut down simulator", "delete-simulator": "Delete simulator", "prune-docker-builder": "Prune build cache",
20
+ };
21
+ /** An action id: the row's kind, target and state, so a changed row gets a new id. */
22
+ export function actionId(kind, target, state) {
23
+ return createHash("sha256").update(JSON.stringify([kind, target, state])).digest("hex").slice(0, 16);
24
+ }
25
+ function action(kind, target, state, block, label = LABELS[kind], confirm) {
26
+ return { id: actionId(kind, target, state), kind, label, allowed: !block, ...(block ? { reason: block } : confirm ? { confirm } : {}) };
27
+ }
28
+ /** What the owner is told before a destructive approve. */
29
+ const CONFIRM = {
30
+ "derived-data": "Removes it. Xcode rebuilds it on the next build.",
31
+ "xctest-devices": "Removes the test clone. The next UI test run makes a new one.",
32
+ "device-support": "Removes it. Xcode copies it again when that device connects.",
33
+ cache: "Removes it. It is rebuilt when needed.",
34
+ tmp: "Removes the folder and everything in it.",
35
+ node_modules: "Removes it. pnpm install brings it back.",
36
+ };
37
+ export async function duBytes(target) {
38
+ try {
39
+ // -x: one file system; nice: a background scan never competes with builds.
40
+ const { stdout } = await exec("nice", ["-n", "15", "du", "-sk", "-x", target], { timeout: 120_000, maxBuffer: 1024 * 1024 });
41
+ const kb = Number(stdout.trim().split(/\s+/)[0]);
42
+ return Number.isFinite(kb) ? kb * 1024 : undefined;
43
+ }
44
+ catch (error) {
45
+ // du exits 1 when some entries were unreadable; its total still counts the rest.
46
+ const stdout = error.stdout;
47
+ const kb = Number(String(stdout ?? "").trim().split(/\s+/)[0]);
48
+ return stdout && Number.isFinite(kb) ? kb * 1024 : undefined;
49
+ }
50
+ }
51
+ async function children(dir) {
52
+ return (await readdir(dir).catch(() => [])).filter(name => name !== ".DS_Store").map(name => path.join(dir, name));
53
+ }
54
+ const isDir = async (p) => (await lstat(p).catch(() => undefined))?.isDirectory() ?? false;
55
+ const has = async (p) => Boolean(await lstat(p).catch(() => undefined));
56
+ /** Checkouts under the roots (their direct children, plus each repo's linked worktrees and .claude/worktrees). */
57
+ export async function findCheckouts(roots, limit = 400) {
58
+ const found = new Set();
59
+ const add = async (dir) => { if (found.size < limit)
60
+ found.add(await realpath(dir).catch(() => dir)); };
61
+ for (const root of roots) {
62
+ const scanned = path.basename(root) === ".cache" ? (await children(root)).filter(p => path.basename(p).startsWith("fanout-")) : [root];
63
+ for (const base of scanned)
64
+ for (const dir of await children(base)) {
65
+ if (!await isDir(dir) || !await has(path.join(dir, ".git")))
66
+ continue;
67
+ await add(dir);
68
+ for (const inner of await children(path.join(dir, ".claude", "worktrees")))
69
+ if (await has(path.join(inner, ".git")))
70
+ await add(inner);
71
+ if (!await isDir(path.join(dir, ".git")))
72
+ continue; // a linked worktree: its main lists the rest
73
+ const listed = await housekeepingGit(dir, "worktree", "list", "--porcelain").catch(() => "");
74
+ for (const entry of parseWorktreeList(listed))
75
+ if (!entry.bare && !entry.prunable && await isDir(entry.path))
76
+ await add(entry.path);
77
+ }
78
+ }
79
+ return [...found].sort();
80
+ }
81
+ export function defaultRoots(home = homedir(), platform = process.platform) {
82
+ return [path.join(home, "Projects"), path.join(home, "Sites"), path.join(home, ".cache"), ...tmpRoots(platform)];
83
+ }
84
+ const inside = (child, parent) => child === parent || child.startsWith(parent + path.sep);
85
+ export async function scanInventory(options) {
86
+ const started = Date.now();
87
+ const now = options.now ?? started;
88
+ const platform = options.platform ?? process.platform;
89
+ const home = options.home ?? homedir();
90
+ const errors = [];
91
+ const sizeOf = options.sizeOf ?? duBytes;
92
+ // One process and pane listing for the whole scan.
93
+ const [processes, panes] = await Promise.all([options.processes(), options.panes()]);
94
+ const sources = { processes: async () => processes, panes: async () => panes };
95
+ const sessionRows = await (options.sessions?.() ?? Promise.resolve([])).catch(error => { errors.push({ check: "sessions", message: String(error) }); return []; });
96
+ const context = { ...sources, ...(options.rules ? { rules: options.rules } : {}), tmpRoots: options.tmpRoots ?? tmpRoots(platform), now,
97
+ protected: undefined };
98
+ // Worktrees.
99
+ const worktrees = [];
100
+ const checkouts = await findCheckouts(options.roots ?? defaultRoots(home, platform)).catch(error => { errors.push({ check: "worktrees", message: String(error) }); return []; });
101
+ for (const dir of checkouts) {
102
+ const linked = !await isDir(path.join(dir, ".git"));
103
+ const { facts, blockers } = await inspectCheckout(dir, linked ? "worktree" : "repository", sources);
104
+ const inPanes = sessionRows.filter(row => row.cwd && inside(row.cwd, dir));
105
+ const procs = processes.filter(proc => inside(proc.cwd, dir) && proc.pid !== process.pid).slice(0, 10);
106
+ const main = facts?.main ?? !linked;
107
+ const state = { facts, blockers: blockers.map(b => b.code) };
108
+ const block = main ? "It is the repository's main checkout." : blockers.length ? plainReason(blockers) : undefined;
109
+ worktrees.push({
110
+ id: actionId("remove-worktree", dir, "row"), repo: facts?.repo ?? dir, ...(facts?.branch ? { branch: facts.branch } : {}), path: dir, main,
111
+ ...(facts?.lastCommitAt ? { lastCommitAt: facts.lastCommitAt } : {}),
112
+ dirty: facts?.dirty ?? 0, untracked: facts?.untracked ?? 0, unpushed: facts?.unpushed ?? 0, stashes: facts?.stashes ?? 0,
113
+ ...(facts?.inProgress.length ? { inProgress: facts.inProgress[0] } : {}), ...(facts?.locked ? { locked: true } : {}),
114
+ sessions: inPanes.map(row => ({ pane: row.pane, ...(row.agent ? { agent: row.agent } : {}), ...(row.title ? { title: row.title } : {}) })),
115
+ processes: procs.map(proc => ({ pid: proc.pid, ...(proc.command ? { command: proc.command } : {}) })),
116
+ action: action("remove-worktree", dir, state, block, LABELS["remove-worktree"], `Removes the folder.${facts?.branch ? ` The branch ${facts.branch} stays, and its commits are on a remote.` : " Its commits are on a remote."}`),
117
+ });
118
+ }
119
+ // Sizes last: the slow part, and a checkout nested in another is counted in both.
120
+ for (const row of worktrees) {
121
+ const size = await sizeOf(row.path);
122
+ if (size !== undefined)
123
+ row.sizeBytes = size;
124
+ }
125
+ // Space.
126
+ const space = [];
127
+ const pathRow = async (kind, area, target, title, withAction = true) => {
128
+ const info = await lstat(target).catch(() => undefined);
129
+ if (!info || info.isSymbolicLink())
130
+ return;
131
+ const size = await sizeOf(target);
132
+ if (size === undefined || size === 0)
133
+ return;
134
+ const decision = withAction ? await deletionDecision(target, context) : undefined;
135
+ const user = decision && !decision.allowed ? decision.blockers?.find(b => b.code === "live-process" || b.code === "bound-pane") : undefined;
136
+ space.push({ id: actionId("delete-path", target, "row"), area, kind, title, path: target, sizeBytes: size, lastUsedAt: new Date(info.mtimeMs).toISOString(),
137
+ ...(user ? { inUse: user.detail.replace(/ runs in .*$/, "") } : {}), ...(!withAction ? { note: "Phren clears this cache by age on its own." } : {}),
138
+ ...(decision ? { action: action("delete-path", target, [size, info.mtimeMs], decision.allowed ? undefined : decision.reason, kind === "node_modules" ? "Delete node_modules" : kind === "tmp" ? "Delete folder" : "Clear cache", CONFIRM[kind]) } : {}) });
139
+ };
140
+ const KINDS = { "derived-data": "derived-data", "xctest-devices": "xctest-devices", "ios-device-support": "device-support" };
141
+ for (const rule of options.rules ?? cacheRules(home, platform)) {
142
+ try {
143
+ if (["npm-cacache", "swiftpm-cache"].includes(rule.id)) {
144
+ await pathRow("cache", "disk", rule.root, `${rule.id === "npm-cacache" ? "npm" : "SwiftPM"} cache`, false);
145
+ continue;
146
+ }
147
+ for (const entry of await children(rule.root))
148
+ await pathRow(KINDS[rule.id] ?? "cache", rule.id === "xctest-devices" ? "simulators" : "disk", entry, `${path.basename(rule.root)}/${path.basename(entry)}`);
149
+ }
150
+ catch (error) {
151
+ errors.push({ check: `space:${rule.id}`, message: String(error) });
152
+ }
153
+ }
154
+ for (const root of options.tmpRoots ?? tmpRoots(platform)) {
155
+ for (const entry of await children(root)) {
156
+ if (checkouts.includes(await realpath(entry).catch(() => entry)))
157
+ continue; // listed as a worktree
158
+ const info = await lstat(entry).catch(() => undefined);
159
+ if (!info?.isDirectory() || info.uid !== process.getuid?.())
160
+ continue;
161
+ await pathRow("tmp", "disk", entry, entry);
162
+ }
163
+ }
164
+ for (const dir of checkouts) {
165
+ const modules = path.join(dir, "node_modules");
166
+ if (await isDir(modules))
167
+ await pathRow("node_modules", "disk", modules, `${path.basename(dir)}/node_modules`);
168
+ }
169
+ if (platform === "darwin" && options.simulators) {
170
+ try {
171
+ const building = await (options.xcodebuildRunning?.() ?? Promise.resolve(false));
172
+ for (const sim of await options.simulators()) {
173
+ const size = await sizeOf(sim.dataPath);
174
+ if (!size)
175
+ continue;
176
+ const booted = sim.state === "Booted";
177
+ const kind = booted ? "shutdown-simulator" : "delete-simulator";
178
+ const block = building ? "An Xcode build or test is running." : undefined;
179
+ space.push({ id: actionId(kind, sim.udid, "row"), area: "simulators", kind: "simulator", title: `${sim.name} (${sim.state.toLowerCase()})`, udid: sim.udid,
180
+ sizeBytes: size, action: action(kind, sim.udid, [sim.state, building], block, LABELS[kind], booted ? "Shuts the simulator down. Its data stays." : "Deletes the simulator and its data.") });
181
+ }
182
+ }
183
+ catch (error) {
184
+ errors.push({ check: "space:simulators", message: String(error) });
185
+ }
186
+ }
187
+ if (options.docker) {
188
+ try {
189
+ for (const row of await options.docker()) {
190
+ if (!row.sizeBytes)
191
+ continue;
192
+ const build = /build cache/i.test(row.type);
193
+ const note = /volume/i.test(row.type) ? "Phren never deletes docker volumes: they hold data."
194
+ : /image/i.test(row.type) ? "Phren doesn't remove docker images." : "Phren doesn't remove docker containers.";
195
+ space.push({ id: actionId("prune-docker-builder", row.type, "row"), area: "docker", kind: "docker", title: `Docker ${row.type.toLowerCase()}`, sizeBytes: row.sizeBytes,
196
+ ...(build ? { action: action("prune-docker-builder", "builder", [row.sizeBytes], row.reclaimableBytes ? undefined : "Nothing in it can be pruned.", LABELS["prune-docker-builder"], "Prunes build cache older than a week. Images, containers and volumes stay.") } : { note }) });
197
+ }
198
+ }
199
+ catch (error) {
200
+ errors.push({ check: "space:docker", message: String(error) });
201
+ }
202
+ }
203
+ space.sort((a, b) => b.sizeBytes - a.sizeBytes);
204
+ space.splice(options.spaceLimit ?? 500);
205
+ // Sessions.
206
+ const dispatches = await (options.dispatches?.() ?? Promise.resolve([])).catch(() => undefined);
207
+ const sessions = sessionRows.map(row => {
208
+ const block = dispatches ? paneCloseBlock({ server: row.pane.target.server, pane: row.pane.target.pane, status: row.status, role: row.role }, dispatches)
209
+ : "Phren couldn't check its dispatches, so it stays open.";
210
+ const target = `${row.pane.target.server}/${row.pane.target.pane}`;
211
+ return { id: actionId("close-pane", target, "row"), pane: row.pane, ...(row.agent ? { agent: row.agent } : {}), ...(row.title ? { title: row.title } : {}),
212
+ ...(row.project ? { project: row.project } : {}), ...(row.status ? { status: row.status } : {}), ...(row.idleSeconds !== undefined ? { idleSeconds: row.idleSeconds } : {}),
213
+ ...(row.cwd ? { cwd: row.cwd } : {}), ...(row.dispatch ? { dispatch: row.dispatch } : {}), ...(row.role ? { role: row.role } : {}),
214
+ ...receiptOf(row, dispatches),
215
+ action: action("close-pane", target, [row.status, block], block, LABELS["close-pane"], "Closes the pane and stops its agent.") };
216
+ }).sort((a, b) => (b.idleSeconds ?? 0) - (a.idleSeconds ?? 0));
217
+ return { collectedAt: new Date(now).toISOString(), durationMs: Date.now() - started, worktrees, space, sessions, ...(errors.length ? { errors } : {}) };
218
+ }
219
+ /** The pane's open dispatch, newest first, as the phone shows it. */
220
+ function receiptOf(row, dispatches) {
221
+ const receipt = [...dispatches ?? []].reverse().find(d => d.id && !d.closedAt && d.server === row.pane.target.server && d.pane === row.pane.target.pane);
222
+ return receipt?.id ? { receipt: { id: receipt.id, returnRead: receipt.returned?.read ?? false } } : {};
223
+ }
224
+ /** Simulators with their data folders (macOS). */
225
+ export async function listSimulators(home = homedir()) {
226
+ const { stdout } = await exec("/usr/bin/xcrun", ["simctl", "list", "devices", "-j"], { timeout: 20_000, maxBuffer: 8 * 1024 * 1024 });
227
+ const devices = JSON.parse(stdout).devices ?? {};
228
+ const out = [];
229
+ for (const list of Object.values(devices))
230
+ for (const device of list) {
231
+ if (!device.udid || !/^[A-F0-9-]{36}$/i.test(device.udid))
232
+ continue;
233
+ const dataPath = path.join(home, "Library/Developer/CoreSimulator/Devices", device.udid);
234
+ out.push({ udid: device.udid.toUpperCase(), name: String(device.name ?? "Simulator").slice(0, 120), state: String(device.state ?? "Unknown"), dataPath });
235
+ }
236
+ return out;
237
+ }
238
+ const UNITS = { B: 1, KB: 1e3, MB: 1e6, GB: 1e9, TB: 1e12, KIB: 1024, MIB: 1024 ** 2, GIB: 1024 ** 3 };
239
+ export function parseDockerSize(text) {
240
+ const match = /^([\d.]+)\s*([KMGT]?i?B)/i.exec(text.trim());
241
+ return match ? Math.round(Number(match[1]) * (UNITS[match[2].toUpperCase()] ?? 1)) : 0;
242
+ }
243
+ /** `docker system df`, when docker answers. */
244
+ export async function dockerUsage() {
245
+ const { stdout } = await exec("docker", ["system", "df", "--format", "{{json .}}"], { timeout: 20_000 }).catch(() => ({ stdout: "" }));
246
+ return stdout.split("\n").filter(Boolean).map(line => {
247
+ const row = JSON.parse(line);
248
+ return { type: String(row.Type ?? "Unknown"), sizeBytes: parseDockerSize(String(row.Size ?? "0B")), reclaimableBytes: parseDockerSize(String(row.Reclaimable ?? "0B")) };
249
+ });
250
+ }
251
+ export async function xcodebuildRunning() {
252
+ return exec("pgrep", ["-x", "xcodebuild"], { timeout: 5_000 }).then(() => true, () => false);
253
+ }
254
+ /** Agent panes from one server's workspace overview (the Hook's `/v1/workspaces` shape). */
255
+ export function sessionRowsFromOverview(overview, now = Date.now()) {
256
+ const rows = [];
257
+ const list = (value) => Array.isArray(value) ? value.filter((v) => !!v && typeof v === "object") : [];
258
+ const text = (value) => typeof value === "string" && value ? value : undefined;
259
+ for (const group of list(overview.groups))
260
+ for (const tab of list(group.children)) {
261
+ const target = tab.target;
262
+ if (typeof tab.agent !== "string" || !target || typeof target.server !== "string" || typeof target.pane !== "string")
263
+ continue;
264
+ const changedAt = typeof tab.lastChangedAt === "string" ? Date.parse(tab.lastChangedAt) : NaN;
265
+ const label = text(tab.label) && !/^\d+$/.test(String(tab.label)) ? text(tab.label) : text(group.label);
266
+ rows.push({
267
+ pane: { target: { server: target.server, ...(target.workspace ? { workspace: target.workspace } : {}), ...(target.tab ? { tab: target.tab } : {}), pane: target.pane },
268
+ ...(label ? { label } : {}) },
269
+ agent: tab.agent, ...(text(tab.title) ? { title: text(tab.title) } : {}), ...(text(tab.agentStatus) ? { status: text(tab.agentStatus) } : {}),
270
+ ...(text(tab.role) ? { role: text(tab.role) } : {}), ...(text(tab.cwd) ? { cwd: text(tab.cwd) } : {}),
271
+ ...(Number.isFinite(changedAt) ? { idleSeconds: Math.max(0, Math.floor((now - changedAt) / 1000)) } : {}),
272
+ ...(text(tab.dispatch) ? { dispatch: text(tab.dispatch) } : {}),
273
+ });
274
+ }
275
+ return rows;
276
+ }