rvlib-shipkit 2.24.0 → 2.25.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 (81) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/package.json +1 -1
  3. package/src/agent-time/live.ts +153 -0
  4. package/src/annex/offload.ts +16 -7
  5. package/src/check.ts +3 -1
  6. package/src/checks/SK004-gitignore-policy.check.ts +32 -11
  7. package/src/checks/SK027-agent-wiki-links.check.ts +1 -1
  8. package/src/checks/SK033-global-contribution.check.ts +1 -1
  9. package/src/checks/SK036-draft-media-size.check.ts +1 -1
  10. package/src/checks/SK040-release-words.check.ts +1 -1
  11. package/src/checks/SK042-post-kinds.check.ts +1 -1
  12. package/src/cli/cmd_Annex.ts +12 -7
  13. package/src/cli/cmd_Assets.ts +5 -5
  14. package/src/cli/cmd_Backup.ts +11 -5
  15. package/src/cli/cmd_Capacity.ts +10 -6
  16. package/src/cli/cmd_Checks.ts +12 -1
  17. package/src/cli/cmd_Ci.ts +2 -2
  18. package/src/cli/cmd_Commands.ts +11 -2
  19. package/src/cli/cmd_ConfigKeys.ts +17 -0
  20. package/src/cli/cmd_Home.ts +1 -1
  21. package/src/cli/cmd_Keys.ts +4 -1
  22. package/src/cli/cmd_Lanes.ts +35 -0
  23. package/src/cli/cmd_Mv.ts +6 -7
  24. package/src/cli/cmd_Rec.ts +22 -7
  25. package/src/cli/cmd_Review.ts +107 -39
  26. package/src/cli/cmd_Shot.ts +15 -4
  27. package/src/cli/cmd_Status.ts +6 -5
  28. package/src/cli/cmd_Time.ts +10 -4
  29. package/src/cli/cmd_Veille.ts +10 -6
  30. package/src/cli/family-help.ts +136 -0
  31. package/src/cli/family-pages.ts +0 -19
  32. package/src/cli/kit/calls.ts +35 -0
  33. package/src/cli/kit/project-cli.ts +2 -12
  34. package/src/cli/registry.ts +39 -6
  35. package/src/cli.ts +8 -4
  36. package/src/core/capacity.ts +89 -33
  37. package/src/core/check-runner.ts +5 -1
  38. package/src/core/floor-resolve.ts +6 -2
  39. package/src/core/floor.ts +6 -2
  40. package/src/core/history-files.ts +18 -0
  41. package/src/core/jobs.ts +35 -16
  42. package/src/core/layout.ts +2 -2
  43. package/src/core/nearest.ts +16 -0
  44. package/src/core/remove-tree.ts +19 -0
  45. package/src/core/runs.ts +12 -3
  46. package/src/core/throwaway-worktree.ts +22 -4
  47. package/src/core/trace-audit.ts +17 -4
  48. package/src/home/daemon-jobs.ts +41 -4
  49. package/src/home/machine-temp.ts +2 -10
  50. package/src/ledger/gate-checks.ts +3 -2
  51. package/src/ledger/git-key.ts +25 -4
  52. package/src/ledger/git-scan.ts +10 -0
  53. package/src/media-store/backup/daemon.ts +92 -20
  54. package/src/media-store/backup/run.ts +21 -15
  55. package/src/media-store/backup/sources.ts +166 -21
  56. package/src/media-store/backup/watch.ts +106 -0
  57. package/src/media-store/daemon.ts +36 -8
  58. package/src/media-store/hand.ts +3 -1
  59. package/src/mv/mv-md.ts +50 -18
  60. package/src/pb/run-pb.ts +2 -10
  61. package/src/plan/repo-source.ts +25 -14
  62. package/src/recordings/model.ts +1 -1
  63. package/src/release/run-bump.ts +3 -2
  64. package/src/release/run-release.ts +12 -4
  65. package/src/review/cells.ts +2 -1
  66. package/src/review/format.ts +1 -1
  67. package/src/review/model.ts +14 -1
  68. package/src/review/store.ts +15 -7
  69. package/src/review/trailer-model.ts +2 -2
  70. package/src/shot/client.ts +4 -2
  71. package/src/shot/serve-shot.ts +71 -2
  72. package/src/shot/shooter.ts +65 -11
  73. package/src/shot/shot-ask.ts +32 -9
  74. package/src/suite/select.ts +13 -2
  75. package/src/suite/test-units.ts +31 -12
  76. package/src/trailer/graph.ts +2 -1
  77. package/src/ts/config.ts +12 -35
  78. package/src/ts/rename.ts +31 -17
  79. package/src/ts/workspaces.ts +45 -0
  80. package/src/wiki/run-wiki.ts +7 -2
  81. package/src/wiki/scan-md.ts +2 -1
