rvlib-shipkit 2.24.0 → 2.26.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 (99) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/package.json +2 -2
  3. package/src/agent-time/hooks.ts +329 -0
  4. package/src/agent-time/live.ts +153 -0
  5. package/src/agent-time/render.ts +14 -2
  6. package/src/agent-time/report.ts +56 -4
  7. package/src/agent-time/store.ts +59 -5
  8. package/src/annex/offload.ts +16 -7
  9. package/src/check.ts +3 -1
  10. package/src/checks/SK004-gitignore-policy.check.ts +32 -11
  11. package/src/checks/SK027-agent-wiki-links.check.ts +1 -1
  12. package/src/checks/SK033-global-contribution.check.ts +1 -1
  13. package/src/checks/SK036-draft-media-size.check.ts +1 -1
  14. package/src/checks/SK040-release-words.check.ts +1 -1
  15. package/src/checks/SK042-post-kinds.check.ts +1 -1
  16. package/src/checks/SK045-slow-hooks.check.ts +47 -0
  17. package/src/checks/SK046-hook-records.check.ts +76 -0
  18. package/src/cli/cmd_Annex.ts +12 -7
  19. package/src/cli/cmd_Assets.ts +5 -5
  20. package/src/cli/cmd_Backup.ts +14 -6
  21. package/src/cli/cmd_Capacity.ts +10 -6
  22. package/src/cli/cmd_Checks.ts +12 -1
  23. package/src/cli/cmd_Ci.ts +2 -2
  24. package/src/cli/cmd_Commands.ts +11 -2
  25. package/src/cli/cmd_ConfigKeys.ts +17 -0
  26. package/src/cli/cmd_Home.ts +1 -1
  27. package/src/cli/cmd_Keys.ts +4 -1
  28. package/src/cli/cmd_Lanes.ts +35 -0
  29. package/src/cli/cmd_Mv.ts +6 -7
  30. package/src/cli/cmd_Rec.ts +22 -7
  31. package/src/cli/cmd_Releases.ts +30 -0
  32. package/src/cli/cmd_Review.ts +130 -43
  33. package/src/cli/cmd_Shot.ts +15 -4
  34. package/src/cli/cmd_Status.ts +6 -5
  35. package/src/cli/cmd_Time.ts +18 -6
  36. package/src/cli/cmd_Veille.ts +10 -6
  37. package/src/cli/family-help.ts +136 -0
  38. package/src/cli/family-pages.ts +0 -19
  39. package/src/cli/kit/calls.ts +35 -0
  40. package/src/cli/kit/project-cli.ts +2 -12
  41. package/src/cli/registry.ts +41 -7
  42. package/src/cli.ts +8 -4
  43. package/src/commands/runner.ts +5 -1
  44. package/src/core/capacity.ts +89 -33
  45. package/src/core/check-runner.ts +5 -1
  46. package/src/core/floor-resolve.ts +6 -2
  47. package/src/core/floor.ts +6 -2
  48. package/src/core/history-files.ts +22 -0
  49. package/src/core/jobs.ts +35 -16
  50. package/src/core/layout.ts +2 -2
  51. package/src/core/nearest.ts +16 -0
  52. package/src/core/remove-tree.ts +19 -0
  53. package/src/core/runs.ts +12 -3
  54. package/src/core/signal-name.ts +6 -0
  55. package/src/core/throwaway-worktree.ts +22 -4
  56. package/src/core/trace-audit.ts +22 -4
  57. package/src/core/transient.ts +6 -0
  58. package/src/drill/run.ts +1 -1
  59. package/src/home/daemon-jobs.ts +41 -4
  60. package/src/home/machine-temp.ts +2 -10
  61. package/src/ledger/gate-checks.ts +26 -4
  62. package/src/ledger/git-key.ts +25 -4
  63. package/src/ledger/git-scan.ts +59 -7
  64. package/src/media-store/backup/daemon.ts +103 -20
  65. package/src/media-store/backup/run.ts +21 -15
  66. package/src/media-store/backup/sources.ts +163 -21
  67. package/src/media-store/backup/watch.ts +106 -0
  68. package/src/media-store/daemon.ts +36 -8
  69. package/src/media-store/hand.ts +3 -1
  70. package/src/mv/mv-md.ts +50 -18
  71. package/src/pb/run-pb.ts +2 -10
  72. package/src/plan/repo-source.ts +25 -14
  73. package/src/recordings/model.ts +1 -1
  74. package/src/reflect/transcript.ts +21 -3
  75. package/src/release/run-bump.ts +3 -2
  76. package/src/release/run-release.ts +12 -4
  77. package/src/releases/model.ts +18 -0
  78. package/src/releases/store.ts +13 -1
  79. package/src/repo-config.ts +11 -1
  80. package/src/review/cells.ts +2 -1
  81. package/src/review/format.ts +1 -1
  82. package/src/review/inbox-hook.ts +35 -0
  83. package/src/review/model.ts +26 -7
  84. package/src/review/store.ts +15 -7
  85. package/src/review/trailer-model.ts +2 -2
  86. package/src/shot/client.ts +4 -2
  87. package/src/shot/serve-shot.ts +71 -2
  88. package/src/shot/shooter.ts +65 -11
  89. package/src/shot/shot-ask.ts +32 -9
  90. package/src/suite/judge-suites.ts +77 -10
  91. package/src/suite/select.ts +13 -2
  92. package/src/suite/suite-cli.ts +72 -31
  93. package/src/suite/test-units.ts +31 -12
  94. package/src/trailer/graph.ts +2 -1
  95. package/src/ts/config.ts +12 -35
  96. package/src/ts/rename.ts +31 -17
  97. package/src/ts/workspaces.ts +45 -0
  98. package/src/wiki/run-wiki.ts +8 -2
  99. package/src/wiki/scan-md.ts +42 -1
