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.
Files changed (139) hide show
  1. package/CHANGELOG.md +44 -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/annex/annex.ts +3 -0
  8. package/src/annex/born.ts +464 -0
  9. package/src/annex/flush.ts +46 -0
  10. package/src/annex/offload.ts +171 -38
  11. package/src/annex/snapshots.ts +53 -0
  12. package/src/annex/tidy.ts +368 -0
  13. package/src/asks/asks-queue.ts +32 -11
  14. package/src/checks/SK041-annex-links.check.ts +4 -2
  15. package/src/checks/SK043-scratch-on-the-mac.check.ts +45 -0
  16. package/src/checks/SK044-behind-upstream.check.ts +38 -0
  17. package/src/cli/cmd_Annex.ts +60 -9
  18. package/src/cli/cmd_Asks.ts +2 -0
  19. package/src/cli/cmd_Backup.ts +7 -5
  20. package/src/cli/cmd_Bump.ts +1 -0
  21. package/src/cli/cmd_Capacity.ts +26 -0
  22. package/src/cli/cmd_Check.ts +1 -0
  23. package/src/cli/cmd_Checks.ts +1 -0
  24. package/src/cli/cmd_Ci.ts +1 -0
  25. package/src/cli/cmd_Commands.ts +50 -14
  26. package/src/cli/cmd_Home.ts +0 -1
  27. package/src/cli/cmd_Hooks.ts +1 -0
  28. package/src/cli/cmd_Mv.ts +1 -0
  29. package/src/cli/cmd_Rec.ts +17 -7
  30. package/src/cli/cmd_Reflect.ts +1 -0
  31. package/src/cli/cmd_Releases.ts +1 -0
  32. package/src/cli/cmd_Review.ts +124 -17
  33. package/src/cli/cmd_Secret.ts +41 -2
  34. package/src/cli/cmd_Shot.ts +1 -0
  35. package/src/cli/cmd_Status.ts +1 -0
  36. package/src/cli/cmd_Time.ts +3 -1
  37. package/src/cli/cmd_Tmp.ts +82 -0
  38. package/src/cli/cmd_Wiki.ts +1 -0
  39. package/src/cli/registry.ts +13 -1
  40. package/src/collections/pings.ts +1 -1
  41. package/src/core/capacity.ts +71 -0
  42. package/src/core/check-runner.ts +86 -15
  43. package/src/core/machine-db.ts +8 -0
  44. package/src/core/motherhome.ts +67 -9
  45. package/src/core/slots.ts +49 -12
  46. package/src/core/trace-audit.ts +4 -1
  47. package/src/drill/run.ts +5 -2
  48. package/src/home/daemon-jobs.ts +10 -3
  49. package/src/home/global-units.ts +3 -0
  50. package/src/home/gui-app/ShipkitGui.swift +1 -0
  51. package/src/home/home-launchd.ts +11 -3
  52. package/src/home/home-routes.ts +11 -4
  53. package/src/home/machine-host.ts +65 -0
  54. package/src/home/machine-stores.ts +30 -4
  55. package/src/home/machine-temp.ts +493 -0
  56. package/src/home/other-macs.ts +74 -0
  57. package/src/home/pm.ts +4 -1
  58. package/src/home/run-daemon.ts +10 -2
  59. package/src/home/run-pm.ts +1 -0
  60. package/src/home/serve-web.ts +2 -2
  61. package/src/home/via-hub.ts +6 -1
  62. package/src/identities/identities.ts +92 -24
  63. package/src/init-repo.ts +7 -3
  64. package/src/ledger/ledger.ts +6 -0
  65. package/src/ledger/store.ts +6 -0
  66. package/src/media-store/backup/keys.ts +21 -6
  67. package/src/media-store/backup/manifest.ts +52 -11
  68. package/src/media-store/backup/restore.ts +17 -10
  69. package/src/media-store/backup/run.ts +5 -2
  70. package/src/media-store/backup/sources.ts +2 -1
  71. package/src/media-store/daemon.ts +2 -2
  72. package/src/media-store/purge.ts +4 -0
  73. package/src/mv/mv-md.ts +121 -42
  74. package/src/recordings/load.ts +3 -3
  75. package/src/recordings/model.ts +7 -0
  76. package/src/recordings/open.ts +12 -0
  77. package/src/recordings/presets.ts +12 -5
  78. package/src/recordings/recorder-app/Capture.swift +34 -5
  79. package/src/recordings/recorder-app/Clip.swift +126 -17
  80. package/src/recordings/recorder-app/Editor.swift +177 -7
  81. package/src/recordings/recorder-app/Hud.swift +189 -0
  82. package/src/recordings/recorder-app/Tray.swift +179 -36
  83. package/src/recordings/recorder-app/icon.svg +16 -0
  84. package/src/recordings/recorder-app/main.swift +349 -18
  85. package/src/recordings/recorder-app.ts +8 -4
  86. package/src/recordings/recorder.shipkit.ts +2 -1
  87. package/src/recordings/routes.ts +52 -6
  88. package/src/recordings/run-recorder.ts +2 -1
  89. package/src/recordings/share.ts +27 -0
  90. package/src/recordings/take.ts +36 -4
  91. package/src/recordings/view.ts +11 -0
  92. package/src/reflect/transcript.ts +56 -11
  93. package/src/releases/from-card.ts +45 -3
  94. package/src/releases/model.ts +6 -0
  95. package/src/releases/store.ts +8 -1
  96. package/src/repo-config.ts +14 -4
  97. package/src/review/cells.ts +24 -3
  98. package/src/review/format.ts +33 -9
  99. package/src/review/media-kind.ts +14 -11
  100. package/src/review/media-read.ts +6 -5
  101. package/src/review/model.ts +104 -7
  102. package/src/review/paste.ts +2 -1
  103. package/src/review/previews.ts +123 -36
  104. package/src/review/routes.ts +29 -18
  105. package/src/review/store.ts +74 -12
  106. package/src/review/threads.ts +7 -5
  107. package/src/secrets/copy.ts +110 -0
  108. package/src/secrets/list.ts +17 -7
  109. package/src/serve/hub-app/home-strip.css +5 -0
  110. package/src/serve/hub-app/home-strip.tsx +18 -0
  111. package/src/serve/hub-app/hub-app.tsx +2 -1
  112. package/src/serve/hub-app/hub.css +18 -0
  113. package/src/serve/hub-app/inbox.css +1 -0
  114. package/src/serve/hub-app/pull-refresh.tsx +88 -0
  115. package/src/serve/hub-app/recordings-st.ts +135 -24
  116. package/src/serve/hub-app/recordings-view.tsx +293 -54
  117. package/src/serve/hub-app/recordings.css +77 -24
  118. package/src/serve/hub-app/review/review-cells.tsx +52 -13
  119. package/src/serve/hub-app/review/review-list.tsx +6 -1
  120. package/src/serve/hub-app/review/review-st.ts +6 -5
  121. package/src/serve/hub-app/review/review-thread.tsx +3 -1
  122. package/src/serve/hub-app/review/review-views.tsx +18 -11
  123. package/src/serve/hub-app/review/thread-st.ts +82 -14
  124. package/src/serve/hub-app/review.css +15 -2
  125. package/src/serve/hub-runtime.ts +2 -1
  126. package/src/serve/run-serve.ts +4 -2
  127. package/src/serve/serve-hub.ts +9 -2
  128. package/src/shipkit-files.ts +5 -0
  129. package/src/social/drafts.ts +4 -3
  130. package/src/social/load.ts +7 -2
  131. package/src/social/publish/discord.ts +10 -3
  132. package/src/suite/child-tools.ts +45 -0
  133. package/src/suite/judge-suites.ts +10 -22
  134. package/src/suite/select.ts +83 -8
  135. package/src/suite/suite-cli.ts +38 -14
  136. package/src/suite/suite-cores.ts +68 -0
  137. package/src/suite/suite-reads-preload.ts +8 -6
  138. package/src/ts/config.ts +44 -0
  139. package/src/ts/rename.ts +11 -1
