rvlib-shipkit 2.22.0 → 2.23.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 (52) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/package.json +1 -1
  3. package/src/annex/annex.ts +3 -0
  4. package/src/annex/born.ts +464 -0
  5. package/src/annex/flush.ts +46 -0
  6. package/src/annex/offload.ts +171 -38
  7. package/src/annex/snapshots.ts +53 -0
  8. package/src/annex/tidy.ts +368 -0
  9. package/src/checks/SK041-annex-links.check.ts +4 -2
  10. package/src/checks/SK043-scratch-on-the-mac.check.ts +45 -0
  11. package/src/cli/cmd_Annex.ts +60 -9
  12. package/src/cli/cmd_Home.ts +28 -0
  13. package/src/cli/cmd_Rec.ts +17 -7
  14. package/src/cli/cmd_Review.ts +27 -3
  15. package/src/core/machine-db.ts +8 -0
  16. package/src/home/claude-temp.ts +139 -0
  17. package/src/home/daemon-jobs.ts +10 -3
  18. package/src/home/global-units.ts +3 -0
  19. package/src/home/machine-stores.ts +27 -3
  20. package/src/home/pm.ts +4 -1
  21. package/src/home/run-pm.ts +1 -0
  22. package/src/identities/identities.ts +92 -24
  23. package/src/media-store/daemon.ts +2 -2
  24. package/src/media-store/purge.ts +4 -0
  25. package/src/recordings/load.ts +3 -3
  26. package/src/recordings/model.ts +7 -0
  27. package/src/recordings/open.ts +12 -0
  28. package/src/recordings/presets.ts +12 -5
  29. package/src/recordings/recorder-app/Capture.swift +34 -5
  30. package/src/recordings/recorder-app/Clip.swift +218 -54
  31. package/src/recordings/recorder-app/Editor.swift +177 -7
  32. package/src/recordings/recorder-app/Hud.swift +189 -0
  33. package/src/recordings/recorder-app/Tray.swift +179 -36
  34. package/src/recordings/recorder-app/icon.svg +16 -0
  35. package/src/recordings/recorder-app/main.swift +363 -29
  36. package/src/recordings/recorder-app.ts +8 -4
  37. package/src/recordings/recorder.shipkit.ts +2 -1
  38. package/src/recordings/routes.ts +52 -6
  39. package/src/recordings/run-recorder.ts +2 -1
  40. package/src/recordings/share.ts +27 -0
  41. package/src/recordings/take.ts +36 -4
  42. package/src/recordings/view.ts +11 -0
  43. package/src/repo-config.ts +9 -1
  44. package/src/review/model.ts +33 -4
  45. package/src/serve/hub-app/hub.css +4 -0
  46. package/src/serve/hub-app/recordings-st.ts +135 -24
  47. package/src/serve/hub-app/recordings-view.tsx +293 -54
  48. package/src/serve/hub-app/recordings.css +77 -24
  49. package/src/shipkit-files.ts +5 -0
  50. package/src/social/drafts.ts +4 -3
  51. package/src/social/load.ts +7 -2
  52. package/src/social/publish/discord.ts +10 -3
@@ -57,8 +57,10 @@ export class RecCommand extends Command {
57
57
  async execute(): Promise<number> {
58
58
  return run(this.context, async (io) => {
59
59
  const { listRecordings } = await import('../recordings/model.ts')
60
+ const { webpPath } = await import('../recordings/share.ts')
60
61
  const all = await listRecordings(this.repo === undefined ? {} : { repo: this.repo })
61
- for (const r of all) io.out(this.json ? JSON.stringify(r) : line(r))
62
+ // webp: where the app keeps the WebP a copy makes of what plays
63
+ for (const r of all) io.out(this.json ? JSON.stringify({ ...r, webp: webpPath(r) }) : line(r))
62
64
  if (!this.json && all.length === 0) io.out('no recording yet: a hotkey of the menu bar app records one (sk rec presets lists them)')
63
65
  return 0
64
66
  })
@@ -120,7 +122,9 @@ export class RecImportCommand extends Command {
120
122
  } catch (e) {
121
123
  failed = (e as Error).message
122
124
  }
123
- if (this.json) io.out(JSON.stringify({ ok: failed === null, recording: rec, said, ...(failed ? { error: failed } : {}), ...(warn ? { warn } : {}) }))
125
+ // webp: where the app keeps the WebP its shot made of this take
126
+ const { webpPath } = await import('../recordings/share.ts')
127
+ if (this.json) io.out(JSON.stringify({ ok: failed === null, recording: { ...rec, webp: webpPath(rec) }, said, ...(failed ? { error: failed } : {}), ...(warn ? { warn } : {}) }))
124
128
  else if (failed) io.err(`FAIL: ${failed}; the take is filed: ${rec.dir}`)
125
129
  return failed ? 1 : 0
126
130
  })