@@ -1,24 +1,42 @@
1
- // the daemon's backup job (wiki tools/shipkit/media-store.md, Backup, The daemon): one look, in a child process the
2
- // daemon starts every 2 min (home/daemon-jobs.ts), never on its loop. A cheap stamp of the sources (paths, sizes,
3
- // times, no hashing); once it moved and then held still for one look, a run, at most one each 10 min; a run every 6 h
4
- // whatever moved, which takes the sqlite snapshots. Each failure is one line in the log
1
+ // the daemon's backup job (wiki tools/shipkit/media-store-backup.md, The daemon). The daemon watches the sources
2
+ // (watch.ts) and starts a look only when one may have moved, a run waits, or a clock says so (`backupDue`, a few
3
+ // reads of the machine db). The look, in its child process, reads again only the paths the watch heard, on the list
4
+ // the last look kept; a full walk every SAFETY_MS catches what no event told. Once the stamp moved and then held
5
+ // still for one look (or waited WAIT_MAX_MS while sources kept moving), a run, at most one each 10 min; a run every
6
+ // 6 h whatever moved, which reads every byte again
5
7
  import { machineGet, machineSet } from '../../core/machine-db.ts'
8
+ import type { RepoBackup } from '../../repo-config.ts'
6
9
  import type { Space } from '../space.ts'
7
10
  import { backupRun, lastRun } from './run.ts'
8
- import { collect, localFiles, stampOfSources } from './sources.ts'
11
+ import { backupOfRepo, collect, localFiles, missedBy, movesLocals, patchLocals, refreshSources, stampOfSources, type Collect, type Source } from './sources.ts'
9
12
 
13
+ /** the daemon looks this often: a look starts the child only when `backupDue` says so */
10
14
  export const BACKUP_EVERY_MS = 120_000
11
- const FLOOR_MS = 10 * 60_000
12
- const EVERY_MS = 6 * 3600_000
15
+ export const FLOOR_MS = 10 * 60_000
16
+ export const EVERY_MS = 6 * 3600_000
17
+ /** a full walk at least this often: a watch that died, a root nobody watches, an event the system dropped */
18
+ export const SAFETY_MS = 30 * 60_000
19
+ /** a change that waits this long goes up even while other sources keep moving: an agent that writes every minute
20
+ * never holds the rest back */
21
+ export const WAIT_MAX_MS = 30 * 60_000
13
22
  /** the git walk for `*.local.*` files, kept this long per repo */
14
23
  const LOCALS_MS = 30 * 60_000
15
24
 
16
- /** the stamp the last look saw and the one the last good run sent; `backup-` rows are left out of the snapshot */
17
- const STAMPS = 'backup-stamps'
25
+ /** the stamp the last look saw, the one the last good run sent, and the last full walk; `backup-` rows are left out
26
+ * of the snapshot */
27
+ export const STAMPS = 'backup-stamps'
18
28
  const LOCALS = 'backup-locals'
19
29
  const NO_SPACE = 'backup-no-space'
30
+ /** the list the last look kept, so the next one reads only what moved */
31
+ const SOURCES = 'backup-sources'
32
+ /** the paths the daemon heard, handed to the look it starts: kept undone until a look took them */
33
+ export const BATCH = 'backup-moved'
34
+ /** each repo's `backup.paths`, for the daemon's watch: a look writes them, the watch reads them */
35
+ export const NAMED = 'backup-named'
20
36
 
