rvlib-shipkit 2.23.0 → 2.24.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.
Files changed (97) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/package.json +1 -1
  3. package/src/agent-time/render.ts +28 -14
  4. package/src/agent-time/report.ts +46 -25
  5. package/src/agent-time/store.ts +30 -10
  6. package/src/agent-time/timeline.ts +43 -15
  7. package/src/asks/asks-queue.ts +32 -11
  8. package/src/checks/SK044-behind-upstream.check.ts +38 -0
  9. package/src/cli/cmd_Asks.ts +2 -0
  10. package/src/cli/cmd_Backup.ts +7 -5
  11. package/src/cli/cmd_Bump.ts +1 -0
  12. package/src/cli/cmd_Capacity.ts +26 -0
  13. package/src/cli/cmd_Check.ts +1 -0
  14. package/src/cli/cmd_Checks.ts +1 -0
  15. package/src/cli/cmd_Ci.ts +1 -0
  16. package/src/cli/cmd_Commands.ts +50 -14
  17. package/src/cli/cmd_Home.ts +0 -29
  18. package/src/cli/cmd_Hooks.ts +1 -0
  19. package/src/cli/cmd_Mv.ts +1 -0
  20. package/src/cli/cmd_Reflect.ts +1 -0
  21. package/src/cli/cmd_Releases.ts +1 -0
  22. package/src/cli/cmd_Review.ts +97 -14
  23. package/src/cli/cmd_Secret.ts +41 -2
  24. package/src/cli/cmd_Shot.ts +1 -0
  25. package/src/cli/cmd_Status.ts +1 -0
  26. package/src/cli/cmd_Time.ts +3 -1
  27. package/src/cli/cmd_Tmp.ts +82 -0
  28. package/src/cli/cmd_Wiki.ts +1 -0
  29. package/src/cli/registry.ts +13 -1
  30. package/src/collections/pings.ts +1 -1
  31. package/src/core/capacity.ts +71 -0
  32. package/src/core/check-runner.ts +86 -15
  33. package/src/core/motherhome.ts +67 -9
  34. package/src/core/slots.ts +49 -12
  35. package/src/core/trace-audit.ts +4 -1
  36. package/src/drill/run.ts +5 -2
  37. package/src/home/gui-app/ShipkitGui.swift +1 -0
  38. package/src/home/home-launchd.ts +11 -3
  39. package/src/home/home-routes.ts +11 -4
  40. package/src/home/machine-host.ts +65 -0
  41. package/src/home/machine-stores.ts +19 -17
  42. package/src/home/machine-temp.ts +493 -0
  43. package/src/home/other-macs.ts +74 -0
  44. package/src/home/run-daemon.ts +10 -2
  45. package/src/home/serve-web.ts +2 -2
  46. package/src/home/via-hub.ts +6 -1
  47. package/src/init-repo.ts +7 -3
  48. package/src/ledger/ledger.ts +6 -0
  49. package/src/ledger/store.ts +6 -0
  50. package/src/media-store/backup/keys.ts +21 -6
  51. package/src/media-store/backup/manifest.ts +52 -11
  52. package/src/media-store/backup/restore.ts +17 -10
  53. package/src/media-store/backup/run.ts +5 -2
  54. package/src/media-store/backup/sources.ts +2 -1
  55. package/src/mv/mv-md.ts +121 -42
  56. package/src/reflect/transcript.ts +56 -11
  57. package/src/releases/from-card.ts +45 -3
  58. package/src/releases/model.ts +6 -0
  59. package/src/releases/store.ts +8 -1
  60. package/src/repo-config.ts +5 -3
  61. package/src/review/cells.ts +24 -3
  62. package/src/review/format.ts +33 -9
  63. package/src/review/media-kind.ts +14 -11
  64. package/src/review/media-read.ts +6 -5
  65. package/src/review/model.ts +71 -3
  66. package/src/review/paste.ts +2 -1
  67. package/src/review/previews.ts +123 -36
  68. package/src/review/routes.ts +29 -18
  69. package/src/review/store.ts +74 -12
  70. package/src/review/threads.ts +7 -5
  71. package/src/secrets/copy.ts +110 -0
  72. package/src/secrets/list.ts +17 -7
  73. package/src/serve/hub-app/home-strip.css +5 -0
  74. package/src/serve/hub-app/home-strip.tsx +18 -0
  75. package/src/serve/hub-app/hub-app.tsx +2 -1
  76. package/src/serve/hub-app/hub.css +14 -0
  77. package/src/serve/hub-app/inbox.css +1 -0
  78. package/src/serve/hub-app/pull-refresh.tsx +88 -0
  79. package/src/serve/hub-app/review/review-cells.tsx +52 -13
  80. package/src/serve/hub-app/review/review-list.tsx +6 -1
  81. package/src/serve/hub-app/review/review-st.ts +6 -5
  82. package/src/serve/hub-app/review/review-thread.tsx +3 -1
  83. package/src/serve/hub-app/review/review-views.tsx +18 -11
  84. package/src/serve/hub-app/review/thread-st.ts +82 -14
  85. package/src/serve/hub-app/review.css +15 -2
  86. package/src/serve/hub-runtime.ts +2 -1
  87. package/src/serve/run-serve.ts +4 -2
  88. package/src/serve/serve-hub.ts +9 -2
  89. package/src/suite/child-tools.ts +45 -0
  90. package/src/suite/judge-suites.ts +10 -22
  91. package/src/suite/select.ts +83 -8
  92. package/src/suite/suite-cli.ts +38 -14
  93. package/src/suite/suite-cores.ts +68 -0
  94. package/src/suite/suite-reads-preload.ts +8 -6
  95. package/src/ts/config.ts +44 -0
  96. package/src/ts/rename.ts +11 -1
  97. package/src/home/claude-temp.ts +0 -139
