@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.
- package/dist/bridge/dispatch.js +17 -3
- package/dist/bridge/files.d.ts +1 -1
- package/dist/bridge/housekeeping/command.d.ts +5 -0
- package/dist/bridge/housekeeping/command.js +106 -0
- package/dist/bridge/housekeeping/housekeeper.d.ts +123 -0
- package/dist/bridge/housekeeping/housekeeper.js +459 -0
- package/dist/bridge/housekeeping/inventory.d.ts +145 -0
- package/dist/bridge/housekeeping/inventory.js +276 -0
- package/dist/bridge/housekeeping/report.d.ts +672 -0
- package/dist/bridge/housekeeping/report.js +168 -0
- package/dist/bridge/housekeeping/safety.d.ts +177 -0
- package/dist/bridge/housekeeping/safety.js +466 -0
- package/dist/bridge/owner-proof.d.ts +41 -0
- package/dist/bridge/owner-proof.js +119 -0
- package/dist/bridge/push.js +3 -1
- package/dist/bridge/resources.d.ts +8 -0
- package/dist/bridge/resources.js +18 -5
- package/dist/bridge/server-pane-routes.d.ts +6 -0
- package/dist/bridge/server-pane-routes.js +1 -1
- package/dist/bridge/server-routes.d.ts +6 -0
- package/dist/bridge/server-routes.js +53 -4
- package/dist/bridge/server.js +44 -8
- package/dist/bridge-hook.mjs +3093 -1219
- package/dist/cli-registry.js +18 -1
- package/dist/fanout/command.js +42 -15
- package/dist/heavy/budget-status.d.ts +26 -0
- package/dist/heavy/budget-status.js +26 -0
- package/dist/heavy/budget.d.ts +39 -0
- package/dist/heavy/budget.js +57 -0
- package/dist/heavy/command.d.ts +15 -0
- package/dist/heavy/command.js +119 -0
- package/dist/heavy/reap.d.ts +70 -0
- package/dist/heavy/reap.js +211 -0
- package/dist/heavy/slots.d.ts +58 -0
- package/dist/heavy/slots.js +142 -0
- package/dist/modules/registry.js +5 -4
- package/package.json +1 -1
- package/starter/global/skills/conductor/SKILL.md +10 -0
- package/starter/global/skills/fanout/SKILL.md +30 -0
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { lstat, mkdir, readdir, readFile, statfs, unlink } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import { atomicInPrivateDir, bridgeRoot } from "../protocol.js";
|
|
7
|
+
import { badgeOf, buildReport, healthOf, viewOf, } from "./report.js";
|
|
8
|
+
import { scanInventory } from "./inventory.js";
|
|
9
|
+
import { paneCloseBlock, plainReason, removeApprovedPath, removeWorktreeSafely } from "./safety.js";
|
|
10
|
+
/**
|
|
11
|
+
* The Hook's housekeeping pass: every TICK_MS, and at once when free disk
|
|
12
|
+
* drops below the floor or the computer becomes stressed, run each check,
|
|
13
|
+
* store the report for RETAIN_DAYS, and serve the phone's view of it. Checks
|
|
14
|
+
* only observe and propose. Acting happens in `approve` (the owner) or, in a
|
|
15
|
+
* later slice, for allow-listed caches; both go through safety.ts against
|
|
16
|
+
* fresh state, never the stored report.
|
|
17
|
+
*/
|
|
18
|
+
export const TICK_MS = 15 * 60_000;
|
|
19
|
+
export const RETAIN_DAYS = 14;
|
|
20
|
+
/** Below this the RC suites fail; the audit's floor for warning and cleaning. */
|
|
21
|
+
export const DISK_FLOOR_BYTES = 20 * 1024 ** 3;
|
|
22
|
+
/** Approve answers within this; later work comes back `started` and lands in `cleaned`. */
|
|
23
|
+
export const APPROVE_BUDGET_MS = 45_000;
|
|
24
|
+
/** The inventory scan (sizes are slow) runs hourly and on request. */
|
|
25
|
+
export const SCAN_MS = 60 * 60_000;
|
|
26
|
+
/** An inventory older than this is marked stale. */
|
|
27
|
+
const STALE_MS = 2 * SCAN_MS;
|
|
28
|
+
const MAX_REPORTS = 2000;
|
|
29
|
+
const MAX_FILE_BYTES = 8 * 1024 * 1024;
|
|
30
|
+
const DAY = 86_400_000;
|
|
31
|
+
/** Machine-health findings that are housekeeping's business, and their area. */
|
|
32
|
+
const HEALTH_AREAS = {
|
|
33
|
+
swap: "memory", load: "memory", "memory-hog": "memory", "memory-leak": "memory", oom: "memory",
|
|
34
|
+
disk: "disk", orphan: "sessions", "stale-lock": "sessions", "simulator-clones": "simulators",
|
|
35
|
+
};
|
|
36
|
+
const SUSTAINED = new Set(["swap", "load", "memory-hog", "memory-leak"]);
|
|
37
|
+
/** Warnings are machine-health findings, with their ids and wording, so the
|
|
38
|
+
* phone and the conductor's `machine_health` name the same thing the same way. */
|
|
39
|
+
export const healthCheck = {
|
|
40
|
+
name: "health",
|
|
41
|
+
run: async ({ resources }) => (resources.health ?? []).flatMap(finding => {
|
|
42
|
+
const area = HEALTH_AREAS[finding.check];
|
|
43
|
+
if (!area)
|
|
44
|
+
return [];
|
|
45
|
+
// Disk under the RC floor wakes the owner at once; pressure only once it lasts (see `pass`).
|
|
46
|
+
const notify = finding.check === "disk" && (resources.disk?.freeBytes ?? Infinity) < DISK_FLOOR_BYTES;
|
|
47
|
+
return [{ id: finding.id, section: "warning", area, kind: "health", severity: finding.severity, title: finding.title,
|
|
48
|
+
reason: finding.detail, fix: finding.fix, target: { name: finding.check }, fingerprint: finding.severity, ...(notify ? { notify } : {}) }];
|
|
49
|
+
}),
|
|
50
|
+
};
|
|
51
|
+
export const DEFAULT_CHECKS = [healthCheck];
|
|
52
|
+
async function readJson(file, fallback) {
|
|
53
|
+
const info = await lstat(file).catch(() => undefined);
|
|
54
|
+
if (!info?.isFile() || info.size > MAX_FILE_BYTES)
|
|
55
|
+
return fallback;
|
|
56
|
+
try {
|
|
57
|
+
return JSON.parse(await readFile(file, "utf8"));
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return fallback;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/** `<bridge>/housekeeping/`: reports/ (one file per pass), cleaned.json, dismissed.json. */
|
|
64
|
+
export class HousekeepingStore {
|
|
65
|
+
dir;
|
|
66
|
+
reports;
|
|
67
|
+
constructor(dir = path.join(bridgeRoot(), "housekeeping")) {
|
|
68
|
+
this.dir = dir;
|
|
69
|
+
this.reports = path.join(dir, "reports");
|
|
70
|
+
}
|
|
71
|
+
async names() {
|
|
72
|
+
const entries = await readdir(this.reports).catch((error) => { if (error.code === "ENOENT")
|
|
73
|
+
return []; throw error; });
|
|
74
|
+
return entries.filter(name => /^\d{8}T\d{6}Z-[a-f0-9]{12}\.json$/.test(name)).sort();
|
|
75
|
+
}
|
|
76
|
+
async save(report, now) {
|
|
77
|
+
await mkdir(this.reports, { recursive: true, mode: 0o700 });
|
|
78
|
+
const stamp = report.generatedAt.replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
|
|
79
|
+
await atomicInPrivateDir(path.join(this.reports, `${stamp}-${report.id}.json`), report);
|
|
80
|
+
const names = await this.names();
|
|
81
|
+
for (const [index, name] of names.entries()) {
|
|
82
|
+
const at = Date.parse(name.replace(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z.*/, "$1-$2-$3T$4:$5:$6Z"));
|
|
83
|
+
if (at < now - RETAIN_DAYS * DAY || index < names.length - MAX_REPORTS)
|
|
84
|
+
await unlink(path.join(this.reports, name)).catch(() => { });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
async latest() {
|
|
88
|
+
for (const name of (await this.names()).reverse()) {
|
|
89
|
+
const report = await readJson(path.join(this.reports, name), undefined);
|
|
90
|
+
if (report?.version === 1)
|
|
91
|
+
return report; // a torn or foreign file: try the one before
|
|
92
|
+
}
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
async cleaned(now) {
|
|
96
|
+
return (await readJson(path.join(this.dir, "cleaned.json"), [])).filter(entry => Date.parse(entry.at) >= now - RETAIN_DAYS * DAY);
|
|
97
|
+
}
|
|
98
|
+
async addCleaned(entry, now) {
|
|
99
|
+
const kept = [...await this.cleaned(now), entry].slice(-5000);
|
|
100
|
+
await atomicInPrivateDir(path.join(this.dir, "cleaned.json"), kept);
|
|
101
|
+
}
|
|
102
|
+
async inventory() {
|
|
103
|
+
return readJson(path.join(this.dir, "inventory.json"), undefined);
|
|
104
|
+
}
|
|
105
|
+
async setInventory(inventory) {
|
|
106
|
+
await atomicInPrivateDir(path.join(this.dir, "inventory.json"), inventory);
|
|
107
|
+
}
|
|
108
|
+
async dismissed() {
|
|
109
|
+
return new Map(Object.entries(await readJson(path.join(this.dir, "dismissed.json"), {})));
|
|
110
|
+
}
|
|
111
|
+
async setDismissed(marks, now) {
|
|
112
|
+
// A mark for a state that has not come back in a month is dropped.
|
|
113
|
+
const live = [...marks].filter(([, mark]) => Date.parse(mark.at) >= now - 30 * DAY);
|
|
114
|
+
await atomicInPrivateDir(path.join(this.dir, "dismissed.json"), Object.fromEntries(live));
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
export class Housekeeper {
|
|
118
|
+
options;
|
|
119
|
+
current;
|
|
120
|
+
loaded = false;
|
|
121
|
+
running;
|
|
122
|
+
queue = Promise.resolve();
|
|
123
|
+
cachedView;
|
|
124
|
+
lastEdge = { lowDisk: false, stressed: false };
|
|
125
|
+
inventory;
|
|
126
|
+
inventoryLoaded = false;
|
|
127
|
+
scanning;
|
|
128
|
+
store;
|
|
129
|
+
now;
|
|
130
|
+
constructor(options) {
|
|
131
|
+
this.options = options;
|
|
132
|
+
this.store = options.store ?? new HousekeepingStore();
|
|
133
|
+
this.now = options.now ?? Date.now;
|
|
134
|
+
}
|
|
135
|
+
async latest() {
|
|
136
|
+
if (!this.loaded) {
|
|
137
|
+
this.current ??= await this.store.latest();
|
|
138
|
+
this.loaded = true;
|
|
139
|
+
}
|
|
140
|
+
return this.current;
|
|
141
|
+
}
|
|
142
|
+
/** One pass. Concurrent callers share the pass in flight. */
|
|
143
|
+
run(trigger = "tick", persist = true) {
|
|
144
|
+
if (this.running)
|
|
145
|
+
return this.running;
|
|
146
|
+
const pass = this.pass(trigger, persist).finally(() => { this.running = undefined; });
|
|
147
|
+
this.running = pass;
|
|
148
|
+
return pass;
|
|
149
|
+
}
|
|
150
|
+
async pass(trigger, persist) {
|
|
151
|
+
const startedAt = this.now();
|
|
152
|
+
const resources = await this.options.resources();
|
|
153
|
+
const context = { resources, now: startedAt, processes: this.options.processes, panes: this.options.panes };
|
|
154
|
+
const drafts = [], errors = [];
|
|
155
|
+
for (const check of this.options.checks ?? DEFAULT_CHECKS) {
|
|
156
|
+
try {
|
|
157
|
+
drafts.push(...await check.run(context));
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
errors.push({ check: check.name, message: error instanceof Error ? error.message.slice(0, 300) : String(error) });
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const previous = await this.latest();
|
|
164
|
+
// Pressure notifies once it was already there on the previous pass.
|
|
165
|
+
const before = new Set(previous?.items.map(item => item.id));
|
|
166
|
+
for (const draft of drafts)
|
|
167
|
+
if (draft.id && SUSTAINED.has(draft.target.name) && before.has(draft.id))
|
|
168
|
+
draft.notify = true;
|
|
169
|
+
const report = buildReport({ computer: this.options.computer, trigger, startedAt, finishedAt: this.now(), drafts, previous, health: healthOf(resources), errors });
|
|
170
|
+
if (persist) {
|
|
171
|
+
await this.store.save(report, this.now());
|
|
172
|
+
this.current = report;
|
|
173
|
+
this.loaded = true;
|
|
174
|
+
this.cachedView = undefined;
|
|
175
|
+
// Warm the view: the inbox and the overview badge read it synchronously.
|
|
176
|
+
await this.view();
|
|
177
|
+
}
|
|
178
|
+
return report;
|
|
179
|
+
}
|
|
180
|
+
async latestInventory() {
|
|
181
|
+
if (!this.inventoryLoaded) {
|
|
182
|
+
this.inventory ??= await this.store.inventory();
|
|
183
|
+
this.inventoryLoaded = true;
|
|
184
|
+
}
|
|
185
|
+
return this.inventory;
|
|
186
|
+
}
|
|
187
|
+
/** Scan the inventory in the background; concurrent callers share the scan. */
|
|
188
|
+
scan() {
|
|
189
|
+
if (this.scanning)
|
|
190
|
+
return this.scanning;
|
|
191
|
+
const run = (async () => {
|
|
192
|
+
const inventory = await scanInventory({ ...this.options.inventory, processes: this.options.processes, panes: this.options.panes, now: this.now() });
|
|
193
|
+
await this.store.setInventory(inventory);
|
|
194
|
+
this.inventory = inventory;
|
|
195
|
+
this.inventoryLoaded = true;
|
|
196
|
+
return inventory;
|
|
197
|
+
})().finally(() => { this.scanning = undefined; this.cachedView = undefined; });
|
|
198
|
+
this.scanning = run;
|
|
199
|
+
this.cachedView = undefined;
|
|
200
|
+
return run;
|
|
201
|
+
}
|
|
202
|
+
/** The phone's view of the newest report; undefined before the first pass. */
|
|
203
|
+
async view(includeDismissed = false, includeInventory = false) {
|
|
204
|
+
const plain = !includeDismissed && !includeInventory;
|
|
205
|
+
if (plain && this.cachedView)
|
|
206
|
+
return this.cachedView;
|
|
207
|
+
const report = await this.latest();
|
|
208
|
+
if (!report)
|
|
209
|
+
return undefined;
|
|
210
|
+
const scanned = await this.latestInventory();
|
|
211
|
+
const inventory = scanned ? { collectedAt: scanned.collectedAt, scanning: Boolean(this.scanning),
|
|
212
|
+
ids: [...scanned.worktrees, ...scanned.space, ...scanned.sessions].map(row => row.action?.id ?? row.id) } : undefined;
|
|
213
|
+
const view = viewOf(report, { cleaned: await this.store.cleaned(this.now()), dismissed: await this.store.dismissed(), includeDismissed,
|
|
214
|
+
nextCheckAt: new Date(Date.parse(report.generatedAt) + TICK_MS).toISOString(), ...(inventory ? { inventory } : {}),
|
|
215
|
+
...(includeInventory && scanned ? { include: inventoryOf(scanned, Boolean(this.scanning), this.now() - Date.parse(scanned.collectedAt) > STALE_MS) } : {}) });
|
|
216
|
+
if (plain)
|
|
217
|
+
this.cachedView = view;
|
|
218
|
+
return view;
|
|
219
|
+
}
|
|
220
|
+
/** The overview badge, from the cached view: no pass, no git. */
|
|
221
|
+
async badge() {
|
|
222
|
+
const view = await this.view();
|
|
223
|
+
return view ? badgeOf(view, this.now()) : undefined;
|
|
224
|
+
}
|
|
225
|
+
/** Called with each resource read: a fresh drop below the disk floor or a
|
|
226
|
+
* fresh stressed state runs a pass now rather than at the next tick. */
|
|
227
|
+
observe(resources) {
|
|
228
|
+
const lowDisk = !!resources.disk && resources.disk.freeBytes < DISK_FLOOR_BYTES;
|
|
229
|
+
const stressed = resources.level === "stressed";
|
|
230
|
+
const edge = lowDisk && !this.lastEdge.lowDisk ? "low-disk" : stressed && !this.lastEdge.stressed ? "high-load" : undefined;
|
|
231
|
+
this.lastEdge = { lowDisk, stressed };
|
|
232
|
+
return edge ? this.run(edge) : undefined;
|
|
233
|
+
}
|
|
234
|
+
/** Warnings worth waking the owner for, as owner-inbox sources keyed by item
|
|
235
|
+
* id: a reworded finding stays one row, which resolves itself when it goes. */
|
|
236
|
+
inboxSources() {
|
|
237
|
+
const view = this.cachedView;
|
|
238
|
+
if (!view || !this.current)
|
|
239
|
+
return [];
|
|
240
|
+
return view.warnings.filter(item => item.notify).map(item => ({
|
|
241
|
+
source: `housekeeping:${item.id}`, kind: "needs-you", title: `Housekeeping on ${this.current.computer}: ${item.title}`.slice(0, 500),
|
|
242
|
+
}));
|
|
243
|
+
}
|
|
244
|
+
serial(work) {
|
|
245
|
+
const next = this.queue.then(work, work);
|
|
246
|
+
this.queue = next.catch(() => { });
|
|
247
|
+
return next;
|
|
248
|
+
}
|
|
249
|
+
/** Hide items until their state changes. Unknown ids are ignored. */
|
|
250
|
+
dismiss(ids) {
|
|
251
|
+
return this.serial(async () => {
|
|
252
|
+
const report = await this.latest();
|
|
253
|
+
const marks = await this.store.dismissed();
|
|
254
|
+
const at = new Date(this.now()).toISOString();
|
|
255
|
+
for (const item of report?.items ?? [])
|
|
256
|
+
if (ids.includes(item.id))
|
|
257
|
+
marks.set(item.id, { fingerprint: item.fingerprint, at });
|
|
258
|
+
await this.store.setDismissed(marks, this.now());
|
|
259
|
+
this.cachedView = undefined;
|
|
260
|
+
return { revision: (await this.view())?.revision ?? "" };
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
restore(ids) {
|
|
264
|
+
return this.serial(async () => {
|
|
265
|
+
const marks = await this.store.dismissed();
|
|
266
|
+
for (const id of ids)
|
|
267
|
+
marks.delete(id);
|
|
268
|
+
await this.store.setDismissed(marks, this.now());
|
|
269
|
+
this.cachedView = undefined;
|
|
270
|
+
return { revision: (await this.view())?.revision ?? "" };
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Apply the owner's approval. A fresh pass runs first and each id is judged
|
|
275
|
+
* against it: an id that is no longer there (its state changed) is `gone`,
|
|
276
|
+
* a kept item or a warning is `refused`, and an action re-checks safety
|
|
277
|
+
* against the disk itself as it runs. Work past APPROVE_BUDGET_MS comes back
|
|
278
|
+
* `started` and finishes in the background, landing in `cleaned`.
|
|
279
|
+
*/
|
|
280
|
+
approve(ids, by) {
|
|
281
|
+
return this.serial(async () => {
|
|
282
|
+
const started = this.now();
|
|
283
|
+
const fresh = await this.run("approve");
|
|
284
|
+
const items = new Map(fresh.items.map(item => [item.id, item]));
|
|
285
|
+
const results = [];
|
|
286
|
+
const later = [];
|
|
287
|
+
let acted = false;
|
|
288
|
+
for (const id of ids) {
|
|
289
|
+
const item = items.get(id) ?? await this.inventoryItem(id);
|
|
290
|
+
if (!item) {
|
|
291
|
+
results.push({ id, status: "gone" });
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
if (item.section === "kept") {
|
|
295
|
+
results.push({ id, status: "refused", reason: plainReason(item.blockers ?? []) || item.reason });
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
if (item.section === "warning") {
|
|
299
|
+
results.push({ id, status: "refused", reason: "This is a warning; there is nothing to apply." });
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
if (!item.action || !EXECUTORS[item.action]) {
|
|
303
|
+
results.push({ id, status: "refused", reason: "This computer's Hook can't do that yet." });
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
if (this.now() - started > APPROVE_BUDGET_MS) {
|
|
307
|
+
later.push(item);
|
|
308
|
+
results.push({ id, status: "started" });
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
const outcome = await this.apply(item, by);
|
|
312
|
+
acted ||= outcome.status === "done";
|
|
313
|
+
results.push(outcome.status === "done" ? { id, status: "done", freedBytes: outcome.freedBytes } : { id, status: outcome.status, reason: outcome.reason });
|
|
314
|
+
}
|
|
315
|
+
if (later.length)
|
|
316
|
+
void (async () => { for (const item of later)
|
|
317
|
+
await this.apply(item, by); await this.run("approve"); })().catch(() => { });
|
|
318
|
+
if (acted)
|
|
319
|
+
await this.run("approve");
|
|
320
|
+
return { results, revision: (await this.view())?.revision ?? "" };
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
async freeBytes() {
|
|
324
|
+
if (this.options.freeBytes)
|
|
325
|
+
return this.options.freeBytes();
|
|
326
|
+
const stats = await statfs(homedir());
|
|
327
|
+
return Number(stats.bavail) * Number(stats.bsize);
|
|
328
|
+
}
|
|
329
|
+
async apply(item, by) {
|
|
330
|
+
const before = await this.freeBytes();
|
|
331
|
+
let outcome;
|
|
332
|
+
// The same roots the scan used, so a row is judged at approval by the rules that listed it.
|
|
333
|
+
const inv = this.options.inventory;
|
|
334
|
+
const context = { processes: this.options.processes, panes: this.options.panes, ...(inv?.rules ? { rules: inv.rules } : {}), ...(inv?.tmpRoots ? { tmpRoots: inv.tmpRoots } : {}) };
|
|
335
|
+
try {
|
|
336
|
+
outcome = await EXECUTORS[item.action](item, context, this.fresh());
|
|
337
|
+
}
|
|
338
|
+
catch (error) {
|
|
339
|
+
outcome = { status: "failed", reason: error instanceof Error ? error.message.slice(0, 300) : String(error) };
|
|
340
|
+
}
|
|
341
|
+
if (outcome.status !== "done")
|
|
342
|
+
return outcome;
|
|
343
|
+
// What the volume really gained, not what the item estimated.
|
|
344
|
+
const freedBytes = Math.max(0, (await this.freeBytes()) - before);
|
|
345
|
+
await this.store.addCleaned({ id: item.id, at: new Date(this.now()).toISOString(), area: item.area, kind: item.kind, title: item.title, target: item.target,
|
|
346
|
+
freedBytes, ...(item.sizeBytes !== undefined ? { reportedBytes: item.sizeBytes } : {}), by }, this.now());
|
|
347
|
+
// The row is gone from what the phone sees until the next scan confirms it.
|
|
348
|
+
if (this.inventory) {
|
|
349
|
+
const keep = (rows) => rows.filter(row => row.action?.id !== item.fingerprint);
|
|
350
|
+
this.inventory = { ...this.inventory, worktrees: keep(this.inventory.worktrees), space: keep(this.inventory.space), sessions: keep(this.inventory.sessions) };
|
|
351
|
+
await this.store.setInventory(this.inventory);
|
|
352
|
+
}
|
|
353
|
+
this.cachedView = undefined;
|
|
354
|
+
return { status: "done", freedBytes };
|
|
355
|
+
}
|
|
356
|
+
/** An inventory row (prefixed id) as an approvable item; it is re-checked live by its executor. */
|
|
357
|
+
async inventoryItem(id) {
|
|
358
|
+
const inventory = await this.latestInventory();
|
|
359
|
+
if (!inventory)
|
|
360
|
+
return undefined;
|
|
361
|
+
const tree = inventory.worktrees.find(row => row.action.id === id);
|
|
362
|
+
const room = inventory.space.find(row => row.action?.id === id);
|
|
363
|
+
const pane = inventory.sessions.find(row => row.action.id === id);
|
|
364
|
+
const found = tree ? { section: "worktrees", row: tree } : room ? { section: "space", row: room } : pane ? { section: "sessions", row: pane } : undefined;
|
|
365
|
+
if (!found)
|
|
366
|
+
return undefined;
|
|
367
|
+
// The fingerprint holds the row's own action id, which is how a handled row leaves the inventory.
|
|
368
|
+
const base = { section: "suggestion", since: inventory.collectedAt, id, reason: "" };
|
|
369
|
+
if (found.section === "worktrees") {
|
|
370
|
+
const tree = found.row;
|
|
371
|
+
return { ...base, fingerprint: tree.action.id, area: "worktrees", kind: "worktree", title: path.basename(tree.path),
|
|
372
|
+
target: { path: tree.path, repo: tree.repo, ...(tree.branch ? { branch: tree.branch } : {}) }, action: "remove-worktree",
|
|
373
|
+
...(tree.sizeBytes !== undefined ? { sizeBytes: tree.sizeBytes } : {}) };
|
|
374
|
+
}
|
|
375
|
+
if (found.section === "space") {
|
|
376
|
+
const room = found.row;
|
|
377
|
+
if (!room.action)
|
|
378
|
+
return undefined;
|
|
379
|
+
return { ...base, fingerprint: room.action.id, area: room.area, kind: room.kind === "simulator" ? "simulator" : room.kind === "docker" ? "docker" : room.kind === "tmp" ? "tmp" : "cache",
|
|
380
|
+
title: room.title, target: { ...(room.path ? { path: room.path } : {}), ...(room.udid ? { udid: room.udid } : {}), ...(room.kind === "docker" ? { name: "builder" } : {}) },
|
|
381
|
+
action: room.action.kind, sizeBytes: room.sizeBytes };
|
|
382
|
+
}
|
|
383
|
+
const session = found.row;
|
|
384
|
+
return { ...base, fingerprint: session.action.id, area: "sessions", kind: "pane", title: session.pane.label ?? session.title ?? session.pane.target.pane,
|
|
385
|
+
target: { name: `${session.pane.target.server}/${session.pane.target.pane}` }, action: "close-pane", pane: session.pane };
|
|
386
|
+
}
|
|
387
|
+
/** Live state for executors: fresh sessions and dispatches, never the scan's copy. */
|
|
388
|
+
fresh() {
|
|
389
|
+
const inv = this.options.inventory;
|
|
390
|
+
return {
|
|
391
|
+
sessions: async () => (await inv?.sessions?.()) ?? [],
|
|
392
|
+
dispatches: async () => { if (!inv?.dispatches)
|
|
393
|
+
throw new Error("dispatches unavailable"); return inv.dispatches(); },
|
|
394
|
+
closePane: this.options.closePane,
|
|
395
|
+
command: this.options.command ?? (async (file, args) => { await promisify(execFile)(file, args, { timeout: 120_000 }); }),
|
|
396
|
+
xcodebuildRunning: inv?.xcodebuildRunning ?? (async () => false),
|
|
397
|
+
simulators: inv?.simulators,
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
async function simulatorAction(item, deps, verb) {
|
|
402
|
+
const udid = item.target.udid;
|
|
403
|
+
if (!udid || !/^[A-F0-9-]{36}$/i.test(udid))
|
|
404
|
+
return { status: "refused", reason: "The item names no simulator." };
|
|
405
|
+
if (await deps.xcodebuildRunning())
|
|
406
|
+
return { status: "refused", reason: "An Xcode build or test is running." };
|
|
407
|
+
const sim = (await deps.simulators?.() ?? []).find(row => row.udid === udid.toUpperCase());
|
|
408
|
+
if (!sim)
|
|
409
|
+
return { status: "refused", reason: "The simulator is already gone." };
|
|
410
|
+
if (verb === "delete" && sim.state !== "Shutdown")
|
|
411
|
+
return { status: "refused", reason: "It is running; shut it down first." };
|
|
412
|
+
if (verb === "shutdown" && sim.state !== "Booted")
|
|
413
|
+
return { status: "refused", reason: "It isn't running." };
|
|
414
|
+
await deps.command("/usr/bin/xcrun", ["simctl", verb, udid]);
|
|
415
|
+
return { status: "done", freedBytes: 0 };
|
|
416
|
+
}
|
|
417
|
+
/** What each action does once approved; every one goes through safety.ts. */
|
|
418
|
+
const EXECUTORS = {
|
|
419
|
+
"remove-worktree": async (item, sources) => {
|
|
420
|
+
if (!item.target.path)
|
|
421
|
+
return { status: "refused", reason: "The item names no worktree." };
|
|
422
|
+
const result = await removeWorktreeSafely(item.target.path, sources);
|
|
423
|
+
return result.removed ? { status: "done", freedBytes: 0 } : { status: "refused", reason: plainReason(result.blockers) };
|
|
424
|
+
},
|
|
425
|
+
"delete-path": async (item, sources) => {
|
|
426
|
+
if (!item.target.path)
|
|
427
|
+
return { status: "refused", reason: "The item names no path." };
|
|
428
|
+
const result = await removeApprovedPath(item.target.path, sources);
|
|
429
|
+
return result.removed ? { status: "done", freedBytes: 0 } : { status: "refused", reason: result.decision.allowed ? "" : result.decision.reason };
|
|
430
|
+
},
|
|
431
|
+
"close-pane": async (item, _sources, deps) => {
|
|
432
|
+
const pane = item.pane?.target;
|
|
433
|
+
if (!pane || !deps.closePane)
|
|
434
|
+
return { status: "refused", reason: "This computer's Hook can't close panes." };
|
|
435
|
+
const live = (await deps.sessions()).find(row => row.pane.target.server === pane.server && row.pane.target.pane === pane.pane);
|
|
436
|
+
if (!live)
|
|
437
|
+
return { status: "refused", reason: "The pane is already closed." };
|
|
438
|
+
const dispatches = await deps.dispatches().catch(() => undefined);
|
|
439
|
+
if (!dispatches)
|
|
440
|
+
return { status: "refused", reason: "Phren couldn't check its dispatches, so it stays open." };
|
|
441
|
+
const block = paneCloseBlock({ server: pane.server, pane: pane.pane, status: live.status, role: live.role }, dispatches);
|
|
442
|
+
if (block)
|
|
443
|
+
return { status: "refused", reason: block };
|
|
444
|
+
await deps.closePane(pane.server, pane.pane);
|
|
445
|
+
return { status: "done", freedBytes: 0 };
|
|
446
|
+
},
|
|
447
|
+
"shutdown-simulator": async (item, _sources, deps) => simulatorAction(item, deps, "shutdown"),
|
|
448
|
+
"delete-simulator": async (item, _sources, deps) => simulatorAction(item, deps, "delete"),
|
|
449
|
+
"prune-docker-builder": async (_item, _sources, deps) => {
|
|
450
|
+
// Build cache only, older than a week; never images, containers or volumes.
|
|
451
|
+
await deps.command("docker", ["builder", "prune", "--force", "--filter", "until=168h"]);
|
|
452
|
+
return { status: "done", freedBytes: 0 };
|
|
453
|
+
},
|
|
454
|
+
};
|
|
455
|
+
/** The inventory as the view carries it: the scan, its state, and nothing internal. */
|
|
456
|
+
function inventoryOf(scan, scanning, stale) {
|
|
457
|
+
return { collectedAt: scan.collectedAt, durationMs: scan.durationMs, ...(scanning ? { scanning: true } : {}), ...(stale ? { stale: true } : {}),
|
|
458
|
+
worktrees: scan.worktrees, space: scan.space, sessions: scan.sessions, ...(scan.errors?.length ? { errors: scan.errors } : {}) };
|
|
459
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import type { ActionKind, Area, PaneLink } from "./report.js";
|
|
2
|
+
import { type BoundPane, cacheRules, type LiveProcess, type PaneDispatch } from "./safety.js";
|
|
3
|
+
export interface InventoryAction {
|
|
4
|
+
id: string;
|
|
5
|
+
kind: ActionKind;
|
|
6
|
+
label: string;
|
|
7
|
+
allowed: boolean;
|
|
8
|
+
reason?: string;
|
|
9
|
+
confirm?: string;
|
|
10
|
+
}
|
|
11
|
+
export interface InventoryWorktree {
|
|
12
|
+
id: string;
|
|
13
|
+
repo: string;
|
|
14
|
+
branch?: string;
|
|
15
|
+
path: string;
|
|
16
|
+
main: boolean;
|
|
17
|
+
sizeBytes?: number;
|
|
18
|
+
lastCommitAt?: string;
|
|
19
|
+
dirty: number;
|
|
20
|
+
untracked: number;
|
|
21
|
+
unpushed: number;
|
|
22
|
+
stashes: number;
|
|
23
|
+
inProgress?: string;
|
|
24
|
+
locked?: true;
|
|
25
|
+
sessions: Array<{
|
|
26
|
+
pane: PaneLink;
|
|
27
|
+
agent?: string;
|
|
28
|
+
title?: string;
|
|
29
|
+
}>;
|
|
30
|
+
processes: Array<{
|
|
31
|
+
pid: number;
|
|
32
|
+
command?: string;
|
|
33
|
+
}>;
|
|
34
|
+
action: InventoryAction;
|
|
35
|
+
}
|
|
36
|
+
export type SpaceKind = "cache" | "derived-data" | "xctest-devices" | "device-support" | "simulator" | "docker" | "tmp" | "node_modules";
|
|
37
|
+
export interface InventorySpace {
|
|
38
|
+
id: string;
|
|
39
|
+
area: Area;
|
|
40
|
+
kind: SpaceKind;
|
|
41
|
+
title: string;
|
|
42
|
+
path?: string;
|
|
43
|
+
udid?: string;
|
|
44
|
+
sizeBytes: number;
|
|
45
|
+
lastUsedAt?: string;
|
|
46
|
+
action?: InventoryAction;
|
|
47
|
+
/** Who is using it now, when that is why it stays. */
|
|
48
|
+
inUse?: string;
|
|
49
|
+
/** Why a row with no action is never handled here. */
|
|
50
|
+
note?: string;
|
|
51
|
+
}
|
|
52
|
+
export interface InventorySession {
|
|
53
|
+
id: string;
|
|
54
|
+
pane: PaneLink;
|
|
55
|
+
agent?: string;
|
|
56
|
+
title?: string;
|
|
57
|
+
project?: string;
|
|
58
|
+
status?: string;
|
|
59
|
+
idleSeconds?: number;
|
|
60
|
+
cwd?: string;
|
|
61
|
+
dispatch?: string;
|
|
62
|
+
role?: string;
|
|
63
|
+
receipt?: {
|
|
64
|
+
id: string;
|
|
65
|
+
returnRead: boolean;
|
|
66
|
+
};
|
|
67
|
+
action: InventoryAction;
|
|
68
|
+
}
|
|
69
|
+
export interface Inventory {
|
|
70
|
+
collectedAt: string;
|
|
71
|
+
durationMs: number;
|
|
72
|
+
worktrees: InventoryWorktree[];
|
|
73
|
+
space: InventorySpace[];
|
|
74
|
+
sessions: InventorySession[];
|
|
75
|
+
errors?: Array<{
|
|
76
|
+
check: string;
|
|
77
|
+
message: string;
|
|
78
|
+
}>;
|
|
79
|
+
}
|
|
80
|
+
/** An agent pane as the Hook's overview shows it. */
|
|
81
|
+
export interface SessionRow {
|
|
82
|
+
pane: PaneLink;
|
|
83
|
+
agent?: string;
|
|
84
|
+
title?: string;
|
|
85
|
+
project?: string;
|
|
86
|
+
status?: string;
|
|
87
|
+
role?: string;
|
|
88
|
+
idleSeconds?: number;
|
|
89
|
+
cwd?: string;
|
|
90
|
+
dispatch?: string;
|
|
91
|
+
}
|
|
92
|
+
export interface InventoryOptions {
|
|
93
|
+
home?: string;
|
|
94
|
+
platform?: NodeJS.Platform;
|
|
95
|
+
/** Folders whose direct children are checked for checkouts. */
|
|
96
|
+
roots?: string[];
|
|
97
|
+
tmpRoots?: string[];
|
|
98
|
+
rules?: ReturnType<typeof cacheRules>;
|
|
99
|
+
processes: () => Promise<LiveProcess[]>;
|
|
100
|
+
panes: () => Promise<BoundPane[]>;
|
|
101
|
+
sessions?: () => Promise<SessionRow[]>;
|
|
102
|
+
dispatches?: () => Promise<PaneDispatch[]>;
|
|
103
|
+
/** Bytes under a path; `du` by default. Undefined when it could not be measured. */
|
|
104
|
+
sizeOf?: (target: string) => Promise<number | undefined>;
|
|
105
|
+
simulators?: () => Promise<Array<{
|
|
106
|
+
udid: string;
|
|
107
|
+
name: string;
|
|
108
|
+
state: string;
|
|
109
|
+
dataPath: string;
|
|
110
|
+
}>>;
|
|
111
|
+
docker?: () => Promise<Array<{
|
|
112
|
+
type: string;
|
|
113
|
+
sizeBytes: number;
|
|
114
|
+
reclaimableBytes: number;
|
|
115
|
+
}>>;
|
|
116
|
+
xcodebuildRunning?: () => Promise<boolean>;
|
|
117
|
+
now?: number;
|
|
118
|
+
/** How many space rows to keep. */
|
|
119
|
+
spaceLimit?: number;
|
|
120
|
+
}
|
|
121
|
+
export declare const LABELS: Record<ActionKind, string>;
|
|
122
|
+
/** An action id: the row's kind, target and state, so a changed row gets a new id. */
|
|
123
|
+
export declare function actionId(kind: ActionKind, target: string, state: unknown): string;
|
|
124
|
+
export declare function duBytes(target: string): Promise<number | undefined>;
|
|
125
|
+
/** Checkouts under the roots (their direct children, plus each repo's linked worktrees and .claude/worktrees). */
|
|
126
|
+
export declare function findCheckouts(roots: string[], limit?: number): Promise<string[]>;
|
|
127
|
+
export declare function defaultRoots(home?: string, platform?: NodeJS.Platform): string[];
|
|
128
|
+
export declare function scanInventory(options: InventoryOptions): Promise<Inventory>;
|
|
129
|
+
/** Simulators with their data folders (macOS). */
|
|
130
|
+
export declare function listSimulators(home?: string): Promise<Array<{
|
|
131
|
+
udid: string;
|
|
132
|
+
name: string;
|
|
133
|
+
state: string;
|
|
134
|
+
dataPath: string;
|
|
135
|
+
}>>;
|
|
136
|
+
export declare function parseDockerSize(text: string): number;
|
|
137
|
+
/** `docker system df`, when docker answers. */
|
|
138
|
+
export declare function dockerUsage(): Promise<Array<{
|
|
139
|
+
type: string;
|
|
140
|
+
sizeBytes: number;
|
|
141
|
+
reclaimableBytes: number;
|
|
142
|
+
}>>;
|
|
143
|
+
export declare function xcodebuildRunning(): Promise<boolean>;
|
|
144
|
+
/** Agent panes from one server's workspace overview (the Hook's `/v1/workspaces` shape). */
|
|
145
|
+
export declare function sessionRowsFromOverview(overview: Record<string, unknown>, now?: number): SessionRow[];
|