@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
@@ -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>;
@@ -162,6 +165,7 @@ export declare const capabilities: {
162
165
  sudo: boolean;
163
166
  sudoOutcome: boolean;
164
167
  secretExec: boolean;
168
+ ownerProof: number;
165
169
  previewDeltas: boolean;
166
170
  quickChat: boolean;
167
171
  agentFolder: boolean;
@@ -189,6 +193,8 @@ export declare const capabilities: {
189
193
  worktreeRemove: boolean;
190
194
  terminalResolve: boolean;
191
195
  conversationSearch: boolean;
196
+ housekeeping: number;
197
+ housekeepingInventory: number;
192
198
  };
193
199
  export declare function capabilitiesForModules(snapshot: ModuleSnapshot): Record<string, unknown>;
194
200
  export declare function requireRoute(snapshot: ModuleSnapshot, method: string, route: string): void;
@@ -9,6 +9,7 @@ import { ACCOUNT_ROLES, isAccountRole, setAccountSettings, setComputerAllowedPoo
9
9
  import { claudeHome } from "./claude-accounts.js";
10
10
  import { localMoveAvailability, moveComputers } from "./move-computers.js";
11
11
  import { ownerRequest, requestPeer } from "./request-origin.js";
12
+ import { bodyDigest, OwnerProof } from "./owner-proof.js";
12
13
  import { listMoves, moveSessionFields, readMove } from "./session-move.js";
13
14
  import { getTaskRoute, getTaskDirectoryRoute, updateTaskRoute, createTaskRoute, saveTaskRoute, launchTaskRoute } from "./task-routes.js";
14
15
  import { ownerInboxView } from "./owner-inbox-view.js";
@@ -58,6 +59,7 @@ import { conversationSearch } from "./conversation-search.js";
58
59
  import { listUploads, removeUpload, saveUpload, uploadImage } from "./uploads.js";
59
60
  import { currentModel, currentStep } from "./steps.js";
60
61
  import { capacityRoom, usageForCaller } from "./usage.js";
62
+ import { pressureReason, readBudget, readPressure } from "../heavy/budget.js";
61
63
  import { SCHEDULE_EVENT_BODY_CAP } from "./schedule-events.js";
62
64
  import { updateScheduleRoute } from "./schedule-update.js";
63
65
  import { cachedStoreWarnings, healthDetails, listsCaller } from "./health.js";
@@ -118,7 +120,7 @@ export async function effectiveStatusRows(server, s, budgetMs = STATUS_ENRICH_BU
118
120
  export const capabilities = { browsers: true, turnCheckpoints: true, transcript: true, progress: true, images: true, prompt: true, stop: true,
119
121
  terminal: "ssh-pty", shell: "ssh-pty", paneTerminal: "ssh-pty", paneLayout: true, deskPresence: true, herdr: true, sessionRename: true, sessionSeen: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
120
122
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
121
- files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", simulatorStream: process.platform === "darwin", simulatorDevices: process.platform === "darwin", simulatorDrag: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, afterTurnQueue: true, queuedMessageActions: ["claude"], deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, secretExec: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, moveConductor: true, moveToComputer: true, moveConductorToComputer: true, moveResume: true, moveSummaryByTarget: true, moveConversationCopy: true, claudeAccountAdd: true, accountPools: true, workerRelocation: 1, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true, gitRemoteIdentity: true, gitWatch: true, worktreeRemove: true, terminalResolve: true, conversationSearch: true };
123
+ files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", simulatorStream: process.platform === "darwin", simulatorDevices: process.platform === "darwin", simulatorDrag: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, afterTurnQueue: true, queuedMessageActions: ["claude"], deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, secretExec: true, ownerProof: 1, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, moveConductor: true, moveToComputer: true, moveConductorToComputer: true, moveResume: true, moveSummaryByTarget: true, moveConversationCopy: true, claudeAccountAdd: true, accountPools: true, workerRelocation: 1, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true, gitRemoteIdentity: true, gitWatch: true, worktreeRemove: true, terminalResolve: true, conversationSearch: true, housekeeping: 1, housekeepingInventory: 1 };
122
124
  export function capabilitiesForModules(snapshot) {
123
125
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
124
126
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -155,6 +157,9 @@ async function codePackageStatus(store, enabled) {
155
157
  const from = loadedFrom();
156
158
  return code && from ? { loadedFrom: from } : { missing: true };
157
159
  }
160
+ /** Owner-only actions need the paired phone's signature once it has signed one (owner-proof.ts). */
161
+ const ownerProof = new OwnerProof();
162
+ const bodyDigests = new WeakMap();
158
163
  async function body(request, cap = 11_500_000) {
159
164
  let size = 0;
160
165
  const chunks = [];
@@ -164,7 +169,9 @@ async function body(request, cap = 11_500_000) {
164
169
  throw new BridgeError(413, "Request is too large.");
165
170
  chunks.push(chunk);
166
171
  }
167
- return object(JSON.parse(Buffer.concat(chunks).toString() || "{}"));
172
+ const raw = Buffer.concat(chunks);
173
+ bodyDigests.set(request, bodyDigest(raw));
174
+ return object(JSON.parse(raw.toString() || "{}"));
168
175
  }
169
176
  export function selectedServer(url) {
170
177
  const mux = url.searchParams.get("mux");
@@ -695,10 +702,14 @@ export function createRouteHandler(ctx) {
695
702
  // Both bounded so a peer's capacity probe never waits on a cold `claude auth status` or usage read; missing means unknown.
696
703
  // PHREN_LAUNCH_CHECK=off turns this Hook's availability checks off, including what it advertises to dispatch.
697
704
  // `usage` is the room left per Codex and Claude account, so `anywhere` can break a tie by it.
698
- const [inventory, limits] = await Promise.all([launchCheckOff() ? undefined : harnessInventoryWithin(2_500), within(2_500, accountUsage.limits(true))]);
705
+ const [inventory, limits, pressure] = await Promise.all([launchCheckOff() ? undefined : harnessInventoryWithin(2_500), within(2_500, accountUsage.limits(true)),
706
+ within(2_500, readPressure())]);
707
+ // Memory or load past this computer's budget (heavy/budget.ts): `anywhere` passes it over, and an agent may not name it.
708
+ const overBudget = pressure ? pressureReason(pressure, readBudget(pressure.totalBytes)) : undefined;
699
709
  result = { product: "phren-hook", protocol: PROTOCOL, computer: info.computer, servers: live.map(server => server.session), ...linksBack,
700
710
  working: snapshots.reduce((sum, value) => sum + objects(value.panes).filter(pane => pane.agent && pane.agent_status === "working").length, 0),
701
- ...(inventory ? { harnesses: inventory.harnesses } : {}), ...(limits ? { usage: capacityRoom(limits, Date.now()) } : {}) };
711
+ ...(inventory ? { harnesses: inventory.harnesses } : {}), ...(limits ? { usage: capacityRoom(limits, Date.now()) } : {}),
712
+ ...(overBudget ? { overBudget } : {}) };
702
713
  break;
703
714
  }
704
715
  case "/v1/speech/voices": {
@@ -825,6 +836,22 @@ export function createRouteHandler(ctx) {
825
836
  result = { ...result, ...await fromPeers("/v1/resources") };
826
837
  break;
827
838
  }
839
+ case "/v1/housekeeping": {
840
+ // The newest housekeeping report (docs/housekeeping.md); null before the first pass.
841
+ // This computer only; the phone asks each computer itself. `peers=1` is for `phren housekeeping`.
842
+ if (!ctx.housekeeper)
843
+ throw new BridgeError(404, "Housekeeping is not running on this Hook.");
844
+ const dismissed = url.searchParams.get("dismissed") === "1", inventory = url.searchParams.get("inventory") === "1";
845
+ // Before the first scheduled pass, run one now so the answer always has the full shape.
846
+ const view = await ctx.housekeeper.view(dismissed, inventory) ?? (await ctx.housekeeper.run("manual"), await ctx.housekeeper.view(dismissed, inventory));
847
+ // No scan yet: start one; `inventory` appears once it lands (the revision changes).
848
+ if (inventory && !view?.inventory)
849
+ void ctx.housekeeper.scan().catch(() => { });
850
+ result = { computer: info.computer, ...view };
851
+ if (url.searchParams.get("peers") === "1")
852
+ result = { ...result, ...await fromPeers("/v1/housekeeping") };
853
+ break;
854
+ }
828
855
  case "/v1/push/status":
829
856
  result = agentHooks.push.status;
830
857
  break;
@@ -995,6 +1022,7 @@ export function createRouteHandler(ctx) {
995
1022
  }
996
1023
  else if (request.method === "POST") {
997
1024
  const data = await body(request, url.pathname === "/v1/schedules/events" ? SCHEDULE_EVENT_BODY_CAP : undefined);
1025
+ await ownerProof.check(request, url.pathname, data, bodyDigests.get(request));
998
1026
  if (url.pathname.startsWith("/v1/conductor/move/"))
999
1027
  await ctx.succession.authorize(z.string().uuid().parse(data.id), requestPeer(request), url.pathname.endsWith("/prepare") ? z.string().uuid().parse(data.originId) : undefined);
1000
1028
  const executeConductor = async (action, payload, origin, remote = false) => {
@@ -1197,6 +1225,26 @@ export function createRouteHandler(ctx) {
1197
1225
  else if (url.pathname === "/v1/sessions/seen") {
1198
1226
  result = await markSessionSeen(data);
1199
1227
  }
1228
+ else if (url.pathname === "/v1/housekeeping/scan") {
1229
+ // Owner-only: a fresh inventory (sizes take a while); the answer comes back through the view's revision.
1230
+ if (!ownerRequest(request, data))
1231
+ throw new BridgeError(403, "Only the owner starts a housekeeping scan.");
1232
+ if (!ctx.housekeeper)
1233
+ throw new BridgeError(404, "Housekeeping is not running on this Hook.");
1234
+ void ctx.housekeeper.scan().catch(() => { });
1235
+ result = { started: true };
1236
+ }
1237
+ else if (url.pathname === "/v1/housekeeping/approve" || url.pathname === "/v1/housekeeping/dismiss" || url.pathname === "/v1/housekeeping/restore") {
1238
+ // Owner-only, and owner-proof signed once the phone signs (owner-proof.ts): agents and peers never apply housekeeping.
1239
+ if (!ownerRequest(request, data))
1240
+ throw new BridgeError(403, "Only the owner applies or dismisses housekeeping.");
1241
+ if (!ctx.housekeeper)
1242
+ throw new BridgeError(404, "Housekeeping is not running on this Hook.");
1243
+ const input = z.object({ ids: z.array(z.string().regex(/^[\w:.-]{1,200}$/)).min(1).max(200), revision: z.string().max(64).optional(),
1244
+ by: z.enum(["phone", "cli"]).optional() }).strict().parse(data);
1245
+ result = url.pathname.endsWith("/approve") ? await ctx.housekeeper.approve(input.ids, input.by ?? "phone")
1246
+ : url.pathname.endsWith("/dismiss") ? await ctx.housekeeper.dismiss(input.ids) : await ctx.housekeeper.restore(input.ids);
1247
+ }
1200
1248
  else if (url.pathname === "/v1/jobs/cleanup") {
1201
1249
  // Ends only registered worker process groups whose pane is gone.
1202
1250
  result = { ok: true, ...await ctx.resources.cleanupJobs() };
@@ -1441,6 +1489,7 @@ export function createRouteHandler(ctx) {
1441
1489
  if (url.pathname !== "/v1/conductor/grants" && url.pathname !== "/v1/authority" && url.pathname !== "/v1/approval-rules")
1442
1490
  throw new BridgeError(404, "Unknown Phren Hook route.");
1443
1491
  const data = await body(request);
1492
+ await ownerProof.check(request, url.pathname, data, bodyDigests.get(request));
1444
1493
  if (url.pathname === "/v1/conductor/grants" && request.headers?.["x-phren-origin"] === "peer")
1445
1494
  throw new BridgeError(403, "Peer conductor operations require the authenticated generation-scoped routes.");
1446
1495
  if (url.pathname === "/v1/approval-rules") {
@@ -8,6 +8,9 @@ import { setChoiceReaders } from "./account-choice.js";
8
8
  import { AccountFailover } from "./account-failover.js";
9
9
  import { ownerInboxSources } from "./owner-inbox-sources.js";
10
10
  import { OwnerInbox } from "./owner-inbox.js";
11
+ import { Housekeeper, SCAN_MS as HOUSEKEEPING_SCAN_MS, TICK_MS as HOUSEKEEPING_TICK_MS } from "./housekeeping/housekeeper.js";
12
+ import { liveProcessCwds } from "./housekeeping/safety.js";
13
+ import { dockerUsage, listSimulators, sessionRowsFromOverview, xcodebuildRunning } from "./housekeeping/inventory.js";
11
14
  import { closeFinishedWorker } from "./worker-close.js";
12
15
  import { cleanupIdempotencyLocks, markHookServerProcess } from "./dispatch-idempotency.js";
13
16
  import { isLocalComputer } from "./dispatch-hosts.js";
@@ -17,7 +20,7 @@ import { sessionStalls } from "./stalls.js";
17
20
  import { TurnQueue } from "./turn-queue.js";
18
21
  import { turnQueuePaneReader } from "./turn-queue-pane.js";
19
22
  import { HandOffQueue } from "./hand-off-queue.js";
20
- import { paneRouteOnce, promptGuards } from "./server-pane-routes.js";
23
+ import { allPaneSessions, paneRouteOnce, promptGuards } from "./server-pane-routes.js";
21
24
  import { FanoutMessages } from "./fanout-messages.js";
22
25
  import { activateModules as moduleSnapshot } from "../modules/runtime.js";
23
26
  import { disabledHint } from "../modules/registry.js";
@@ -38,7 +41,7 @@ import { approvalPushCapability } from "./push.js";
38
41
  import { startChangeRetention } from "./changes.js";
39
42
  import { CodeReindexer, CodeRoutes } from "./code-routes.js";
40
43
  import { WorkspaceContextUsage } from "./context.js";
41
- import { DispatchService, reconcileInterruptedDispatches } from "./dispatch.js";
44
+ import { DispatchService, dispatchStatus, reconcileInterruptedDispatches } from "./dispatch.js";
42
45
  import { DispatchReturns, hookWorkers } from "./dispatch-returns.js";
43
46
  import { findPane, paneChatState, paneIdentity, recentServers, sharedSnapshot, snapshot, validateTarget } from "./herdr.js";
44
47
  import { LaunchLimiter } from "./limits.js";
@@ -156,7 +159,12 @@ export async function serve(version, options = {}) {
156
159
  if ("approvalPush" in activeCapabilities) {
157
160
  Object.defineProperty(activeCapabilities, "approvalPush", { enumerable: true, get: () => approvalPushCapability(agentHooks.push.status) });
158
161
  }
159
- const inbox = dispatches ? new OwnerInbox(() => ownerInboxSources(agentHooks)) : undefined;
162
+ // Assigned once resources exist below; the inbox only reads it on its ticks.
163
+ let housekeeper;
164
+ const inbox = dispatches ? new OwnerInbox(async () => {
165
+ const observed = await ownerInboxSources(agentHooks);
166
+ return { ...observed, sources: [...observed.sources, ...housekeeper?.inboxSources() ?? []] };
167
+ }) : undefined;
160
168
  const modelCatalog = options.modelCatalog ?? new ModelCatalog();
161
169
  const modelSwitcher = new ModelSwitcher(agentHooks, modelCatalog);
162
170
  const settingsSwitcher = new SettingsSwitcher(agentHooks);
@@ -227,6 +235,20 @@ export async function serve(version, options = {}) {
227
235
  // A Claude launch that names no account runs under the one with the most room (account-choice.ts).
228
236
  setChoiceReaders({ usage: () => accountUsage.limits(true) });
229
237
  const resources = new ResourceMonitor();
238
+ // Housekeeping (housekeeping/): a report every 15 minutes and on a fresh low-disk or stressed edge.
239
+ housekeeper = new Housekeeper({ computer: hostname(), resources: () => resources.read(), processes: () => liveProcessCwds(),
240
+ panes: async () => (await allPaneSessions()).map(session => ({ pane: session.pane, cwd: session.cwd, title: session.title })),
241
+ inventory: {
242
+ sessions: async () => (await Promise.all((await recentServers()).map(async (server) => {
243
+ const name = String(server.session);
244
+ return sessionRowsFromOverview(await readWorkspaces(name, await sharedSnapshot(name, 4000), false));
245
+ }))).flat(),
246
+ dispatches: async () => (await dispatchStatus()).flatMap(receipt => receipt.target ? [{ id: receipt.id, server: receipt.target.server, pane: receipt.target.pane,
247
+ ...(receipt.returned ? { returned: { read: receipt.returned.read } } : {}), ...(receipt.closedAt ? { closedAt: receipt.closedAt } : {}) }] : []),
248
+ ...(process.platform === "darwin" ? { simulators: () => listSimulators(), xcodebuildRunning } : {}),
249
+ docker: dockerUsage,
250
+ },
251
+ closePane: (server, pane) => terminalProvider().closePane(server, pane) });
230
252
  const tabActivity = new TabActivityStore();
231
253
  const codexQuestions = new CodexQuestions(undefined, codexServers);
232
254
  const scheduleStore = defaultPhrenPath();
@@ -292,19 +314,22 @@ export async function serve(version, options = {}) {
292
314
  await rm(path.join(root, "changes-scratch"), { recursive: true, force: true });
293
315
  const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, settingsSwitcher, info, activeCapabilities });
294
316
  const { stream } = streams;
317
+ // One workspaces reader for the overview stream and the housekeeping inventory's sessions.
318
+ const readWorkspaces = workspacesReader({ modules, info, agentHooks, journal, tabActivity, contextUsage, turnQueue });
295
319
  // The phone's overview, pushed over a WebSocket when it changes.
296
320
  const overview = overviewStream({
297
- read: workspacesReader({ modules, info, agentHooks, journal, tabActivity, contextUsage, turnQueue }),
321
+ read: readWorkspaces,
298
322
  info: () => ({ ...info, capabilities: info.capabilities }),
299
323
  renew: server => agentHooks.overview.renew(server),
300
- resources: () => resources.read(),
324
+ // The overview's resources frame carries the housekeeping badge; the phone re-fetches /v1/housekeeping when its revision changes.
325
+ resources: async () => { const value = await resources.read(); const badge = await housekeeper?.badge().catch(() => undefined); return badge ? { ...value, housekeeping: badge } : value; },
301
326
  sudo: agentHooks.sudo,
302
327
  secrets: agentHooks.secrets,
303
328
  });
304
329
  const gitWatch = new GitWatch();
305
330
  // 256 KiB: gitboy's /memory/files asks about up to 500 paths in one query string.
306
331
  const http = createServer({ maxHeaderSize: 256 * 1024 }, createRouteHandler({ version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks,
307
- journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, settingsSwitcher, permissionModeSwitcher, sideQuestions, accountUsage, resources, codexQuestions, launches, locatedDirectories,
332
+ journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, settingsSwitcher, permissionModeSwitcher, sideQuestions, accountUsage, resources, housekeeper, codexQuestions, launches, locatedDirectories,
308
333
  fanoutMessages, canary, streams, returns, handOffs, inbox, mover, succession, storePulls, gitboyWebhooks, turnQueue, browsers }));
309
334
  http.requestTimeout = 20_000;
310
335
  http.headersTimeout = 10_000;
@@ -394,7 +419,18 @@ export async function serve(version, options = {}) {
394
419
  const canaryTimer = setInterval(() => { countTick("canary"); void dailyCanaryDue().then(due => due ? canary("daily") : undefined).catch(() => { }); }, 10 * 60_000);
395
420
  // A new high machine health finding reaches the phone once (machine-health-alerts.ts).
396
421
  const healthAlerts = new HealthAlerts(finding => agentHooks.push.notifyMachineHealth({ computer: hostname(), ...finding }));
397
- const healthTimer = setInterval(() => { countTick("health"); void resources.read().then(value => healthAlerts.observe(value.health, Date.now())).catch(() => { }); }, ALERT_CHECK_MS);
422
+ const healthTimer = setInterval(() => {
423
+ countTick("health");
424
+ void resources.read().then(value => {
425
+ healthAlerts.observe(value.health, Date.now());
426
+ void housekeeper?.observe(value)?.catch(() => { });
427
+ }).catch(() => { });
428
+ }, ALERT_CHECK_MS);
429
+ const housekeepingTimer = setInterval(() => { countTick("housekeeping"); void housekeeper?.run().catch(() => { }); }, HOUSEKEEPING_TICK_MS);
430
+ setTimeout(() => { void housekeeper?.run().catch(() => { }); }, 60_000).unref();
431
+ // The inventory (sizes are slow, niced): hourly, the first a few minutes after start.
432
+ const inventoryTimer = setInterval(() => { countTick("housekeeping-scan"); void housekeeper?.scan().catch(() => { }); }, HOUSEKEEPING_SCAN_MS);
433
+ setTimeout(() => { void housekeeper?.scan().catch(() => { }); }, 3 * 60_000).unref();
398
434
  let recording = false;
399
435
  const activityTimer = setInterval(() => {
400
436
  countTick("activity");
@@ -445,7 +481,7 @@ export async function serve(version, options = {}) {
445
481
  })().finally(() => { recording = false; }).catch(() => { });
446
482
  }, 5000);
447
483
  await new Promise(resolve => {
448
- const stop = () => { browsers.close(); gitboyWebhooks.stop(); storePulls.stop(); storeSync.stop(); fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(dreamTimer); clearInterval(canaryTimer); clearInterval(healthTimer); clearInterval(codexAuthTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); codexServers.close(); gitWatch.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
484
+ const stop = () => { browsers.close(); gitboyWebhooks.stop(); storePulls.stop(); storeSync.stop(); fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(dreamTimer); clearInterval(canaryTimer); clearInterval(healthTimer); clearInterval(housekeepingTimer); clearInterval(inventoryTimer); clearInterval(codexAuthTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); codexServers.close(); gitWatch.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
449
485
  process.once("SIGTERM", stop);
450
486
  process.once("SIGINT", stop);
451
487
  });