@@ -3,11 +3,12 @@
3
3
  // and the machine db (consistent sqlite snapshots), the machine's private folder, the agents' memories of each house
4
4
  // repo; in each house repo, every untracked file of `.shipkit/` and the hand tuned `.comfy-ts/` files, and its
5
5
  // gitignored `*.local.*` files; and what the repo's config adds (`backup`: paths kept whole, sqlite files). Never a cache, a log, a scratch folder, a lock, a dev database it did not name or a media file a kind of
6
- // the store holds. Walked with async fs: the daemon runs this between requests
6
+ // the store holds. Walked with sync fs (half the CPU of an async walk): it runs in the job's child or the cli, never on
7
+ // the daemon's loop. A look of the daemon reads again only the paths its watch heard (a Scope)
7
8
  import type { Dirent } from 'node:fs'
8
9
  import { lstat, readdir } from 'node:fs/promises'
9
- import { existsSync, statSync } from 'node:fs'
10
- import { basename, extname, join, relative, sep } from 'node:path'
10
+ import { existsSync, lstatSync, readdirSync, statSync } from 'node:fs'
11
+ import { basename, dirname, extname, join, relative, sep } from 'node:path'
11
12
  import { homeDir } from '../../home/home-paths.ts'
12
13
  import { machineDbPath } from '../../core/machine-db.ts'
13
14
  import { MACHINE_PRIVATE } from '../../core/layout.ts'
@@ -31,7 +32,7 @@ export interface Source {
31
32
  }
32
33
 
33
34
  /** `.shipkit/` folders rebuilt, scratch, logs, runtime, or media the store or another owner keeps */
34
- const SHIPKIT_DENY = new Set(['cache', 'tmp', 'logs', 'wrapper', 'locks', 'shots', 'backups', 'cloud', 'review-watchers', 'worktrees', 'node_modules', '.git'])
35
+ const SHIPKIT_DENY = new Set(['cache', 'tmp', 'logs', 'review-auto', 'wrapper', 'locks', 'shots', 'backups', 'cloud', 'review-watchers', 'worktrees', 'node_modules', '.git'])
35
36
  const FILE_DENY = /^(?:STATUS(?:\.full)?\.md|\.DS_Store|\.review-index\.json|review-dispatcher\.json)$|\.(?:log|pid|lock|sqlite(?:-wal|-shm)?|db(?:-wal|-shm)?)$/
36
37
  /** the review store's media go up as the `review` kind: only its records come here */
37
38
  const RECORD = /\.(?:json|jsonl|md|txt|csv)$/
