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
package/src/core/floor.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // the floor as read from the disk: plain fs behind core/floor-resolve.ts, which
2
2
  // owns the resolution. Every caller outside a check resolves here; a check
3
3
  // resolves through its context (checkFloorReader) so it stays keyed on its reads.
4
- import { existsSync } from 'fs'
4
+ import { existsSync, readdirSync } from 'fs'
5
5
  import { join } from 'path'
6
6
  import { gitBin } from './git-bin.ts'
7
7
  import { fsUnitReader } from '../release/units.ts'
@@ -11,7 +11,11 @@ import type { RepoConfig } from '../repo-config.ts'
11
11
 
12
12
  export * from './floor-resolve.ts'
13
13
 
14
- export const fsFloorReader = (root: string): FloorReader => ({ ...fsUnitReader(root), which: (bin) => Bun.which(bin) })
14
+ export const fsFloorReader = (root: string): FloorReader => ({
15
+ ...fsUnitReader(root),
16
+ subdirs: (rel) => { try { return readdirSync(join(root, rel), { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name) } catch { return [] } },
17
+ which: (bin) => Bun.which(bin),
18
+ })
15
19
 
16
20
  export function resolveFloor(c: RepoConfig, root: string, io: FloorReader = fsFloorReader(root)): FloorResolution {
17
21
  return resolveWith(c, root, io)
@@ -0,0 +1,18 @@
1
+ // the files that record what was true when they were written: a plan, a
2
+ // changelog, a journal. A rename leaves them as written, and a link in one
3
+ // may name a path that is gone, as long as git once held it.
4
+ import { gitBin } from './git-bin.ts'
5
+
6
+ /** a repo relative path of a plan, a changelog or a journal: a file or a folder named so */
7
+ export const isHistoryFile = (rel: string): boolean =>
8
+ rel.startsWith('.shipkit/plans/') || rel.split('/').some((s) => /^(?:changelog|journal)(?:$|[.\-_/])/i.test(s))
9
+
10
+ /** whether git ever held a file whose path is `token` or ends with `/token`, on any branch of the repo at `cwd` */
11
+ export function onceAPath(cwd: string, token: string): boolean {
12
+ try {
13
+ const p = Bun.spawnSync([gitBin(), 'log', '-1', '--format=%h', '--all', '--', `:(glob)**/${token}`, `:(glob)${token}`], { cwd, stdout: 'pipe', stderr: 'ignore' })
14
+ return p.exitCode === 0 && p.stdout.toString().trim() !== ''
15
+ } catch {
16
+ return false
17
+ }
18
+ }
package/src/core/jobs.ts CHANGED
@@ -19,6 +19,8 @@ import { fmtStamp } from './wire.ts'
19
19
 
20
20
  /** status exit code while the run has no verdict yet */
21
21
  export const STILL_RUNNING = 3
22
+ /** how long `status --wait` holds: a run that goes on past it is asked again */
23
+ export const WAIT_CAP_MS = 10 * 60 * 1000
22
24
 
23
25
  export type JobKind = 'ci' | 'check'
24
26
  export type Job = { id: string; pid: number; args: string[]; startedAt: number; kind?: JobKind }
@@ -92,7 +94,7 @@ export function startDetached(root: string, o: { cli: string; args: string[] }):
92
94
  pid,
93
95
  lines: [
94
96
  `ok: gate started in the background as ${id} (pid ${pid}): ${ciLine(o.args)}`,
95
- ` fix: shipkit status ${id} prints it, and exits ${STILL_RUNNING} until it has a verdict`,
97
+ ` fix: shipkit status ${id} --wait returns when it has a verdict (without --wait: the run so far, exit ${STILL_RUNNING} until then)`,
96
98
  ],
97
99
  }
98
100
  }
@@ -128,42 +130,59 @@ export function recordExit(root: string, id: string, code: number): void {
128
130
  atomicWrite(join(dir, 'exit.json'), JSON.stringify({ code, finishedAt: Date.now() } satisfies Exit))
129
131
  }
130
132
 