@@ -0,0 +1,368 @@
1
+ // scratch by itself (wiki tools/shipkit/annex.md, Scratch by itself): one pass, the daemon's `annex` job and `sk annex
2
+ // tidy`. Every offload record brought in line with the drive (born.ts: a spill while it is away, merged back when it
3
+ // returns), every folder a config declares born linked to the annex, stale scratch moved off the Mac once its disk is
4
+ // under the floor or the repo over its cap, and the annex's own scratch trimmed to its cap.
5
+ //
6
+ // the one constraint a reader breaks first: a folder is stale only when nothing under it moved for a day at the least,
7
+ // whatever the pressure: lanes write into scratch all day, and the offload's own checks are the net, not the plan
8
+ import { existsSync, lstatSync, readdirSync, readFileSync, rmSync, type Stats, writeFileSync } from 'node:fs'
9
+ import { dirname, join } from 'node:path'
10
+ import { machineDbPath, machineGet, machineSet } from '../core/machine-db.ts'
11
+ import { freeBytes } from '../media-store/purge.ts'
12
+ import { annexSpecs, type AnnexSpec, driveFree, isPresent, keepFree, type Sweep } from './annex.ts'
13
+ import { bear, bornCheck, deadStage, type Pass, sayOnce, settle } from './born.ts'
14
+ import { editOffloads, type Offload, offload, offloads, PART_MARK, type Probe, SCRATCH } from './offload.ts'
15
+ import { held, heldWords, localSnapshots } from './snapshots.ts'
16
+
17
+ const GB = 1e9
18
+ const DAY = 86_400_000
19
+
20
+ /** the house's scratch policy, `serve.annexScratch` of the house config: the default of every house repo */
21
+ export type AnnexScratch = {
22
+ /** scratch folders every house repo keeps on the annex from their first byte, repo relative */
23
+ born?: string[]
24
+ /** the most a repo's `.shipkit/tmp` and `.shipkit/cache` may hold on the Mac, in GB (20) */
25
+ capGb?: number
26
+ /** under this much free space on the Mac's disk, stale scratch moves to the annex, in GB (40) */
27
+ floorGb?: number
28
+ /** a folder nothing touched for this many days is stale (3); under the floor, 1 */
29
+ staleDays?: number
30
+ }
31
+
32
+ /** a repo's own scratch policy, `annex` in its repo.config.ts. Declaring it is the opt in: a repo without it is
33
+ * touched by no born folder and no stale pass, the house's included (`annex: {}` takes the house defaults) */
34
+ export type RepoAnnex = {
35
+ /** scratch folders this repo keeps on the annex from their first byte, beside the house's: each under
36
+ * `.shipkit/tmp` or `.shipkit/cache` */
37
+ born?: string[]
38
+ /** scratch folders that never leave the Mac: read hot, a measured slower read on the annex */
39
+ keep?: string[]
40
+ /** the most this repo's scratch may hold on the Mac, in GB, in place of the house's cap */
41
+ capGb?: number
42
+ }
43
+
44
+ export type ScratchPolicy = { born: string[]; keep: string[]; capGb: number; floorGb: number; staleDays: number }
45
+
46
+ export const SCRATCH_DEFAULTS = { capGb: 20, floorGb: 40, staleDays: 3 }
47
+ /** a file of the annex's scratch untouched for this long may go when the annex is over its scratch cap */
48
+ export const SCRATCH_KEEP_DAYS = 14
49
+ /** a stale folder smaller than this stays: a link per tiny folder frees nothing (measured on one repo: 164 folders
50
+ * stale for a day held 1.8 GB, one of them over 50 MB) */
51
+ const MIN_STALE_BYTES = 50e6
52
+ /** a fresh folder this big is looked into: its stale children move one by one */
53
+ const DESCEND_BYTES = 1e9
54
+ export const ANNEX_EVERY_MS = 30_000
55
+ /** the declarations, the stale scratch and the cap are read this often; the records every pass */
56
+ export const FULL_EVERY_MS = 10 * 60_000
57
+ const SWEEP_EVERY_MS = 60 * 60_000
58
+ const FULL_AT = 'annex-full-at'
59
+ const SWEPT_AT = 'annex-scratch-swept-at'
60
+ /** the last measure of each annex's scratch, `{ [path]: { files, bytes, at } }`: `sk annex` prints it */
61
+ export const SCRATCH_USE = 'annex-scratch-use'
62
+
63
+ /** the policy of a repo that declared `annex`; null for one that did not: nothing of its scratch moves by itself */
64
+ export function policyOf(house: AnnexScratch | undefined, repo: RepoAnnex): ScratchPolicy
65
+ export function policyOf(house: AnnexScratch | undefined, repo: RepoAnnex | undefined): ScratchPolicy | null
66
+ export function policyOf(house: AnnexScratch | undefined, repo: RepoAnnex | undefined): ScratchPolicy | null {
67
+ if (repo === undefined) return null
68
+ return {
69
+ born: [...new Set([...(house?.born ?? []), ...(repo?.born ?? [])])],
70
+ keep: [...(repo?.keep ?? [])],
71
+ capGb: repo?.capGb ?? house?.capGb ?? SCRATCH_DEFAULTS.capGb,
72
+ floorGb: house?.floorGb ?? SCRATCH_DEFAULTS.floorGb,
73
+ staleDays: Math.max(1, house?.staleDays ?? SCRATCH_DEFAULTS.staleDays),
74
+ }
75
+ }
76
+
77
+ /** bytes of a repo's scratch on the Mac: `.shipkit/tmp` and `.shipkit/cache`, links not followed, so an offloaded
78
+ * folder counts nothing and a spill counts whole (`du`: 0.5 s on 36 GB) */
79
+ export function scratchOnMac(root: string): number {
80
+ const dirs = SCRATCH.map((d) => join(root, d)).filter((d) => lstatSync(d, { throwIfNoEntry: false })?.isDirectory() === true)
81
+ if (dirs.length === 0) return 0
82
+ const r = Bun.spawnSync(['du', '-skP', ...dirs], { stdout: 'pipe', stderr: 'ignore' })
83
+ return r.stdout.toString().split('\n').reduce((n, l) => n + (Number(l.split('\t')[0]) || 0) * 1024, 0)
84
+ }
85
+
86
+ /** every entry under `dir` by lstat, a link never followed (a recursive readdir follows one into a loop: a build's
87
+ * node_modules link), one that vanishes meanwhile skipped */
88
+ function eachEntry(dir: string, fn: (path: string, s: Stats) => void): void {
89
+ let names: string[]
90
+ try {
91
+ names = readdirSync(dir)
92
+ } catch {
93
+ return
94
+ }
95
+ for (const n of names) {
96
+ const p = join(dir, n)
97
+ const s = lstatSync(p, { throwIfNoEntry: false })
98
+ if (!s) continue
99
+ fn(p, s)
100
+ if (s.isDirectory()) eachEntry(p, fn)
101
+ }
102
+ }
103
+
104
+ /** the bytes under `dir` and the newest time of anything in it, links not followed */
105
+ function walk(dir: string): { bytes: number; newest: number } {
106
+ const out = { bytes: 0, newest: lstatSync(dir).mtimeMs }
107
+ eachEntry(dir, (_, s) => {
108
+ out.newest = Math.max(out.newest, s.mtimeMs)
109
+ if (s.isFile()) out.bytes += s.size
110
+ })
111
+ return out
112
+ }
113
+
114
+ /** the name a move in flight leaves: an offload's `.part` or aside, a swap first move's aside, a copy brought back */
115
+ const IN_FLIGHT = /\.\d+\.(part|offloading|moving|back)$/
116
+
117
+ export type Stale = { rel: string; bytes: number; newest: number }
118
+
119
+ /** folders of the repo's scratch nothing touched for `days`, 50 MB or more, oldest first: each child of
120
+ * `.shipkit/tmp` and `.shipkit/cache`, and the children of a fresh one of 1 GB or more. Never a born or kept folder,
121
+ * nor one that holds one */
122
+ export function staleFolders(root: string, p: ScratchPolicy, now: number, days: number, o: { minBytes?: number; descendBytes?: number } = {}): Stale[] {
123
+ const minBytes = o.minBytes ?? MIN_STALE_BYTES
124
+ const descendBytes = o.descendBytes ?? DESCEND_BYTES
125
+ const fixed = [...p.born, ...p.keep]
126
+ const inside = (rel: string): boolean => fixed.some((k) => rel === k || rel.startsWith(`${k}/`))
127
+ const holds = (rel: string): boolean => fixed.some((k) => k.startsWith(`${rel}/`))
128
+ const out: Stale[] = []
129
+ const look = (rel: string, depth: number): void => {
130
+ for (const name of readdirSync(join(root, rel))) {
131
+ const r = `${rel}/${name}`
132
+ if (IN_FLIGHT.test(name) || inside(r) || lstatSync(join(root, r), { throwIfNoEntry: false })?.isDirectory() !== true) continue
133
+ let w
134
+ try {
135
+ w = walk(join(root, r))
136
+ } catch {
137
+ continue
138
+ }
139
+ if (!holds(r) && w.newest < now - days * DAY && w.bytes >= minBytes) out.push({ rel: r, ...w })
140
+ else if (depth === 1 && w.bytes >= descendBytes) look(r, 2)
141
+ }
142
+ }
143
+ for (const base of SCRATCH) if (lstatSync(join(root, base), { throwIfNoEntry: false })?.isDirectory() && !inside(base)) look(base, 1)
144
+ return out.sort((a, b) => a.newest - b.newest || b.bytes - a.bytes)
145
+ }
146
+
147
+ export type Aged = { moved: { rel: string; bytes: number }[]; refused: { rel: string; why: string }[]; onMac: number; free: number; days: number | null }
148
+
149
+ /** stale scratch of `root` to the annex, oldest first, while the disk is under the floor or the repo over its cap */
150
+ export async function agePass(root: string, p: ScratchPolicy, o: Probe & { now?: number; dry?: boolean; minBytes?: number }): Promise<Aged> {
151
+ const now = o.now ?? Date.now()
152
+ let onMac = scratchOnMac(root)
153
+ let free = freeBytes(root)
154
+ const pressed = (): boolean => free < p.floorGb * GB || onMac > p.capGb * GB
155
+ const out: Aged = { moved: [], refused: [], onMac, free, days: null }
156
+ if (!pressed()) return out
157
+ const days = free < p.floorGb * GB ? 1 : p.staleDays
158
+ out.days = days
159
+ for (const s of staleFolders(root, p, now, days, o)) {
160
+ if (!pressed()) break
161
+ try {
162
+ const m = await offload(root, s.rel, { ...o, dry: o.dry === true })
163
+ onMac -= m.bytes
164
+ if (o.dry) free += m.bytes
165
+ else free = freeBytes(root)
166
+ out.moved.push({ rel: s.rel, bytes: m.bytes })
167
+ } catch (e) {
168
+ out.refused.push({ rel: s.rel, why: (e as Error).message })
169
+ }
170
+ }
171
+ out.onMac = onMac
172
+ out.free = free
173
+ return out
174
+ }
175
+
176
+ /** trim an annex's scratch (`offload/`) under its `scratchMaxGb`, and its drive to `keepFreeGb`: files untouched for
177
+ * SCRATCH_KEEP_DAYS at the least, oldest first. A loser a merge kept is never one of them: it goes only by a hand.
178
+ * A staging folder shipkit marked whose process is dead goes at every sweep. Its measure is kept for `sk annex` */
179
+ export function scratchSweep(spec: AnnexSpec, o: { dry?: boolean; now?: number } = {}): Sweep {
180
+ const now = o.now ?? Date.now()
181
+ const dir = join(spec.path, 'offload')
182
+ const files: { path: string; size: number; used: number }[] = []
183
+ const out: Sweep = { annex: spec.path, files: 0, bytes: 0, freed: { files: 0, bytes: 0 } }
184
+ const present = isPresent(spec)
185
+ const kept = new Set(offloads().flatMap((r) => r.kept ?? []))
186
+ const stages: string[] = []
187
+ let parts = 0
188
+ let keptBytes = 0
189
+ eachEntry(dir, (path, s) => {
190
+ if (stages.some((st) => path.startsWith(`${st}/`))) return
191
+ if (s.isDirectory() && /\.\d+\.part$/.test(path) && existsSync(join(path, PART_MARK))) {
192
+ stages.push(path)
193
+ if (present && deadStage(path)) {
194
+ if (!o.dry) rmSync(path, { recursive: true, force: true })
195
+ parts++
196
+ out.freed.files++
197
+ }
198
+ } else if (s.isFile() && kept.has(path)) keptBytes += s.size
199
+ else if (s.isFile()) files.push({ path, size: s.size, used: s.mtimeMs })
200
+ })
201
+ files.sort((a, b) => a.used - b.used)
202
+ let bytes = files.reduce((n, f) => n + f.size, keptBytes)
203
+ out.files = files.length
204
+ out.bytes = bytes
205
+ if (!present) return out
206
+ const cap = spec.scratchMaxGb === undefined ? Infinity : spec.scratchMaxGb * GB
207
+ let free = driveFree(spec.path)
208
+ for (const f of files) {
209
+ if ((bytes <= cap && free >= keepFree(spec)) || f.used > now - SCRATCH_KEEP_DAYS * DAY) break
210
+ if (!o.dry) rmSync(f.path, { force: true })
211
+ bytes -= f.size
212
+ free += f.size
213
+ out.freed.files++
214
+ out.freed.bytes += f.size
215
+ }
216
+ if (!o.dry) machineSet(SCRATCH_USE, { ...(machineGet<Record<string, unknown>>(SCRATCH_USE) ?? {}), [spec.path]: { files: files.length - (out.freed.files - parts), bytes, at: now } })
217
+ return out
218
+ }
219
+
220
+ /** one pass at a time on the machine: the daemon's and a hand's. A holder that died frees it */
221
+ function passLock(): (() => void) | null {
222
+ const path = join(dirname(machineDbPath()), 'annex-pass.pid')
223
+ for (let i = 0; i < 2; i++) {
224
+ try {
225
+ writeFileSync(path, String(process.pid), { flag: 'wx' })
226
+ return () => rmSync(path, { force: true })
227
+ } catch {
228
+ const pid = Number(readFileSync(path, 'utf8').trim())
229
+ let alive = false
230
+ try {
231
+ alive = pid > 0 && process.kill(pid, 0)
232
+ } catch {
233
+ alive = false
234
+ }
235
+ if (alive) return null
236
+ rmSync(path, { force: true })
237
+ }
238
+ }
239
+ return null
240
+ }
241
+
242
+ /** the daemon looks at this every 30 s, a few stats: a link that dangles, a spill whose drive is back, an aside left,
243
+ * a born folder gone, or the full pass due */
244
+ export function annexDue(now: number): boolean {
245
+ if (!annexAuto()) return false
246
+ if (now - (machineGet<number>(FULL_AT) ?? 0) >= FULL_EVERY_MS) return true
247
+ for (const r of offloads()) {
248
+ if (r.aside !== undefined) return true
249
+ const at = join(r.repo, r.rel)
250
+ const l = lstatSync(at, { throwIfNoEntry: false })
251
+ if (l?.isSymbolicLink() && !existsSync(at)) return true
252
+ if (r.spill !== undefined && existsSync(r.target)) return true
253
+ if (r.born && r.spill === undefined && !l?.isSymbolicLink()) return true
254
+ }
255
+ return false
256
+ }
257
+
258
+ export type TickOpts = Probe & {
259
+ roots: string[]
260
+ /** the house repo, whose config holds `serve.annexScratch` */
261
+ house: string | null
262
+ print: (l: string) => void
263
+ printErr: (l: string) => void
264
+ now?: number
265
+ /** the declarations, the stale scratch and the cap now, whenever the last full pass ran */
266
+ full?: boolean
267
+ /** what the stale pass and the sweep would do; no record is settled, no folder linked */
268
+ dry?: boolean
269
+ openUnder?: Pass['openUnder']
270
+ }
271
+
272
+ const AUTO_KEY = 'annex-auto'
273
+ /** the owner's switch, off until it is turned on (`sk annex tidy --auto on`): the daemon's job moves nothing before */
274
+ export const annexAuto = (): boolean => machineGet<boolean>(AUTO_KEY) === true
275
+ export const setAnnexAuto = (on: boolean): boolean => machineSet(AUTO_KEY, on)
276
+
277
+ /** one pass: the daemon's `annex` job (only once the switch is on), `sk annex tidy` (a hand's: `full`) */
278
+ export async function annexTick(o: TickOpts): Promise<void> {
279
+ if (!o.full && !annexAuto()) return
280
+ const release = passLock()
281
+ if (!release) {
282
+ o.printErr('annex: another annex pass runs: this one stops')
283
+ return
284
+ }
285
+ try {
286
+ await tick(o)
287
+ } finally {
288
+ release()
289
+ }
290
+ }
291
+
292
+ async function tick(o: TickOpts): Promise<void> {
293
+ const now = o.now ?? Date.now()
294
+ const say = (l: string): void => (l.startsWith('WARN') ? o.printErr(l) : o.print(l))
295
+ const pass: Pass = { ...o, say, now, loud: o.full === true }
296
+ const specs = await annexSpecs()
297
+ const roots = new Set(o.roots)
298
+ if (!o.dry)
299
+ for (const r of offloads())
300
+ if (roots.has(r.repo))
301
+ try {
302
+ settle(r, specs, pass)
303
+ } catch (e) {
304
+ o.printErr(`WARN annex: ${r.rel} of ${r.repo} not settled: ${(e as Error).message}`)
305
+ }
306
+ if (!o.full && now - (machineGet<number>(FULL_AT) ?? 0) < FULL_EVERY_MS) return
307
+ if (!o.dry) machineSet(FULL_AT, now)
308
+ const { loadRepoConfig } = await import('../repo-config.ts')
309
+ const house = o.house ? ((await loadRepoConfig(o.house).catch(() => null))?.serve?.annexScratch ?? undefined) : undefined
310
+ let floor = policyOf(house, {}).floorGb
311
+ for (const root of roots) {
312
+ if (!existsSync(join(root, 'repo.config.ts'))) continue
313
+ let cfg
314
+ try {
315
+ cfg = await loadRepoConfig(root)
316
+ } catch (e) {
317
+ o.printErr(`WARN annex: ${root}: its repo.config.ts does not load, its scratch is left as it is: ${(e as Error).message}`)
318
+ continue
319
+ }
320
+ const p = policyOf(house, cfg.annex)
321
+ if (p === null) {
322
+ // not opted in: its records stay as they are, none of them born
323
+ if (o.dry) o.print(`${root}: no annex key in its repo.config.ts: nothing of its scratch moves by itself (annex: {} opts in)`)
324
+ else if (offloads().some((x) => x.repo === root && x.born === true)) editOffloads((list) => list.map((x) => (x.repo === root && x.born === true ? { ...x, born: false } : x)))
325
+ continue
326
+ }
327
+ if (o.dry) {
328
+ for (const rel of p.born) {
329
+ const r = offloads().find((x) => x.repo === root && x.rel === rel)
330
+ const c = r ? null : await bornCheck(root, rel, specs, { ...o, say: () => undefined })
331
+ o.print(`born ${rel}: ${r ? (r.spill !== undefined ? 'a spill on the Mac' : 'on the annex') : c && 'why' in c ? c.why : 'would be linked to the annex'}`)
332
+ }
333
+ } else {
334
+ for (const rel of p.born)
335
+ try {
336
+ await bear(root, rel, specs, pass)
337
+ } catch (e) {
338
+ o.printErr(`WARN annex: ${rel} of ${root} not linked: ${(e as Error).message}`)
339
+ }
340
+ const unborn = (x: Offload): boolean => x.repo === root && x.born === true && !p.born.includes(x.rel)
341
+ if (offloads().some(unborn)) editOffloads((list) => list.map((x) => (unborn(x) ? { ...x, born: false } : x)))
342
+ }
343
+ floor = p.floorGb
344
+ const a = await agePass(root, p, { ...o, now })
345
+ if (a.days === null) {
346
+ if (o.dry) o.print(`${root}: scratch on the Mac ${(a.onMac / GB).toFixed(1)} GB of ${p.capGb} GB, the disk ${(a.free / GB).toFixed(1)} GB free over its ${p.floorGb} GB floor: nothing to move`)
347
+ continue
348
+ }
349
+ for (const m of a.moved) o.print(`${o.dry ? 'would move' : 'ok: annex: moved'} ${m.rel} of ${root} (stale ${a.days} days, ${(m.bytes / GB).toFixed(1)} GB)`)
350
+ const key = `aged:${root}`
351
+ if (a.onMac > p.capGb * GB && !o.dry)
352
+ sayOnce(key, `WARN annex: ${root}: ${(a.onMac / GB).toFixed(1)} GB of scratch on the Mac, over its ${p.capGb} GB cap, and nothing more stale for ${a.days} days moves${a.refused.length > 0 ? `; refused: ${a.refused[0]!.rel}: ${a.refused[0]!.why}` : ''}: what is fresh stays, a folder that belongs on the annex goes in annex.born`, say, o.full)
353
+ else if (!o.dry) sayOnce(key, null, say)
354
+ if (o.dry) for (const r of a.refused) o.print(`refused ${r.rel}: ${r.why}`)
355
+ }
356
+ // the disk under its floor once every repo moved what it could: said once for the machine, never once a repo
357
+ const free = freeBytes(o.house ?? [...roots][0] ?? '/')
358
+ if (!o.dry) {
359
+ const words = free < floor * GB ? heldWords(held(offloads(), localSnapshots())) : null
360
+ sayOnce('floor', free < floor * GB ? `WARN annex: the Mac's disk has ${(free / GB).toFixed(1)} GB free, under its ${floor} GB floor, with every stale scratch folder moved${words ? `; ${words}` : ''}` : null, say, o.full)
361
+ }
362
+ if (!o.full && now - (machineGet<number>(SWEPT_AT) ?? 0) < SWEEP_EVERY_MS) return
363
+ if (!o.dry) machineSet(SWEPT_AT, now)
364
+ for (const a of specs.filter(isPresent)) {
365
+ const s = scratchSweep(a, { dry: o.dry === true, now })
366
+ if (s.freed.files > 0) o.print(`${o.dry ? 'would free' : 'ok: annex: freed'} ${s.freed.files} scratch files of ${a.path} (${(s.freed.bytes / GB).toFixed(1)} GB), untouched ${SCRATCH_KEEP_DAYS} days`)
367
+ }
368
+ }
@@ -25,9 +25,34 @@ export function slugify(title: string, max = 40): string {
25
25
  return (lastDash > 0 ? cut.slice(0, lastDash) : cut).replace(/-+$/, '')
26
26
  }