@@ -43,10 +44,38 @@ const COMFY_KEEP = ['drafts', 'llm-configs', 'settings.json', 'lora-keywords.jso
43
44
  const REPO_EXTRA = ['agent/global-contribution.md', 'proposal', '.local']
44
45
  const CODE = /\.(?:[cm]?[jt]sx?)$/
45
46
 
46
- async function walk(dir: string, keep: (rel: string, isDir: boolean) => boolean, out: string[], base = dir): Promise<void> {
47
+ /** the paths a look reads again, each one with everything under it: a walk enters only the folders on the way */
48
+ export class Scope {
49
+ private readonly at: Set<string>
50
+ private readonly above = new Set<string>()
51
+ constructor(paths: Iterable<string>) {
52
+ this.at = new Set([...paths].map((p) => (p.length > 1 ? p.replace(/\/+$/, '') : p)))
53
+ for (const p of this.at) for (let d = dirname(p); !this.above.has(d); d = dirname(d)) {
54
+ this.above.add(d)
55
+ if (d === dirname(d)) break
56
+ }
57
+ }
58
+ get size(): number {
59
+ return this.at.size
60
+ }
61
+ /** at or under a path of the scope */
62
+ covers(abs: string): boolean {
63
+ for (let p = abs; ; p = dirname(p)) {
64
+ if (this.at.has(p)) return true
65
+ if (p === dirname(p)) return false
66
+ }
67
+ }
68
+ /** a folder a walk enters: on the way to a path of the scope, or under one */
69
+ reaches(abs: string): boolean {
70
+ return this.above.has(abs) || this.covers(abs)
71
+ }
72
+ }
73
+
74
+ async function walk(dir: string, keep: (rel: string, isDir: boolean) => boolean, out: string[], base = dir, scope?: Scope): Promise<void> {
75
+ if (scope && !scope.reaches(dir)) return
47
76
  let names: Dirent[]
48
77
  try {
49
- names = await readdir(dir, { withFileTypes: true })
78
+ names = readdirSync(dir, { withFileTypes: true })
50
79
  } catch {
51
80
  return
52
81
  }
@@ -54,8 +83,8 @@ async function walk(dir: string, keep: (rel: string, isDir: boolean) => boolean,
54
83
  const abs = join(dir, d.name)
55
84
  const rel = relative(base, abs)
56
85
  if (d.isDirectory()) {
57
- if (keep(rel, true)) await walk(abs, keep, out, base)
58
- } else if (d.isFile() && keep(rel, false)) out.push(abs)
86
+ if (keep(rel, true)) await walk(abs, keep, out, base, scope)
87
+ } else if (d.isFile() && keep(rel, false) && (!scope || scope.covers(abs))) out.push(abs)
59
88
  }
60
89
  }
61
90
 
@@ -70,6 +99,7 @@ const shipkitKeep = (rel: string, isDir: boolean): boolean => {
70
99
  }
71
100
 
72
101
  const comfyKeep = (rel: string): boolean => COMFY_KEEP.some((k) => rel === k || rel.startsWith(`${k}${sep}`))
102
+ const comfyWalkKeep = (rel: string, isDir: boolean): boolean => (isDir ? COMFY_KEEP.some((k) => k === rel.split(sep)[0]) : comfyKeep(rel))
73
103
 
74
104
  async function git(repo: string, args: string[]): Promise<string[]> {
75
105
  const p = Bun.spawn(['git', '-C', repo, ...args], { stdout: 'pipe', stderr: 'ignore' })
@@ -84,6 +114,25 @@ export async function localFiles(repo: string): Promise<string[]> {
84
114
  return names.filter((n) => basename(n) !== 'settings.local.json' && !CODE.test(n) && !n.split('/').some((p) => p === 'node_modules')).map((n) => join(repo, n))
85
115
  }
86
116
 
117
+ /** a repo's kept `*.local.*` list with these heard paths read again: one `git check-ignore` of them, never the
118
+ * repo's walk (seconds in a repo with large ignored folders) */
119
+ export async function patchLocals(repo: string, files: readonly string[], heard: readonly string[]): Promise<string[]> {
120
+ const rels = heard.filter((p) => p.startsWith(`${repo}${sep}`) && isLocalName(p.slice(repo.length + 1))).map((p) => p.slice(repo.length + 1))
121
+ if (rels.length === 0) return [...files]
122
+ const p = Bun.spawn(['git', '-C', repo, 'check-ignore', '-z', '--stdin'], { stdin: 'pipe', stdout: 'pipe', stderr: 'ignore' })
123
+ p.stdin.write(rels.join('\0') + '\0')
124
+ await p.stdin.end()
125
+ const ignored = new Set((await new Response(p.stdout).text()).split('\0').filter((n) => n !== ''))
126
+ await p.exited
127
+ const out = new Set(files)
128
+ for (const rel of rels) {
129
+ const abs = join(repo, rel)
130
+ out.delete(abs)
131
+ if (ignored.has(rel) && lstatSync(abs, { throwIfNoEntry: false })?.isFile()) out.add(abs)
132
+ }
133
+ return [...out].sort()
134
+ }
135
+
87
136
  /** the agents' config roots under the home: `.claude`, `.claude-<account>` */
88
137
  async function agentRoots(home: string): Promise<string[]> {
89
138
  const names = await readdir(home).catch(() => [] as string[])
@@ -100,6 +149,8 @@ export interface Collect {
100
149
  locals?: (repo: string) => Promise<string[]>
101
150
  /** each repo's `backup` key; by default its repo.config.ts, read again when the file moves */
102
151
  backupOf?: (repo: string) => Promise<RepoBackup | null>
152
+ /** only the sources at or under these paths: what a full collect gives there, nothing else is read */
153
+ scope?: Scope
103
154
  }
104
155
 
105
156
  const configs = new Map<string, { mtime: number; backup: RepoBackup | null }>()
@@ -121,6 +172,7 @@ const WHOLE_DENY = /^(?:\.DS_Store)$|\.(?:pid|lock)$|-(?:wal|shm|journal)$/
121
172
 
122
173
  /** every source the backup holds now, under the home folder, sorted by path */
123
174
  export async function collect(o: Collect): Promise<Source[]> {
175
+ const scope = o.scope
124
176
  const files: string[] = []
125
177
  const add = (abs: string): void => void files.push(abs)
126
178
  // the backup's own objects and records, and the pids, move by themselves: left out, else every run differs
@@ -129,15 +181,16 @@ export async function collect(o: Collect): Promise<Source[]> {
129
181
  // the Mac's own names stay out: a run restored on another Mac must not make it take this one's name
130
182
  [machineDbPath(), { tables: null, except: { state: "name like 'pid:%' or name like 'backup-%' or name in ('machine-name', 'tailnet-name')" } }],
131
183
  ])
132
- await walk(join(homeDir(), 'veille'), () => true, files)
184
+ await walk(join(homeDir(), 'veille'), () => true, files, undefined, scope)
133
185
  add(join(o.home, ORDER_FILE))
134
- await walk(join(o.home, MACHINE_PRIVATE), () => true, files)
135
- for (const root of await agentRoots(o.home)) for (const repo of o.repos) await walk(join(root, sessionName(repo), 'memory'), () => true, files)
186
+ await walk(join(o.home, MACHINE_PRIVATE), () => true, files, undefined, scope)
187
+ for (const root of await agentRoots(o.home)) for (const repo of o.repos) await walk(join(root, sessionName(repo), 'memory'), () => true, files, undefined, scope)
188
+ const repos = scope ? o.repos.filter((r) => scope.reaches(r)) : o.repos
136
189
  // the git walks of ignored trees take seconds each: all at once
137
- const locals = new Map(await Promise.all(o.repos.map(async (r) => [r, await (o.locals ?? localFiles)(r)] as const)))
190
+ const locals = new Map(await Promise.all(repos.map(async (r) => [r, await (o.locals ?? localFiles)(r)] as const)))
138
191
  const whole = new Set<string>()
139
192
  const extra: Source[] = []
140
- for (const repo of o.repos) {
193
+ for (const repo of repos) {
141
194
  let cfg: RepoBackup | null = null
142
195
  try {
143
196
  cfg = await (o.backupOf ?? backupOfRepo)(repo)
@@ -151,7 +204,7 @@ export async function collect(o: Collect): Promise<Source[]> {
151
204
  const st = await lstat(abs).catch(() => null)
152
205
  const got: string[] = []
153
206
  if (st?.isFile()) got.push(abs)
154
- else if (st?.isDirectory()) await walk(abs, (rel, isDir) => (isDir ? !['.git', 'node_modules'].includes(basename(rel)) : !WHOLE_DENY.test(basename(rel))), got)
207
+ else if (st?.isDirectory()) await walk(abs, (rel, isDir) => (isDir ? !['.git', 'node_modules'].includes(basename(rel)) : !WHOLE_DENY.test(basename(rel))), got, abs, scope)
155
208
  else extra.push({ abs, rel: relative(o.home, abs), size: 0, mtime: 0, broken: `the repo's backup.paths names it and it is not on the disk` })
156
209
  for (const f of got) if (!tracked.has(f)) {
157
210
  files.push(f)
@@ -165,29 +218,118 @@ export async function collect(o: Collect): Promise<Source[]> {
165
218
  for (const n of hits) sqlite.set(join(repo, n), { tables: null, ...(except ? { except } : {}) })
166
219
  }
167
220
  const mine: string[] = []
168
- await walk(join(repo, '.shipkit'), shipkitKeep, mine)
169
- await walk(join(repo, '.comfy-ts'), (rel, isDir) => (isDir ? COMFY_KEEP.some((k) => k === rel.split(sep)[0]) : comfyKeep(rel)), mine)
221
+ await walk(join(repo, '.shipkit'), shipkitKeep, mine, undefined, scope)
222
+ await walk(join(repo, '.comfy-ts'), comfyWalkKeep, mine, undefined, scope)
170
223
  for (const x of REPO_EXTRA) {
171
224
  const abs = join(repo, x)
172
225
  const st = await lstat(abs).catch(() => null)
173
226
  if (st?.isFile()) mine.push(abs)
174
- else if (st?.isDirectory()) await walk(abs, (rel, isDir) => isDir || !FILE_DENY.test(basename(rel)), mine)
227
+ else if (st?.isDirectory()) await walk(abs, (rel, isDir) => isDir || !FILE_DENY.test(basename(rel)), mine, abs, scope)
175
228
  }
176
229
  mine.push(...(locals.get(repo) ?? []))
177
230
  for (const f of mine) if (!tracked.has(f)) files.push(f)
178
231
  }
179
232
  const out = new Map<string, Source>()
180
233
  for (const abs of [...files, ...sqlite.keys()]) {
181
- if (out.has(abs)) continue
182
- const st = await lstat(abs).catch(() => null)
234
+ if (out.has(abs) || (scope && !scope.covers(abs))) continue
235
+ const st = lstatSync(abs, { throwIfNoEntry: false })
183
236
  if (!st?.isFile()) continue
184
237
  const rel = relative(o.home, abs)
185
238
  if (rel.startsWith('..') || rel === '') continue
186
239
  const cut = sqlite.get(abs)
187
240
  out.set(abs, { abs, rel, size: st.size, mtime: Math.floor(st.mtimeMs), ...(cut !== undefined ? { sqlite: cut } : whole.has(abs) ? { whole: true as const } : {}) })
188
241
  }
189
- for (const x of extra) out.set(`extra\0${x.rel}`, x)
190
- return [...out.values()].sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0))
242
+ for (const x of extra) if (!scope || scope.covers(x.abs)) out.set(`extra\0${x.rel}`, x)
243
+ return sortSources([...out.values()])
244
+ }
245
+
246
+ const sortSources = (list: Source[]): Source[] => list.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : a.broken === b.broken ? 0 : a.broken ? 1 : -1))
247
+
248
+ /** the paths a look reads again for these moved paths: a repo's config moving reads the whole repo again (its
249
+ * `backup` key may name other paths) */
250
+ export function scopeOf(moved: readonly string[], repos: readonly string[]): Scope {
251
+ const all = new Set(moved)
252
+ for (const p of moved) if (basename(p) === 'repo.config.ts' && repos.includes(dirname(p))) all.add(dirname(p))
253
+ return new Scope(all)
254
+ }
255
+
256
+ /** the last list with the moved paths read again: the list a full collect gives, at the cost of what moved (a
257
+ * repo's own sqlite keeps the size and time of the last full walk: snapshotted live at each run, out of the stamp) */
258
+ export async function refreshSources(prev: readonly Source[], moved: readonly string[], o: Collect): Promise<Source[]> {
259
+ // the home's databases are read at each look: two stats, and one that appears is held from its first run
260
+ const scope = scopeOf([...moved, mediaDbPath(), machineDbPath()], o.repos)
261
+ const fresh = await collect({ ...o, scope })
262
+ return sortSources([...prev.filter((s) => !scope.covers(s.abs)), ...fresh])
263
+ }
264
+
265
+ /** the sources of `full` that `held` lacks or holds another size or time of: what no event told (a sqlite moves by
266
+ * itself and is snapshotted on the clock) */
267
+ export function missedBy(held: readonly Source[], full: readonly Source[]): string[] {
268
+ const was = new Map(held.map((s) => [s.abs, s]))
269
+ return full.filter((s) => !s.sqlite && !s.broken && (was.get(s.abs)?.size !== s.size || was.get(s.abs)?.mtime !== s.mtime)).map((s) => s.rel)
270
+ }
271
+
272
+ const isLocalName = (rel: string): boolean => {
273
+ const name = basename(rel)
274
+ return name.includes('.local.') && name !== 'settings.local.json' && !CODE.test(name) && !rel.split(sep).includes('node_modules')
275
+ }
276
+
277
+ /** a moved path the repo's `*.local.*` git walk must read again */
278
+ export const movesLocals = (abs: string, repos: readonly string[]): string | null => (isLocalName(abs) ? (repos.find((r) => abs.startsWith(`${r}${sep}`)) ?? null) : null)
279
+
280
+ export { isTransient } from '../../core/transient.ts'
281
+
282
+ const isFileName = (name: string): boolean => /\.[^.]+$/.test(name) && !name.startsWith('.')
283
+
284
+ /** how the daemon's watch takes a path it hears: `due`, it could be a source or change which files are (the config's
285
+ * `backup` key, a `*.local.*` file); null, never a source (a denied folder, a status file, a rule's log): a path
286
+ * that moves by itself and makes the backup due would make it due forever */
287
+ export type Heard = 'due' | null
288
+
289
+ const due = (b: boolean): Heard => (b ? 'due' : null)
290
+
291
+ /** a path under a repo, as the watch hears it. A name with no extension is judged as a folder (`.shipkit/tmp` is
292
+ * denied as one), a name with one as a file */
293
+ export function repoPathHeard(rel: string, named: readonly string[] = []): Heard {
294
+ if (rel === '') return null
295
+ if (rel === 'repo.config.ts') return 'due'
296
+ const parts = rel.split(sep)
297
+ // a worktree under `.claude/worktrees/` is a checkout of its own: the repo's git walk never enters it
298
+ if (parts.includes('.git') || parts.includes('node_modules') || (parts[0] === '.claude' && parts[1] === 'worktrees')) return null
299
+ for (const p of named) if (rel === p || rel.startsWith(`${p}${sep}`) || p.startsWith(`${rel}${sep}`)) return due(!WHOLE_DENY.test(basename(rel)))
300
+ if (isLocalName(rel)) return 'due'
301
+ const name = parts[parts.length - 1]!
302
+ const asItem = (keep: (r: string, isDir: boolean) => boolean, under: string[]): boolean => {
303
+ if (under.length === 0) return true
304
+ for (let i = 1; i < under.length; i++) if (!keep(under.slice(0, i).join(sep), true)) return false
305
+ const r = under.join(sep)
306
+ return isFileName(name) ? keep(r, false) : keep(r, true)
307
+ }
308
+ if (parts[0] === '.shipkit') return due(asItem(shipkitKeep, parts.slice(1)))
309
+ if (parts[0] === '.comfy-ts') return due(asItem(comfyWalkKeep, parts.slice(1)))
310
+ for (const x of REPO_EXTRA) if (rel === x || rel.startsWith(`${x}${sep}`) || x.startsWith(`${rel}${sep}`)) return due(!FILE_DENY.test(name))
311
+ return null
312
+ }
313
+
314
+ /** what the daemon watches: each root, whether it reads its tree, and which paths under it count. A root missing
315
+ * when the watch starts is left to the safety walk */
316
+ export interface WatchRoot {
317
+ dir: string
318
+ recursive: boolean
319
+ heard: (rel: string) => Heard
320
+ }
321
+
322
+ /** `named` gives a repo's `backup.paths` as the last look read them: asked at each event, so a new name counts at once */
323
+ export async function watchRoots(home: string, repos: readonly string[], named: (repo: string) => readonly string[] = () => []): Promise<WatchRoot[]> {
324
+ const order = join(home, ORDER_FILE)
325
+ const memory = new Set(repos.map(sessionName))
326
+ return [
327
+ { dir: join(homeDir(), 'veille'), recursive: true, heard: () => 'due' },
328
+ { dir: join(home, MACHINE_PRIVATE), recursive: true, heard: () => 'due' },
329
+ { dir: dirname(order), recursive: false, heard: (rel) => due(rel === basename(order)) },
330
+ ...(await agentRoots(home)).map((dir): WatchRoot => ({ dir, recursive: true, heard: (rel) => { const [repo, folder] = rel.split(sep); return due(memory.has(repo ?? '') && (folder === undefined || folder === 'memory')) } })),
331
+ ...repos.map((r): WatchRoot => ({ dir: r, recursive: true, heard: (rel) => repoPathHeard(rel, named(r)) })),
332
+ ]
191
333
  }
192
334
 
193
335
  /** a cheap stamp of the sources that are files (a sqlite moves every few seconds; its snapshot runs on the clock) */
@@ -0,0 +1,106 @@
1
+ // the daemon's watch of the backup's sources: a path it hears that could be a source (`watchRoots`) is noted, and the
2
+ // next look reads only the noted paths again. The callback only notes: the loop answers every page. A clean stop hands
3
+ // what it heard to the next daemon (a reload in place); a daemon that did not stop cleanly starts with a full walk
4
+ import { watch, type FSWatcher } from 'node:fs'
5
+ import { basename, join } from 'node:path'
6
+ import { machineDelete, machineGet, machineSet } from '../../core/machine-db.ts'
7
+ import { backupDue, BATCH, NAMED, type Batch } from './daemon.ts'
8
+ import { isTransient, watchRoots } from './sources.ts'
9
+
10
+ /** what a stopping daemon heard and no look took yet, for the next one */
11
+ const HELD = 'backup-heard'
12
+ /** a stop this recent is a hand over (a reload in place): the next daemon takes what it heard, else it walks */
13
+ export const HANDOVER_MS = 60_000
14
+ /** past this many paths, the next look walks every source */
15
+ export const MAX_PATHS = 2_000
16
+
17
+ type Held = { at: number; paths: string[]; all: boolean }
18
+
19
+ export interface BackupWatchOptions {
20
+ home: string
21
+ /** the house repos, archived ones included */
22
+ repos: readonly string[]
23
+ now?: () => number
24
+ printErr?: (l: string) => void
25
+ }
26
+
27
+ export class BackupWatch {
28
+ private readonly heard = new Set<string>()
29
+ /** the next look walks every source */
30
+ private all = false
31
+ /** a watch stopped: every look walks, as with no watch */
32
+ private blind = false
33
+ private named: Record<string, string[]> = {}
34
+ private readonly watchers: FSWatcher[] = []
35
+ private readonly now: () => number
36
+
37
+ constructor(private readonly o: BackupWatchOptions) {
38
+ this.now = o.now ?? Date.now
39
+ }
40
+
41
+ /** no watch at all: every look walks every source, as before there was one */
42
+ blindly(): this {
43
+ this.blind = true
44
+ return this
45
+ }
46
+
47
+ async start(): Promise<this> {
48
+ const held = machineGet<Held>(HELD)
49
+ machineDelete(HELD)
50
+ if (held != null && this.now() - held.at <= HANDOVER_MS) {
51
+ for (const p of held.paths) this.heard.add(p)
52
+ this.all = held.all
53
+ } else this.all = true
54
+ this.named = machineGet<Record<string, string[]>>(NAMED) ?? {}
55
+ for (const root of await watchRoots(this.o.home, this.o.repos, (r) => this.named[r] ?? [])) {
56
+ let w: FSWatcher
57
+ try {
58
+ w = watch(root.dir, { recursive: root.recursive }, (_event, name) => {
59
+ if (this.all) return
60
+ // no name, or the root itself: the system says its tree changed in ways it did not list
61
+ const rel = name == null ? '' : String(name)
62
+ if (rel === '') return void (this.all = true)
63
+ if (isTransient(basename(rel)) || root.heard(rel) == null) return
64
+ if (this.heard.size >= MAX_PATHS) {
65
+ this.all = true
66
+ this.heard.clear()
67
+ } else this.heard.add(join(root.dir, rel))
68
+ })
69
+ } catch {
70
+ // a root not on the disk yet: the safety walk finds what lands there
71
+ continue
72
+ }
73
+ w.on('error', (e) => {
74
+ if (!this.blind) this.o.printErr?.(`WARN backup: the watch of ${root.dir} stopped (${(e as Error).message}): each look walks every source until the daemon reloads`)
75
+ this.blind = true
76
+ })
77
+ this.watchers.push(w)
78
+ }
79
+ return this
80
+ }
81
+
82
+ /** the paths heard since the last look, for a test or a probe */
83
+ pending(): { paths: string[]; all: boolean } {
84
+ return { paths: [...this.heard].sort(), all: this.all || this.blind }
85
+ }
86
+
87
+ /** the daemon's look: a few reads of the machine db, never a walk. When due, the paths heard go to the look it
88
+ * starts, with those of a look that did not finish */
89
+ due(now: number): boolean {
90
+ this.named = machineGet<Record<string, string[]>>(NAMED) ?? this.named
91
+ if (!backupDue(now, this.all || this.blind || this.heard.size > 0)) return false
92
+ const was = machineGet<Batch>(BATCH)
93
+ const undone = was?.done === false ? was : null
94
+ const paths = [...new Set([...(undone?.paths ?? []), ...this.heard])]
95
+ const all = this.all || this.blind || (undone?.all ?? false) || paths.length > MAX_PATHS
96
+ machineSet(BATCH, { paths: all ? [] : paths.sort(), all, done: false } satisfies Batch)
97
+ this.heard.clear()
98
+ this.all = false
99
+ return true
100
+ }
101
+
102
+ stop(): void {
103
+ for (const w of this.watchers.splice(0)) w.close()
104
+ machineSet(HELD, { at: this.now(), paths: [...this.heard], all: this.all || this.blind } satisfies Held)
105
+ }
106
+ }
@@ -1,8 +1,9 @@
1
1
  // the daemon's media job (wiki tools/shipkit/media-store.md, The daemon): one pass, in a child process the daemon
2
- // starts every 30 s (home/daemon-jobs.ts), never on its loop. Every kind of every house repo scanned into the machine
3
- // index once its store moved, what waits sent up, and (when the owner turned it on) the disk purged under 40 GB free.
4
- // Each failure is one line in the daemon's log
5
- import { existsSync } from 'node:fs'
2
+ // starts when `mediaDue` says so (home/daemon-jobs.ts), never on its loop. Every kind of every house repo scanned into
3
+ // the machine index once its store moved, what waits sent up, and (when the owner turned it on) the disk purged under
4
+ // 40 GB free. Each failure is one line in the daemon's log
5
+ import { existsSync, statSync } from 'node:fs'
6
+ import { resolve } from 'node:path'
6
7
  import { machineGet, machineSet } from '../core/machine-db.ts'
7
8
  import type { MediaKind } from './kind.ts'
8
9
  import { FREE_MIN_BYTES, freeBytes, purge, purgeCandidates, windowDays } from './purge.ts'
@@ -11,6 +12,8 @@ import { syncKind } from './sync.ts'
11
12
  import { mb, uploadWaiting } from './upload.ts'
12
13
 
13
14
  export const MEDIA_EVERY_MS = 30_000
15
+ /** a pass that found nothing to do: the next one this much later, unless a store's folder moves first */
16
+ export const MEDIA_QUIET_MS = 5 * 60_000
14
17
  const PURGE_EVERY_MS = 10 * 60_000
15
18
  const AUTO_KEY = 'media-purge-auto'
16
19
 
@@ -22,17 +25,34 @@ export const setAutoPurge = (on: boolean): boolean => machineSet(AUTO_KEY, on)
22
25
  const SYNCED = 'media-synced'
23
26
  const PURGED_AT = 'media-purged-at'
24
27
  const NO_SPACE = 'media-no-space'
28
+ /** when the next pass is due, and the folders whose move brings it sooner */
29
+ const NEXT = 'media-next'
30
+
31
+ type Next = { at: number; since: number; dirs: string[] }
32
+
33
+ /** the daemon's look, in its own process: a stat of each store folder, never a walk. Due at the time the last pass
34
+ * named, or as soon as a store's folder moved since that pass began (a new card, a new take) */
35
+ export function mediaDue(now: number): boolean {
36
+ const n = machineGet<Next>(NEXT)
37
+ if (n == null || now >= n.at) return true
38
+ return n.dirs.some((d) => (statSync(d, { throwIfNoEntry: false })?.mtimeMs ?? 0) > n.since)
39
+ }
25
40
 
26
41
  /** one pass of the daemon's media job, in its child process: what `startMediaStore` does each tick, with what it
27
42
  * remembers in the machine db */
28
- export async function mediaTick(o: { roots: string[]; kinds: () => readonly MediaKind[]; print: (l: string) => void; printErr: (l: string) => void }): Promise<void> {
43
+ export async function mediaTick(o: { roots: string[]; kinds: () => readonly MediaKind[]; print: (l: string) => void; printErr: (l: string) => void; now?: () => number }): Promise<void> {
44
+ const now = o.now ?? Date.now
45
+ const since = now()
29
46
  const synced = machineGet<Record<string, string>>(SYNCED) ?? {}
47
+ const kinds = o.kinds()
30
48
  const stores = o.roots.flatMap((root) =>
31
- o.kinds().flatMap((kind) => {
49
+ kinds.flatMap((kind) => {
32
50
  const dir = kind.storeOf(root)
33
51
  return dir && existsSync(dir) ? [{ kind, root, dir }] : []
34
52
  }),
35
53
  )
54
+ // work done or left: the next pass at the usual period, else after the quiet one
55
+ let busy = false
36
56
  try {
37
57
  let moved = false
38
58
  for (const { kind, root, dir } of stores) {
@@ -44,8 +64,10 @@ export async function mediaTick(o: { roots: string[]; kinds: () => readonly Medi
44
64
  // files left to hash: the next pass goes on with them
45
65
  synced[id] = r.left > 0 ? '' : stamp
46
66
  moved = true
67
+ if (r.filled > 0 || r.left > 0) busy = true
47
68
  if (r.filled > 0) o.print(`ok: media store: ${r.filled} ${kind.kind} files of ${root} hashed${r.left > 0 ? `, ${r.left} to go` : ''}`)
48
69
  } catch (e) {
70
+ busy = true
49
71
  o.printErr(`WARN media store: the ${kind.kind} files of ${root} did not sync: ${(e as Error).message}`)
50
72
  }
51
73
  }
@@ -59,10 +81,11 @@ export async function mediaTick(o: { roots: string[]; kinds: () => readonly Medi
59
81
  }
60
82
  machineSet(NO_SPACE, '')
61
83
  const up = await uploadWaiting(space, { limit: 200, jobs: 3 })
84
+ if (up.up + up.there + up.failed.length > 0) busy = true
62
85
  if (up.up + up.there > 0) o.print(`ok: media store: ${up.up} up (${mb(up.bytes)})${up.there > 0 ? `, ${up.there} already there` : ''}`)
63
86
  if (up.failed.length > 0) o.printErr(`WARN media store: ${up.failed.length} uploads failed, tried again later; first: ${up.failed[0]?.key}: ${up.failed[0]?.error}`)
64
- if (autoPurgeOn() && Date.now() - (machineGet<number>(PURGED_AT) ?? 0) > PURGE_EVERY_MS) {
65
- machineSet(PURGED_AT, Date.now())
87
+ if (autoPurgeOn() && now() - (machineGet<number>(PURGED_AT) ?? 0) > PURGE_EVERY_MS) {
88
+ machineSet(PURGED_AT, now())
66
89
  for (const { kind, root, dir } of stores) {
67
90
  if (freeBytes(dir) >= FREE_MIN_BYTES) continue
68
91
  const { candidates } = await purgeCandidates(kind, dir, { olderDays: windowDays(freeBytes(dir)) })
@@ -72,6 +95,11 @@ export async function mediaTick(o: { roots: string[]; kinds: () => readonly Medi
72
95
  }
73
96
  }
74
97
  } catch (e) {
98
+ busy = true
75
99
  o.printErr(`WARN media store: the pass broke: ${(e as Error).message}`)
100
+ } finally {
101
+ // a store that is the repo itself (a hand label) moves with every save there: the index is its record
102
+ const dirs = [...new Set(stores.filter((s) => resolve(s.dir) !== resolve(s.root)).map((s) => s.dir))]
103
+ machineSet(NEXT, { at: since + (busy ? MEDIA_EVERY_MS : MEDIA_QUIET_MS), since, dirs } satisfies Next)
76
104
  }
77
105
  }
@@ -36,9 +36,11 @@ const rowsOf = (label: string, store: string): { item: string; name: string; key
36
36
  }
37
37
 
38
38
  export function handKind(label: string): MediaKind {
39
+ // read once per kind: a pass asks it for every house repo, and each read scans the whole files table
40
+ let held: string[] | null = null
39
41
  return {
40
42
  kind: label,
41
- storeOf: (root) => (storesOf(label).includes(resolve(root)) ? resolve(root) : null),
43
+ storeOf: (root) => ((held ??= storesOf(label)).includes(resolve(root)) ? resolve(root) : null),
42
44
  // the index is the record: read it again every 10 min, to see a file the disk let go
43
45
  stamp: () => String(Math.floor(Date.now() / 600_000)),
44
46
  async scan(store) {