21
- type Stamps = { seen: string; ran: string }
37
+ /** `waitAt`: since when a stamp the last run did not send waits */
38
+ export type Stamps = { seen: string; ran: string; fullAt?: number; waitAt?: number }
39
+ export type Batch = { paths: string[]; all: boolean; done: boolean }
22
40
  type Locals = Record<string, { at: number; files: string[] }>
23
41
 
24
42
  export interface BackupTick {
@@ -28,10 +46,27 @@ export interface BackupTick {
28
46
  print: (l: string) => void
29
47
  printErr: (l: string) => void
30
48
  now?: () => number
49
+ /** each repo's `backup` key; by default its config */
50
+ backupOf?: (repo: string) => Promise<RepoBackup | null>
31
51
  }
32
52
 
33
- /** one look of the daemon's backup job, in its child process: a run when it is due, else nothing. What a look
34
- * remembers lives in the machine db, so a daemon restart never makes a run of its own */
53
+ /** the daemon's read before it starts a look (no walk, no child): something heard, a batch a look did not take, the
54
+ * safety walk due, a run the floor held back, or the 6 h run */
55
+ export function backupDue(now: number, heard: boolean): boolean {
56
+ if (heard) return true
57
+ const s = machineGet<Stamps>(STAMPS)
58
+ if (s == null || now - (s.fullAt ?? 0) >= SAFETY_MS) return true
59
+ if (machineGet<Batch>(BATCH)?.done === false) return true
60
+ const last = lastRun()
61
+ const since = last ? now - Date.parse(last.at) : Infinity
62
+ if (since >= EVERY_MS) return true
63
+ // with no Space a run never lands: only a change or a clock brings the next look
64
+ return s.seen !== s.ran && since >= FLOOR_MS && !machineGet<string>(NO_SPACE)
65
+ }
66
+
67
+ /** one look of the daemon's backup job, in its child process: the moved paths read again (or every source, on the
68
+ * safety clock), then a run when it is due. What a look remembers lives in the machine db, so a daemon restart
69
+ * never makes a run of its own */
35
70
  export async function backupTick(o: BackupTick): Promise<void> {
36
71
  const now = o.now ?? Date.now
37
72
  const locals: Locals = machineGet<Locals>(LOCALS) ?? {}
@@ -45,13 +80,50 @@ export async function backupTick(o: BackupTick): Promise<void> {
45
80
  return files
46
81
  }
47
82
  try {
48
- const stamp = stampOfSources(await collect({ home: o.home, repos: o.repos, locals: cachedLocals }))
49
- if (walked) machineSet(LOCALS, locals)
83
+ const started = now()
50
84
  const held: Stamps = machineGet<Stamps>(STAMPS) ?? { seen: '', ran: '' }
85
+ const batch = machineGet<Batch>(BATCH)
86
+ const moved = batch && !batch.done ? batch.paths : []
87
+ const prev = machineGet<Source[]>(SOURCES)
51
88
  const last = lastRun()
52
- const since = last ? now() - Date.parse(last.at) : Infinity
53
- const due = since >= EVERY_MS || (stamp !== held.ran && stamp === held.seen && since >= FLOOR_MS)
54
- machineSet(STAMPS, { ...held, seen: stamp } satisfies Stamps)
89
+ const since = last ? started - Date.parse(last.at) : Infinity
90
+ const sixHours = since >= EVERY_MS
91
+ const all = batch?.done === false && batch.all
92
+ const full = prev == null || all || started - (held.fullAt ?? 0) >= SAFETY_MS || sixHours
93
+ // a heard `*.local.*` path is read again in the kept git walk, alone
94
+ for (const r of new Set(moved.map((p) => movesLocals(p, o.repos)).filter((r) => r != null))) {
95
+ const kept = locals[r]
96
+ if (kept == null) continue
97
+ locals[r] = { at: kept.at, files: await patchLocals(r, kept.files, moved) }
98
+ walked = true
99
+ }
100
+ // each config read says its named paths: the daemon's watch hears them
101
+ const named = machineGet<Record<string, string[]>>(NAMED) ?? {}
102
+ const namedWas = JSON.stringify(named)
103
+ const backupOf = async (repo: string): Promise<RepoBackup | null> => {
104
+ const b = await (o.backupOf ?? backupOfRepo)(repo)
105
+ named[repo] = b?.paths ?? []
106
+ return b
107
+ }
108
+ const c: Collect = { home: o.home, repos: o.repos, locals: cachedLocals, backupOf }
109
+ // on a full walk, what the events told is read first: what the walk finds beyond it, no event told
110
+ const told = full && prev != null && !all ? await refreshSources(prev, moved, c) : null
111
+ const list = full ? await collect(c) : await refreshSources(prev, moved, c)
112
+ if (told != null) {
113
+ // said: a watch that went quiet is seen here, not after a lost file
114
+ const missed = missedBy(told, list)
115
+ if (missed.length > 0) o.printErr(`note: backup: the safety walk found ${missed.length} changes no file event told, first ${missed[0]}`)
116
+ }
117
+ if (walked) machineSet(LOCALS, locals)
118
+ if (JSON.stringify(named) !== namedWas) machineSet(NAMED, named)
119
+ machineSet(SOURCES, list)
120
+ if (batch && !batch.done) machineSet(BATCH, { ...batch, done: true } satisfies Batch)
121
+ const stamp = stampOfSources(list)
122
+ const waitAt = stamp === held.ran ? undefined : (held.waitAt ?? started)
123
+ const waited = waitAt != null && started - waitAt >= WAIT_MAX_MS
124
+ const due = sixHours || (stamp !== held.ran && (stamp === held.seen || waited) && since >= FLOOR_MS)
125
+ const fullAt = full ? started : held.fullAt
126
+ machineSet(STAMPS, { seen: stamp, ran: held.ran, ...(fullAt != null ? { fullAt } : {}), ...(waitAt != null ? { waitAt } : {}) } satisfies Stamps)
55
127
  if (!due) return
56
128
  const { space, why } = await o.space()
57
129
  // said once per reason: a look is a child of its own
@@ -61,10 +133,10 @@ export async function backupTick(o: BackupTick): Promise<void> {
61
133
  return
62
134
  }
63
135
  machineSet(NO_SPACE, '')
64
- const r = await backupRun(space, { home: o.home, repos: o.repos, locals: cachedLocals })
65
- if (r.failed.length === 0) machineSet(STAMPS, { seen: stamp, ran: stamp } satisfies Stamps)
136
+ const r = await backupRun(space, { ...c, sources: list, rehash: sixHours, now: new Date(now()) })
137
+ if (r.failed.length === 0) machineSet(STAMPS, { seen: stamp, ran: stamp, ...(fullAt != null ? { fullAt } : {}) } satisfies Stamps)
66
138
  if (r.failed.length > 0) o.printErr(`WARN backup: ${r.failed.length} objects did not go up, no manifest written; first: ${r.failed[0]?.key}: ${r.failed[0]?.error}`)
67
- else if (r.manifest) o.print(`ok: backup: ${r.files} files, ${r.sent} objects up (${(r.sentBytes / 1e6).toFixed(1)} MB), ${r.refused.length} refused, manifest ${r.manifest}`)
139
+ else if (r.manifest) o.print(`ok: backup: ${r.files} files, ${r.sent} objects up (${(r.sentBytes / 1e6).toFixed(1)} MB), ${r.read} read again, ${r.refused.length} refused, manifest ${r.manifest}`)
68
140
  } catch (e) {
69
141
  // a hand run holds the lock: the next look tries again, and says so (a lock that never goes stops every backup)
70
142
  const msg = (e as Error).message
@@ -21,7 +21,8 @@ import { collect, type Collect, type Source } from './sources.ts'
21
21
  import { machineName } from '../../home/machine-host.ts'
22
22
 
23
23
  const LAST = 'backup-last'
24
- /** the files named whole, by path: their size, time, sha and key, so an unchanged archive is never read again */
24
+ /** every file a run held, by path: its size, time, sha and key, so a file whose size and time held is never read
25
+ * again (the 6 h run reads every byte again) */
25
26
  const SEEN = 'backup-seen'
26
27
 
27
28
  export interface Last {
@@ -44,11 +45,14 @@ export interface Ready {
44
45
  file?: string
45
46
  /** the object's size: a sqlite's is its gzip */
46
47
  size: number
47
- /** a path the repo names whole: its sha kept by its size and time */
48
+ /** a path the repo names whole: no size bound, read as a stream */
48
49
  whole?: true
50
+ /** read from the disk by this run, not taken from the last run's sha */
51
+ read?: true
49
52
  }
50
53
 
51
- /** every source read: hashed, snapshotted, or refused */
54
+ /** every source read: hashed, snapshotted, or refused. A file whose size and time equal the last run's, its object
55
+ * up, keeps that run's sha unread (`seen`; empty reads every byte) */
52
56
  export async function prepare(sources: readonly Source[], scratch: string, seen: Seen = machineGet<Seen>(SEEN) ?? {}): Promise<{ ready: Ready[]; refused: Refused[] }> {
53
57
  const ready: Ready[] = []
54
58
  const refused: Refused[] = []
@@ -71,15 +75,15 @@ export async function prepare(sources: readonly Source[], scratch: string, seen:
71
75
  const gz = new Uint8Array(gzipSync(raw))
72
76
  // a snapshot is a new file each run: its live file's time would move the part with no change
73
77
  const entry: Entry = { path: s.rel, sha: sha256(raw), size: raw.length, mtime: 0, key: `${BACKUP_LABEL}/${sha256(gz)}.gz`, sqlite: { ...s.sqlite, rows: snap.rows } }
74
- ready.push({ entry, bytes: gz, size: gz.length })
78
+ ready.push({ entry, bytes: gz, size: gz.length, read: true })
79
+ continue
80
+ }
81
+ const was = seen[s.rel]
82
+ if (was && was.size === s.size && was.mtime === s.mtime && isUp(was.key)) {
83
+ ready.push({ entry: { path: s.rel, sha: was.sha, size: was.size, mtime: s.mtime, key: was.key }, size: was.size, ...(s.whole ? { whole: true as const } : {}) })
75
84
  continue
76
85
  }
77
86
  if (s.whole) {
78
- const was = seen[s.rel]
79
- if (was && was.size === s.size && was.mtime === s.mtime && isUp(was.key)) {
80
- ready.push({ entry: { path: s.rel, sha: was.sha, size: was.size, mtime: s.mtime, key: was.key }, size: was.size, whole: true })
81
- continue
82
- }
83
87
  const copy = join(scratch, `${ready.length}-whole${extname(s.abs)}`)
84
88
  copyFileSync(s.abs, copy, constants.COPYFILE_FICLONE)
85
89
  const r = await fileRefusal(copy, basename(s.abs))
@@ -88,7 +92,7 @@ export async function prepare(sources: readonly Source[], scratch: string, seen:
88
92
  refused.push({ path: s.rel, why: r.why })
89
93
  continue
90
94
  }
91
- ready.push({ entry: { path: s.rel, sha: r.sha, size: r.size, mtime: s.mtime, key: mediaKey(BACKUP_LABEL, { sha: r.sha }, s.abs) }, file: copy, size: r.size, whole: true })
95
+ ready.push({ entry: { path: s.rel, sha: r.sha, size: r.size, mtime: s.mtime, key: mediaKey(BACKUP_LABEL, { sha: r.sha }, s.abs) }, file: copy, size: r.size, whole: true, read: true })
92
96
  continue
93
97
  }
94
98
  const bytes = new Uint8Array(await Bun.file(s.abs).arrayBuffer())
@@ -98,7 +102,7 @@ export async function prepare(sources: readonly Source[], scratch: string, seen:
98
102
  continue
99
103
  }
100
104
  const sha = sha256(bytes)
101
- ready.push({ entry: { path: s.rel, sha, size: bytes.length, mtime: s.mtime, key: mediaKey(BACKUP_LABEL, { sha }, s.abs) }, bytes, size: bytes.length })
105
+ ready.push({ entry: { path: s.rel, sha, size: bytes.length, mtime: s.mtime, key: mediaKey(BACKUP_LABEL, { sha }, s.abs) }, bytes, size: bytes.length, read: true })
102
106
  } catch (e) {
103
107
  refused.push({ path: s.rel, why: `not read: ${(e as Error).message}` })
104
108
  }
@@ -117,6 +121,8 @@ export interface RunResult {
117
121
  there: number
118
122
  refused: Refused[]
119
123
  failed: { key: string; error: string }[]
124
+ /** files read from the disk; the others kept the last run's sha */
125
+ read: number
120
126
  /** the run written, null when nothing changed since `last` or an upload failed */
121
127
  manifest: string | null
122
128
  /** what the record of the run cost: its parts sent (of all), their bytes, and the run's own bytes */
@@ -208,20 +214,20 @@ function lock(): () => void {
208
214
  }
209
215
 
210
216
  /** one run: every source to the Space, then the run's parts the Space lacks, then the run itself, last */
211
- export async function backupRun(space: Space, o: Collect & { now?: Date; jobs?: number }): Promise<RunResult> {
217
+ export async function backupRun(space: Space, o: Collect & { now?: Date; jobs?: number; sources?: readonly Source[]; rehash?: boolean }): Promise<RunResult> {
212
218
  const unlock = lock()
213
219
  const scratch = mkdtempSync(join(tmpdir(), 'shipkit-backup-'))
214
220
  try {
215
221
  const now = o.now ?? new Date()
216
- const { ready, refused } = await prepare(await collect(o), scratch)
222
+ const { ready, refused } = await prepare(o.sources ?? (await collect(o)), scratch, o.rehash ? {} : undefined)
217
223
  const files = ready.map((r) => r.entry)
218
224
  const digest = digestOf(files, refused)
219
225
  const last = await lastOf(space, scratch)
220
- const out: RunResult = { files: files.length, bytes: ready.reduce((n, r) => n + r.entry.size, 0), sent: 0, sentBytes: 0, there: 0, refused, failed: [], manifest: null, record: { parts: 0, partsSent: 0, partsBytes: 0, runBytes: 0 }, last, digest }
226
+ const out: RunResult = { files: files.length, bytes: ready.reduce((n, r) => n + r.entry.size, 0), sent: 0, sentBytes: 0, there: 0, refused, failed: [], read: ready.filter((r) => r.read).length, manifest: null, record: { parts: 0, partsSent: 0, partsBytes: 0, runBytes: 0 }, last, digest }
221
227
  await sendAll(space, ready, scratch, o.jobs ?? 8, out)
222
228
  if (out.failed.length > 0) return out
223
229
  const seen: Seen = {}
224
- for (const r of ready) if (r.whole) seen[r.entry.path] = { size: r.entry.size, mtime: r.entry.mtime, sha: r.entry.sha, key: r.entry.key }
230
+ for (const r of ready) if (!r.entry.sqlite) seen[r.entry.path] = { size: r.entry.size, mtime: r.entry.mtime, sha: r.entry.sha, key: r.entry.key }
225
231
  machineSet(SEEN, seen)
226
232
  if (last?.digest === digest) return out
227
233
  const enc = encodeRun({ at: now.toISOString(), host: hostname(), home: o.home, digest, files, refused }, o.repos.map((r) => relative(o.home, r)))
@@ -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,121 @@ 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
+ /** a write in flight: an atomic write's temp file (`x.tmp`, `x.tmp.<pid>.<hex>`, `.STATUS.md.tmp-<n>`) or an editor's
281
+ * partial copy (`.!<pid>!x`). Its rename into place is heard on its own, so the watch never hears the temp: the gate
282
+ * writes one at each run */
283
+ export const isTransient = (name: string): boolean => /\.tmp(?:$|[-.])|^\.!\d+!/.test(name)
284
+
285
+ const isFileName = (name: string): boolean => /\.[^.]+$/.test(name) && !name.startsWith('.')
286
+
287
+ /** how the daemon's watch takes a path it hears: `due`, it could be a source or change which files are (the config's
288
+ * `backup` key, a `*.local.*` file); null, never a source (a denied folder, a status file, a rule's log): a path
289
+ * that moves by itself and makes the backup due would make it due forever */
290
+ export type Heard = 'due' | null
291
+
292
+ const due = (b: boolean): Heard => (b ? 'due' : null)
293
+
294
+ /** a path under a repo, as the watch hears it. A name with no extension is judged as a folder (`.shipkit/tmp` is
295
+ * denied as one), a name with one as a file */
296
+ export function repoPathHeard(rel: string, named: readonly string[] = []): Heard {
297
+ if (rel === '') return null
298
+ if (rel === 'repo.config.ts') return 'due'
299
+ const parts = rel.split(sep)
300
+ // a worktree under `.claude/worktrees/` is a checkout of its own: the repo's git walk never enters it
301
+ if (parts.includes('.git') || parts.includes('node_modules') || (parts[0] === '.claude' && parts[1] === 'worktrees')) return null
302
+ for (const p of named) if (rel === p || rel.startsWith(`${p}${sep}`) || p.startsWith(`${rel}${sep}`)) return due(!WHOLE_DENY.test(basename(rel)))
303
+ if (isLocalName(rel)) return 'due'
304
+ const name = parts[parts.length - 1]!
305
+ const asItem = (keep: (r: string, isDir: boolean) => boolean, under: string[]): boolean => {
306
+ if (under.length === 0) return true
307
+ for (let i = 1; i < under.length; i++) if (!keep(under.slice(0, i).join(sep), true)) return false
308
+ const r = under.join(sep)
309
+ return isFileName(name) ? keep(r, false) : keep(r, true)
310
+ }
311
+ if (parts[0] === '.shipkit') return due(asItem(shipkitKeep, parts.slice(1)))
312
+ if (parts[0] === '.comfy-ts') return due(asItem(comfyWalkKeep, parts.slice(1)))
313
+ for (const x of REPO_EXTRA) if (rel === x || rel.startsWith(`${x}${sep}`) || x.startsWith(`${rel}${sep}`)) return due(!FILE_DENY.test(name))
314
+ return null
315
+ }
316
+
317
+ /** what the daemon watches: each root, whether it reads its tree, and which paths under it count. A root missing
318
+ * when the watch starts is left to the safety walk */
319
+ export interface WatchRoot {
320
+ dir: string
321
+ recursive: boolean
322
+ heard: (rel: string) => Heard
323
+ }
324
+
325
+ /** `named` gives a repo's `backup.paths` as the last look read them: asked at each event, so a new name counts at once */
326
+ export async function watchRoots(home: string, repos: readonly string[], named: (repo: string) => readonly string[] = () => []): Promise<WatchRoot[]> {
327
+ const order = join(home, ORDER_FILE)
328
+ const memory = new Set(repos.map(sessionName))
329
+ return [
330
+ { dir: join(homeDir(), 'veille'), recursive: true, heard: () => 'due' },
331
+ { dir: join(home, MACHINE_PRIVATE), recursive: true, heard: () => 'due' },
332
+ { dir: dirname(order), recursive: false, heard: (rel) => due(rel === basename(order)) },
333
+ ...(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')) } })),
334
+ ...repos.map((r): WatchRoot => ({ dir: r, recursive: true, heard: (rel) => repoPathHeard(rel, named(r)) })),
335
+ ]
191
336
  }
192
337
 
193
338
  /** a cheap stamp of the sources that are files (a sqlite moves every few seconds; its snapshot runs on the clock) */