@@ -1,5 +1,5 @@
1
1
  // the machine's own stores and their caps (core/retention.ts owns the model):
2
- // every log under the home dir, and the gui window's Chrome profile. And the
2
+ // the temp folders, every log under the home dir, and the gui window's Chrome profile. And the
3
3
  // daemon's retention job that sweeps every store, the repos' and these, in a
4
4
  // child process (daemon-jobs.ts).
5
5
  import { existsSync, lstatSync, readdirSync, rmSync, statSync } from 'fs'
@@ -7,7 +7,7 @@ import { join } from 'path'
7
7
  import { repoStores, sweepStores, walkUse, type Store } from '../core/retention.ts'
8
8
  import { capLog, LOG_MAX_BYTES } from './supervise.ts'
9
9
  import { machineSet } from '../core/machine-db.ts'
10
- import { CLAUDE_TEMP_GUARD_MS, CLAUDE_TEMP_MAX_BYTES, claudeTempAuto, claudeTempRoot, planClaudeTemp, trimClaudeTemp } from './claude-temp.ts'
10
+ import { sweepTemp, tempAuto, tempAutoAt, tempRoots, tempUse } from './machine-temp.ts'
11
11
 
12
12
  /** a log nothing wrote for this long belongs to a process that is gone (a
13
13
  * repo removed, a resource dropped) */
@@ -54,23 +54,24 @@ const profileInUse = (profile: string): boolean => {
54
54
  try { return lstatSync(join(profile, 'SingletonLock')).isSymbolicLink() } catch { return false }
55
55
  }
56
56
 