131
- function latestJob(root: string): string | null {
133
+ /** the latest run of this checkout. `own`: one a `--detach` started, never a job of the daemon */
134
+ function latestJob(root: string, own: boolean): Job | null {
132
135
  let best: Job | null = null
133
136
  try {
134
137
  for (const name of readdirSync(join(root, JOBS))) {
135
138
  const j = readJson<Job>(join(root, JOBS, name, 'job.json'))
136
- if (j != null && (best == null || j.startedAt > best.startedAt)) best = j
139
+ if (j == null || (own && existsSync(jobOpts(root, name)))) continue
140
+ if (best == null || j.startedAt > best.startedAt) best = j
137
141
  }
138
142
  } catch { return null }
139
- return best?.id ?? null
143
+ return best
140
144
  }
141
145
 
142
- /** the run's wire lines so far, then one line on where it stands. The code is
143
- * the gate's own exit code once it has one, STILL_RUNNING before, 1 for a
144
- * run that died without a verdict, 2 for an id nobody started here. */
146
+ /** one line on where the run stands, then its wire lines so far: the first
147
+ * line is the answer. The code is the gate's own exit code once it has one,
148
+ * STILL_RUNNING before, 1 for a run that died without a verdict, 2 for an id
149
+ * nobody started here. With no id: the latest run a `--detach` started, since
150
+ * a job of the daemon is nobody's question. */
145
151
  export function jobStatus(root: string, id?: string): { code: number; lines: string[] } {
146
- const want = id ?? latestJob(root)
152
+ const want = id ?? latestJob(root, true)?.id
147
153
  if (want == null) return { code: 2, lines: ['FAIL: no detached run in this checkout yet', ' fix: shipkit ci --detach starts one'] }
148
154
  const dir = jobDir(root, want)
149
155
  const job = readJson<Job>(join(dir, 'job.json'))
150
156
  if (job == null) return { code: 2, lines: [`FAIL: no detached run '${want}' in this checkout`, ` fix: shipkit status (no id) shows the latest one`] }
151
- const lines = [`ok: run ${job.id}: ${ciLine(job.args, job.kind)} (pid ${job.pid}, started ${fmtStamp(job.startedAt)})`]
157
+ const what = `${ciLine(job.args, job.kind)} (pid ${job.pid}, started ${fmtStamp(job.startedAt)})`
152
158
  let out = ''
153
159
  try { out = readFileSync(join(dir, 'out.log'), 'utf8') } catch { /* nothing printed yet */ }
154
- lines.push(...out.split('\n').filter((l) => l !== ''))
160
+ const wire = out.split('\n').filter((l) => l !== '')
155
161
  const exit = (): Exit | null => readJson<Exit>(join(dir, 'exit.json'))
156
162
  let e = exit()
157
- if (e == null && alive(job.pid)) {
158
- lines.push(`skip: run ${job.id} still running (${((Date.now() - job.startedAt) / 1000).toFixed(1)}s so far), status exits ${STILL_RUNNING} until it has a verdict`)
159
- return { code: STILL_RUNNING, lines }
163
+ if (e == null && jobAlive(job.pid)) {
164
+ return { code: STILL_RUNNING, lines: [`skip: run ${job.id} still running (${((Date.now() - job.startedAt) / 1000).toFixed(1)}s so far), status exits ${STILL_RUNNING} until it has a verdict: ${what}`, ...wire] }
160
165
  }
161
166
  // it may have written its verdict between the two reads
162
167
  e ??= exit()
163
- if (e == null) return { code: 1, lines: [...lines, `FAIL: run ${job.id} died without a verdict (pid ${job.pid} is gone)`, ` fix: ${ciLine(job.args, job.kind)}`] }
168
+ if (e == null) return { code: 1, lines: [`FAIL: run ${job.id} died without a verdict (pid ${job.pid} is gone): ${what}`, ` fix: ${ciLine(job.args, job.kind)}`, ...wire] }
164
169
  const took = `${((e.finishedAt - job.startedAt) / 1000).toFixed(1)}s`
165
- lines.push(e.code === 0 ? `ok: run ${job.id} finished green in ${took}` : `FAIL: run ${job.id} finished red (exit ${e.code}) in ${took}`)
166
- return { code: e.code, lines }
170
+ const verdict = e.code === 0 ? `ok: run ${job.id} finished green in ${took}` : `FAIL: run ${job.id} finished red (exit ${e.code}) in ${took}`
171
+ return { code: e.code, lines: [`${verdict}: ${what}`, ...wire] }
172
+ }
173
+
174
+ /** the status of a run once it has a verdict: one call that returns when the
175
+ * run ends, in place of a poll every few seconds. Past the cap it answers
176
+ * STILL_RUNNING like a plain status. */
177
+ export async function waitStatus(root: string, id?: string, o: { capMs?: number; pollMs?: number } = {}): Promise<{ code: number; lines: string[] }> {
178
+ const want = id ?? latestJob(root, true)?.id
179
+ const until = Date.now() + (o.capMs ?? WAIT_CAP_MS)
180
+ const pending = (): boolean => {
181
+ const j = want == null ? null : readJob(root, want)
182
+ return j != null && readExit(root, j.id) == null && jobAlive(j.pid)
183
+ }
184
+ while (pending() && Date.now() < until) await Bun.sleep(o.pollMs ?? 250)
185
+ return jobStatus(root, want)
167
186
  }
168
187
 
169
188
  /** finished runs older than a week go, then the oldest past the count cap;
@@ -37,8 +37,8 @@ export const LAYOUT = {
37
37
  // the social folder (contract v3): one folder a draft, the week's rhythm. The SK004 block re-includes it in a
38
38
  // private repo only, like plans (wiki tools/shipkit/social.md)
39
39
  social: sk('social'),
40
- // the owner's own voice: his takes of a trailer's lines, one a text (trailer/sound/takes.ts). The SK004 block
41
- // re-includes it in a private repo only: a recording is his voice
40
+ // the owner's own voice: his takes of a trailer's lines, one a text (trailer/sound/takes.ts). Local in every
41
+ // repo: the SK004 block never re-includes it, a recording is his voice
42
42
  voice: sk('voice'),
43
43
  // local: the facts (sha, size, type) of every draft media, so a file the disk let go keeps its key in the media
44
44
  // store (wiki tools/shipkit/social.md, Media)
@@ -0,0 +1,16 @@
1
+ // the names a mistyped one was probably meant as, for a refusal that names the
2
+ // next thing to type: equal, a name it begins, or a name that begins it up to
3
+ // a separator (`recipes:check` → `recipes`, never `r`), case, `_` and `-`
4
+ // aside. Short on purpose: a refusal lists a few, never the whole set.
5
+
6
+ const norm = (s: string): string => s.toLowerCase().replace(/[_-]/g, '')
7
+
8
+ /** the names of `have` close enough to `want`, at most `max` */
9
+ export function nearest(want: string, have: readonly string[], max = 5): string[] {
10
+ const w = norm(want)
11
+ if (w === '') return []
12
+ return have.filter((n) => {
13
+ const h = norm(n)
14
+ return h !== '' && (h.startsWith(w) || (w.startsWith(h) && /[^a-z0-9]/.test(w[h.length] ?? '')))
15
+ }).slice(0, max)
16
+ }
@@ -0,0 +1,19 @@
1
+ // a tree removed even when it holds a read only folder (a module cache, a snapshot written 0555 on purpose): the
2
+ // caller has already proven the tree is its own to remove. Links are never followed, a link goes as a link.
3
+ import { rmSync } from 'fs'
4
+
5
+ /** every folder and file under `path` made writable by its owner, links never followed */
6
+ export function makeWritable(path: string): void {
7
+ Bun.spawnSync(['chmod', '-R', '-P', 'u+rwx', path], { stdout: 'ignore', stderr: 'ignore' })
8
+ }
9
+
10
+ /** `path` removed; a refusal for a read only folder inside makes the tree writable and tries once more */
11
+ export function removeTree(path: string): void {
12
+ try {
13
+ rmSync(path, { recursive: true, force: true })
14
+ } catch (e) {
15
+ if (!['EACCES', 'EPERM', 'ENOTEMPTY'].includes((e as { code?: string }).code ?? '')) throw e
16
+ makeWritable(path)
17
+ rmSync(path, { recursive: true, force: true })
18
+ }
19
+ }
package/src/core/runs.ts CHANGED
@@ -52,8 +52,10 @@ export type FixWhen = 'none' | 'ci' | 'manual'
52
52
 
53
53
  /** how an answer is kept. Every variant names its one parameter */
54
54
  export type CacheDecl =
55
- /** keyed on the content of these repo paths (and the check's own code) */
56
- | { by: 'files'; inputs: string[]; key: ((env: CheckEnv) => string) | null }
55
+ /** keyed on the content of these repo paths (and the check's own code).
56
+ * `optional` names the inputs a repo may lack: absent, the key carries
57
+ * `absent` for it; any other input missing from disk refuses the key */
58
+ | { by: 'files'; inputs: string[]; optional?: string[]; key: ((env: CheckEnv) => string) | null }
57
59
  /** keyed on what the body read through its context, re-checked before a replay */
58
60
  | { by: 'reads' }
59
61
  /** a clean answer about the world keeps for `span` */
@@ -129,9 +131,16 @@ export function cacheProblem(c: unknown): string | null {
129
131
  const keys = want[by]
130
132
  const missing = keys.filter((k) => !(k in o))
131
133
  if (missing.length > 0) return `cache { by: '${by}' } is missing ${missing.join(', ')}: every key is explicit`
132
- const unknown = Object.keys(o).filter((k) => k !== 'by' && !keys.includes(k))
134
+ // the one key that may be left out: check files written before it exist in every repo
135
+ const unknown = Object.keys(o).filter((k) => k !== 'by' && !keys.includes(k) && !(by === 'files' && k === 'optional'))
133
136
  if (unknown.length > 0) return `cache { by: '${by}' } has unknown key ${unknown.join(', ')} (it takes ${keys.length === 0 ? 'nothing else' : keys.join(', ')})`
134
137
  if (by === 'files' && (!Array.isArray(o.inputs) || o.inputs.length === 0 || o.inputs.some((p) => typeof p !== 'string' || p === ''))) return `cache.inputs is a non empty list of repo relative paths`
138
+ if (by === 'files' && 'optional' in o) {
139
+ const opt = o.optional
140
+ if (!Array.isArray(opt) || opt.some((p) => typeof p !== 'string')) return `cache.optional is a list of paths from cache.inputs`
141
+ const stray = opt.filter((p) => !(o.inputs as string[]).includes(p))
142
+ if (stray.length > 0) return `cache.optional names ${stray.join(', ')}, which cache.inputs does not: an optional path is one of the inputs`
143
+ }
135
144
  if ((by === 'files' || by === 'ttl') && o.key !== null && typeof o.key !== 'function') return `cache.key is null or a function of { root, config }`
136
145
  if (by === 'fact' && typeof o.key !== 'function') return `cache { by: 'fact' } needs key: a function of { root, config } returning the declared value`
137
146
  if (by === 'ttl') {
@@ -6,10 +6,11 @@
6
6
  // a folder it can prove it made: a linked worktree of that repo, at the path
7
7
  // this module derives, carrying the mark it wrote into the worktree's own git
8
8
  // dir. Anything else at that path is refused and left as it is.
9
- import { existsSync, lstatSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'fs'
9
+ import { existsSync, lstatSync, readFileSync, realpathSync, writeFileSync } from 'fs'
10
10
  import { tmpdir } from 'os'
11
11
  import { join } from 'path'
12
12
  import { gitBin } from './git-bin.ts'
13
+ import { removeTree } from './remove-tree.ts'
13
14
 
14
15
  const git = (cwd: string, args: string[]): { code: number; out: string } => {
15
16
  const p = Bun.spawnSync([gitBin(), ...args], { cwd, stdout: 'pipe', stderr: 'pipe' })
@@ -52,7 +53,7 @@ export function throwawayCheckout(repo: string, purpose: string, sha: string): {
52
53
  // the only reset of a working tree to a commit in this toolkit: a proven throwaway
53
54
  const back = git(dir, ['reset', '--hard', '--quiet', sha])
54
55
  if (back.code !== 0) {
55
- rmSync(dir, { recursive: true, force: true })
56
+ removeTree(dir)
56
57
  git(repo, ['worktree', 'prune'])
57
58
  }
58
59
  }
@@ -66,7 +67,24 @@ export function throwawayCheckout(repo: string, purpose: string, sha: string): {
66
67
  const own = ownGitDir(repo, dir)
67
68
  if ('refuse' in own) return { error: `the throwaway checkout at ${dir} fails its own proof (${own.refuse})` }
68
69
  }
69
- const clean = git(dir, ['clean', '-ffdxq'])
70
- if (clean.code !== 0) return { error: `cannot clean the throwaway checkout at ${dir}: ${clean.out}` }
70
+ if (git(dir, ['clean', '-ffdxq']).code !== 0) {
71
+ // a check may write a folder read only (a snapshot, a module cache), and git clean cannot remove one: each
72
+ // path it would remove goes through removeTree, which makes it writable first
73
+ for (const row of git(dir, ['clean', '-ffdxn']).out.split('\n')) {
74
+ const rel = row.match(/^Would remove (.+?)\/?$/)?.[1]
75
+ if (rel != null) removeTree(join(dir, rel))
76
+ }
77
+ const clean = git(dir, ['clean', '-ffdxq'])
78
+ if (clean.code !== 0) return { error: cleanRefusal(dir, clean.out) }
79
+ }
71
80
  return { dir }
72
81
  }
82
+
83
+ /** a clean that still fails, as one line: how many paths git refused, the first one, the fix */
84
+ export function cleanRefusal(dir: string, out: string): string {
85
+ const refused = [...out.matchAll(/^warning: failed to remove (.+?): (.+)$/gm)]
86
+ const first = refused[0]
87
+ if (first == null) return `cannot clean the throwaway checkout at ${dir}: ${out.split('\n')[0] ?? 'git clean failed'}`
88
+ const n = refused.length
89
+ return `cannot clean the throwaway checkout at ${dir}: git refused ${n} path${n === 1 ? '' : 's'}, first ${join(dir, first[1] ?? '')} (${first[2]}). fix: chmod -R u+w ${dir}, then run again`
90
+ }
@@ -26,6 +26,7 @@ import { SUITE_SELECT_ENV } from '../suite/reads-env.ts'
26
26
  import { gitBin } from './git-bin.ts'
27
27
  import { auditReportPath, auditedExtras, ignoredFor, pendingByTask, readAuditReport, type AuditReport, type AuditTask, type IgnoredInputs } from './audit-report.ts'
28
28
  import { addIgnoredInputs } from './ignored-block.ts'
29
+ import { runLeakGuard } from '../hooks/leak-guard.ts'
29
30
  import { loadRepoConfig } from '../repo-config.ts'
30
31
 
31
32
  /** how long an audit answers for the tree: about a day, like SK030 */
@@ -89,8 +90,11 @@ function inTree(p: string, declared: string[], extras: string[]): boolean {
89
90
  /** the fewest entries that cover what was read: each file by itself, or a
90
91
  * dir by content once more than three files under it were read (its own
91
92
  * dir, or the outermost dir the task also listed); each listed dir as
92
- * `dir/**`, the outermost one only, unless a content entry covers it */
93
- export function proposeInputs(content: string[], listed: string[]): string[] {
93
+ * `dir/**`, the outermost one only, unless a content entry covers it.
94
+ * An entry `leaks` refuses (the commit leak guard, which reads the config
95
+ * the fix pass writes) becomes its nearest parent it lets through, in the
96
+ * same form; one with no such parent below the root is left out */
97
+ export function proposeInputs(content: string[], listed: string[], leaks: (entry: string) => boolean = () => false): string[] {
94
98
  const minimal = (xs: string[]): string[] => {
95
99
  const sorted = [...new Set(xs)].sort()
96
100
  return sorted.filter((x) => !sorted.some((y) => y !== x && under(x, y)))
@@ -106,7 +110,15 @@ export function proposeInputs(content: string[], listed: string[]): string[] {
106
110
  const again = new Map<string, string[]>()
107
111
  for (const [d, f] of regroup) again.set(d, [...(again.get(d) ?? []), f])
108
112
  const bytes = minimal([...again].flatMap(([dir, files]) => (files.length > 3 && dir !== '.' ? [dir] : files)))
109
- return [...bytes, ...tops.filter((d) => !bytes.some((b) => under(d, b))).map((d) => `${d}/**`)].sort()
113
+ const lifted = (entry: string, names: boolean): string | null => {
114
+ const form = (d: string): string => (names ? `${d}/**` : d)
115
+ let d = entry
116
+ while (d !== '.' && leaks(form(d))) d = posix.dirname(d)
117
+ return d === '.' ? null : d
118
+ }
119
+ const byContent = minimal(bytes.map((b) => lifted(b, false)).filter((b): b is string => b != null))
120
+ const byNames = minimal(tops.map((t) => lifted(t, true)).filter((t): t is string => t != null)).filter((d) => !byContent.some((b) => under(d, b)))
121
+ return [...byContent, ...byNames.map((d) => `${d}/**`)].sort()
110
122
  }
111
123
 
112
124
  /** the dirs a task depends on as dirs: every one it listed, and every one a
@@ -131,6 +143,7 @@ export async function traceAudit(root: string, config: RepoConfig, o: { fresh?:
131
143
  if (off != null) return { at: now, skipped: off, tasks: [] }
132
144
  const tasks: AuditTask[] = []
133
145
  const toolkit = toolkitDir(root)
146
+ const leaks = (entry: string): boolean => runLeakGuard(root, { keywordFile: config.hooks?.keywordFile, allow: config.hooks?.leakAllow, staged: false, text: [{ label: 'ignoredInputs proposal', content: entry }] }).status === 'hit'
134
147
  for (const g of await composeChecks(root, config)) {
135
148
  const u = g.runnable
136
149
  if (u.body.cmd == null || g.row.runs.off != null || !g.row.runs.onCi || g.row.decl.inputs == null) continue
@@ -159,7 +172,7 @@ export async function traceAudit(root: string, config: RepoConfig, o: { fresh?:
159
172
  const outside = declared == null ? new Set<string>() : inWorkTree(root, files.filter((p) => !ignored.has(p) && !(toolkit != null && under(p, toolkit)) && !inTree(p, declared, extras)))
160
173
  const missF = files.filter((p) => (ignored.has(p) ? !covered(p, false, extras) : outside.has(p)))
161
174
  const missD = dirs.filter((p) => ignored.has(p) && !covered(p, true, extras))
162
- tasks.push({ id: u.id, status: 'audited', uncovered: [...missF, ...missD].sort(), propose: proposeInputs(missF, missD) })
175
+ tasks.push({ id: u.id, status: 'audited', uncovered: [...missF, ...missD].sort(), propose: proposeInputs(missF, missD, leaks) })
163
176
  } finally {
164
177
  dropTrace(t.dir)
165
178
  }
@@ -8,10 +8,11 @@
8
8
  // every page; a sync walk, a VACUUM or a hash pass there holds every page with it (tests/daemon-jobs.test.ts)
9
9
  import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'
10
10
  import { join } from 'node:path'
11
+ import { homedir } from 'node:os'
11
12
  import { machineGet } from '../core/machine-db.ts'
12
13
  import { loopWatch } from '../core/loop-watch.ts'
13
14
  import { BACKUP_EVERY_MS } from '../media-store/backup/daemon.ts'
14
- import { MEDIA_EVERY_MS } from '../media-store/daemon.ts'
15
+ import { MEDIA_EVERY_MS, mediaDue } from '../media-store/daemon.ts'
15
16
  import { ANNEX_EVERY_MS, annexDue } from '../annex/tidy.ts'
16
17
  import { SWEEP_EVERY_MS, SWEPT_AT } from './machine-stores.ts'
17
18
  import { contextSourcesStamp, GLOBAL_CONTEXT_DONE, GLOBAL_CONTEXT_EVERY_MS, GLOBAL_CONTEXT_MAX_MS } from './global-context.ts'
@@ -28,6 +29,14 @@ export interface DaemonJob {
28
29
  /** a cheap read in the daemon (a stat, never a walk; async when it gives the loop back between two): false skips
29
30
  * the child for this look. `root` is the house repo the children run in */
30
31
  due?: (now: number, root: string) => boolean | Promise<boolean>
32
+ /** what the daemon holds for this job while it runs (a file watch whose callback only notes a path): started with
33
+ * the jobs, stopped with them; its `due` replaces the job's */
34
+ hold?: (root: string, printErr: (l: string) => void) => Promise<JobHold>
35
+ }
36
+
37
+ export interface JobHold {
38
+ due: (now: number) => boolean
39
+ stop: () => void
31
40
  }
32
41
 
33
42
  /** a child gets this long; past it, it is killed and said */
@@ -36,17 +45,33 @@ export const JOB_MAX_MS = 60 * 60_000
36
45
  export const JOB_NICE = 15
37
46
 
38
47
  export const DAEMON_JOBS: readonly DaemonJob[] = [
39
- { id: 'media store', everyMs: MEDIA_EVERY_MS, firstMs: 15_000 },
48
+ // a stat of each store folder: a pass that found nothing waits MEDIA_QUIET_MS, unless a store moves
49
+ { id: 'media store', everyMs: MEDIA_EVERY_MS, firstMs: 15_000, due: (now) => mediaDue(now) },
40
50
  // the scratch on the annex: a spill when the drive leaves, merged back when it returns, born folders, stale scratch
41
51
  { id: 'annex', everyMs: ANNEX_EVERY_MS, firstMs: 20_000, due: (now) => annexDue(now) },
42
52
  { id: 'retention sweep', everyMs: 5 * 60_000, firstMs: 10_000, due: (now) => now - (machineGet<number>(SWEPT_AT) ?? 0) >= SWEEP_EVERY_MS },
43
- { id: 'backup', everyMs: BACKUP_EVERY_MS, firstMs: BACKUP_EVERY_MS },
53
+ // a watch of the sources: a look only once a source may have moved, a run waits, or a clock says so
54
+ { id: 'backup', everyMs: BACKUP_EVERY_MS, firstMs: BACKUP_EVERY_MS, hold: (root, printErr) => backupHold(root, printErr) },
44
55
  // the house's generated context: its unit files are imported to be read, a second of compile the loop never pays
45
56
  { id: 'global context', everyMs: GLOBAL_CONTEXT_EVERY_MS, firstMs: 30_000, due: async (now, root) => contextDue(now, await contextSourcesStamp(root)) },
46
57
  // every global process with a url as an app in ~/Applications: built when missing or stale, removed when gone (process-apps.ts)
47
58
  { id: 'apps', everyMs: APPS_EVERY_MS, firstMs: 45_000, due: async (now, root) => appsDue(now, await appsSourcesStamp(root)) },
48
59
  ]
49
60
 
61
+ async function backupHold(root: string, printErr: (l: string) => void): Promise<JobHold> {
62
+ const { houseRepos } = await import('../serve/project-gutter.ts')
63
+ const { BackupWatch } = await import('../media-store/backup/watch.ts')
64
+ let w: InstanceType<typeof BackupWatch>
65
+ try {
66
+ const house = houseRepos(root, homedir())
67
+ w = await new BackupWatch({ home: homedir(), repos: [...house.repos, ...house.archived].map((r) => r.path), printErr }).start()
68
+ } catch (e) {
69
+ printErr(`WARN daemon job backup: no watch of its sources (${(e as Error).message}): each look walks every source`)
70
+ w = new BackupWatch({ home: homedir(), repos: [] }).blindly()
71
+ }
72
+ return { due: (now) => w.due(now), stop: () => w.stop() }
73
+ }
74
+
50
75
  /** the context is due when its sources' stamp moved since the last write, or that write is old */
51
76
  export function contextDue(now: number, stamp: string | null): boolean {
52
77
  if (stamp == null) return false
@@ -99,6 +124,7 @@ export function startJobs(d: JobsDeps, jobs: readonly DaemonJob[] = DAEMON_JOBS,
99
124
  const pidFile = (id: JobId): string => join(d.dir, `${slug(id)}.pid`)
100
125
  const exitFile = (id: JobId): string => join(d.dir, `${slug(id)}.exit`)
101
126
  const startedAt = new Map<JobId, number>()
127
+ const holds = new Map<JobId, JobHold>()
102
128
 
103
129
  /** the pid of the job's child that still runs, else null; a finished child's failure said once */
104
130
  const running = (id: JobId): number | null => {
@@ -140,14 +166,22 @@ export function startJobs(d: JobsDeps, jobs: readonly DaemonJob[] = DAEMON_JOBS,
140
166
 
141
167
  const look = async (job: DaemonJob, force: boolean): Promise<number | null> => {
142
168
  if (running(job.id) != null) return null
143
- const due = job.due
169
+ const hold = holds.get(job.id)
170
+ const due = hold != null ? (t: number): boolean => hold.due(t) : job.due
144
171
  if (!force && due != null && !(await loopWatch.spanned(`${job.id} (due)`, () => due(now(), d.cwd)))) return null
145
172
  return launch(job)
146
173
  }
147
174
 
148
175
  const timers: ReturnType<typeof setTimeout>[] = []
176
+ let stopped = false
149
177
  if (o.timers !== false)
150
178
  for (const job of jobs) {
179
+ // a hold that does not start leaves the job's own due: the look runs as it would with no hold
180
+ if (job.hold != null)
181
+ void job.hold(d.cwd, d.printErr).then(
182
+ (h) => (stopped ? h.stop() : void holds.set(job.id, h)),
183
+ (e) => d.printErr(`WARN daemon job ${job.id}: its watch did not start (${(e as Error).message}): each look runs as with no watch`),
184
+ )
151
185
  const tick = (): void => void look(job, false).catch((e) => d.printErr(`WARN daemon job ${job.id}: ${(e as Error).message}`))
152
186
  const first = setTimeout(() => {
153
187
  tick()
@@ -161,7 +195,10 @@ export function startJobs(d: JobsDeps, jobs: readonly DaemonJob[] = DAEMON_JOBS,
161
195
 
162
196
  return {
163
197
  stop: () => {
198
+ stopped = true
164
199
  for (const t of timers) clearTimeout(t)
200
+ for (const h of holds.values()) h.stop()
201
+ holds.clear()
165
202
  },
166
203
  async run(id, ro = {}) {
167
204
  const job = jobs.find((j) => j.id === id)
@@ -11,6 +11,7 @@ import { homedir } from 'node:os'
11
11
  import { basename, dirname, join, sep } from 'node:path'
12
12
  import { gitBin } from '../core/git-bin.ts'
13
13
  import { machineDbPath, machineGet, machineSet } from '../core/machine-db.ts'
14
+ import { removeTree } from '../core/remove-tree.ts'
14
15
 
15
16
  /** a unit written this recently is never touched while the disk has room */
16
17
  export const TEMP_GUARD_MS = 24 * 60 * 60 * 1000
@@ -324,15 +325,6 @@ export function planTemp(root: TempRoot, o: PlanOptions): Plan | null {
324
325
  return { root: real, drop, keep, fresh: c.fresh }
325
326
  }
326
327
 
327
- /** a unit removed; one with a read only folder inside (a module cache) is made writable first, links never followed */
328
- function remove(path: string): void {
329
- try { rmSync(path, { recursive: true, force: true }) } catch (e) {
330
- if (!['EACCES', 'EPERM', 'ENOTEMPTY'].includes((e as { code?: string }).code ?? '')) throw e
331
- Bun.spawnSync(['chmod', '-R', '-P', 'u+rwx', path], { stdout: 'ignore', stderr: 'ignore' })
332
- rmSync(path, { recursive: true, force: true })
333
- }
334
- }
335
-
336
328
  export const gb = (n: number): string => `${(n / 1e9).toFixed(2)} GB`
337
329
 
338
330
  /** what one pass did to one root, as `sk tmp` reads it back */
@@ -356,7 +348,7 @@ export function trimTemp(root: TempRoot, o: TrimOptions): Pass | null {
356
348
  if (now == null) continue
357
349
  if (stamp(now) >= plan.fresh) { pass.kept++; continue }
358
350
  const records = [...new Set([u.path, ...u.gits])].map(worktreeRecord).filter((r): r is string => r != null)
359
- try { remove(u.path) } catch (e) {
351
+ try { removeTree(u.path) } catch (e) {
360
352
  o.printErr(`WARN ${root.id}: ${u.path} not deleted (${(e as Error).message})`)
361
353
  pass.failed++
362
354
  continue
@@ -234,9 +234,9 @@ function derivedRuns(o: { gate: boolean; build: boolean; inputs?: string[]; ttl?
234
234
  }
235
235
 
236
236
  /** the cache half of a check file, as the key layer reads it */
237
- function declOfCache(cache: CacheDecl, env: CheckEnv): { inputs?: string[]; ttl?: string; never?: string; key?: string; reads?: boolean } {
237
+ function declOfCache(cache: CacheDecl, env: CheckEnv): { inputs?: string[]; optional?: string[]; ttl?: string; never?: string; key?: string; reads?: boolean } {
238
238
  switch (cache.by) {
239
- case 'files': return { inputs: cache.inputs, key: cache.key?.(env) }
239
+ case 'files': return { inputs: cache.inputs, optional: cache.optional, key: cache.key?.(env) }
240
240
  case 'reads': return { reads: true }
241
241
  case 'ttl': return { ttl: cache.span, key: cache.key?.(env) }
242
242
  case 'fact': return { ttl: FOREVER, key: cache.key(env) }
@@ -412,6 +412,7 @@ export async function composeChecks(root: string, c: RepoConfig, o: ComposeOpts
412
412
  decl: {
413
413
  id: u.id,
414
414
  inputs: cache.inputs,
415
+ optional: cache.optional,
415
416
  code: u.rel == null ? undefined : [u.rel],
416
417
  // a built-in's code is the toolkit's: keyed on its own closure
417
418
  // there, never on the toolkit as a whole
@@ -51,6 +51,9 @@ import { installIdentity, toolchainIdentity, type LibSource } from './toolchain-
51
51
  * so an old ledger can never answer a new question. */
52
52
  export const KEY_VERSION = 4
53
53
 
54
+ /** the object id an optional input carries while it is not on disk */
55
+ export const ABSENT = 'absent'
56
+
54
57
  /** `dir/**` names a dir a task only LISTS: keyed on the names under it */
55
58
  export const isNamesInput = (p: string): boolean => p.endsWith('/**')
56
59
 
@@ -74,6 +77,10 @@ export type CheckDecl = {
74
77
  id: string
75
78
  /** CONTENT: repo-relative paths this check reads. Presence declares the population. */
76
79
  inputs?: string[]
80
+ /** the inputs a repo may lack, each one of `inputs`. Absent, the key
81
+ * carries `absent` for it, so the key moves when it appears. Any other
82
+ * input missing from disk refuses the key: a typo must never key */
83
+ optional?: string[]
77
84
  /** WORLD: clean-pass duration, e.g. '24h'. Presence declares the population. */
78
85
  ttl?: string
79
86
  /** repo-relative entry files of the check's OWN code — the module-graph
@@ -302,6 +309,12 @@ export class KeyLayer {
302
309
  return new KeyLayer(root, decls, registration, scan, scanError, closureByCheck, codeOids, toolchain, [...paths].sort(), o.scope ?? null, performance.now() - started)
303
310
  }
304
311
 
312
+ /** what the scan saw of every declared input of the layer that git does not ignore, as one id; null when the
313
+ * scan failed. The ignored inputs stay out: a run writes some of them, so their id moves with every run */
314
+ treeStamp(): string | null {
315
+ return this.scan == null ? null : this.scan.treeOid
316
+ }
317
+
305
318
  /** the key for one check, or the reason there is none. */
306
319
  keyFor(id: string): CheckKey {
307
320
  const d = this.decls.find((u) => u.id === id)
@@ -346,16 +359,24 @@ export class KeyLayer {
346
359
 
347
360
  let inputs: string[]
348
361
  let names: string[]
362
+ let optional: Set<string>
349
363
  try {
350
364
  inputs = (d.inputs ?? []).filter((p) => !isNamesInput(p)).map(normalizeInput).sort()
351
365
  names = (d.inputs ?? []).filter(isNamesInput).map((p) => normalizeInput(p.slice(0, -3))).sort()
366
+ optional = new Set((d.optional ?? []).map(normalizeInput))
352
367
  } catch (e) {
353
368
  return { ...base, reason: e instanceof Error ? e.message : String(e) }
354
369
  }
355
- const stale = inputs.filter((p) => scan.missing.includes(p))
356
- if (stale.length > 0) return { ...base, reason: `declared input(s) not on disk: ${stale.join(', ')}` }
370
+ // absent means not on disk at all: a path git cannot name while it
371
+ // exists (a submodule, an empty folder) keys nothing, optional or not
372
+ const notOnDisk = (p: string): boolean => !existsSync(join(this.root, p))
373
+ const absent = new Set(inputs.filter((p) => optional.has(p) && scan.missing.includes(p) && notOnDisk(p)))
374
+ const stale = inputs.filter((p) => scan.missing.includes(p) && !absent.has(p))
375
+ const gone = stale.filter(notOnDisk)
376
+ if (gone.length > 0) return { ...base, reason: `declared input(s) not on disk: ${gone.join(', ')}` }
377
+ if (stale.length > 0) return { ...base, reason: `declared input(s) on disk that git could not name (a submodule, an empty folder): ${stale.join(', ')}` }
357
378
  const hidden = inputs.flatMap((p) => scan.excluded.get(p) ?? [])
358
- const inputOids: [string, string][] = inputs.map((p) => [p, scan.oidByPath.get(p) ?? ''])
379
+ const inputOids: [string, string][] = inputs.map((p) => [p, absent.has(p) ? ABSENT : scan.oidByPath.get(p) ?? ''])
359
380
  if (inputOids.some(([, oid]) => oid === '')) return { ...base, reason: 'git could not name one of the declared inputs' }
360
381
 
361
382
  if (!ownReadable) return { ...base, reason: `git could not hash this check's own source: ${own.filter((p) => this.codeOids.get(p) == null).join(', ')}` }
@@ -460,7 +481,7 @@ export class KeyLayer {
460
481
  let h = this.namesMemo.get(rel)
461
482
  if (h == null) {
462
483
  const abs = join(this.root, rel)
463
- if (!existsSync(abs)) h = 'absent'
484
+ if (!existsSync(abs)) h = ABSENT
464
485
  else {
465
486
  const all: string[] = []
466
487
  const walk = (d: string, prefix: string): void => {
@@ -200,9 +200,19 @@ function dropAtExit(p: string): void {
200
200
  /** a scratch index older than this is swept whatever its pid: pids are reused */
201
201
  export const SCAN_INDEX_KEEP_MS = 60 * 60 * 1000
202
202
 
203
+ /** the lock git leaves on the warm ignored index is stale past this: git holds it for one command, seconds at most
204
+ * on the largest tree measured, and a git that was killed leaves it forever. One left in a repo failed every scan
205
+ * there for eleven days: no check had a key, nothing was cached, and each save ran the whole gate again */
206
+ export const SCAN_LOCK_STALE_MS = 2 * 60 * 1000
207
+ const IGNORED_LOCK = 'scan-ignored.idx.lock'
208
+
203
209
  /** the scratch indexes of processes that are gone (killed ones leave theirs),
204
210
  * and any past the keep window */
205
211
  export function sweepScanIndexes(dir: string, now: number): void {
212
+ try {
213
+ const lock = join(dir, IGNORED_LOCK)
214
+ if (statSync(lock).mtimeMs < now - SCAN_LOCK_STALE_MS) rmSync(lock, { force: true })
215
+ } catch { /* no lock, or a live git just released it */ }
206
216
  try {
207
217
  for (const f of readdirSync(dir)) {
208
218
  const m = /^scan-(\d+)\.idx(\.tmp)?$/.exec(f)