simcast-host 0.0.0-stage → 0.9.0

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.
@@ -0,0 +1,419 @@
1
+ // `simcast-host clean`: frees disk space the agent's caches use.
2
+ // planClean() lists what could go, applyClean() deletes it, cleanCmd() is the
3
+ // command (prints the plan, asks, refuses while the agent is busy).
4
+ //
5
+ // Only paths under <agentHome>/projects/ and ~/Library/Developer/Xcode/DerivedData
6
+ // are ever deleted (assertSafePath runs before each rm), and symlinks are never
7
+ // followed: sizes use lstat, and a symlinked folder on the way to a target is refused.
8
+ import fs from 'node:fs';
9
+ import fsp from 'node:fs/promises';
10
+ import os from 'node:os';
11
+ import path from 'node:path';
12
+ import readline from 'node:readline';
13
+ import { run, runOk } from './exec.js';
14
+ import { freeDiskGB } from './macinfo.js';
15
+ import { uid } from './paths.js';
16
+ import { pidAlive, readStatus } from './runtime.js';
17
+ import { agentHome, loadState, projectPaths } from './state.js';
18
+
19
+ export const DEFAULTS = { keepBuilds: 1, idleDays: 14 };
20
+ const DAY_MS = 24 * 60 * 60 * 1000;
21
+ const WALK_CONCURRENCY = 32;
22
+
23
+ const projectsRoot = () => path.join(agentHome, 'projects');
24
+ export const xcodeDerivedDataDir = () => path.join(os.homedir(), 'Library', 'Developer', 'Xcode', 'DerivedData');
25
+ export const allowedRoots = () => [projectsRoot(), xcodeDerivedDataDir()];
26
+
27
+ // Throws unless `target` is strictly inside one of `roots` and no folder between
28
+ // that root and the target is a symlink (which could point anywhere). The target
29
+ // itself may be a symlink: rm removes the link, not what it points to.
30
+ export function assertSafePath(target, roots = allowedRoots()) {
31
+ if (typeof target !== 'string' || !target) throw new Error('Refusing to delete an empty path');
32
+ const abs = path.resolve(target);
33
+ for (const root of roots.map((r) => path.resolve(r))) {
34
+ const rel = path.relative(root, abs);
35
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) continue;
36
+ const parts = rel.split(path.sep);
37
+ let dir = root;
38
+ for (const part of parts.slice(0, -1)) {
39
+ dir = path.join(dir, part);
40
+ let st;
41
+ try {
42
+ st = fs.lstatSync(dir);
43
+ } catch {
44
+ return abs; // a missing parent: nothing there to delete
45
+ }
46
+ if (st.isSymbolicLink()) throw new Error(`Refusing to delete ${abs}: ${dir} is a symlink`);
47
+ }
48
+ return abs;
49
+ }
50
+ throw new Error(`Refusing to delete ${abs}: it is not under ${roots.join(' or ')}`);
51
+ }
52
+
53
+ // Bytes used by a file or folder tree (lstat sizes; symlinks count as themselves).
54
+ // Walks folders with a bounded number of readdirs in flight.
55
+ export async function dirSize(root) {
56
+ let st;
57
+ try {
58
+ st = await fsp.lstat(root);
59
+ } catch {
60
+ return 0;
61
+ }
62
+ if (!st.isDirectory()) return st.size;
63
+ let total = st.size;
64
+ const queue = [root];
65
+ let active = 0;
66
+ const walk = async (dir) => {
67
+ let entries;
68
+ try {
69
+ entries = await fsp.readdir(dir, { withFileTypes: true });
70
+ } catch {
71
+ return;
72
+ }
73
+ await Promise.all(entries.map(async (e) => {
74
+ const full = path.join(dir, e.name);
75
+ if (e.isDirectory()) queue.push(full);
76
+ try {
77
+ const s = await fsp.lstat(full);
78
+ total += s.size;
79
+ } catch {
80
+ // gone while walking
81
+ }
82
+ }));
83
+ };
84
+ await new Promise((resolve, reject) => {
85
+ const pump = () => {
86
+ if (!queue.length && !active) return resolve();
87
+ while (active < WALK_CONCURRENCY && queue.length) {
88
+ active++;
89
+ walk(queue.pop()).then(() => {
90
+ active--;
91
+ pump();
92
+ }, reject);
93
+ }
94
+ };
95
+ pump();
96
+ });
97
+ return total;
98
+ }
99
+
100
+ function lstatOrNull(p) {
101
+ try {
102
+ return fs.lstatSync(p);
103
+ } catch {
104
+ return null;
105
+ }
106
+ }
107
+
108
+ function realDirs(dir) {
109
+ try {
110
+ return fs.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);
111
+ } catch {
112
+ return [];
113
+ }
114
+ }
115
+
116
+ // When a project was last used: state.lastRun.at, else its folder's mtime.
117
+ function lastUsed(id) {
118
+ const at = loadState(id).lastRun?.at;
119
+ const t = typeof at === 'number' ? at : Date.parse(at);
120
+ if (Number.isFinite(t)) return t;
121
+ return lstatOrNull(projectPaths(id).base)?.mtimeMs ?? 0;
122
+ }
123
+
124
+ const daysAgo = (t, now) => Math.floor((now - t) / DAY_MS);
125
+
126
+ async function unavailableSimulators() {
127
+ try {
128
+ const r = await run('xcrun', ['simctl', 'list', 'devices', 'unavailable', '-j'], { capture: true });
129
+ if (r.code !== 0) return 0;
130
+ const { devices = {} } = JSON.parse(r.stdout.toString());
131
+ return Object.values(devices).flat().filter((d) => d && d.isAvailable === false).length;
132
+ } catch {
133
+ return 0;
134
+ }
135
+ }
136
+
137
+ // [{ kind, path?, command?, bytes, reason, project?, count? }]
138
+ export async function planClean(opts = {}) {
139
+ const keepBuilds = opts.keepBuilds ?? DEFAULTS.keepBuilds;
140
+ const idleDays = opts.idleDays ?? DEFAULTS.idleDays;
141
+ const now = opts.now ?? Date.now();
142
+ const items = [];
143
+ const add = async (item) => items.push({ ...item, bytes: await dirSize(item.path) });
144
+
145
+ for (const id of realDirs(projectsRoot()).sort()) {
146
+ const p = projectPaths(id);
147
+ const used = lastUsed(id);
148
+ const idle = now - used > idleDays * DAY_MS;
149
+ const since = `last used ${daysAgo(used, now)} days ago`;
150
+ if (idle && opts.projects) {
151
+ await add({ kind: 'project', project: id, path: p.base, reason: `idle project, ${since}` });
152
+ continue;
153
+ }
154
+ const builds = lstatOrNull(p.builds)?.isDirectory()
155
+ ? fs.readdirSync(p.builds)
156
+ .map((name) => ({ name, st: lstatOrNull(path.join(p.builds, name)) }))
157
+ .filter((b) => b.st)
158
+ .sort((a, b) => b.st.mtimeMs - a.st.mtimeMs)
159
+ : [];
160
+ for (const b of builds.slice(keepBuilds)) {
161
+ await add({ kind: 'old-build', project: id, path: path.join(p.builds, b.name), reason: `older than the newest ${keepBuilds} build${keepBuilds === 1 ? '' : 's'}` });
162
+ }
163
+ if (idle && lstatOrNull(p.derived)?.isDirectory()) {
164
+ await add({ kind: 'derived-data', project: id, path: p.derived, reason: `project idle over ${idleDays} days, ${since}` });
165
+ }
166
+ }
167
+
168
+ if (opts.xcodeDerivedData) {
169
+ const dir = xcodeDerivedDataDir();
170
+ let names = [];
171
+ try {
172
+ names = fs.readdirSync(dir).sort();
173
+ } catch {
174
+ // no Xcode DerivedData
175
+ }
176
+ for (const name of names) {
177
+ await add({ kind: 'xcode-derived-data', path: path.join(dir, name), reason: "Xcode's global DerivedData" });
178
+ }
179
+ }
180
+
181
+ const count = await unavailableSimulators();
182
+ if (count > 0) {
183
+ items.push({
184
+ kind: 'unavailable-simulators',
185
+ command: ['xcrun', 'simctl', 'delete', 'unavailable'],
186
+ count,
187
+ bytes: 0,
188
+ reason: `${count} simulator${count === 1 ? '' : 's'} on runtimes that are no longer installed`,
189
+ });
190
+ }
191
+ return items;
192
+ }
193
+
194
+ // Deletes each item in order. Returns { freedBytes, errors: [{ item, message }], stopped }.
195
+ // shouldStop() is asked before each item; true ends the run there (stopped: true).
196
+ export async function applyClean(items, { onItem, shouldStop } = {}) {
197
+ let freedBytes = 0;
198
+ const errors = [];
199
+ for (const item of items) {
200
+ if (shouldStop?.()) return { freedBytes, errors, stopped: true };
201
+ try {
202
+ if (item.path) {
203
+ const safe = assertSafePath(item.path);
204
+ await fsp.rm(safe, { recursive: true, force: true, maxRetries: 3 });
205
+ } else if (item.command) {
206
+ const [cmd, ...args] = item.command;
207
+ await runOk(cmd, args);
208
+ }
209
+ freedBytes += item.bytes || 0;
210
+ onItem?.(item, null);
211
+ } catch (err) {
212
+ errors.push({ item, message: err.message });
213
+ onItem?.(item, err);
214
+ }
215
+ }
216
+ return { freedBytes, errors, stopped: false };
217
+ }
218
+
219
+ export function formatBytes(n) {
220
+ if (!n) return '0 B';
221
+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];
222
+ let i = 0;
223
+ let v = n;
224
+ while (v >= 1000 && i < units.length - 1) {
225
+ v /= 1000;
226
+ i++;
227
+ }
228
+ return `${i === 0 ? v : v.toFixed(1)} ${units[i]}`;
229
+ }
230
+
231
+ const GROUPS = [
232
+ ['old-build', (o) => `Old builds (keeping the newest ${o.keepBuilds} per project)`],
233
+ ['derived-data', (o) => `DerivedData of projects idle over ${o.idleDays} days`],
234
+ ['project', (o) => `Projects idle over ${o.idleDays} days (--projects)`],
235
+ ['xcode-derived-data', () => "Xcode's DerivedData (--xcode-derived-data)"],
236
+ ['unavailable-simulators', () => 'Unavailable simulators'],
237
+ ];
238
+ const SHOW_PER_GROUP = 20;
239
+
240
+ // `idWidth` lines up the project column within a group.
241
+ function itemLabel(item, idWidth = 0) {
242
+ if (item.kind === 'unavailable-simulators') return `${item.count} device${item.count === 1 ? '' : 's'} (xcrun simctl delete unavailable)`;
243
+ if (item.kind === 'xcode-derived-data') return path.basename(item.path);
244
+ const rel = path.relative(projectPaths(item.project).base, item.path).split(path.sep).join('/');
245
+ return rel ? `${item.project.padEnd(idWidth)} ${rel}` : item.project;
246
+ }
247
+
248
+ function printPlan(items, opts) {
249
+ for (const [kind, title] of GROUPS) {
250
+ const group = items.filter((i) => i.kind === kind);
251
+ if (!group.length) continue;
252
+ console.log(`${title(opts)}:`);
253
+ const idWidth = Math.max(0, ...group.map((i) => i.project?.length || 0));
254
+ const labels = group.map((i) => itemLabel(i, idWidth));
255
+ const width = Math.max(...labels.map((l) => l.length));
256
+ group.slice(0, SHOW_PER_GROUP).forEach((item, i) => {
257
+ const size = kind === 'unavailable-simulators' ? '' : ` ${formatBytes(item.bytes).padStart(8)}`;
258
+ console.log(` ${labels[i].padEnd(kind === 'unavailable-simulators' ? 0 : width)}${size}`);
259
+ });
260
+ if (group.length > SHOW_PER_GROUP) {
261
+ const rest = group.slice(SHOW_PER_GROUP);
262
+ console.log(` ... and ${rest.length} more (${formatBytes(rest.reduce((s, i) => s + i.bytes, 0))})`);
263
+ }
264
+ console.log('');
265
+ }
266
+ console.log(`Total: ${formatBytes(items.reduce((s, i) => s + i.bytes, 0))}`);
267
+ }
268
+
269
+ const USAGE = `Usage: simcast-host clean [--yes] [--dry-run] [--keep-builds N] [--idle-days N]
270
+ [--projects] [--xcode-derived-data] [--force] [--json]
271
+
272
+ Frees disk space: old builds (keeps the newest ${DEFAULTS.keepBuilds} per project), DerivedData of
273
+ projects idle over ${DEFAULTS.idleDays} days, and unavailable simulators.
274
+ --projects also delete whole idle projects (the next run syncs and builds again)
275
+ --xcode-derived-data also empty ~/Library/Developer/Xcode/DerivedData
276
+ --force clean even while the agent is busy
277
+ --yes don't ask; without a terminal, clean only runs with --yes
278
+ `;
279
+
280
+ // Returns the options, or a usage error message.
281
+ export function parseCleanArgs(args) {
282
+ const opts = { ...DEFAULTS, yes: false, dryRun: false, projects: false, xcodeDerivedData: false, force: false, json: false, help: false };
283
+ const bool = { '--yes': 'yes', '-y': 'yes', '--dry-run': 'dryRun', '--projects': 'projects', '--xcode-derived-data': 'xcodeDerivedData', '--force': 'force', '--json': 'json', '--help': 'help', '-h': 'help' };
284
+ const num = { '--keep-builds': 'keepBuilds', '--idle-days': 'idleDays' };
285
+ for (let i = 0; i < args.length; i++) {
286
+ let arg = args[i];
287
+ let value;
288
+ const eq = arg.indexOf('=');
289
+ if (arg.startsWith('--') && eq > 0) {
290
+ value = arg.slice(eq + 1);
291
+ arg = arg.slice(0, eq);
292
+ }
293
+ if (bool[arg] && value === undefined) {
294
+ opts[bool[arg]] = true;
295
+ } else if (num[arg]) {
296
+ if (value === undefined) value = args[++i];
297
+ if (value === undefined || !/^\d+$/.test(value)) return `${arg} needs a whole number (got ${value ?? 'nothing'})`;
298
+ opts[num[arg]] = Number(value);
299
+ } else {
300
+ return `Unknown option: ${args[i]}`;
301
+ }
302
+ }
303
+ return opts;
304
+ }
305
+
306
+ function ask(question) {
307
+ return new Promise((resolve) => {
308
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
309
+ let answered = false;
310
+ rl.question(question, (answer) => {
311
+ answered = true;
312
+ rl.close();
313
+ resolve(/^y(es)?$/i.test(answer.trim()));
314
+ });
315
+ rl.on('close', () => {
316
+ if (!answered) resolve(false);
317
+ });
318
+ });
319
+ }
320
+
321
+ const isTTY = () => process.env.SIMCAST_ASSUME_TTY === '1' || Boolean(process.stdin.isTTY && process.stdout.isTTY);
322
+
323
+ // What the running agent is busy with (a sync or build), or null. A busy flag
324
+ // left by a dead agent doesn't count.
325
+ function agentBusy() {
326
+ const status = readStatus();
327
+ return status?.busy && pidAlive(status.pid) ? status.busy : null;
328
+ }
329
+
330
+ // hooks (tests only): afterPlan() runs once the plan is made, afterItem() after
331
+ // each deleted item, so a test can make the agent "busy" at those points.
332
+ export async function cleanCmd(args = [], hooks = {}) {
333
+ const opts = parseCleanArgs(args);
334
+ if (typeof opts === 'string') {
335
+ console.error(`${opts}\n\n${USAGE}`);
336
+ return 64;
337
+ }
338
+ if (opts.help) {
339
+ process.stdout.write(USAGE);
340
+ return 0;
341
+ }
342
+ if (uid() === 0) {
343
+ console.error("Don't run simcast-host clean as root (sudo). Run it as your own user.");
344
+ return 1;
345
+ }
346
+ const busyAtStart = agentBusy();
347
+ if (busyAtStart && !opts.force) {
348
+ console.error(`The agent is busy (${busyAtStart}). Try again when it finishes, or use --force.`);
349
+ return 1;
350
+ }
351
+
352
+ const log = opts.json ? () => {} : (...a) => console.log(...a);
353
+ const freeBefore = await freeDiskGB();
354
+ let items;
355
+ try {
356
+ items = await planClean(opts);
357
+ } catch (err) {
358
+ console.error(`Could not plan the clean: ${err.message}`);
359
+ return 1;
360
+ }
361
+ await hooks.afterPlan?.();
362
+
363
+ // --dry-run always just prints; without a terminal, --yes is needed to delete.
364
+ const dryRun = opts.dryRun || (!opts.yes && (opts.json || !isTTY()));
365
+ if (!opts.json) {
366
+ if (freeBefore != null) log(`Free disk: ${freeBefore} GB\n`);
367
+ if (!items.length) {
368
+ log('Nothing to clean.');
369
+ return 0;
370
+ }
371
+ printPlan(items, opts);
372
+ log('');
373
+ }
374
+ if (!items.length) {
375
+ console.log(JSON.stringify({ items, freedBytes: 0, dryRun, errors: [], freeGBBefore: freeBefore, freeGBAfter: freeBefore }, null, 2));
376
+ return 0;
377
+ }
378
+ if (!dryRun && !opts.yes) {
379
+ if (!(await ask('Delete these? [y/N] '))) {
380
+ log('Nothing was deleted.');
381
+ return 0;
382
+ }
383
+ }
384
+ if (dryRun) {
385
+ if (opts.json) {
386
+ console.log(JSON.stringify({ items, freedBytes: 0, dryRun: true, errors: [], freeGBBefore: freeBefore, freeGBAfter: freeBefore }, null, 2));
387
+ } else {
388
+ log(opts.dryRun ? 'Dry run: nothing was deleted.' : 'Dry run: nothing was deleted. Run with --yes to delete.');
389
+ }
390
+ return 0;
391
+ }
392
+
393
+ // The agent may have started a build while we planned or asked (and the busy
394
+ // flag is on disk at once, see claim()), so look again before and between items.
395
+ const busyNow = () => !opts.force && Boolean(agentBusy());
396
+ if (busyNow()) {
397
+ console.error('The agent became busy, stopped; run clean again later.');
398
+ return 1;
399
+ }
400
+ const { freedBytes, errors, stopped } = await applyClean(items, {
401
+ onItem: (item, err) => {
402
+ if (err) console.error(`Could not delete ${item.path || item.command.join(' ')}: ${err.message}`);
403
+ hooks.afterItem?.(item);
404
+ },
405
+ shouldStop: busyNow,
406
+ });
407
+ if (stopped) {
408
+ console.error(`The agent became busy, stopped; run clean again later.${freedBytes ? ` Freed ${formatBytes(freedBytes)} so far.` : ''}`);
409
+ return 1;
410
+ }
411
+ const freeAfter = await freeDiskGB();
412
+ if (opts.json) {
413
+ console.log(JSON.stringify({ items, freedBytes, dryRun: false, errors: errors.map((e) => ({ kind: e.item.kind, path: e.item.path, message: e.message })), freeGBBefore: freeBefore, freeGBAfter: freeAfter }, null, 2));
414
+ } else {
415
+ log(`Freed ${formatBytes(freedBytes)}.`);
416
+ if (freeAfter != null) log(`Free disk: ${freeAfter} GB${freeBefore != null ? ` (was ${freeBefore} GB)` : ''}`);
417
+ }
418
+ return errors.length ? 1 : 0;
419
+ }