@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
@@ -0,0 +1,466 @@
1
+ import { execFile } from "node:child_process";
2
+ import { lstat, readdir, readlink, realpath, rm, stat } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import path from "node:path";
5
+ import { promisify } from "node:util";
6
+ import { git as runGit } from "../projects.js";
7
+ /**
8
+ * The housekeeping safety rules. Every housekeeping check and action goes
9
+ * through this module; nothing else in `bridge/housekeeping/` may run git,
10
+ * delete a path or remove a worktree. The rules come from the owner, after
11
+ * the 2026-11-08 incident in which a cleanup worker deleted worktrees with
12
+ * unpushed commits and ran `git reset --hard` across about 24 repositories:
13
+ *
14
+ * 1. Never delete a worktree or repository that has uncommitted changes,
15
+ * untracked files, commits on no remote, a stash, an operation in
16
+ * progress, a dirty or unpushed submodule, a live process inside it or a
17
+ * pane bound to it. Inspection that fails counts as a blocker.
18
+ * 2. Never run git reset, checkout, clean, restore, switch, push, branch or a
19
+ * stash change, and never pass --force. Git runs only through
20
+ * `housekeepingGit`, which admits a fixed set of read-only commands plus
21
+ * `worktree remove` (without force) and `worktree prune`.
22
+ * 3. Suggest by default. Only a path inside an allow-listed cache root,
23
+ * old enough and not in use, may be acted on without the owner.
24
+ */
25
+ const exec = promisify(execFile);
26
+ // ---------------------------------------------------------------------------
27
+ // Rule 2: the git gate.
28
+ export class SafetyViolation extends Error {
29
+ code;
30
+ constructor(code, message) {
31
+ super(message);
32
+ this.code = code;
33
+ this.name = "SafetyViolation";
34
+ }
35
+ }
36
+ /** Subcommands that only read. */
37
+ const READ_ONLY = new Set(["status", "rev-list", "rev-parse", "for-each-ref", "symbolic-ref", "log", "show-ref", "ls-files"]);
38
+ /** Subcommands that discard or rewrite work; named so the refusal says why. */
39
+ const BANNED = new Set(["reset", "checkout", "clean", "restore", "switch", "push", "branch", "rebase", "merge", "pull", "fetch",
40
+ "commit", "am", "cherry-pick", "revert", "rm", "mv", "gc", "prune", "reflog", "update-ref", "filter-branch", "replace", "tag", "notes", "config"]);
41
+ /** Throws unless `args` is a git invocation housekeeping may run. Global
42
+ * options before the subcommand (-c, -C, --git-dir, --work-tree) are refused
43
+ * outright: they could re-target or reconfigure the command. */
44
+ export function assertHousekeepingGit(args) {
45
+ const [sub, ...rest] = args;
46
+ if (!sub || sub.startsWith("-"))
47
+ throw new SafetyViolation("git-global-option", `Housekeeping never passes git global options (${sub ?? "none"}).`);
48
+ for (const arg of rest) {
49
+ if (arg === "--")
50
+ break;
51
+ if (arg === "--force" || arg === "-f" || /^-[a-zA-Z]*f[a-zA-Z]*$/.test(arg) && sub === "worktree" || arg.startsWith("--force"))
52
+ throw new SafetyViolation("git-force", `Housekeeping never forces a git command (git ${sub} ${arg}).`);
53
+ }
54
+ if (BANNED.has(sub))
55
+ throw new SafetyViolation("git-banned", `Housekeeping never runs git ${sub}.`);
56
+ if (READ_ONLY.has(sub))
57
+ return;
58
+ const verb = rest[0];
59
+ if (sub === "stash" && verb === "list")
60
+ return;
61
+ if (sub === "submodule" && verb === "status")
62
+ return;
63
+ if (sub === "worktree" && (verb === "list" || verb === "remove"))
64
+ return;
65
+ if (sub === "worktree" && verb === "prune" && rest.every(arg => ["prune", "--dry-run", "-n", "--verbose", "-v"].includes(arg)))
66
+ return;
67
+ throw new SafetyViolation("git-not-allowed", `Housekeeping may not run git ${[sub, verb].filter(Boolean).join(" ")}.`);
68
+ }
69
+ /** The only git runner housekeeping uses. */
70
+ export async function housekeepingGit(cwd, ...args) {
71
+ assertHousekeepingGit(args);
72
+ return runGit(cwd, ...args);
73
+ }
74
+ const PLAIN = {
75
+ "not-a-checkout": "It isn't a checkout Phren can inspect.",
76
+ symlink: "It is a symbolic link; Phren never follows one.",
77
+ "inspection-failed": "Phren couldn't check it, so it stays.",
78
+ "main-checkout": "It is the repository's main checkout.",
79
+ "linked-worktrees": "Other worktrees depend on it.",
80
+ locked: "The worktree is locked.",
81
+ "uncommitted-changes": "It has uncommitted changes.",
82
+ "untracked-files": "It has untracked files.",
83
+ "unpushed-commits": "It has commits that aren't on any remote.",
84
+ stash: "The repository has stashed changes.",
85
+ "in-progress-operation": "A rebase, merge or similar is in progress.",
86
+ "dirty-submodule": "A submodule has uncommitted changes.",
87
+ "unpushed-submodule": "A submodule has commits that aren't on any remote.",
88
+ "live-process": "A process is using it now.",
89
+ "bound-pane": "An agent pane is working in it.",
90
+ "in-use": "Something is using it now.",
91
+ };
92
+ /** One plain sentence for the first blocker, for the phone. */
93
+ export function plainReason(blockers) {
94
+ return blockers.length ? PLAIN[blockers[0].code] : "";
95
+ }
96
+ const IN_PROGRESS = ["rebase-merge", "rebase-apply", "MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "BISECT_LOG"];
97
+ const inside = (child, parent) => child === parent || child.startsWith(parent.endsWith(path.sep) ? parent : parent + path.sep);
98
+ const exists = (p) => lstat(p).then(() => true, () => false);
99
+ async function canonical(p) { return realpath(p).catch(() => path.resolve(p)); }
100
+ /** Processes and panes whose folder is `dir` or inside it. */
101
+ export async function inUseBlockers(dir, sources) {
102
+ const blockers = [];
103
+ const [processes, panes] = await Promise.all([sources.processes(), sources.panes()]);
104
+ for (const proc of processes) {
105
+ if (proc.pid === process.pid)
106
+ continue;
107
+ if (inside(await canonical(proc.cwd), dir))
108
+ blockers.push({ code: "live-process", detail: `pid ${proc.pid}${proc.command ? ` (${proc.command})` : ""} runs in ${proc.cwd}` });
109
+ }
110
+ for (const pane of panes) {
111
+ if (inside(await canonical(pane.cwd), dir))
112
+ blockers.push({ code: "bound-pane", detail: `pane ${pane.pane}${pane.title ? ` (${pane.title})` : ""} runs in ${pane.cwd}` });
113
+ }
114
+ return blockers;
115
+ }
116
+ async function submoduleBlockers(dir) {
117
+ const blockers = [];
118
+ const output = await housekeepingGit(dir, "submodule", "status", "--recursive");
119
+ for (const line of output.split("\n")) {
120
+ if (!line.trim() || line[0] === "-")
121
+ continue; // uninitialized: nothing checked out to lose
122
+ const rest = /^[ +U]/.test(line) ? line.slice(1) : line;
123
+ const space = rest.indexOf(" ");
124
+ if (space < 0)
125
+ continue;
126
+ let sub = rest.slice(space + 1);
127
+ const describe = sub.lastIndexOf(" (");
128
+ if (describe > 0 && sub.endsWith(")"))
129
+ sub = sub.slice(0, describe);
130
+ const checkout = path.join(dir, sub);
131
+ if (!(await stat(checkout).catch(() => undefined))?.isDirectory())
132
+ continue;
133
+ if ((await housekeepingGit(checkout, "status", "--porcelain=v1", "--untracked-files=normal")).trim())
134
+ blockers.push({ code: "dirty-submodule", detail: `submodule ${sub} has uncommitted changes` });
135
+ const unpushed = Number((await housekeepingGit(checkout, "rev-list", "--count", "HEAD", "--not", "--remotes")).trim()) || 0;
136
+ if (unpushed > 0)
137
+ blockers.push({ code: "unpushed-submodule", detail: `submodule ${sub} has ${unpushed} commit(s) on no remote` });
138
+ }
139
+ return blockers;
140
+ }
141
+ /**
142
+ * What `dir` holds and every reason it must not be deleted (no blockers means
143
+ * nothing would be lost). `worktree`: a linked worktree, removed with `git
144
+ * worktree remove`; only its HEAD's commits matter, since its branch stays.
145
+ * `repository`: the whole repository folder; every local branch counts, and
146
+ * linked worktrees block. Stashes block either way: the owner's rule names
147
+ * them without exception.
148
+ */
149
+ export async function inspectCheckout(dir, target, sources) {
150
+ const info = await lstat(dir).catch(() => undefined);
151
+ if (!info)
152
+ return { blockers: [{ code: "not-a-checkout", detail: `${dir} does not exist` }] };
153
+ if (info.isSymbolicLink())
154
+ return { blockers: [{ code: "symlink", detail: `${dir} is a symbolic link; housekeeping never follows one` }] };
155
+ if (!info.isDirectory())
156
+ return { blockers: [{ code: "not-a-checkout", detail: `${dir} is not a folder` }] };
157
+ const abs = await canonical(dir);
158
+ const blockers = [];
159
+ let facts;
160
+ try {
161
+ const top = await canonical((await housekeepingGit(abs, "rev-parse", "--show-toplevel")).trim());
162
+ if (top !== abs)
163
+ return { blockers: [{ code: "not-a-checkout", detail: `${dir} is inside ${top}, not a checkout root` }] };
164
+ const gitDir = await canonical(path.resolve(abs, (await housekeepingGit(abs, "rev-parse", "--git-dir")).trim()));
165
+ const commonDir = await canonical(path.resolve(abs, (await housekeepingGit(abs, "rev-parse", "--git-common-dir")).trim()));
166
+ const isMain = gitDir === commonDir;
167
+ const worktrees = parseWorktreeList(await housekeepingGit(abs, "worktree", "list", "--porcelain"));
168
+ if (target === "worktree" && isMain)
169
+ blockers.push({ code: "main-checkout", detail: "this is the repository's main checkout, not a linked worktree" });
170
+ if (target === "repository") {
171
+ const linked = worktrees.filter(w => w.path !== abs && !w.prunable);
172
+ if (linked.length)
173
+ blockers.push({ code: "linked-worktrees", detail: `${linked.length} linked worktree(s) depend on it: ${linked.map(w => w.path).slice(0, 5).join(", ")}` });
174
+ }
175
+ const self = worktrees.find(w => w.path === abs);
176
+ if (self?.locked !== undefined)
177
+ blockers.push({ code: "locked", detail: `worktree is locked${self.locked ? `: ${self.locked}` : ""}` });
178
+ const status = (await housekeepingGit(abs, "status", "--porcelain=v1", "-z", "--untracked-files=normal", "--ignore-submodules=none")).split("\0").filter(Boolean);
179
+ let tracked = 0, untracked = 0;
180
+ for (let i = 0; i < status.length; i++) {
181
+ const code = status[i].slice(0, 2);
182
+ if (code === "??")
183
+ untracked++;
184
+ else
185
+ tracked++;
186
+ if (/[RC]/.test(code))
187
+ i++;
188
+ }
189
+ if (tracked)
190
+ blockers.push({ code: "uncommitted-changes", detail: `${tracked} changed tracked path(s)` });
191
+ if (untracked)
192
+ blockers.push({ code: "untracked-files", detail: `${untracked} untracked path(s) not ignored` });
193
+ const hasHead = await housekeepingGit(abs, "rev-parse", "--verify", "--quiet", "HEAD").then(() => true, () => false);
194
+ let unpushed = 0, lastCommitAt;
195
+ if (hasHead) {
196
+ const refs = target === "repository" ? ["HEAD", "--branches"] : ["HEAD"];
197
+ unpushed = Number((await housekeepingGit(abs, "rev-list", "--count", ...refs, "--not", "--remotes")).trim()) || 0;
198
+ if (unpushed > 0)
199
+ blockers.push({ code: "unpushed-commits", detail: `${unpushed} commit(s) on no remote branch` });
200
+ const stamp = (await housekeepingGit(abs, "log", "-1", "--format=%cI", "HEAD")).trim();
201
+ if (stamp)
202
+ lastCommitAt = new Date(stamp).toISOString();
203
+ }
204
+ const stashes = (await housekeepingGit(abs, "stash", "list")).split("\n").filter(Boolean);
205
+ if (stashes.length)
206
+ blockers.push({ code: "stash", detail: `${stashes.length} stash entr${stashes.length === 1 ? "y" : "ies"}` });
207
+ const inProgress = [];
208
+ for (const marker of IN_PROGRESS) {
209
+ if (await exists(path.join(gitDir, marker))) {
210
+ inProgress.push(marker);
211
+ blockers.push({ code: "in-progress-operation", detail: `${marker} is present: an operation is in progress` });
212
+ }
213
+ }
214
+ blockers.push(...await submoduleBlockers(abs));
215
+ const mainPath = worktrees[0] && !worktrees[0].bare ? worktrees[0].path : undefined;
216
+ facts = { main: isMain, ...(self?.branch ? { branch: self.branch } : {}), ...(mainPath ? { repo: mainPath } : {}),
217
+ dirty: tracked, untracked, unpushed, stashes: stashes.length, inProgress, locked: self?.locked !== undefined, ...(lastCommitAt ? { lastCommitAt } : {}) };
218
+ }
219
+ catch (error) {
220
+ // Fail closed: what could not be inspected is kept.
221
+ blockers.push({ code: "inspection-failed", detail: error instanceof Error ? error.message.slice(0, 300) : String(error) });
222
+ }
223
+ try {
224
+ blockers.push(...await inUseBlockers(abs, sources));
225
+ }
226
+ catch (error) {
227
+ blockers.push({ code: "inspection-failed", detail: `could not list processes or panes: ${error instanceof Error ? error.message : error}` });
228
+ }
229
+ return { ...(facts ? { facts } : {}), blockers };
230
+ }
231
+ /** Every reason `dir` must not be deleted; see `inspectCheckout`. */
232
+ export async function checkoutBlockers(dir, target, sources) {
233
+ return (await inspectCheckout(dir, target, sources)).blockers;
234
+ }
235
+ export function parseWorktreeList(porcelain) {
236
+ const out = [];
237
+ let current;
238
+ for (const line of porcelain.split("\n")) {
239
+ if (line.startsWith("worktree ")) {
240
+ current = { path: line.slice(9) };
241
+ out.push(current);
242
+ continue;
243
+ }
244
+ if (!current)
245
+ continue;
246
+ if (line.startsWith("branch "))
247
+ current.branch = line.slice(7).replace(/^refs\/heads\//, "");
248
+ else if (line === "locked" || line.startsWith("locked "))
249
+ current.locked = line.slice(7);
250
+ else if (line === "prunable" || line.startsWith("prunable "))
251
+ current.prunable = line.slice(9) || "prunable";
252
+ else if (line === "bare")
253
+ current.bare = true;
254
+ }
255
+ return out;
256
+ }
257
+ /** Remove a linked worktree only if it has no blockers right now, re-checked
258
+ * against fresh state, and only with plain `git worktree remove`. A refusal
259
+ * from git leaves the worktree where it is; nothing retries with force. */
260
+ export async function removeWorktreeSafely(dir, sources) {
261
+ const blockers = await checkoutBlockers(dir, "worktree", sources);
262
+ if (blockers.length)
263
+ return { removed: false, blockers };
264
+ const abs = await canonical(dir);
265
+ await housekeepingGit(abs, "worktree", "remove", "--", abs);
266
+ return { removed: true, blockers: [] };
267
+ }
268
+ /** Caches the disk-janitor proved safe to remove; every other path is
269
+ * suggest-only. Platform-specific roots are listed only where they exist. */
270
+ export function cacheRules(home = homedir(), platform = process.platform) {
271
+ const rules = [
272
+ { id: "phren-ci-builds", root: path.join(home, "phren-ci-builds"), minAgeDays: 7 },
273
+ { id: "npm-cacache", root: path.join(home, ".npm", "_cacache"), minAgeDays: 30 },
274
+ ];
275
+ if (platform === "darwin")
276
+ rules.push({ id: "xctest-devices", root: path.join(home, "Library/Developer/XCTestDevices"), minAgeDays: 2 }, { id: "derived-data", root: path.join(home, "Library/Developer/Xcode/DerivedData"), minAgeDays: 14 }, { id: "ios-device-support", root: path.join(home, "Library/Developer/Xcode/iOS DeviceSupport"), minAgeDays: 90 }, { id: "swiftpm-cache", root: path.join(home, "Library/Caches/org.swift.swiftpm"), minAgeDays: 30 });
277
+ return rules;
278
+ }
279
+ /** Paths housekeeping never acts on, whatever a rule says. DeviceFS is a live
280
+ * view of booted simulators that `du` reports as ~160 GB; docker volumes hold
281
+ * data; the store and project folders hold work. */
282
+ export function protectedRoots(home = homedir()) {
283
+ return [
284
+ path.join(home, "Library/Developer/CoreDevice"),
285
+ "/var/lib/docker/volumes",
286
+ path.join(home, ".docker/volumes"),
287
+ path.join(home, ".phren"),
288
+ path.join(home, "Projects"),
289
+ path.join(home, "Sites"),
290
+ path.join(home, ".ssh"),
291
+ ];
292
+ }
293
+ /**
294
+ * Whether `target` may be removed without the owner. `auto` only for an entry
295
+ * strictly inside an allow-listed root (resolved without following a link at
296
+ * the target), past the rule's age, under no protected root, and with no
297
+ * process or pane in it. Anything else is `suggest` (the owner may approve)
298
+ * or `keep` (a safety rule holds it).
299
+ */
300
+ export async function cacheDecision(target, context) {
301
+ const info = await lstat(target).catch(() => undefined);
302
+ if (!info)
303
+ return { verdict: "keep", reason: "missing" };
304
+ if (info.isSymbolicLink())
305
+ return { verdict: "keep", reason: "symlink" };
306
+ // Resolve the parent, not the target, so a link at the target is never followed.
307
+ const abs = path.join(await canonical(path.dirname(target)), path.basename(target));
308
+ for (const root of context.protected ?? protectedRoots()) {
309
+ const real = await canonical(root);
310
+ if (inside(abs, real) || inside(real, abs))
311
+ return { verdict: "keep", reason: "protected-path" };
312
+ }
313
+ let matched;
314
+ for (const rule of context.rules ?? cacheRules()) {
315
+ const root = await canonical(rule.root);
316
+ if (abs !== root && inside(abs, root)) {
317
+ matched = rule;
318
+ break;
319
+ }
320
+ }
321
+ if (!matched)
322
+ return { verdict: "suggest", reason: "outside-allowlist" };
323
+ const ageDays = ((context.now ?? Date.now()) - info.mtimeMs) / 86_400_000;
324
+ if (ageDays < matched.minAgeDays)
325
+ return { verdict: "suggest", rule: matched.id, reason: "too-recent" };
326
+ const blockers = await inUseBlockers(abs, context).catch(error => [{ code: "inspection-failed", detail: String(error) }]);
327
+ if (blockers.length)
328
+ return { verdict: "keep", rule: matched.id, reason: "in-use", blockers };
329
+ return { verdict: "auto", rule: matched.id };
330
+ }
331
+ /** Delete an allow-listed cache entry, re-deciding against fresh state first.
332
+ * Refuses (returns the decision) unless the decision is `auto` now, or the
333
+ * owner approved it and the only thing short of `auto` is its age: an owner
334
+ * may clear a recent cache entry, never a path outside the cache roots. */
335
+ export async function removeCacheEntry(target, context, ownerApproved = false) {
336
+ const decision = await cacheDecision(target, context);
337
+ const approvedRecent = ownerApproved && decision.verdict === "suggest" && decision.reason === "too-recent";
338
+ if (decision.verdict !== "auto" && !approvedRecent)
339
+ return { removed: false, decision };
340
+ await rm(target, { recursive: true, force: false, maxRetries: 0 });
341
+ return { removed: true, decision };
342
+ }
343
+ // ---------------------------------------------------------------------------
344
+ // Owner-approved deletions beyond the caches: /tmp entries and node_modules.
345
+ /** Scratch roots whose direct children the owner may delete. */
346
+ export function tmpRoots(platform = process.platform) {
347
+ return platform === "darwin" ? ["/private/tmp"] : ["/tmp"];
348
+ }
349
+ const TMP_MIN_AGE_MS = 24 * 3_600_000;
350
+ /**
351
+ * Whether the owner may delete `target`, decided now against the disk:
352
+ * - an entry inside an allow-listed cache root (any age, since the owner asked);
353
+ * - a direct child of a scratch root this user owns, untouched for a day, not
354
+ * a git checkout (those go through the worktree rules), with nothing in it;
355
+ * - a checkout's own `node_modules` (it has package.json), with nothing
356
+ * running in that checkout.
357
+ * Never a symlink, never under a protected root except that node_modules.
358
+ */
359
+ export async function deletionDecision(target, context) {
360
+ const info = await lstat(target).catch(() => undefined);
361
+ if (!info)
362
+ return { allowed: false, reason: "It is already gone." };
363
+ if (info.isSymbolicLink())
364
+ return { allowed: false, reason: "It is a symbolic link; Phren never follows one." };
365
+ const parent = await canonical(path.dirname(target));
366
+ const abs = path.join(parent, path.basename(target));
367
+ const inUse = async (dir) => {
368
+ const blockers = await inUseBlockers(dir, context).catch(error => [{ code: "inspection-failed", detail: String(error) }]);
369
+ return blockers.length ? { allowed: false, reason: plainReason(blockers), blockers } : undefined;
370
+ };
371
+ if (path.basename(abs) === "node_modules" && info.isDirectory()) {
372
+ if (!await exists(path.join(parent, "package.json")) || !await exists(path.join(parent, ".git")))
373
+ return { allowed: false, reason: "Phren only clears node_modules at the top of a checkout." };
374
+ return await inUse(parent) ?? { allowed: true, rule: "node-modules" };
375
+ }
376
+ const cache = await cacheDecision(target, context);
377
+ if (cache.verdict === "auto")
378
+ return { allowed: true, rule: cache.rule };
379
+ if (cache.verdict === "suggest" && cache.rule)
380
+ return { allowed: true, rule: cache.rule }; // only too recent; the owner asked
381
+ if (cache.verdict === "keep" && cache.reason !== "protected-path")
382
+ return { allowed: false, reason: cache.blockers?.length ? plainReason(cache.blockers) : "Phren won't remove it.", ...(cache.blockers ? { blockers: cache.blockers } : {}) };
383
+ if (cache.verdict === "keep")
384
+ return { allowed: false, reason: "It is under a folder Phren never touches." };
385
+ for (const root of context.tmpRoots ?? tmpRoots()) {
386
+ if (parent !== await canonical(root))
387
+ continue;
388
+ if (info.uid !== (context.uid ?? process.getuid?.() ?? info.uid))
389
+ return { allowed: false, reason: "Another user owns it." };
390
+ if ((context.now ?? Date.now()) - info.mtimeMs < TMP_MIN_AGE_MS)
391
+ return { allowed: false, reason: "It was changed in the last day." };
392
+ if (info.isDirectory() && await exists(path.join(abs, ".git")))
393
+ return { allowed: false, reason: "It is a git checkout; remove it as a worktree." };
394
+ return await inUse(abs) ?? { allowed: true, rule: "tmp" };
395
+ }
396
+ return { allowed: false, reason: "Phren only deletes caches, scratch folders and node_modules." };
397
+ }
398
+ /** Delete what the owner approved, deciding again just before. */
399
+ export async function removeApprovedPath(target, context) {
400
+ const decision = await deletionDecision(target, context);
401
+ if (!decision.allowed)
402
+ return { removed: false, decision };
403
+ await rm(target, { recursive: true, force: false, maxRetries: 0 });
404
+ return { removed: true, decision };
405
+ }
406
+ /** Why a pane must stay open, or undefined if the owner may close it. A
407
+ * pane whose dispatch return is unread keeps the evidence (the 2026-11-08
408
+ * lesson); a working or waiting agent and the conductor stay too. */
409
+ export function paneCloseBlock(pane, dispatches) {
410
+ if (pane.role === "conductor")
411
+ return "It is the conductor.";
412
+ if (pane.status === "working")
413
+ return "Its agent is working.";
414
+ if (pane.status === "blocked" || pane.status === "waiting")
415
+ return "Its agent is waiting for an answer.";
416
+ for (const receipt of dispatches) {
417
+ if (receipt.closedAt || receipt.server !== pane.server || receipt.pane !== pane.pane)
418
+ continue;
419
+ if (!receipt.returned)
420
+ return "Its dispatched work hasn't returned yet.";
421
+ if (!receipt.returned.read)
422
+ return "Its return hasn't been read yet.";
423
+ }
424
+ return undefined;
425
+ }
426
+ /** What an item of a given kind may be: only a cache can ever be `auto`. */
427
+ export function allowedVerdict(kind, proposed) {
428
+ return proposed === "auto" && kind !== "cache" ? "suggest" : proposed;
429
+ }
430
+ // ---------------------------------------------------------------------------
431
+ // Production in-use sources.
432
+ /** Every process's working directory this user can see: `lsof` on macOS,
433
+ * `/proc/<pid>/cwd` on Linux. A failure throws, so callers fail closed. */
434
+ export async function liveProcessCwds(platform = process.platform) {
435
+ if (platform === "linux") {
436
+ const out = [];
437
+ for (const entry of await readdir("/proc")) {
438
+ if (!/^\d+$/.test(entry))
439
+ continue;
440
+ const cwd = await readlink(`/proc/${entry}/cwd`).catch(() => undefined);
441
+ if (cwd)
442
+ out.push({ pid: Number(entry), cwd });
443
+ }
444
+ return out;
445
+ }
446
+ // lsof exits 1 when some processes could not be read; its output is still valid.
447
+ const { stdout } = await exec("lsof", ["-n", "-P", "-d", "cwd", "-F", "pcn"], { timeout: 15_000, maxBuffer: 16 * 1024 * 1024 })
448
+ .catch((error) => { if (typeof error.stdout === "string" && error.stdout)
449
+ return { stdout: error.stdout }; throw error; });
450
+ return parseLsofCwds(stdout);
451
+ }
452
+ export function parseLsofCwds(output) {
453
+ const out = [];
454
+ let pid = 0, command;
455
+ for (const line of output.split("\n")) {
456
+ if (line.startsWith("p")) {
457
+ pid = Number(line.slice(1));
458
+ command = undefined;
459
+ }
460
+ else if (line.startsWith("c"))
461
+ command = line.slice(1);
462
+ else if (line.startsWith("n") && pid)
463
+ out.push({ pid, cwd: line.slice(1), ...(command ? { command } : {}) });
464
+ }
465
+ return out;
466
+ }
@@ -26,6 +26,7 @@ const ROUTES = new Set([
26
26
  "POST /v1/conductor/make", "POST /v1/conductor/stop",
27
27
  "POST /v1/push/register",
28
28
  "POST /v1/sets/link",
29
+ "POST /v1/housekeeping/approve", "POST /v1/housekeeping/dismiss", "POST /v1/housekeeping/restore", "POST /v1/housekeeping/scan",
29
30
  ]);
30
31
  const payloadSchema = z.object({
31
32
  domain: z.literal(DOMAIN), nonce: z.string().uuid(), at: z.string().datetime({ offset: true }),
@@ -67,7 +67,9 @@ export function fanoutBlockedPushPayload(value) {
67
67
  export function machineHealthPushPayload(value, host) {
68
68
  return {
69
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" },
70
+ // `housekeeping`: the same finding is a housekeeping warning with this id; a newer app opens it there, an older one routes to resources.
71
+ phren: { kind: "machineHealth", ...(host ? { host } : {}), computer: value.computer, id: value.id, title: value.title, detail: value.detail, fix: value.fix, route: "resources",
72
+ housekeeping: { computer: value.computer, id: value.id } },
71
73
  };
72
74
  }
73
75
  export function schedulePushPayload(value) {
@@ -1,3 +1,5 @@
1
+ import { type AgentBudget } from "../heavy/budget-status.js";
2
+ import type { Pressure } from "../heavy/budget.js";
1
3
  import { type CleanupReport, type JobSource, type ProcessLike, type TrackedJob } from "./job-registry.js";
2
4
  import { type HealthFinding } from "./machine-health.js";
3
5
  /**
@@ -77,6 +79,8 @@ export interface ComputerResources {
77
79
  warnings: Array<"load-high" | "memory-low" | "disk-low" | "battery-low">;
78
80
  /** Named health findings with severity and a fix (machine-health.ts), worst first. */
79
81
  health?: HealthFinding[];
82
+ /** The budget for agent work and its two pools (heavy/budget-status.ts). */
83
+ budget?: AgentBudget;
80
84
  }
81
85
  /** What the computer is, read once per Hook run: "MacBook Pro", "Apple M1 Max",
82
86
  * 32 GB; on Linux the DMI vendor and product ("Dell XPS 13 9310") and the CPU's
@@ -132,6 +136,8 @@ export declare function parseSwap(output: string): number | undefined;
132
136
  export declare function parseMeminfo(text: string): ComputerResources["memory"];
133
137
  /** Gauge fill and warnings from the numbers. */
134
138
  export declare function assess(value: Omit<ComputerResources, "pressure" | "level" | "warnings">): Pick<ComputerResources, "pressure" | "level" | "warnings">;
139
+ /** This computer's memory: the one reader behind the resources gauge and the agent budget (heavy/budget.ts). */
140
+ export declare function readMemory(platform?: NodeJS.Platform): Promise<ComputerResources["memory"]>;
135
141
  /** Seconds from `ps`'s `etime` (`[[dd-]hh:]mm:ss`), or undefined. */
136
142
  export declare function parseEtime(value: string): number | undefined;
137
143
  /** Each row's start time (epoch ms, to about a second) from a `pid=,etime=`
@@ -163,6 +169,8 @@ export interface ResourceDeps {
163
169
  jobs?: JobSource;
164
170
  /** Named findings for this read from the numbers and the process table. */
165
171
  health?: (value: ComputerResources, rows: ProcessRow[]) => HealthFinding[];
172
+ /** The agent budget for this read's memory and load. */
173
+ budget?: (pressure: Pressure) => AgentBudget;
166
174
  }
167
175
  export declare function collectResources(deps: ResourceDeps): Promise<ComputerResources>;
168
176
  /** One collection at a time, reused for `RESOURCES_MAX_AGE_MS`. */
@@ -3,6 +3,7 @@ import { readdir, readFile, statfs } from "node:fs/promises";
3
3
  import { cpus, loadavg, totalmem, uptime } from "node:os";
4
4
  import path from "node:path";
5
5
  import { promisify } from "node:util";
6
+ import { agentBudget } from "../heavy/budget-status.js";
6
7
  import { homeDir } from "../home-paths.js";
7
8
  import { recentServers, sharedSnapshot } from "./herdr.js";
8
9
  import { JobRegistry, jobPgids, paneKey } from "./job-registry.js";
@@ -311,6 +312,12 @@ async function darwinMemory() {
311
312
  ...(pressure.trim() && Number.isFinite(code) ? { pressure: code >= 4 ? "critical" : code >= 2 ? "warn" : "normal" } : {}),
312
313
  ...(swapUsedBytes !== undefined ? { swapUsedBytes } : {}) };
313
314
  }
315
+ /** This computer's memory: the one reader behind the resources gauge and the agent budget (heavy/budget.ts). */
316
+ export function readMemory(platform = process.platform) {
317
+ return platform === "darwin" ? darwinMemory()
318
+ : platform === "linux" ? readFile("/proc/meminfo", "utf8").then(parseMeminfo).catch(() => ({ totalBytes: totalmem() }))
319
+ : Promise.resolve({ totalBytes: totalmem() });
320
+ }
314
321
  async function linuxBattery() {
315
322
  const root = "/sys/class/power_supply";
316
323
  const names = await readdir(root).catch(() => []);
@@ -399,9 +406,7 @@ export async function collectResources(deps) {
399
406
  const platform = deps.platform;
400
407
  const registry = deps.jobs ?? new JobRegistry();
401
408
  const [memory, disk, battery, rows, registered, hardware] = await Promise.all([
402
- platform === "darwin" ? darwinMemory()
403
- : platform === "linux" ? readFile("/proc/meminfo", "utf8").then(parseMeminfo).catch(() => ({ totalBytes: totalmem() }))
404
- : Promise.resolve({ totalBytes: totalmem() }),
409
+ readMemory(platform),
405
410
  statfs(deps.home()).then(info => ({ path: "~", totalBytes: info.blocks * info.bsize, freeBytes: info.bavail * info.bsize })).catch(() => undefined),
406
411
  platform === "darwin" ? run("/usr/bin/pmset", ["-g", "batt"]).then(parsePmset).catch(() => undefined)
407
412
  : platform === "linux" ? linuxBattery() : Promise.resolve(undefined),
@@ -422,7 +427,15 @@ export async function collectResources(deps) {
422
427
  memory, ...(disk ? { disk } : {}), ...(battery ? { battery } : {}), ...(hardware ? { hardware } : {}),
423
428
  heavy: owners.size || jobs.length ? heavyProcesses(rows, owners, jobs) : preliminary,
424
429
  };
425
- const result = { ...value, ...assess(value) };
430
+ const pressureNow = { totalBytes: memory.totalBytes, load1: one, cores,
431
+ ...(memory.availablePercent !== undefined ? { availableBytes: Math.round(memory.totalBytes * memory.availablePercent / 100) } : {}) };
432
+ const budget = deps.budget ? (() => { try {
433
+ return deps.budget(pressureNow);
434
+ }
435
+ catch {
436
+ return undefined;
437
+ } })() : undefined;
438
+ const result = { ...value, ...assess(value), ...(budget ? { budget } : {}) };
426
439
  const check = deps.health;
427
440
  if (!check)
428
441
  return result;
@@ -446,7 +459,7 @@ export class ResourceMonitor {
446
459
  this.registry = deps.jobs ?? new JobRegistry();
447
460
  const health = new MachineHealth(process.env.PHREN_HEALTH_PROBES === "off" ? undefined : new PlatformProbes());
448
461
  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 };
462
+ health: (value, rows) => health.assess(value, rows, this.deps.now()), budget: pressure => agentBudget(pressure, this.deps.now()), ...deps, jobs: this.registry };
450
463
  }
451
464
  async read() {
452
465
  if (this.cached && this.deps.now() - this.cached.at < this.maxAgeMs)
@@ -3,6 +3,7 @@ import type { IncomingHttpHeaders, ServerResponse } from "node:http";
3
3
  import { type GitWriteDiagnostics } from "./git-write-policy.js";
4
4
  import type { AgentHooks } from "./agent-hooks.js";
5
5
  import { type WorktreeWorker } from "./git-worktrees.js";
6
+ import { type WorktreeRemovalLiveSession } from "./git-worktree-remove.js";
6
7
  import { type ModelSwitcher } from "./model-switch.js";
7
8
  import { type PermissionModeSwitcher } from "./permission-mode.js";
8
9
  import type { SettingsSwitcher } from "./settings-switch.js";
@@ -35,6 +36,11 @@ export declare function gitRepository(pane: Json, target: Target, child: unknown
35
36
  * an agent launched into a new worktree from the phone is named here. Listed
36
37
  * last, so a sub-agent or fan-out manifest for the same folder wins a tie. */
37
38
  export declare function herdrWorktreeWorkers(s: Json): WorktreeWorker[];
39
+ /** Every live pane on every running terminal server, including the requesting
40
+ * one even when discovery left it out. A server that cannot be read, or any
41
+ * discovery failure, fails the request: removal is never allowed on an
42
+ * incomplete session check. */
43
+ export declare function allPaneSessions(requested?: string[]): Promise<WorktreeRemovalLiveSession[]>;
38
44
  /** What `takesPrompt` checks before typing into a Claude pane Herdr reads working: nothing structured
39
45
  * pending there and no dialog on its screen. */
40
46
  export declare function promptGuards(agentHooks: Pick<AgentHooks, "approval" | "terminalPrompt" | "servedQuestion">, target: Target): Required<PromptGuards>;
@@ -123,7 +123,7 @@ function stoppedServer(error) {
123
123
  * one even when discovery left it out. A server that cannot be read, or any
124
124
  * discovery failure, fails the request: removal is never allowed on an
125
125
  * incomplete session check. */
126
- async function allPaneSessions(requested = []) {
126
+ export async function allPaneSessions(requested = []) {
127
127
  const running = await serversStrict();
128
128
  const names = [...new Set([...requested, ...running.map(server => String(server.session)).filter(Boolean)])];
129
129
  const snapshots = await Promise.all(names.map(async (name) => {
@@ -25,6 +25,7 @@ import type { SettingsSwitcher } from "./settings-switch.js";
25
25
  import type { SideQuestions } from "./side-questions.js";
26
26
  import { type AccountUsageReader } from "./usage.js";
27
27
  import type { ResourceMonitor } from "./resources.js";
28
+ import type { Housekeeper } from "./housekeeping/housekeeper.js";
28
29
  import type { Scheduler } from "./schedules.js";
29
30
  import type { TranscriptStreams } from "./server-stream.js";
30
31
  /** The Hook's HTTP API over its Unix socket: module gating, the GET routes,
@@ -78,6 +79,8 @@ export interface RouteContext {
78
79
  sideQuestions: SideQuestions;
79
80
  accountUsage: AccountUsageReader;
80
81
  resources: ResourceMonitor;
82
+ /** Housekeeping reports (housekeeping/); absent in route tests that do not need it. */
83
+ housekeeper?: Housekeeper;
81
84
  codexQuestions: CodexQuestions;
82
85
  launches: LaunchLimiter;
83
86
  locatedDirectories: Set<string>;
@@ -190,6 +193,8 @@ export declare const capabilities: {
190
193
  worktreeRemove: boolean;
191
194
  terminalResolve: boolean;
192
195
  conversationSearch: boolean;
196
+ housekeeping: number;
197
+ housekeepingInventory: number;
193
198
  };
194
199
  export declare function capabilitiesForModules(snapshot: ModuleSnapshot): Record<string, unknown>;
195
200
  export declare function requireRoute(snapshot: ModuleSnapshot, method: string, route: string): void;