@@ -165,7 +169,7 @@ export class RecPresetsCommand extends Command {
165
169
  static override usage = Command.Usage({
166
170
  category: 'Record',
167
171
  description: 'the presets the menu bar app runs: hotkey, what it shoots, its options, what runs after',
168
- details: `${DETAILS}\n\nThe house config's recorder.presets (shipkit's own video and still when it names none), then each repo's own as <repo>/<name>. A wrong preset or a hotkey two presets claim is printed and exits 1. --json is what the app reads: presets, problems, the house repos and the one a take goes to by default.`,
172
+ details: `${DETAILS}\n\nThe house config's recorder.presets (shipkit's own video and still when it names none), then each repo's own as <repo>/<name>. A wrong preset or a hotkey two presets claim is printed and exits 1. --json is what the app reads: presets, the tray's hotkeys, problems, the house repos and the one a take goes to by default.`,
169
173
  examples: [['what the hotkeys do', 'sk rec presets']],
170
174
  })
171
175
  json = Option.Boolean('--json', false, { description: 'the app\'s read: presets, problems, repos, the default repo' })
@@ -182,6 +186,7 @@ export class RecPresetsCommand extends Command {
182
186
  const opts = [p.still ? 'still' : 'video', p.mic && 'mic', p.systemAudio && 'system sound', p.clicks && 'clicks', p.countdown && `countdown ${p.countdown}s`, p.seconds && `${p.seconds}s`].filter(Boolean).join(', ')
183
187
  io.out(`${p.id.padEnd(18)} ${p.keys.join(' ').padEnd(28)} ${shoot}; ${opts}; then ${(p.after ?? []).join(', ') || 'nothing'} (${p.from})`)
184
188
  }
189
+ if (s.trayKeys.length > 0) io.out(`${'tray'.padEnd(18)} ${s.trayKeys.join(' ').padEnd(28)} shows or hides the recent captures`)
185
190
  io.out(`takes go to ${s.repo} (the menu's pick)`)
186
191
  for (const p of s.problems) io.err(`FAIL: ${p}`)
187
192
  return s.problems.length > 0 ? 1 : 0
@@ -301,7 +306,7 @@ export class RecEditCommand extends Command {
301
306
  static override usage = Command.Usage({
302
307
  category: 'Record',
303
308
  description: 'a recording\'s edit as text: printed, or set and exported (keep, speed, crop, mute)',
304
- details: `${DETAILS}\n\nOne line a verb: \`keep 0:01.5-0:12, 0:15-0:40\`, \`speed 2x 0:20-0:30\`, \`crop 1280x720+40+80\`, \`mute\`. Times are the take's. Setting it exports out.mp4 in one ffmpeg pass; an empty text removes the edit, and the take plays again. The take itself never changes.`,
309
+ details: `${DETAILS}\n\nOne line a verb: \`keep 0:01.5-0:12, 0:15-0:40\`, \`speed 2x 0:20-0:30\`, \`crop 1280x720+40+80\`, \`mute\`. Times are the take's. Setting it exports out.mp4 in one ffmpeg pass as a new version; the same text again changes nothing. An empty text removes the edit, and the take plays again. The take itself never changes.`,
305
310
  examples: [['what it is now', 'sk rec edit boss-fight'], ['trim both ends', 'sk rec edit boss-fight --set "keep 0:02-0:31"']],
306
311
  })
307
312
  ref = Option.String()
@@ -309,14 +314,19 @@ export class RecEditCommand extends Command {
309
314
  set = Option.String('--set', { description: 'the whole edit, lines split by a newline or a semicolon' })
310
315
  async execute(): Promise<number> {
311
316
  return run(this.context, async (io) => {
312
- const { editText, saveEdit } = await import('../recordings/take.ts')
317
+ const { editText, sameEdit, saveEdit, versionsOf } = await import('../recordings/take.ts')
313
318
  const r = await find(this.ref, this.repo)
314
319
  if (this.set === undefined) {
315
320
  io.out(editText(r) || '(no edit: the take plays whole)')
316
321
  return 0
317
322
  }
318
- const after = await saveEdit(r, this.set.replace(/;\s*/g, '\n'))
319
- io.out(`ok: ${line(after)}`)
323
+ const text = this.set.replace(/;\s*/g, '\n')
324
+ if (sameEdit(r, text)) {
325
+ io.out(`ok: nothing changed since v${versionsOf(r).at(-1)?.n ?? 0}: no new save`)
326
+ return 0
327
+ }
328
+ const after = await saveEdit(r, text)
329
+ io.out(`ok: v${versionsOf(after).at(-1)?.n ?? 0} ${line(after)}`)
320
330
  return 0
321
331
  })
322
332
  }
@@ -552,17 +552,33 @@ export class ReviewInboxCommand extends Command {
552
552
  }
553
553
  }
554
554
 
555
+ /** the lane that acts on a reply or a seen: --as, else SK_AGENT, else none */
556
+ const laneOfCaller = (as: string | undefined): string | null => as?.trim() || process.env.SK_AGENT?.trim() || null
557
+
558
+ /** why the caller may not reply to or mark seen this card (review/model.ts notAnswererOf), null when it may */
559
+ async function answererRefusal(dir: string, id: string, as: string | undefined, op: 'reply' | 'seen'): Promise<string | null> {
560
+ const { readItem, sessionId } = await import('../review/store.ts')
561
+ const { notAnswererOf } = await import('../review/model.ts')
562
+ const x = readItem(dir, id)
563
+ return x === null ? null : notAnswererOf(x, { lane: laneOfCaller(as), session: sessionId() }, op)
564
+ }
565
+
555
566
  export class ReviewSeenCommand extends Command {
556
567
  static override paths = [['review', 'seen']]
557
568
  static override usage = Command.Usage({ category: 'Review', description: 'mark his answers and replies on these items read, once you acted on them', details: DETAILS })
558
569
  ids = Option.Rest({ required: 1 })
570
+ as = Option.String('--as', { description: 'the lane that read it (else SK_AGENT)' })
559
571
 
560
572
  async execute(): Promise<number> {
561
573
  return run(this.context, async (h) => {
562
574
  const { markSeen } = await import('../review/store.ts')
575
+ // every id checked before any is marked: his answer on another lane's card stays unread for that lane
576
+ const ids: [string, string][] = []
577
+ for (const ref of this.ids) ids.push([ref, await idOf(h.dir, ref).catch(() => ref)])
578
+ const refused = (await Promise.all(ids.map(([, id]) => answererRefusal(h.dir, id, this.as, 'seen')))).filter((w) => w !== null)
579
+ if (refused.length > 0) throw new Error(`nothing marked: ${refused.join('; ')}`)
563
580
  let bad = 0
564
- for (const ref of this.ids) {
565
- const id = await idOf(h.dir, ref).catch(() => ref)
581
+ for (const [ref, id] of ids) {
566
582
  if (markSeen(h.dir, id)) h.out(`${ref}: seen`)
567
583
  else {
568
584
  h.err(`FAIL: review: ${ref}: no such item, or nothing of his to read on it`)
@@ -580,12 +596,15 @@ export class ReviewReplyCommand extends Command {
580
596
  id = Option.String()
581
597
  text = Option.String()
582
598
  image = Option.String('--image', { description: 'an image beside the words' })
599
+ as = Option.String('--as', { description: 'the lane that answers (else SK_AGENT)' })
583
600
 
584
601
  async execute(): Promise<number> {
585
602
  return run(this.context, async (h) => {
586
603
  const { addMessage, agentName } = await import('../review/store.ts')
587
604
  const id = await idOf(h.dir, this.id)
588
- const m = addMessage(h.dir, id, agentName(), this.text, this.image)
605
+ const refused = await answererRefusal(h.dir, id, this.as, 'reply')
606
+ if (refused !== null) throw new Error(refused)
607
+ const m = addMessage(h.dir, id, laneOfCaller(this.as) ?? agentName(), this.text, this.image)
589
608
  h.out(`${id}: ${m.id}`)
590
609
  return 0
591
610
  })
@@ -1086,6 +1105,11 @@ export class ReviewWatchCommand extends Command {
1086
1105
  const lane = this.lane?.trim() || null
1087
1106
  if (lane !== null && !AGENT_RE.test(lane)) throw new Error(`--lane: « ${lane} » is no lane id (${AGENT_RE.source})`)
1088
1107
  const mine = (x: Parameters<typeof coversCard>[1]): boolean => coversCard({ session, lane }, x)
1108
+ if (session === null && lane === null) {
1109
+ const { bareWatchTaken } = await import('../review/model.ts')
1110
+ const taken = bareWatchTaken(liveWatchers(h.dir), process.pid)
1111
+ if (taken !== null) throw new Error(taken)
1112
+ }
1089
1113
  registerWatch(h.dir, { session, lane })
1090
1114
  // before any await: a pull that hangs never keeps a watch alive past its owner
1091
1115
  exitWithOwner()
@@ -52,6 +52,14 @@ export function machineGet<T>(name: string): T | null {
52
52
  try { return JSON.parse(row.value) as T } catch { return null }
53
53
  }
54
54
 
55
+ /** the value, null when no row: a db that does not open THROWS, for a read a write builds on (a busy db read as
56
+ * "nothing" would save one record over all the others) */
57
+ export function machineRead<T>(name: string): T | null {
58
+ const got = withMachine((db) => ({ row: db.query('select value from state where name = ?').get(name) as { value: string } | null }))
59
+ if (got == null) throw new Error(`the machine db does not open: ${name} is not read`)
60
+ return got.row == null ? null : (JSON.parse(got.row.value) as T)
61
+ }
62
+
55
63
  export function machineSet(name: string, value: unknown): boolean {
56
64
  return withMachine((db) => {
57
65
  db.query('insert or replace into state (name, value, at) values (?, ?, ?)').run(name, JSON.stringify(value), Date.now())
@@ -0,0 +1,139 @@
1
+ // claude code's per session scratch, `<temp root>/<project>/<session>/`: nothing
2
+ // trims it but a reboot. A pass of the retention sweep (machine-stores.ts) keeps
3
+ // every session written in the last guard hours, then the newest idle ones while
4
+ // they fit under the cap, and deletes the rest, oldest first.
5
+ //
6
+ // the one constraint a reader breaks first: this deletes for real (the Trash is
7
+ // on the same disk). Nothing outside the checked root, and no link is followed:
8
+ // lstat everywhere, a link is removed as a link.
9
+ import { lstatSync, readdirSync, realpathSync, rmSync } from 'node:fs'
10
+ import { homedir } from 'node:os'
11
+ import { basename, join, sep } from 'node:path'
12
+ import { machineGet, machineSet } from '../core/machine-db.ts'
13
+
14
+ /** what the idle sessions may hold together */
15
+ export const CLAUDE_TEMP_MAX_BYTES = 5e9
16
+ /** a session written this recently is never touched, whatever its size */
17
+ export const CLAUDE_TEMP_GUARD_MS = 24 * 60 * 60 * 1000
18
+
19
+ const AUTO_KEY = 'claude-temp-auto'
20
+ /** the owner's switch, off until it is turned on: the daemon's sweep deletes nothing before */
21
+ export const claudeTempAuto = (): boolean => machineGet<boolean>(AUTO_KEY) === true
22
+ export const setClaudeTempAuto = (on: boolean): boolean => machineSet(AUTO_KEY, on)
23
+
24
+ /** where claude code keeps it on this machine: its own override, else /tmp, then one folder per uid */
25
+ export function claudeTempRoot(env: Record<string, string | undefined> = process.env): string | null {
26
+ const uid = process.getuid?.()
27
+ return uid == null ? null : join(env.CLAUDE_CODE_TMPDIR || '/tmp', `claude-${uid}`)
28
+ }
29
+
30
+ /** the root, resolved once and checked; null when it does not exist; throws on any other shape */
31
+ export function checkedRoot(root: string): string | null {
32
+ const uid = process.getuid?.()
33
+ if (uid == null) throw new Error('no uid on this platform: the claude temp pass does not run')
34
+ if (root.split(/[\\/]/).includes('..')) throw new Error(`${root}: a path with .. is refused`)
35
+ let real: string
36
+ try { real = realpathSync(root) } catch (e) {
37
+ if ((e as { code?: string }).code === 'ENOENT') return null
38
+ throw e
39
+ }
40
+ const s = lstatSync(real)
41
+ if (real === sep || real === homedir() || !s.isDirectory()) throw new Error(`${real}: not a temp folder of its own`)
42
+ if (s.uid !== uid) throw new Error(`${real}: owned by uid ${s.uid}, not ${uid}`)
43
+ if (basename(real) !== `claude-${uid}`) throw new Error(`${real}: not named claude-${uid}`)
44
+ return real
45
+ }
46
+
47
+ export type Unit = { path: string; at: number; bytes: number }
48
+ export type Plan = { root: string; keep: Unit[]; drop: Unit[] }
49
+
50
+ /** newest mtime and size of a tree, lstat only; null once an entry is newer than `fresh` or unreadable */
51
+ function scan(top: string, fresh: number, printErr: (l: string) => void): { at: number; bytes: number } | null {
52
+ let at = 0
53
+ let bytes = 0
54
+ const stack = [top]
55
+ while (stack.length > 0) {
56
+ const p = stack.pop()!
57
+ let s
58
+ try { s = lstatSync(p) } catch { continue }
59
+ at = Math.max(at, s.mtimeMs)
60
+ bytes += s.size
61
+ if (at >= fresh) return null
62
+ if (!s.isDirectory()) continue
63
+ try { for (const n of readdirSync(p)) stack.push(join(p, n)) } catch (e) {
64
+ printErr(`WARN claude temp: ${p} unreadable (${(e as Error).message}), its session kept`)
65
+ return null
66
+ }
67
+ }
68
+ return { at, bytes }
69
+ }
70
+
71
+ const names = (d: string, printErr: (l: string) => void): string[] => {
72
+ try { return readdirSync(d) } catch (e) {
73
+ printErr(`WARN claude temp: ${d} unreadable (${(e as Error).message}), skipped`)
74
+ return []
75
+ }
76
+ }
77
+
78
+ /** every idle unit under the root: newest first under the cap kept, the rest dropped, oldest first */
79
+ export function planClaudeTemp(root: string, o: { now: number; capBytes?: number; guardMs?: number; printErr: (l: string) => void }): Plan | null {
80
+ const real = checkedRoot(root)
81
+ if (real == null) return null
82
+ const fresh = o.now - (o.guardMs ?? CLAUDE_TEMP_GUARD_MS)
83
+ const units: (Unit & { loose: boolean })[] = []
84
+ const loose = (path: string): void => {
85
+ try {
86
+ const s = lstatSync(path)
87
+ if (s.mtimeMs < fresh) units.push({ path, at: s.mtimeMs, bytes: s.size, loose: true })
88
+ } catch { /* raced: gone */ }
89
+ }
90
+ for (const project of names(real, o.printErr)) {
91
+ const pp = join(real, project)
92
+ if (!isDir(pp)) { loose(pp); continue }
93
+ for (const session of names(pp, o.printErr)) {
94
+ const sp = join(pp, session)
95
+ if (!isDir(sp)) { loose(sp); continue }
96
+ const r = scan(sp, fresh, o.printErr)
97
+ if (r != null) units.push({ path: sp, ...r, loose: false })
98
+ }
99
+ }
100
+ // a loose file ranks as the oldest unit: it belongs to no session
101
+ units.sort((a, b) => (b.loose ? -Infinity : b.at) - (a.loose ? -Infinity : a.at))
102
+ const keep: Unit[] = []
103
+ const drop: Unit[] = []
104
+ let total = 0
105
+ for (const u of units) {
106
+ const unit = { path: u.path, at: u.at, bytes: u.bytes }
107
+ if (drop.length === 0 && total + u.bytes <= (o.capBytes ?? CLAUDE_TEMP_MAX_BYTES)) { total += u.bytes; keep.push(unit) } else drop.push(unit)
108
+ }
109
+ return { root: real, keep, drop: drop.reverse() }
110
+ }
111
+
112
+ const isDir = (p: string): boolean => {
113
+ try { return lstatSync(p).isDirectory() } catch { return false }
114
+ }
115
+
116
+ export const gb = (n: number): string => `${(n / 1e9).toFixed(2)} GB`
117
+ const days = (ms: number): string => `${(ms / 86_400_000).toFixed(1)}d`
118
+
119
+ /** one pass: each dropped unit removed (or only named, `dry`), one line each; the bytes freed */
120
+ export function trimClaudeTemp(root: string, o: { now: number; dry?: boolean; capBytes?: number; guardMs?: number; print: (l: string) => void; printErr: (l: string) => void }): number {
121
+ const plan = planClaudeTemp(root, o)
122
+ if (plan == null) return 0
123
+ let freed = 0
124
+ for (const u of plan.drop) {
125
+ if (!u.path.startsWith(plan.root + sep) || u.path.split(sep).includes('..')) throw new Error(`${u.path}: outside ${plan.root}, the pass stops`)
126
+ const line = `${u.path.slice(plan.root.length + 1)} idle ${days(o.now - u.at)} ${gb(u.bytes)}`
127
+ if (o.dry !== true) {
128
+ try { rmSync(u.path, { recursive: true, force: true }) } catch (e) {
129
+ o.printErr(`WARN claude temp: ${u.path} not deleted (${(e as Error).message})`)
130
+ continue
131
+ }
132
+ }
133
+ freed += u.bytes
134
+ o.print(`claude temp: ${o.dry === true ? 'would delete' : 'deleted'} ${line}`)
135
+ }
136
+ const kept = plan.keep.reduce((n, u) => n + u.bytes, 0)
137
+ if (o.dry === true || plan.drop.length > 0) o.print(`claude temp: ${o.dry === true ? 'would free' : 'freed'} ${gb(freed)} in ${plan.drop.length} units; kept ${plan.keep.length} idle units, ${gb(kept)} of ${gb(o.capBytes ?? CLAUDE_TEMP_MAX_BYTES)}, and every session written in the last ${(o.guardMs ?? CLAUDE_TEMP_GUARD_MS) / 3_600_000} h`)
138
+ return freed
139
+ }
@@ -1,5 +1,5 @@
1
1
  // THE DAEMON'S BACKGROUND JOBS, OFF ITS LOOP (wiki tools/shipkit/home.md, Nothing heavy on the daemon's loop): the
2
- // backup, the retention sweep, the media store, the house's global context and the process apps each run as a child process (`sk daemon job <id>`, niced), started
2
+ // backup, the retention sweep, the media store, the annex, the house's global context and the process apps each run as a child process (`sk daemon job <id>`, niced), started
3
3
  // detached with its pid in a file, its lines appended to the daemon's log. The daemon only starts it and reads the
4
4
  // pid: an in place restart adopts a child still running and never starts a second one. What a job remembers between
5
5
  // two runs lives in the machine db, so a restart never redoes a job's work.
@@ -12,11 +12,12 @@ import { machineGet } from '../core/machine-db.ts'
12
12
  import { loopWatch } from '../core/loop-watch.ts'
13
13
  import { BACKUP_EVERY_MS } from '../media-store/backup/daemon.ts'
14
14
  import { MEDIA_EVERY_MS } from '../media-store/daemon.ts'
15
+ import { ANNEX_EVERY_MS, annexDue } from '../annex/tidy.ts'
15
16
  import { SWEEP_EVERY_MS, SWEPT_AT } from './machine-stores.ts'
16
17
  import { contextSourcesStamp, GLOBAL_CONTEXT_DONE, GLOBAL_CONTEXT_EVERY_MS, GLOBAL_CONTEXT_MAX_MS } from './global-context.ts'
17
18
  import { APPS_DONE, APPS_EVERY_MS, appsDue, appsSourcesStamp } from './process-apps.ts'
18
19
 
19
- export type JobId = 'backup' | 'retention sweep' | 'media store' | 'global context' | 'apps'
20
+ export type JobId = 'backup' | 'retention sweep' | 'media store' | 'annex' | 'global context' | 'apps'
20
21
 
21
22
  export interface DaemonJob {
22
23
  id: JobId
@@ -36,6 +37,8 @@ export const JOB_NICE = 15
36
37
 
37
38
  export const DAEMON_JOBS: readonly DaemonJob[] = [
38
39
  { id: 'media store', everyMs: MEDIA_EVERY_MS, firstMs: 15_000 },
40
+ // the scratch on the annex: a spill when the drive leaves, merged back when it returns, born folders, stale scratch
41
+ { id: 'annex', everyMs: ANNEX_EVERY_MS, firstMs: 20_000, due: (now) => annexDue(now) },
39
42
  { id: 'retention sweep', everyMs: 5 * 60_000, firstMs: 10_000, due: (now) => now - (machineGet<number>(SWEPT_AT) ?? 0) >= SWEEP_EVERY_MS },
40
43
  { id: 'backup', everyMs: BACKUP_EVERY_MS, firstMs: BACKUP_EVERY_MS },
41
44
  // the house's generated context: its unit files are imported to be read, a second of compile the loop never pays
@@ -187,6 +190,10 @@ export async function runJobBody(id: JobId, o: { root: string; home: string; pri
187
190
  const { mediaKinds } = await import('../media-kinds.ts')
188
191
  return mediaTick({ roots: repos, kinds: mediaKinds, print: o.print, printErr: o.printErr })
189
192
  }
193
+ if (id === 'annex') {
194
+ const { annexTick } = await import('../annex/tidy.ts')
195
+ return annexTick({ roots: repos, house: o.root, print: o.print, printErr: o.printErr })
196
+ }
190
197
  if (id === 'global context') {
191
198
  const { contextSourcesStamp, houseContext, writeIfChanged } = await import('./global-context.ts')
192
199
  const { machineSet } = await import('../core/machine-db.ts')
@@ -221,5 +228,5 @@ export async function runJobBody(id: JobId, o: { root: string; home: string; pri
221
228
  const { sweepTick } = await import('./machine-stores.ts')
222
229
  const { homeDir } = await import('./home-paths.ts')
223
230
  const { landMotherhome } = await import('../core/motherhome.ts')
224
- return sweepTick({ roots: repos, dir: homeDir(), printErr: o.printErr, also: (now) => { for (const n of landMotherhome({ now })) o.printErr(n) } })
231
+ return sweepTick({ roots: repos, dir: homeDir(), print: o.print, printErr: o.printErr, also: (now) => { for (const n of landMotherhome({ now })) o.printErr(n) } })
225
232
  }
@@ -26,6 +26,8 @@ export type GlobalProcessDecl = {
26
26
  /** as declared: an emoji, or an image path relative to root */
27
27
  icon: string | null
28
28
  actions: ActionDecl[]
29
+ /** pm starts it when pm starts cold */
30
+ atLogin: boolean
29
31
  /** the repo that declares it, and the file, repo-relative */
30
32
  repo: string
31
33
  root: string
@@ -57,6 +59,7 @@ export function toDecl(u: GlobalProcessUnit, repo: RepoRef, file: string): Globa
57
59
  probe: u.probe ?? u.url ?? null,
58
60
  icon: u.icon ?? null,
59
61
  actions: Object.entries(u.actions ?? {}).map(([id, a]) => ({ id, label: a.label, cmd: a.cmd ?? null })),
62
+ atLogin: u.atLogin ?? false,
60
63
  repo: repo.name,
61
64
  root: repo.path,
62
65
  file: relative(repo.path, file).replace(/\\/g, '/'),
@@ -7,6 +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
11
 
11
12
  /** a log nothing wrote for this long belongs to a process that is gone (a
12
13
  * repo removed, a resource dropped) */
@@ -53,9 +54,32 @@ const profileInUse = (profile: string): boolean => {
53
54
  try { return lstatSync(join(profile, 'SingletonLock')).isSymbolicLink() } catch { return false }
54
55
  }
55
56
 
56
- export function machineStores(dir: string): Store[] {
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 []
62
+ 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
+ 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 }
72
+ },
73
+ sweep: (now) => { trimClaudeTemp(root, { now, print: o.print, printErr: o.printErr }) },
74
+ }]
75
+ }
76
+
77
+ const stderr = (l: string): void => void process.stderr.write(`${l}\n`)
78
+
79
+ export function machineStores(dir: string, o: { print?: (l: string) => void; printErr?: (l: string) => void } = {}): Store[] {
57
80
  const profile = join(dir, 'gui-profile')
58
81
  return [
82
+ ...claudeTemp({ print: o.print ?? stderr, printErr: o.printErr ?? stderr }),
59
83
  {
60
84
  id: 'home logs',
61
85
  where: `${dir}/**/*.log`,
@@ -92,12 +116,12 @@ export const SWEEP_EVERY_MS = 60 * 60 * 1000
92
116
  export const SWEPT_AT = 'retention-swept-at'
93
117
  /** one sweep of the daemon's retention job, in its child process: every repo, then the machine, then `also`; its
94
118
  * end time kept, so the daemon's next look waits SWEEP_EVERY_MS whatever restarts in between */
95
- export async function sweepTick(o: { roots: string[]; dir: string; printErr: (l: string) => void; now?: () => number; also?: (now: number) => void }): Promise<void> {
119
+ export async function sweepTick(o: { roots: string[]; dir: string; print?: (l: string) => void; printErr: (l: string) => void; now?: () => number; also?: (now: number) => void }): Promise<void> {
96
120
  const now = (o.now ?? Date.now)()
97
121
  for (const root of o.roots) {
98
122
  for (const r of await sweepStores(repoStores(root), now)) if (r.error != null) o.printErr(`WARN retention sweep of ${r.id} in ${root} failed: ${r.error}`)
99
123
  }
100
- for (const r of await sweepStores(machineStores(o.dir), now)) if (r.error != null) o.printErr(`WARN retention sweep of ${r.id} failed: ${r.error}`)
124
+ for (const r of await sweepStores(machineStores(o.dir, { print: o.print, printErr: o.printErr }), now)) if (r.error != null) o.printErr(`WARN retention sweep of ${r.id} failed: ${r.error}`)
101
125
  o.also?.(now)
102
126
  machineSet(SWEPT_AT, (o.now ?? Date.now)())
103
127
  }
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> {
@@ -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)
@@ -6,7 +6,7 @@ import { homedir } from 'node:os'
6
6
  import { isAbsolute, join } from 'node:path'
7
7
  import { LAYOUT } from '../core/layout.ts'
8
8
  import { parseFrontmatter, rows, section, table, type ProfileRow } from '../social/md.ts'
9
- import { ceilingOf, type PostRating } from './rating.ts'
9
+ import { ceilingOf, ratingIn, type PostRating } from './rating.ts'
10
10
  import { uploadsOf, type Upload } from './shown.ts'
11
11
  import { stepRefs } from './steps.ts'
12
12
 
@@ -97,6 +97,10 @@ export type Account = {
97
97
  ceiling: PostRating
98
98
  /** the venue's own switch a rated post needs, said on its card (X: « mark the media sensitive »); empty, none */
99
99
  sensitive: string
100
+ /** who links to it (`listed:`): every account, or only one rated nsfw */
101
+ listed: Listed
102
+ /** the most links its list holds (`links max:`, the venue's slots); null, no cap */
103
+ linksMax: number | null
100
104
  /** the media a post there may carry (`limits:`); empty, none known */
101
105
  limits: MediaLimits
102
106
  /** absolute */
@@ -192,24 +196,61 @@ function merged(shared: ProfileRow[], own: ProfileRow[]): ProfileRow[] {
192
196
  return [...shared.map((r) => mine.get(r.field) ?? r), ...own.filter((r) => !shared.some((s) => s.field === r.field))]
193
197
  }
194
198
 
195
- /** a text row's value as he pastes it: `[[field]]` the other row's value, `<br>` a new line (a table cell holds none),
196
- * so a venue's text says the bio once, never « the bio » in words */
199
+ /** a text as he pastes it: `[[field]]` that row's value, `<br>` a new line (a table cell holds none); `where` names
200
+ * the text in an error line. A row naming another row, or `self`, is refused, its words kept */
201
+ export function filledText(value: string, rows: readonly ProfileRow[], where: string, errors: string[], self?: ProfileRow): string {
202
+ if (!/\[\[|<br>/.test(value)) return value
203
+ return value
204
+ .replace(/\[\[([^\]]+)\]\]/g, (all, f: string) => {
205
+ const at = rows.find((r) => r.field === f)
206
+ if (at == null || at === self || /\[\[/.test(at.value)) {
207
+ errors.push(`${where} names [[${f}]], ${at == null ? 'no row' : 'a row that names another'}`)
208
+ return all
209
+ }
210
+ return at.value
211
+ })
212
+ .replace(/\s*<br>\s*/g, '\n')
213
+ }
214
+
215
+ /** each text row filled (`filledText`), so a venue's text says the bio once, never « the bio » in words */
197
216
  export function filledRows(list: ProfileRow[], file: string, errors: string[]): ProfileRow[] {
198
- const by = new Map(list.map((r) => [r.field, r]))
199
- return list.map((r) => {
200
- if (r.files.length > 0 || !/\[\[|<br>/.test(r.value)) return r
201
- const value = r.value
202
- .replace(/\[\[([^\]]+)\]\]/g, (all, f: string) => {
203
- const at = by.get(f)
204
- if (at == null || at === r || /\[\[/.test(at.value)) {
205
- errors.push(`${file}: row ${r.field} names [[${f}]], ${at == null ? 'no row' : 'a row that names another'}`)
206
- return all
207
- }
208
- return at.value
209
- })
210
- .replace(/\s*<br>\s*/g, '\n')
211
- return { ...r, value }
212
- })
217
+ return list.map((r) => (r.files.length > 0 ? r : { ...r, value: filledText(r.value, list, `${file}: row ${r.field}`, errors, r) }))
218
+ }
219
+
220
+ /** the computed row an account lists its links in, `[[links]]` in a text */
221
+ export const LINKS = 'links'
222
+ /** `listed:` an account is linked from every account (`all`, the default), or only from an account rated nsfw */
223
+ const LISTED = ['all', 'nsfw'] as const
224
+ export type Listed = (typeof LISTED)[number]
225
+ /** the site's label in a list of links */
226
+ export const SITE_LABEL = 'Site'
227
+
228
+ export type LinkSource = { id: string; name: string; order: number; live: string; listed: Listed; rating: string; linksMax: number | null }
229
+
230
+ /** the links an account shows, one `<label>: <url>` a line: the identity's site first, then every other account online
231
+ * (`live`) in its order, but one `listed: nsfw` on an account not rated nsfw; its `links max` (its slot count) cuts
232
+ * the tail. Read from the accounts' own front matter, so an account that goes live joins every list by itself */
233
+ export function linksOf(self: LinkSource, all: readonly LinkSource[], site: string): string[] {
234
+ const out = site === '' ? [] : [`${SITE_LABEL}: ${site}`]
235
+ for (const a of [...all].sort((x, y) => x.order - y.order || x.id.localeCompare(y.id)))
236
+ if (a.id !== self.id && a.live !== '' && (a.listed === 'all' || self.rating === 'nsfw')) out.push(`${a.name}: ${a.live}`)
237
+ return self.linksMax == null ? out : out.slice(0, self.linksMax)
238
+ }
239
+
240
+ function listedOf(v: string | undefined, file: string, errors: string[]): Listed {
241
+ const w = (v ?? '').trim()
242
+ if (w === '') return 'all'
243
+ if ((LISTED as readonly string[]).includes(w)) return w as Listed
244
+ errors.push(`${file}: listed "${w}" is not ${LISTED.join(' or ')}`)
245
+ return 'all'
246
+ }
247
+
248
+ function linksMaxOf(v: string | undefined, file: string, errors: string[]): number | null {
249
+ const w = (v ?? '').trim()
250
+ if (w === '') return null
251
+ if (/^\d+$/.test(w)) return Number(w)
252
+ errors.push(`${file}: links max "${w}" is no count`)
253
+ return null
213
254
  }
214
255
 
215
256
  function places(dir: string, errors: string[]): Place[] {
@@ -329,11 +370,28 @@ function legal(dir: string, files: string | null): Legal | null {
329
370
  }
330
371
  }
331
372
 
332
- function account(identity: string, id: string, dir: string, shared: ProfileRow[], files: string | null, errors: string[]): Account {
373
+ /** an account's file read, its rows not filled yet: every account's list of links needs each one's front matter first */
374
+ type AccountFile = { id: string; dir: string; file: string; meta: Record<string, string>; body: string; own: ProfileRow[]; src: LinkSource }
375
+
376
+ function accountFile(id: string, dir: string, files: string | null, errors: string[]): AccountFile {
333
377
  const file = join(dir, 'account.md')
334
378
  const { meta, body } = parseFrontmatter(read(file))
335
- linkErrors(file, meta, ['profile', 'live', 'write', 'inbox', 'stats'], errors)
336
379
  const own = rows(body, 'Profile', files)
380
+ const src: LinkSource = {
381
+ id,
382
+ name: meta.name ?? id,
383
+ order: Number(meta.order ?? 99),
384
+ live: meta.live ?? '',
385
+ listed: listedOf(meta.listed, file, errors),
386
+ rating: ratingIn(own),
387
+ linksMax: linksMaxOf(meta['links max'], file, errors),
388
+ }
389
+ return { id, dir, file, meta, body, own, src }
390
+ }
391
+
392
+ function account(identity: string, f: AccountFile, shared: ProfileRow[], files: string | null, errors: string[]): Account {
393
+ const { id, dir, file, meta, body, own } = f
394
+ linkErrors(file, meta, ['profile', 'live', 'write', 'inbox', 'stats'], errors)
337
395
  errors.push(...copiedRows(own, shared, file))
338
396
  const merge = filledRows(merged(shared, own), file, errors)
339
397
  const automation = meta.automation ?? 'none'
@@ -343,8 +401,8 @@ function account(identity: string, id: string, dir: string, shared: ProfileRow[]
343
401
  return {
344
402
  id,
345
403
  identity,
346
- name: meta.name ?? id,
347
- order: Number(meta.order ?? 99),
404
+ name: f.src.name,
405
+ order: f.src.order,
348
406
  handle: meta.handle ?? '',
349
407
  profile: meta.profile ?? '',
350
408
  live: meta.live ?? '',
@@ -364,6 +422,8 @@ function account(identity: string, id: string, dir: string, shared: ProfileRow[]
364
422
  guild,
365
423
  ceiling: ceilingOf(meta.posts, file, errors),
366
424
  sensitive: meta.sensitive ?? '',
425
+ listed: f.src.listed,
426
+ linksMax: f.src.linksMax,
367
427
  limits: limitsOf(meta.limits, file, errors),
368
428
  file,
369
429
  dir,
@@ -397,15 +457,23 @@ function identity(id: string, dir: string, errors: string[]): Identity {
397
457
  // filled once here, so the profile shows and copies a shared text (a tier's lines) as an account does
398
458
  const shared = filledRows(rows(body, 'Profile', files), file, errors)
399
459
  const at = join(dir, 'accounts')
400
- const accounts: Account[] = []
460
+ const found: AccountFile[] = []
401
461
  if (existsSync(at))
402
462
  for (const a of readdirSync(at).sort()) {
403
463
  const adir = join(at, a)
404
464
  if (!statSync(adir).isDirectory()) continue
405
465
  if (!SLUG.test(a)) errors.push(`${adir}: an account folder is kebab case`)
406
466
  else if (!existsSync(join(adir, 'account.md'))) errors.push(`${adir}: no account.md`)
407
- else accounts.push(account(id, a, adir, shared, files, errors))
467
+ else found.push(accountFile(a, adir, files, errors))
408
468
  }
469
+ // the site is the `link` row; each account inherits its list as a row, `[[links]]` in its texts, none while the list
470
+ // is empty (no site, nothing online), so a text naming it says so loud
471
+ const site = shared.find((r) => r.field === 'link' && r.files.length === 0)?.value.trim() ?? ''
472
+ const sources = found.map((f) => f.src)
473
+ const accounts = found.map((f) => {
474
+ const links = linksOf(f.src, sources, site)
475
+ return account(id, f, links.length === 0 ? shared : [...shared, { field: LINKS, value: links.join('\n'), files: [] }], files, errors)
476
+ })
409
477
  accounts.sort((a, b) => a.order - b.order || a.id.localeCompare(b.id))
410
478
  for (const a of accounts) if (a.automation === 'live' && a.secret === '') errors.push(`${a.file}: automation live names no secret (its token name)`)
411
479
  return {
@@ -5,7 +5,7 @@
5
5
  import { existsSync } from 'node:fs'
6
6
  import { machineGet, machineSet } from '../core/machine-db.ts'
7
7
  import type { MediaKind } from './kind.ts'
8
- import { FREE_MIN_BYTES, freeBytes, purge, purgeCandidates } from './purge.ts'
8
+ import { FREE_MIN_BYTES, freeBytes, purge, purgeCandidates, windowDays } from './purge.ts'
9
9
  import { machineSpace } from './space.ts'
10
10
  import { syncKind } from './sync.ts'
11
11
  import { mb, uploadWaiting } from './upload.ts'
@@ -65,7 +65,7 @@ export async function mediaTick(o: { roots: string[]; kinds: () => readonly Medi
65
65
  machineSet(PURGED_AT, Date.now())
66
66
  for (const { kind, root, dir } of stores) {
67
67
  if (freeBytes(dir) >= FREE_MIN_BYTES) continue
68
- const { candidates } = await purgeCandidates(kind, dir)
68
+ const { candidates } = await purgeCandidates(kind, dir, { olderDays: windowDays(freeBytes(dir)) })
69
69
  const r = await purge(kind, dir, space, candidates, { enough: () => freeBytes(dir) >= FREE_MIN_BYTES })
70
70
  if (r.files > 0) o.print(`ok: media store: the disk under ${mb(FREE_MIN_BYTES)} free, ${r.files} ${kind.kind} files of ${root} purged (${mb(r.freed)})`)
71
71
  if (r.refused.length > 0) o.printErr(`WARN media store: ${r.refused.length} ${kind.kind} files of ${root} kept: ${r.refused[0]?.key}: ${r.refused[0]?.why}`)