rvlib-shipkit 2.22.1 → 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.
- package/CHANGELOG.md +44 -0
- package/package.json +1 -1
- package/src/agent-time/render.ts +28 -14
- package/src/agent-time/report.ts +46 -25
- package/src/agent-time/store.ts +30 -10
- package/src/agent-time/timeline.ts +43 -15
- package/src/annex/annex.ts +3 -0
- package/src/annex/born.ts +464 -0
- package/src/annex/flush.ts +46 -0
- package/src/annex/offload.ts +171 -38
- package/src/annex/snapshots.ts +53 -0
- package/src/annex/tidy.ts +368 -0
- package/src/asks/asks-queue.ts +32 -11
- package/src/checks/SK041-annex-links.check.ts +4 -2
- package/src/checks/SK043-scratch-on-the-mac.check.ts +45 -0
- package/src/checks/SK044-behind-upstream.check.ts +38 -0
- package/src/cli/cmd_Annex.ts +60 -9
- package/src/cli/cmd_Asks.ts +2 -0
- package/src/cli/cmd_Backup.ts +7 -5
- package/src/cli/cmd_Bump.ts +1 -0
- package/src/cli/cmd_Capacity.ts +26 -0
- package/src/cli/cmd_Check.ts +1 -0
- package/src/cli/cmd_Checks.ts +1 -0
- package/src/cli/cmd_Ci.ts +1 -0
- package/src/cli/cmd_Commands.ts +50 -14
- package/src/cli/cmd_Home.ts +0 -1
- package/src/cli/cmd_Hooks.ts +1 -0
- package/src/cli/cmd_Mv.ts +1 -0
- package/src/cli/cmd_Rec.ts +17 -7
- package/src/cli/cmd_Reflect.ts +1 -0
- package/src/cli/cmd_Releases.ts +1 -0
- package/src/cli/cmd_Review.ts +124 -17
- package/src/cli/cmd_Secret.ts +41 -2
- package/src/cli/cmd_Shot.ts +1 -0
- package/src/cli/cmd_Status.ts +1 -0
- package/src/cli/cmd_Time.ts +3 -1
- package/src/cli/cmd_Tmp.ts +82 -0
- package/src/cli/cmd_Wiki.ts +1 -0
- package/src/cli/registry.ts +13 -1
- package/src/collections/pings.ts +1 -1
- package/src/core/capacity.ts +71 -0
- package/src/core/check-runner.ts +86 -15
- package/src/core/machine-db.ts +8 -0
- package/src/core/motherhome.ts +67 -9
- package/src/core/slots.ts +49 -12
- package/src/core/trace-audit.ts +4 -1
- package/src/drill/run.ts +5 -2
- package/src/home/daemon-jobs.ts +10 -3
- package/src/home/global-units.ts +3 -0
- package/src/home/gui-app/ShipkitGui.swift +1 -0
- package/src/home/home-launchd.ts +11 -3
- package/src/home/home-routes.ts +11 -4
- package/src/home/machine-host.ts +65 -0
- package/src/home/machine-stores.ts +30 -4
- package/src/home/machine-temp.ts +493 -0
- package/src/home/other-macs.ts +74 -0
- package/src/home/pm.ts +4 -1
- package/src/home/run-daemon.ts +10 -2
- package/src/home/run-pm.ts +1 -0
- package/src/home/serve-web.ts +2 -2
- package/src/home/via-hub.ts +6 -1
- package/src/identities/identities.ts +92 -24
- package/src/init-repo.ts +7 -3
- package/src/ledger/ledger.ts +6 -0
- package/src/ledger/store.ts +6 -0
- package/src/media-store/backup/keys.ts +21 -6
- package/src/media-store/backup/manifest.ts +52 -11
- package/src/media-store/backup/restore.ts +17 -10
- package/src/media-store/backup/run.ts +5 -2
- package/src/media-store/backup/sources.ts +2 -1
- package/src/media-store/daemon.ts +2 -2
- package/src/media-store/purge.ts +4 -0
- package/src/mv/mv-md.ts +121 -42
- package/src/recordings/load.ts +3 -3
- package/src/recordings/model.ts +7 -0
- package/src/recordings/open.ts +12 -0
- package/src/recordings/presets.ts +12 -5
- package/src/recordings/recorder-app/Capture.swift +34 -5
- package/src/recordings/recorder-app/Clip.swift +126 -17
- package/src/recordings/recorder-app/Editor.swift +177 -7
- package/src/recordings/recorder-app/Hud.swift +189 -0
- package/src/recordings/recorder-app/Tray.swift +179 -36
- package/src/recordings/recorder-app/icon.svg +16 -0
- package/src/recordings/recorder-app/main.swift +349 -18
- package/src/recordings/recorder-app.ts +8 -4
- package/src/recordings/recorder.shipkit.ts +2 -1
- package/src/recordings/routes.ts +52 -6
- package/src/recordings/run-recorder.ts +2 -1
- package/src/recordings/share.ts +27 -0
- package/src/recordings/take.ts +36 -4
- package/src/recordings/view.ts +11 -0
- package/src/reflect/transcript.ts +56 -11
- package/src/releases/from-card.ts +45 -3
- package/src/releases/model.ts +6 -0
- package/src/releases/store.ts +8 -1
- package/src/repo-config.ts +14 -4
- package/src/review/cells.ts +24 -3
- package/src/review/format.ts +33 -9
- package/src/review/media-kind.ts +14 -11
- package/src/review/media-read.ts +6 -5
- package/src/review/model.ts +104 -7
- package/src/review/paste.ts +2 -1
- package/src/review/previews.ts +123 -36
- package/src/review/routes.ts +29 -18
- package/src/review/store.ts +74 -12
- package/src/review/threads.ts +7 -5
- package/src/secrets/copy.ts +110 -0
- package/src/secrets/list.ts +17 -7
- package/src/serve/hub-app/home-strip.css +5 -0
- package/src/serve/hub-app/home-strip.tsx +18 -0
- package/src/serve/hub-app/hub-app.tsx +2 -1
- package/src/serve/hub-app/hub.css +18 -0
- package/src/serve/hub-app/inbox.css +1 -0
- package/src/serve/hub-app/pull-refresh.tsx +88 -0
- package/src/serve/hub-app/recordings-st.ts +135 -24
- package/src/serve/hub-app/recordings-view.tsx +293 -54
- package/src/serve/hub-app/recordings.css +77 -24
- package/src/serve/hub-app/review/review-cells.tsx +52 -13
- package/src/serve/hub-app/review/review-list.tsx +6 -1
- package/src/serve/hub-app/review/review-st.ts +6 -5
- package/src/serve/hub-app/review/review-thread.tsx +3 -1
- package/src/serve/hub-app/review/review-views.tsx +18 -11
- package/src/serve/hub-app/review/thread-st.ts +82 -14
- package/src/serve/hub-app/review.css +15 -2
- package/src/serve/hub-runtime.ts +2 -1
- package/src/serve/run-serve.ts +4 -2
- package/src/serve/serve-hub.ts +9 -2
- package/src/shipkit-files.ts +5 -0
- package/src/social/drafts.ts +4 -3
- package/src/social/load.ts +7 -2
- package/src/social/publish/discord.ts +10 -3
- package/src/suite/child-tools.ts +45 -0
- package/src/suite/judge-suites.ts +10 -22
- package/src/suite/select.ts +83 -8
- package/src/suite/suite-cli.ts +38 -14
- package/src/suite/suite-cores.ts +68 -0
- package/src/suite/suite-reads-preload.ts +8 -6
- package/src/ts/config.ts +44 -0
- package/src/ts/rename.ts +11 -1
|
@@ -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
|
+
}
|
package/src/home/pm.ts
CHANGED
|
@@ -97,9 +97,12 @@ export class Pm {
|
|
|
97
97
|
}
|
|
98
98
|
|
|
99
99
|
/** every child up: adopted from its pid record, else started, unless
|
|
100
|
-
* something else already answers its port
|
|
100
|
+
* something else already answers its port. A cold pm (no child to
|
|
101
|
+
* adopt: a login, a reboot) also starts each process declared atLogin */
|
|
101
102
|
async boot(): Promise<void> {
|
|
102
103
|
await Promise.all([...this.children.values()].map((p) => p.ensure()))
|
|
104
|
+
if ([...this.children.values()].some((p) => p.adopted)) return
|
|
105
|
+
await Promise.all(this.d.resources.list.filter((r) => r.decl.atLogin).map((r) => r.set('up')))
|
|
103
106
|
}
|
|
104
107
|
|
|
105
108
|
async tick(): Promise<void> {
|
package/src/home/run-daemon.ts
CHANGED
|
@@ -29,6 +29,8 @@ import { machineCatchUp } from '../plan/catch-up.ts'
|
|
|
29
29
|
import { serveDaemon } from './serve-daemon.ts'
|
|
30
30
|
import { startJobs } from './daemon-jobs.ts'
|
|
31
31
|
import { Widgets } from './widgets.ts'
|
|
32
|
+
import { machinePublicHost } from './machine-host.ts'
|
|
33
|
+
import { OtherMacs } from './other-macs.ts'
|
|
32
34
|
|
|
33
35
|
const CLI = fileURLToPath(new URL('../cli.ts', import.meta.url))
|
|
34
36
|
|
|
@@ -72,7 +74,9 @@ export async function runDaemon(root: string, io: HomeIo, o: { port?: number } =
|
|
|
72
74
|
const reclaimed = reclaimPreviousImage()
|
|
73
75
|
if (reclaimed.killed.length > 0) io.print(`ok: the daemon restarted in place: killed ${reclaimed.killed.length} check process(es) its previous image left running`)
|
|
74
76
|
const c = await loadRepoConfig(root)
|
|
75
|
-
|
|
77
|
+
// asked again on each use: a Mac whose tailscale was down at boot gains its name once it answers
|
|
78
|
+
const publicHost = (): string | null => machinePublicHost(c)
|
|
79
|
+
const otherMacs = new OtherMacs()
|
|
76
80
|
const dir = homeDir()
|
|
77
81
|
// the machine's one plan: every repo and check pair, ticked by the daemon.
|
|
78
82
|
// Its catch up window lives in the machine db, so a restart in place keeps it
|
|
@@ -102,7 +106,10 @@ export async function runDaemon(root: string, io: HomeIo, o: { port?: number } =
|
|
|
102
106
|
// every gate is a detached job: a reload of this process never kills one
|
|
103
107
|
jobs: { cli: CLI },
|
|
104
108
|
// a ping opens the inbox on its item, or on the list for several
|
|
105
|
-
link: (fresh) =>
|
|
109
|
+
link: (fresh) => {
|
|
110
|
+
const host = publicHost()
|
|
111
|
+
return host == null ? undefined : `${publicHome(host)}${fresh.length === 1 ? inboxAddress(repo.name, fresh[0]!.id) : '/inbox'}`
|
|
112
|
+
},
|
|
106
113
|
})
|
|
107
114
|
hubIo.print(`${rt.name} hub → http://localhost:${port}${hubBase(repo.name)}/`)
|
|
108
115
|
return { ...rt, uses: rt.deps.uses ?? [] }
|
|
@@ -122,6 +129,7 @@ export async function runDaemon(root: string, io: HomeIo, o: { port?: number } =
|
|
|
122
129
|
only: onlyRepos(),
|
|
123
130
|
widgets: new Widgets(),
|
|
124
131
|
publicHost,
|
|
132
|
+
otherMacs: () => otherMacs.get(),
|
|
125
133
|
})
|
|
126
134
|
io.print(`daemon → http://127.0.0.1:${home.server.port} (the page: http://localhost:${port})`)
|
|
127
135
|
// the retention sweep (nothing grows unbound, core/retention.ts), the media store and the backup of the
|
package/src/home/run-pm.ts
CHANGED
|
@@ -167,6 +167,7 @@ export async function runPm(root: string, io: HomeIo, o: { port?: number } = {})
|
|
|
167
167
|
// their own process groups, for the next pm to adopt
|
|
168
168
|
if (stopping) return
|
|
169
169
|
stopping = true
|
|
170
|
+
io.print(`pm: ${sig} received, stopping the daemon and the web (the global processes keep running)`)
|
|
170
171
|
code.stop()
|
|
171
172
|
clearInterval(timer)
|
|
172
173
|
clearInterval(reread)
|
package/src/home/serve-web.ts
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
// origin header. The daemon's own guard then refuses any page that calls its
|
|
10
10
|
// port directly, and lets this door through. The host guard runs here too: Bun's dev server, which bundles the page
|
|
11
11
|
// and drives its hot reload, answers only to a loopback Host, so it sits on a port of its own behind this one, and a
|
|
12
|
-
// request reaches it only once its Host is a loopback name or
|
|
12
|
+
// request reaches it only once its Host is a loopback name or this Mac's tailnet name (machine-host.ts)
|
|
13
13
|
import { hostName, loopbackName, REACH_HEADER, reachOfHost, sameOrigin } from '../serve/same-origin.ts'
|
|
14
14
|
import { hubBase } from './home-paths.ts'
|
|
15
15
|
import { forwardPage, pagePath } from '../pages/forward.ts'
|
|
@@ -75,7 +75,7 @@ export function hostAllowed(host: string | null, names: ReadonlySet<string>): bo
|
|
|
75
75
|
}
|
|
76
76
|
|
|
77
77
|
export const hostRefusedText = (host: string | null): string =>
|
|
78
|
-
`refused: the home answers to localhost and to
|
|
78
|
+
`refused: the home answers to localhost and to this Mac's tailnet name, never to ${host == null || host === '' ? 'a request with no Host' : host}`
|
|
79
79
|
|
|
80
80
|
/** the page's colours behind the app on a phone, the --bg tokens of hub.css */
|
|
81
81
|
const THEME = { dark: '#0d0e10', light: '#f6f7f9' } as const
|