57
- /** claude code's session scratch, once the owner's switch is on (claude-temp.ts): what the sessions idle past the
58
- * guard hold, under its cap */
59
- function claudeTemp(o: { print: (l: string) => void; printErr: (l: string) => void }): Store[] {
60
- const root = claudeTempRoot()
61
- if (root == null || !claudeTempAuto()) return []
57
+ /** a temp pass this old stopped running: the sweep is hourly */
58
+ export const TEMP_PASS_MAX_MS = 6 * 60 * 60 * 1000
59
+
60
+ /** the machine's temp folders, once the owner's switch is on (machine-temp.ts): one store for the three roots, since
61
+ * one pass sweeps them all. It reads what the last pass kept, with no walk, and its age is the last pass's (the
62
+ * switch's, before the first one), so a sweep that stopped or never started is loud */
63
+ function temp(o: { print: (l: string) => void; printErr: (l: string) => void }): Store[] {
64
+ if (!tempAuto()) return []
62
65
  return [{
63
- id: 'claude temp',
64
- where: `${root} (sessions idle past ${CLAUDE_TEMP_GUARD_MS / 3_600_000} h)`,
65
- cap: { maxBytes: CLAUDE_TEMP_MAX_BYTES },
66
+ id: 'temp folders',
67
+ where: `${tempRoots().map((r) => r.path).join(', ')} (the age is the last pass's: sk tmp)`,
68
+ cap: { maxAgeMs: TEMP_PASS_MAX_MS },
66
69
  measure: () => {
67
- try {
68
- const p = planClaudeTemp(root, { now: Date.now(), printErr: o.printErr })
69
- const all = p == null ? [] : [...p.keep, ...p.drop]
70
- return { count: all.length, oldestAt: all.length === 0 ? null : Math.min(...all.map((u) => u.at)), bytes: all.reduce((n, u) => n + u.bytes, 0), largestFile: 0 }
71
- } catch { return null }
70
+ const use = tempUse()
71
+ const kept = use?.passes ?? []
72
+ return { count: kept.reduce((n, p) => n + p.kept, 0), oldestAt: use?.at ?? tempAutoAt() ?? Date.now(), bytes: kept.reduce((n, p) => n + p.keptBytes, 0), largestFile: 0 }
72
73
  },
73
- sweep: (now) => { trimClaudeTemp(root, { now, print: o.print, printErr: o.printErr }) },
74
+ sweep: (now) => { sweepTemp({ now, print: o.print, printErr: o.printErr }) },
74
75
  }]
75
76
  }
76
77
 
@@ -79,7 +80,6 @@ const stderr = (l: string): void => void process.stderr.write(`${l}\n`)
79
80
  export function machineStores(dir: string, o: { print?: (l: string) => void; printErr?: (l: string) => void } = {}): Store[] {
80
81
  const profile = join(dir, 'gui-profile')
81
82
  return [
82
- ...claudeTemp({ print: o.print ?? stderr, printErr: o.printErr ?? stderr }),
83
83
  {
84
84
  id: 'home logs',
85
85
  where: `${dir}/**/*.log`,
@@ -106,6 +106,8 @@ export function machineStores(dir: string, o: { print?: (l: string) => void; pri
106
106
  for (const d of GUI_CACHE_DIRS) rmSync(join(profile, d), { recursive: true, force: true })
107
107
  },
108
108
  },
109
+ // last: its walk is the long one, and the stores above never wait on it
110
+ ...temp({ print: o.print ?? stderr, printErr: o.printErr ?? stderr }),
109
111
  ]
110
112
  }
111
113
 
@@ -0,0 +1,493 @@
1
+ // the machine's temp folders: claude code's per session scratch (`<tmp>/claude-<uid>/<project>/<session>/`), the
2
+ // user's temp dir and /tmp. Nothing trims them but a reboot, and every agent and test run writes there. A pass of the
3
+ // retention sweep (machine-stores.ts) deletes each unit nothing wrote for the guard hours and no live process uses,
4
+ // and keeps what it measured, so `sk tmp` answers with no walk.
5
+ //
6
+ // the one constraint a reader breaks first: this deletes for real. Nothing outside a checked root, no link followed
7
+ // (lstat everywhere, a link is removed as a link), nothing another user owns, nothing a live process holds, no git
8
+ // work a remote does not hold: with no reading of the live processes the pass deletes nothing.
9
+ import { closeSync, existsSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, rmSync, statfsSync, writeSync, type Stats } from 'node:fs'
10
+ import { homedir } from 'node:os'
11
+ import { basename, dirname, join, sep } from 'node:path'
12
+ import { gitBin } from '../core/git-bin.ts'
13
+ import { machineDbPath, machineGet, machineSet } from '../core/machine-db.ts'
14
+
15
+ /** a unit written this recently is never touched while the disk has room */
16
+ export const TEMP_GUARD_MS = 24 * 60 * 60 * 1000
17
+ /** under the floor, a unit idle this long can go, the largest first, until the disk is back over the floor */
18
+ export const TEMP_GUARD_LOW_MS = 6 * 60 * 60 * 1000
19
+ /** free space under this is low */
20
+ export const TEMP_FLOOR_BYTES = 40e9
21
+ /** what claude's idle session scratch may hold while the disk has room: a session resumed finds its files */
22
+ export const CLAUDE_TEMP_MAX_BYTES = 5e9
23
+ /** a claude session's own folders (`scratchpad/`, `tasks/`) outlive their pieces this long: a session that waits a
24
+ * night on its owner is not over */
25
+ export const SESSION_SHELL_MS = 7 * 24 * 60 * 60 * 1000
26
+ /** in the user's temp dir, which macOS daemons and apps share, a child with a fixed name (`itunescloudd`, `xcrun_db`)
27
+ * is a unit only when it is this big: no daemon's folder is, a repo script's scratch folder can be */
28
+ export const FIXED_NAME_MIN_BYTES = 100e6
29
+ /** a unit known fresh is counted this far, then its size is a floor */
30
+ const MEASURE_MAX_ENTRIES = 50_000
31
+ /** a deleted unit this big gets its own line */
32
+ const SAY_BYTES = 100e6
33
+
34
+ const AUTO_KEY = 'temp-auto'
35
+ const AUTO_AT = 'temp-auto-at'
36
+ /** the owner's switch, off until it is turned on: nothing deletes before, the daemon's sweep and `sk tmp sweep` alike */
37
+ export const tempAuto = (): boolean => machineGet<boolean>(AUTO_KEY) === true
38
+ export function setTempAuto(on: boolean): boolean {
39
+ if (on && !tempAuto()) machineSet(AUTO_AT, Date.now())
40
+ return machineSet(AUTO_KEY, on)
41
+ }
42
+ /** since when the switch is on */
43
+ export const tempAutoAt = (): number | null => machineGet<number>(AUTO_AT)
44
+
45
+ /** sessions: claude's `<project>/<session>/<folder>/<piece>` tree; entries: each child is a unit */
46
+ export type RootKind = 'sessions' | 'entries'
47
+ export type TempRoot = {
48
+ id: string
49
+ path: string
50
+ kind: RootKind
51
+ capBytes: number
52
+ /** set on a root the system and apps share: a child with no temp shaped name is a unit only at this size or more */
53
+ fixedNameMinBytes?: number
54
+ }
55
+
56
+ /** the user's temp dir as the system names it, never as `$TMPDIR` says: a caller's env must not pick what is swept */
57
+ function userTemp(): string | null {
58
+ if (process.platform !== 'darwin') return null
59
+ const p = Bun.spawnSync(['getconf', 'DARWIN_USER_TEMP_DIR'], { stdout: 'pipe', stderr: 'ignore' })
60
+ const dir = p.stdout.toString().trim().replace(/\/+$/, '')
61
+ return p.exitCode === 0 && dir.startsWith('/') ? dir : null
62
+ }
63
+
64
+ /** the temp roots of this machine: claude code's (its own override, else /tmp, one folder per uid), the user's, /tmp */
65
+ export function tempRoots(env: Record<string, string | undefined> = process.env, user: string | null = userTemp()): TempRoot[] {
66
+ const uid = process.getuid?.()
67
+ if (uid == null) return []
68
+ const all: TempRoot[] = [
69
+ { id: 'claude temp', path: join(env.CLAUDE_CODE_TMPDIR || '/tmp', `claude-${uid}`), kind: 'sessions', capBytes: CLAUDE_TEMP_MAX_BYTES },
70
+ ...(user == null ? [] : [{ id: 'user temp', path: user, kind: 'entries' as const, capBytes: 0, fixedNameMinBytes: FIXED_NAME_MIN_BYTES }]),
71
+ { id: 'tmp', path: '/tmp', kind: 'entries', capBytes: 0 },
72
+ ]
73
+ const seen = new Set<string>()
74
+ return all.filter((r) => {
75
+ let real = r.path
76
+ try { real = realpathSync(r.path) } catch { /* missing: checkedRoot says so */ }
77
+ if (seen.has(real)) return false
78
+ seen.add(real)
79
+ return true
80
+ })
81
+ }
82
+
83
+ /** the root, resolved once and checked; null when it does not exist; throws on any other shape */
84
+ export function checkedRoot(root: string, kind: RootKind = 'sessions', uid = process.getuid?.()): string | null {
85
+ if (uid == null) throw new Error('no uid on this platform: the temp pass does not run')
86
+ if (root.split(/[\\/]/).includes('..')) throw new Error(`${root}: a path with .. is refused`)
87
+ let real: string
88
+ try { real = realpathSync(root) } catch (e) {
89
+ if ((e as { code?: string }).code === 'ENOENT') return null
90
+ throw e
91
+ }
92
+ const s = lstatSync(real)
93
+ if (real === sep || real === homedir() || homedir().startsWith(real + sep) || real.startsWith(homedir() + sep) || !s.isDirectory()) throw new Error(`${real}: not a temp folder of its own`)
94
+ if (kind === 'sessions') {
95
+ if (s.uid !== uid) throw new Error(`${real}: owned by uid ${s.uid}, not ${uid}`)
96
+ if (basename(real) !== `claude-${uid}`) throw new Error(`${real}: not named claude-${uid}`)
97
+ } else if (s.uid !== uid && (s.mode & 0o1000) === 0) throw new Error(`${real}: neither the user's own folder nor a shared temp folder (no sticky bit)`)
98
+ return real
99
+ }
100
+
101
+ export type Unit = { path: string; at: number; bytes: number; files: number }
102
+ /** a unit that stays, and why; `floor`: its walk stopped, the size is a least */
103
+ export type Kept = Unit & { why: string; floor?: boolean }
104
+ /** an idle unit, with every folder of it that holds a `.git` */
105
+ type Idle = Unit & { gits: string[] }
106
+ export type Plan = { root: string; drop: Idle[]; keep: Kept[]; fresh: number }
107
+
108
+ /** when an entry was last written: its content or its inode, so a tree copied with its old times is new */
109
+ const written = (s: Stats): number => Math.max(s.mtimeMs, s.ctimeMs)
110
+
111
+ type Scan = Idle & { fresh: boolean; floor: boolean; foreign: boolean }
112
+ type Ctx = { fresh: number; uid: number; stamp: (s: Stats) => number }
113
+
114
+ /** a tree's newest write, size, file count and git folders, lstat only; null when a folder of it cannot be read */
115
+ function scan(top: string, c: Ctx): Scan | null {
116
+ const r: Scan = { path: top, at: 0, bytes: 0, files: 0, gits: [], fresh: false, floor: false, foreign: false }
117
+ const stack = [top]
118
+ let seen = 0
119
+ while (stack.length > 0) {
120
+ const p = stack.pop()!
121
+ let s
122
+ try { s = lstatSync(p) } catch { continue }
123
+ r.at = Math.max(r.at, c.stamp(s))
124
+ r.bytes += s.size
125
+ if (s.uid !== c.uid) r.foreign = true
126
+ if (r.at >= c.fresh) r.fresh = true
127
+ if (r.fresh && ++seen > MEASURE_MAX_ENTRIES) { r.floor = true; return r }
128
+ if (basename(p) === '.git' && p !== top) r.gits.push(dirname(p))
129
+ if (!s.isDirectory()) { r.files++; continue }
130
+ try { for (const n of readdirSync(p)) stack.push(join(p, n)) } catch { return null }
131
+ }
132
+ return r
133
+ }
134
+
135
+ const names = (d: string, printErr: (l: string) => void): string[] => {
136
+ try { return readdirSync(d) } catch (e) {
137
+ printErr(`WARN temp: ${d} unreadable (${(e as Error).message}), skipped`)
138
+ return []
139
+ }
140
+ }
141
+ const stat = (p: string): Stats | null => {
142
+ try { return lstatSync(p) } catch { return null }
143
+ }
144
+
145
+ /** names an app, the system, the harness or bun (its `node` shim on PATH) owns in a temp folder: never a unit */
146
+ const NOT_OURS = /^\.?(com|org|net|io|dev|app)\.|^TemporaryItems$|^\.DS_Store$|^(cc|ccd|claude)[-.]|^bun-node-/
147
+ /** a name as mkdtemp or a pid makes one: a random suffix (six characters or more, one a digit or a capital) or a
148
+ * number at the end; a uuid is an app's container, never one */
149
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-/i
150
+ const TEMP_SHAPED = /[-._](?=[A-Za-z0-9_]*[A-Z0-9])[A-Za-z0-9_]{6,}$|[-._]\d+$/
151
+ export const tempShaped = (name: string): boolean => !UUID.test(name) && TEMP_SHAPED.test(name)
152
+ /** folders of claude's root the harness itself reads */
153
+ const HARNESS = new Set(['bundled-skills', 'bash-edit-diff'])
154
+
155
+ const ago = (ms: number): string => (ms >= 86_400_000 ? `${(ms / 86_400_000).toFixed(1)} d` : `${Math.max(0, ms / 3_600_000).toFixed(1)} h`)
156
+
157
+ type Found = { idle: Idle[]; keep: Kept[] }
158
+
159
+ /** one unit judged: idle, or kept with its reason */
160
+ function judge(p: string, c: Ctx, now: number, out: Found): void {
161
+ const r = scan(p, c)
162
+ if (r == null) { out.keep.push({ path: p, at: 0, bytes: 0, files: 0, why: 'a folder of it cannot be read' }); return }
163
+ const u: Unit = { path: r.path, at: r.at, bytes: r.bytes, files: r.files }
164
+ if (r.fresh) out.keep.push({ ...u, why: `written ${ago(now - r.at)} ago`, ...(r.floor ? { floor: true } : {}) })
165
+ else if (r.foreign) out.keep.push({ ...u, why: 'holds a file of another user' })
166
+ else out.idle.push({ ...u, gits: r.gits })
167
+ }
168
+
169
+ /** a root of entries: each child the user owns is a unit, a socket or a pipe at the top never is; with `fixedMin`, a
170
+ * child with a fixed name is one only at that size, and a small one is not even listed */
171
+ function entries(real: string, others: string[], fixedMin: number | undefined, c: Ctx, now: number, printErr: (l: string) => void, out: Found): void {
172
+ for (const n of names(real, printErr)) {
173
+ const p = join(real, n)
174
+ const s = stat(p)
175
+ if (s == null || s.uid !== c.uid || NOT_OURS.test(n)) continue
176
+ if (!s.isFile() && !s.isDirectory() && !s.isSymbolicLink()) continue
177
+ if (others.some((o) => o === p || o.startsWith(p + sep))) continue
178
+ if (fixedMin == null || tempShaped(n)) { judge(p, c, now, out); continue }
179
+ const found: Found = { idle: [], keep: [] }
180
+ judge(p, c, now, found)
181
+ out.idle.push(...found.idle.filter((u) => u.bytes >= fixedMin))
182
+ out.keep.push(...found.keep.filter((u) => u.bytes >= fixedMin))
183
+ }
184
+ }
185
+
186
+ /** claude's root: each piece of a session's folders (`scratchpad/<piece>`, `tasks/<file>`) is a unit, and the folders
187
+ * themselves stay, since the harness writes into them without making them again; a session nothing wrote for
188
+ * SESSION_SHELL_MS goes whole */
189
+ function sessions(real: string, c: Ctx, now: number, printErr: (l: string) => void, out: Found): void {
190
+ for (const project of names(real, printErr)) {
191
+ const pp = join(real, project)
192
+ const ps = stat(pp)
193
+ if (ps == null || HARNESS.has(project)) continue
194
+ if (!ps.isDirectory() || !project.startsWith('-')) { judge(pp, c, now, out); continue }
195
+ for (const session of names(pp, printErr)) {
196
+ const sp = join(pp, session)
197
+ const ss = stat(sp)
198
+ if (ss == null) continue
199
+ if (!ss.isDirectory()) { judge(sp, c, now, out); continue }
200
+ const found: Found = { idle: [], keep: [] }
201
+ let shell = c.stamp(ss)
202
+ for (const folder of names(sp, printErr)) {
203
+ const fp = join(sp, folder)
204
+ const fs = stat(fp)
205
+ if (fs == null) continue
206
+ if (!fs.isDirectory()) { judge(fp, c, now, found); continue }
207
+ shell = Math.max(shell, c.stamp(fs))
208
+ for (const piece of names(fp, printErr)) judge(join(fp, piece), c, now, found)
209
+ }
210
+ const at = Math.max(shell, ...found.idle.map((u) => u.at))
211
+ if (found.keep.length === 0 && at < now - SESSION_SHELL_MS) {
212
+ out.idle.push({ path: sp, at, bytes: found.idle.reduce((n, u) => n + u.bytes, 0), files: found.idle.reduce((n, u) => n + u.files, 0), gits: found.idle.flatMap((u) => [u.path, ...u.gits]) })
213
+ } else {
214
+ out.idle.push(...found.idle)
215
+ out.keep.push(...found.keep)
216
+ }
217
+ }
218
+ }
219
+ }
220
+
221
+ const gitOut = (cwd: string, args: string[]): { ok: boolean; out: string } => {
222
+ const p = Bun.spawnSync([gitBin(), ...args], { cwd, stdout: 'pipe', stderr: 'pipe' })
223
+ return { ok: p.exitCode === 0, out: p.stdout.toString().trim() }
224
+ }
225
+
226
+ /** the record a linked worktree at `dir` has in its repo (`<repo git dir>/worktrees/<name>`), or null */
227
+ function worktreeRecord(dir: string): string | null {
228
+ try {
229
+ const dot = join(dir, '.git')
230
+ if (!lstatSync(dot).isFile()) return null
231
+ const m = /^gitdir: (.+)$/m.exec(readFileSync(dot, 'utf8'))
232
+ return m != null && basename(dirname(m[1]!)) === 'worktrees' ? m[1]! : null
233
+ } catch { return null }
234
+ }
235
+
236
+ /** work in one git folder that a delete would lose, in words, or null.
237
+ * - a linked worktree of a repo: a change git has not saved, or a commit no branch holds; a throwaway checkout of
238
+ * shipkit's (core/throwaway-worktree.ts) holds none; one whose repo is gone is plain files
239
+ * - a repo with a remote: a change git has not saved, or a commit no remote holds
240
+ * - a repo with no remote is a fixture or a scratch copy: nothing of it was ever meant to leave the folder */
241
+ function unsavedAt(dir: string): string | null {
242
+ const dot = stat(join(dir, '.git'))
243
+ if (dot == null) return null
244
+ if (dot.isFile()) {
245
+ const record = worktreeRecord(dir)
246
+ if (record == null || !existsSync(record) || existsSync(join(record, 'shipkit-throwaway'))) return null
247
+ const status = gitOut(dir, ['status', '--porcelain'])
248
+ if (!status.ok || status.out !== '') return 'a git worktree with unsaved changes'
249
+ const held = gitOut(dir, ['for-each-ref', '--count=1', '--contains', 'HEAD'])
250
+ return held.ok && held.out !== '' ? null : 'a git worktree on a commit no branch holds'
251
+ }
252
+ let config = ''
253
+ try { config = readFileSync(join(dir, '.git', 'config'), 'utf8') } catch { return null }
254
+ if (!/^\s*\[remote /m.test(config)) return null
255
+ const status = gitOut(dir, ['status', '--porcelain'])
256
+ if (!status.ok || status.out !== '') return 'a git clone with unsaved changes'
257
+ const ahead = gitOut(dir, ['rev-list', '--max-count=1', '--branches', 'HEAD', '--not', '--remotes'])
258
+ return ahead.ok && ahead.out === '' ? null : 'a git clone with commits no remote holds'
259
+ }
260
+
261
+ /** the first git folder of a unit that holds unsaved work, with where */
262
+ function unsaved(u: Idle): string | null {
263
+ for (const dir of new Set([u.path, ...u.gits])) {
264
+ const why = unsavedAt(dir)
265
+ if (why != null) return dir === u.path ? why : `${why} (${dir.slice(u.path.length + 1)})`
266
+ }
267
+ return null
268
+ }
269
+
270
+ /** why a live process uses a path, or null */
271
+ export type InUse = (path: string) => string | null
272
+
273
+ export type PlanOptions = {
274
+ now: number
275
+ /** what the disk needs back to be over the floor: above 0, units idle past the short guard go too, the largest
276
+ * first, until this much is freed, and no idle unit is kept under the cap */
277
+ needBytes?: number
278
+ capBytes?: number
279
+ /** the live processes, read once the walk is done, so a process started during it is seen; null: unreadable */
280
+ live: () => InUse | null
281
+ printErr: (l: string) => void
282
+ /** whose entries are units: the user's; a fixture names another to read every entry as foreign */
283
+ uid?: number
284
+ /** when an entry was last written; a fixture ages its files by mtime alone */
285
+ stamp?: (s: Stats) => number
286
+ /** the other roots: one inside this root is never a unit of it */
287
+ others?: string[]
288
+ }
289
+
290
+ /** every unit of a root: fresh, used, unsaved or under the cap kept, the idle rest dropped: past the guard oldest
291
+ * first, then, while the disk needs room, past the short guard largest first */
292
+ export function planTemp(root: TempRoot, o: PlanOptions): Plan | null {
293
+ const real = checkedRoot(root.path, root.kind)
294
+ const uid = o.uid ?? process.getuid?.()
295
+ if (real == null || uid == null) return null
296
+ const need = Math.max(0, o.needBytes ?? 0)
297
+ const old = o.now - TEMP_GUARD_MS
298
+ const c: Ctx = { fresh: need > 0 ? o.now - TEMP_GUARD_LOW_MS : old, uid, stamp: o.stamp ?? written }
299
+ const found: Found = { idle: [], keep: [] }
300
+ if (root.kind === 'sessions') sessions(real, c, o.now, o.printErr, found)
301
+ else entries(real, o.others ?? [], root.fixedNameMinBytes, c, o.now, o.printErr, found)
302
+ const keep = found.keep
303
+ const inUse = found.idle.length === 0 ? null : o.live()
304
+ const free: Idle[] = []
305
+ for (const u of found.idle) {
306
+ const use = inUse == null ? 'the live processes cannot be read' : inUse(u.path)
307
+ const work = use == null ? unsaved(u) : null
308
+ if (use != null) keep.push({ ...u, why: inUse == null ? use : `in use: ${use}` })
309
+ else if (work != null) keep.push({ ...u, why: work })
310
+ else free.push(u)
311
+ }
312
+ const cap = need > 0 ? 0 : (o.capBytes ?? root.capBytes)
313
+ const drop: Idle[] = []
314
+ let kept = 0
315
+ let freed = 0
316
+ // newest first, so the newest idle units are the ones the cap keeps
317
+ for (const u of free.filter((x) => x.at < old).sort((a, b) => b.at - a.at)) {
318
+ if (drop.length === 0 && kept + u.bytes <= cap) { kept += u.bytes; keep.push({ ...u, why: `idle ${ago(o.now - u.at)}, under the cap` }) } else { drop.push(u); freed += u.bytes }
319
+ }
320
+ drop.reverse()
321
+ for (const u of free.filter((x) => x.at >= old).sort((a, b) => b.bytes - a.bytes)) {
322
+ if (freed < need) { drop.push(u); freed += u.bytes } else keep.push({ ...u, why: `idle ${ago(o.now - u.at)}, inside the guard` })
323
+ }
324
+ return { root: real, drop, keep, fresh: c.fresh }
325
+ }
326
+
327
+ /** a unit removed; one with a read only folder inside (a module cache) is made writable first, links never followed */
328
+ function remove(path: string): void {
329
+ try { rmSync(path, { recursive: true, force: true }) } catch (e) {
330
+ if (!['EACCES', 'EPERM', 'ENOTEMPTY'].includes((e as { code?: string }).code ?? '')) throw e
331
+ Bun.spawnSync(['chmod', '-R', '-P', 'u+rwx', path], { stdout: 'ignore', stderr: 'ignore' })
332
+ rmSync(path, { recursive: true, force: true })
333
+ }
334
+ }
335
+
336
+ export const gb = (n: number): string => `${(n / 1e9).toFixed(2)} GB`
337
+
338
+ /** what one pass did to one root, as `sk tmp` reads it back */
339
+ export type Pass = { id: string; root: string; freed: number; dropped: number; failed: number; kept: number; keptBytes: number; top: Kept[] }
340
+ export type TrimOptions = PlanOptions & { dry?: boolean; print: (l: string) => void; top?: number }
341
+
342
+ /** one pass over one root: each dropped unit removed (or only named, `dry`), a line for each big one */
343
+ export function trimTemp(root: TempRoot, o: TrimOptions): Pass | null {
344
+ const plan = planTemp(root, o)
345
+ if (plan == null) return null
346
+ const top = (k: Kept): Kept => ({ path: k.path, at: k.at, bytes: k.bytes, files: k.files, why: k.why, ...(k.floor === true ? { floor: true } : {}) })
347
+ const pass: Pass = { id: root.id, root: plan.root, freed: 0, dropped: 0, failed: 0, kept: plan.keep.length, keptBytes: plan.keep.reduce((n, u) => n + u.bytes, 0), top: [...plan.keep].sort((a, b) => b.bytes - a.bytes).slice(0, o.top ?? 20).map(top) }
348
+ const verb = o.dry === true ? 'would delete' : 'deleted'
349
+ const stamp = o.stamp ?? written
350
+ let small = 0
351
+ for (const u of plan.drop) {
352
+ if (!u.path.startsWith(plan.root + sep) || u.path.split(sep).includes('..')) throw new Error(`${u.path}: outside ${plan.root}, the pass stops`)
353
+ if (o.dry !== true) {
354
+ // the walk can be minutes old: a unit written since stays
355
+ const now = stat(u.path)
356
+ if (now == null) continue
357
+ if (stamp(now) >= plan.fresh) { pass.kept++; continue }
358
+ const records = [...new Set([u.path, ...u.gits])].map(worktreeRecord).filter((r): r is string => r != null)
359
+ try { remove(u.path) } catch (e) {
360
+ o.printErr(`WARN ${root.id}: ${u.path} not deleted (${(e as Error).message})`)
361
+ pass.failed++
362
+ continue
363
+ }
364
+ // only the record of the worktree just deleted: a prune would also drop one whose drive is unplugged
365
+ for (const r of records) rmSync(r, { recursive: true, force: true })
366
+ }
367
+ pass.freed += u.bytes
368
+ pass.dropped++
369
+ if (u.bytes >= SAY_BYTES) o.print(`${root.id}: ${verb} ${u.path.slice(plan.root.length + 1)} idle ${ago(o.now - u.at)} ${gb(u.bytes)}`)
370
+ else small++
371
+ }
372
+ if (o.dry === true || pass.dropped > 0) o.print(`${root.id}: ${o.dry === true ? 'would free' : 'freed'} ${gb(pass.freed)} in ${pass.dropped} units${small > 0 ? ` (${small} under ${SAY_BYTES / 1e6} MB each)` : ''}; kept ${pass.kept} units, ${gb(pass.keptBytes)}`)
373
+ return pass
374
+ }
375
+
376
+ /** a path as the kernel names it: macOS keeps /tmp and /var under /private */
377
+ const kernelPath = (p: string): string => (/^\/(tmp|var)(\/|$)/.test(p) ? `/private${p}` : p)
378
+
379
+ /** what the live processes of this user hold under `roots`: each open file, working folder and path on a command
380
+ * line or in an environment, with every folder above it. null when the processes cannot be read: the pass then
381
+ * deletes nothing */
382
+ export function liveUse(roots: string[], uid = process.getuid?.()): InUse | null {
383
+ if (uid == null) return null
384
+ const held = new Map<string, string>()
385
+ const hold = (path: string, why: string): void => {
386
+ const p = kernelPath(path)
387
+ const root = roots.find((r) => p.startsWith(r + sep))
388
+ if (root == null) return
389
+ for (let at = p; at.length > root.length; at = dirname(at)) if (!held.has(at)) held.set(at, why)
390
+ }
391
+ const lsof = Bun.spawnSync(['lsof', '-u', String(uid), '-F', 'pn'], { stdout: 'pipe', stderr: 'ignore' })
392
+ const open = lsof.stdout.toString()
393
+ // lsof exits 1 when one file of one process cannot be read: its listing is still whole
394
+ if (!/^p\d+$/m.test(open)) return null
395
+ let pid = '?'
396
+ for (const l of open.split('\n')) {
397
+ if (l.startsWith('p')) pid = l.slice(1)
398
+ else if (l.startsWith('n/')) hold(l.slice(1), `pid ${pid} holds it open`)
399
+ }
400
+ // -E adds each process's environment after its command: a PATH entry or a variable that names a unit holds it
401
+ const ps = Bun.spawnSync(['ps', '-AEo', 'pid=,args='], { stdout: 'pipe', stderr: 'ignore' })
402
+ if (ps.exitCode !== 0) return null
403
+ const paths = /(?:\/private)?\/(?:tmp|var\/folders)\/[^\s'":=,;]+/g
404
+ for (const l of ps.stdout.toString().split('\n')) {
405
+ const m = /^\s*(\d+)\s+(.*)$/.exec(l)
406
+ if (m == null) continue
407
+ for (const p of m[2]!.match(paths) ?? []) hold(p.replace(/\/+$/, ''), `the command or the environment of pid ${m[1]} names it`)
408
+ }
409
+ return (path) => held.get(path) ?? null
410
+ }
411
+
412
+ /** what the last pass measured, kept in the machine db: `sk tmp` prints it with no walk */
413
+ export const TEMP_USE = 'temp-use'
414
+ export type TempUse = { at: number; tookMs: number; free: number; low: boolean; passes: Pass[] }
415
+ export const tempUse = (): TempUse | null => machineGet<TempUse>(TEMP_USE)
416
+
417
+ const lockFile = (): string => join(dirname(machineDbPath()), 'temp-sweep.lock')
418
+ const alive = (pid: number): boolean => {
419
+ try { process.kill(pid, 0); return true } catch { return false }
420
+ }
421
+
422
+ /** one sweeper at a time on the machine: the pid that holds the pass, or a release once taken */
423
+ function takeLock(): { release: () => void } | { pid: number } {
424
+ const file = lockFile()
425
+ mkdirSync(dirname(file), { recursive: true })
426
+ for (let i = 0; i < 2; i++) {
427
+ try {
428
+ const fd = openSync(file, 'wx')
429
+ writeSync(fd, String(process.pid))
430
+ closeSync(fd)
431
+ return { release: () => rmSync(file, { force: true }) }
432
+ } catch {
433
+ let pid = 0
434
+ try { pid = Number(readFileSync(file, 'utf8').trim() || 0) } catch { /* released meanwhile */ }
435
+ if (pid > 0 && alive(pid)) return { pid }
436
+ rmSync(file, { force: true })
437
+ }
438
+ }
439
+ return { pid: 0 }
440
+ }
441
+
442
+ export type SweepOptions = { now?: number; dry?: boolean; roots?: TempRoot[]; print: (l: string) => void; printErr: (l: string) => void; free?: number; live?: () => InUse | null; stamp?: (s: Stats) => number }
443
+
444
+ /** one pass over every temp root, one process at a time on the machine. A real pass keeps what it measured for
445
+ * `sk tmp`, after each root, so a pass cut short still tells; a dry one keeps nothing. null when another process
446
+ * sweeps */
447
+ export function sweepTemp(o: SweepOptions): TempUse | null {
448
+ const lock = takeLock()
449
+ if ('pid' in lock) {
450
+ o.printErr(`temp: a sweep already runs (pid ${lock.pid}): \`sk tmp\` prints what it measured once it ends`)
451
+ return null
452
+ }
453
+ try {
454
+ const started = Date.now()
455
+ const now = o.now ?? started
456
+ const roots = o.roots ?? tempRoots()
457
+ const reals: string[] = []
458
+ for (const r of roots) {
459
+ try {
460
+ const real = checkedRoot(r.path, r.kind)
461
+ if (real != null) reals.push(real)
462
+ } catch { /* trimTemp says why below */ }
463
+ }
464
+ let free = o.free
465
+ if (free == null) {
466
+ const s = statfsSync(reals[0] ?? '/')
467
+ free = s.bavail * s.bsize
468
+ }
469
+ const use: TempUse = { at: now, tookMs: 0, free, low: free < TEMP_FLOOR_BYTES, passes: [] }
470
+ let need = Math.max(0, TEMP_FLOOR_BYTES - free)
471
+ let warned = false
472
+ const live = o.live ?? ((): InUse | null => {
473
+ const l = liveUse(reals)
474
+ if (l == null && !warned) { warned = true; o.printErr('WARN temp: the live processes cannot be read (lsof, ps), so nothing is deleted') }
475
+ return l
476
+ })
477
+ for (const r of roots) {
478
+ try {
479
+ const pass = trimTemp(r, { now, needBytes: need, dry: o.dry, live, print: o.print, printErr: o.printErr, others: reals, ...(o.stamp ? { stamp: o.stamp } : {}) })
480
+ if (pass == null) continue
481
+ need = Math.max(0, need - pass.freed)
482
+ use.passes.push(pass)
483
+ use.tookMs = Date.now() - started
484
+ if (o.dry !== true) machineSet(TEMP_USE, use)
485
+ } catch (e) {
486
+ o.printErr(`WARN ${r.id}: ${(e as Error).message}`)
487
+ }
488
+ }
489
+ return use
490
+ } finally {
491
+ lock.release()
492
+ }
493
+ }
@@ -0,0 +1,74 @@
1
+ // the other Macs whose shipkit home answers on the tailnet, for the page to link (tools/shipkit/home.md, Two
2
+ // machines). Nothing to configure: tailscale lists the peers, and a peer counts once its home answers on the home
3
+ // port. Asked in the background at most every few minutes, so no page poll ever waits on the network.
4
+ import { homePort, publicHome } from './home-paths.ts'
5
+ import { TAILSCALE } from './machine-host.ts'
6
+
7
+ export type OtherMac = { name: string; url: string }
8
+ type Peer = { DNSName?: string; OS?: string; Online?: boolean }
9
+ export type TailscaleStatus = { Self?: { DNSName?: string }; Peer?: Record<string, Peer> }
10
+
11
+ /** the macOS peers online, by tailnet name, this Mac left out */
12
+ export function macPeers(status: TailscaleStatus): { name: string; host: string }[] {
13
+ const self = status.Self?.DNSName?.replace(/\.$/, '')
14
+ return Object.values(status.Peer ?? {})
15
+ .filter((p) => p.OS === 'macOS' && p.Online === true && p.DNSName != null && p.DNSName !== '')
16
+ .map((p) => p.DNSName!.replace(/\.$/, ''))
17
+ .filter((host) => host !== self)
18
+ .map((host) => ({ name: host.split('.')[0]!, host }))
19
+ .sort((a, b) => a.name.localeCompare(b.name))
20
+ }
21
+
22
+ /** `tailscale status --json`, null when no tailscale answers */
23
+ export async function tailscaleStatus(bins: string[] = TAILSCALE): Promise<TailscaleStatus | null> {
24
+ for (const bin of bins) {
25
+ try {
26
+ const p = Bun.spawn([bin, 'status', '--json'], { stdout: 'pipe', stderr: 'ignore' })
27
+ const timer = setTimeout(() => p.kill(), 3000)
28
+ const out = await new Response(p.stdout).text()
29
+ clearTimeout(timer)
30
+ if ((await p.exited) === 0) return JSON.parse(out) as TailscaleStatus
31
+ } catch {
32
+ // a missing binary throws: the next one is tried
33
+ }
34
+ }
35
+ return null
36
+ }
37
+
38
+ /** does a shipkit home answer at this url: the web's own hub.json */
39
+ export async function homeAnswers(url: string, timeoutMs = 2000): Promise<boolean> {
40
+ try {
41
+ const r = await fetch(`${url}/hub.json`, { signal: AbortSignal.timeout(timeoutMs) })
42
+ return r.ok && (r.headers.get('content-type') ?? '').includes('json')
43
+ } catch {
44
+ return false
45
+ }
46
+ }
47
+
48
+ export const OTHER_MACS_EVERY_MS = 5 * 60_000
49
+
50
+ /** the list the page reads: the last answer at once, a fresh ask started behind it once it is old */
51
+ export class OtherMacs {
52
+ list: OtherMac[] = []
53
+ private at = -Infinity
54
+ private asking: Promise<void> | null = null
55
+ constructor(private o: { status?: () => Promise<TailscaleStatus | null>; answers?: (url: string) => Promise<boolean>; port?: number; everyMs?: number } = {}) {}
56
+
57
+ get(now: number = Date.now()): OtherMac[] {
58
+ if (this.asking == null && now - this.at >= (this.o.everyMs ?? OTHER_MACS_EVERY_MS)) {
59
+ this.at = now
60
+ this.asking = this.ask().finally(() => { this.asking = null })
61
+ }
62
+ return this.list
63
+ }
64
+
65
+ /** one ask, awaited: what the background one does */
66
+ async ask(): Promise<void> {
67
+ const status = await (this.o.status ?? tailscaleStatus)()
68
+ if (status == null) return
69
+ const answers = this.o.answers ?? homeAnswers
70
+ const peers = macPeers(status).map((p) => ({ name: p.name, url: publicHome(p.host, this.o.port ?? homePort()) }))
71
+ const up = await Promise.all(peers.map(async (p) => ((await answers(p.url)) ? p : null)))
72
+ this.list = up.filter((p): p is OtherMac => p != null)
73
+ }
74
+ }