27
27
 
28
+ /** the front matter block, between the first two `---` lines: the only place
29
+ * a key lives. A body line that starts with `check:` is prose, and read as a
30
+ * key it would run as shell */
31
+ const splitFront = (md: string): { head: string[]; body: string[] } | null => {
32
+ const lines = md.split(/\r?\n/)
33
+ const end = lines[0]?.trim() === '---' ? lines.findIndex((l, i) => i > 0 && l.trim() === '---') : -1
34
+ return end === -1 ? null : { head: lines.slice(1, end), body: lines.slice(end + 1) }
35
+ }
36
+ const frontMatter = (md: string): string => splitFront(md)?.head.join('\n') ?? ''
37
+
38
+ /** the ask with these keys set in its front matter, where parse reads them; an
39
+ * ask with no block gets one */
40
+ const withKeys = (md: string, keys: [string, string][]): string => {
41
+ const f = splitFront(md) ?? { head: [], body: ['', ...md.split(/\r?\n/)] }
42
+ const head = [...f.head]
43
+ for (const [k, v] of keys) {
44
+ const at = head.findIndex((l) => l.startsWith(`${k}:`))
45
+ if (at === -1) head.push(`${k}: ${v}`)
46
+ else head[at] = `${k}: ${v}`
47
+ }
48
+ return ['---', ...head, '---', ...f.body].join('\n')
49
+ }
50
+ const closedKeys = (): [string, string][] => [['status', 'done'], ['closed', new Date().toISOString().slice(0, 10)]]
51
+
28
52
  const parse = (dir: string, file: string): Ask => {
29
53
  const md = readFileSync(join(dir, file), 'utf8')
30
- const fm = (key: string): string | null => md.match(new RegExp(`^${key}:\\s*(.+)$`, 'm'))?.[1]?.trim() ?? null
54
+ const head = frontMatter(md)
55
+ const fm = (key: string): string | null => head.match(new RegExp(`^${key}:\\s*(.+)$`, 'm'))?.[1]?.trim() ?? null
31
56
  return {
32
57
  file,
33
58
  status: fm('status') ?? 'open',
@@ -100,8 +125,7 @@ function probeAsk(root: string, dir: string, a: Ask, check: string): { passed: t
100
125
  }
101
126
  const done = join(dir, 'done')
102
127
  mkdirSync(done, { recursive: true })
103
- const md = readFileSync(join(dir, a.file), 'utf8').replace(/^status:.*$/m, `status: done\nclosed: ${new Date().toISOString().slice(0, 10)}`)
104
- atomicWrite(join(dir, a.file), md)
128
+ atomicWrite(join(dir, a.file), withKeys(readFileSync(join(dir, a.file), 'utf8'), closedKeys()))
105
129
  renameSync(join(dir, a.file), join(done, a.file))
106
130
  return { passed: true }
107
131
  }
@@ -206,8 +230,7 @@ ${whyBlock}${opts?.kind === 'decision' ? DECISION_BODY : secrets.length > 0 ? cr
206
230
  export function archiveAsk(dir: string, file: string): void {
207
231
  const p = join(dir, file)
208
232
  if (!existsSync(p)) throw new Error(`no such ask: ${file}`)
209
- const md = readFileSync(p, 'utf8').replace(/^status:.*$/m, `status: done\nclosed: ${new Date().toISOString().slice(0, 10)}`)
210
- writeFileSync(p, md)
233
+ writeFileSync(p, withKeys(readFileSync(p, 'utf8'), closedKeys()))
211
234
  const done = join(dir, 'done')
212
235
  mkdirSync(done, { recursive: true })
213
236
  renameSync(p, join(done, file))
@@ -227,12 +250,10 @@ export function markPinged(dir: string, file: string): boolean {
227
250
  const p = join(dir, file)
228
251
  if (!existsSync(p)) return false
229
252
  const md = readFileSync(p, 'utf8')
230
- if (/^pinged:/m.test(md)) return false
231
- const line = `pinged: ${new Date().toISOString().slice(0, 10)}`
232
- const withMark = md.replace(/^status:(.*)$/m, `status:$1\n${line}`)
233
- // a hand-edited ask without status: still gets a durable marker — a
234
- // no-op write here would re-fire the ping every tick forever
235
- writeFileSync(p, withMark !== md ? withMark : `${line}\n${md}`)
253
+ if (/^pinged:/m.test(frontMatter(md))) return false
254
+ // in the front matter, where it is read: a marker parse misses re-fires
255
+ // the ping every tick forever
256
+ writeFileSync(p, withKeys(md, [['pinged', new Date().toISOString().slice(0, 10)]]))
236
257
  return true
237
258
  }
238
259
 
@@ -2,8 +2,10 @@
2
2
  // `sk annex offload` moved to an external drive still reaches its copy there.
3
3
  // It warns, never fails: an unplugged drive is the world, not the repo. A link
4
4
  // that reaches nothing, a recorded folder that is no longer a link (a reset made
5
- // a real folder on the Mac), and a folder on the annex no link reaches are each
6
- // named with the command that settles them
5
+ // a real folder on the Mac), a move in flight (a Mac copy set aside, recorded or
6
+ // not), a spill, a loser a merge kept beside its winner, and a folder on the
7
+ // annex no link reaches are each named with what settles them; a born folder's
8
+ // never names `forget`
7
9
  import { check } from '../check.ts'
8
10
 
9
11
  export const annexLinks = check({
@@ -0,0 +1,45 @@
1
+ // SK043 scratch on the Mac (tools/shipkit/annex.md, Scratch by itself): this repo's `.shipkit/tmp` and `.shipkit/cache`
2
+ // on the Mac's own disk, links not followed, stay under the cap (`annex.capGb`, else the house's `serve.annexScratch`,
3
+ // else 20 GB). A folder born on the annex or moved there is a link and counts nothing; a spill counts whole. It warns,
4
+ // never fails: the daemon's annex job moves stale scratch by itself in a repo that declared `annex`, and this row says
5
+ // when it could not, with the one command that runs the pass now; in a repo that declared none, it names the opt in
6
+ import { check } from '../check.ts'
7
+
8
+ const GB = 1e9
9
+
10
+ /** why the scratch on the Mac is over its cap, null while it is under. `opted`: the repo declares `annex`, so the
11
+ * pass may move its stale scratch */
12
+ export function scratchProblem(bytes: number, capGb: number, opted = true): string | null {
13
+ if (bytes <= capGb * GB) return null
14
+ if (!opted) return `${(bytes / GB).toFixed(1)} GB of .shipkit/tmp and .shipkit/cache on the Mac, over the ${capGb} GB cap, and repo.config.ts declares no annex key, so nothing of it moves by itself: add annex: {} (the house defaults; keep names a folder read hot, born one that lives on the annex), then sk annex tidy --dry lists what would move`
15
+ return `${(bytes / GB).toFixed(1)} GB of .shipkit/tmp and .shipkit/cache on the Mac, over its ${capGb} GB cap: sk annex tidy moves stale scratch to the annex now (sk annex tidy --dry lists it first); a folder that must live there from its first byte goes in annex.born of repo.config.ts`
16
+ }
17
+
18
+ export const scratchOnTheMac = check({
19
+ id: 'SK043',
20
+ blocking: false,
21
+ title: 'scratch on the Mac',
22
+ description: "this repo's .shipkit/tmp and .shipkit/cache on the Mac's disk stay under the scratch cap",
23
+ owner: 'tools/shipkit/annex.md',
24
+ runs: { onPreCommit: false, onCi: false, onFull: true, onRelease: false, onHealth: true, onSave: false, onClock: false },
25
+ cache: { by: 'never', why: 'it measures scratch outside git, one du of about half a second' },
26
+ fix: 'none',
27
+ applies: 'always',
28
+ run: async (c) => {
29
+ const { policyOf, scratchOnMac } = await import('../annex/tidy.ts')
30
+ const { houseRootOf } = await import('../home/home-start.ts')
31
+ const { loadRepoConfig } = await import('../repo-config.ts')
32
+ const house = houseRootOf(c.root)
33
+ const houseScratch = house == null || house === c.root ? c.config.serve?.annexScratch : (await loadRepoConfig(house).catch(() => null))?.serve?.annexScratch
34
+ const p = policyOf(houseScratch, c.config.annex ?? {})
35
+ const { offloads } = await import('../annex/offload.ts')
36
+ const { held, heldWords, localSnapshots } = await import('../annex/snapshots.ts')
37
+ const bytes = scratchOnMac(c.root)
38
+ const why = scratchProblem(bytes, p.capGb, c.config.annex !== undefined)
39
+ const words = heldWords(held(offloads().filter((x) => x.repo === c.root), localSnapshots()))
40
+ if (why) c.warn(words ? `${why}; ${words}` : why)
41
+ else c.ok(`${(bytes / GB).toFixed(1)} GB of scratch on the Mac, cap ${p.capGb} GB${words ? `; ${words}` : ''}`)
42
+ },
43
+ })
44
+
45
+ export default scratchOnTheMac
@@ -0,0 +1,38 @@
1
+ // SK044 behind upstream: after a fetch, the branch holds every commit its upstream has. Two Macs work one repo through
2
+ // git alone (tools/shipkit/home.md, Two machines), so a session on one Mac must learn that the other pushed. It warns
3
+ // and never pulls: a pull moves the tree under every session working in it. No git, no upstream, a fetch that fails:
4
+ // a skip, never red, since it reports the world.
5
+ import { check } from '../check.ts'
6
+ import { probeGitRoot } from '../core/git-root.ts'
7
+
8
+ const firstLine = (text: string): string => text.trim().split('\n')[0] ?? ''
9
+
10
+ export const behindUpstream = check({
11
+ id: 'SK044',
12
+ blocking: false,
13
+ title: 'behind upstream',
14
+ description: 'the branch holds every commit its upstream has, after a fetch',
15
+ owner: 'tools/shipkit/home.md',
16
+ runs: { onPreCommit: false, onCi: false, onFull: false, onRelease: false, onHealth: true, onSave: false, onClock: { every: '30m', inactive: 'wait' } },
17
+ cache: { by: 'never', why: 'it asks the remote what it holds now' },
18
+ fix: 'none',
19
+ applies: 'always',
20
+ run: async (c) => {
21
+ const skip = (why: string): void => void c.lines.push({ kind: 'skip', text: `behind upstream unverified: ${why}` })
22
+ if (probeGitRoot(c.root).root == null) return skip('no git')
23
+ const up = await c.exec(['git', 'rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'], { cwd: c.root })
24
+ if (up.code !== 0) return skip('the branch has no upstream')
25
+ const upstream = up.out.trim()
26
+ // with no remote named, git fetches the branch's own remote
27
+ const fetched = await c.exec(['git', 'fetch', '--quiet'], { cwd: c.root, timeoutMs: 20_000 })
28
+ if (fetched.code !== 0) return skip(`git fetch failed (${firstLine(fetched.out) || `exit ${fetched.code}`})`)
29
+ const count = await c.exec(['git', 'rev-list', '--left-right', '--count', 'HEAD...@{u}'], { cwd: c.root })
30
+ if (count.code !== 0) return skip(`git rev-list says ${firstLine(count.out)}`)
31
+ const [ahead, behind] = count.out.trim().split(/\s+/).map(Number) as [number, number]
32
+ if (behind === 0) return c.ok(`the branch holds every commit of ${upstream}`)
33
+ const how = ahead === 0 ? 'git pull --ff-only' : `git pull, a merge: the branch also holds ${ahead} commit(s) ${upstream} lacks`
34
+ c.warn(`${behind} commit(s) on ${upstream} that this branch lacks: another Mac or session pushed. Pull before you work: ${how}`)
35
+ },
36
+ })
37
+
38
+ export default behindUpstream