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
@@ -0,0 +1,22 @@
1
+ // the files that record what was true when they were written: a plan, an
2
+ // archived repro, a field note, a changelog, a journal. A rename leaves them as
3
+ // written, and a link in one may name a path that is gone, as long as git once
4
+ // held it.
5
+ import { gitBin } from './git-bin.ts'
6
+
7
+ /** the folders of `.shipkit/` that only hold records: plans, archived repros, field notes and their archive */
8
+ const RECORD_DIRS = ['plans', 'repros', 'reflections', 'harvested-reflections']
9
+
10
+ /** a repo relative path of a record: under one of those folders, or a file or a folder named changelog or journal */
11
+ export const isHistoryFile = (rel: string): boolean =>
12
+ RECORD_DIRS.some((d) => rel.startsWith(`.shipkit/${d}/`)) || rel.split('/').some((s) => /^(?:changelog|journal)(?:$|[.\-_/])/i.test(s))
13
+
14
+ /** whether git ever held a file whose path is `token` or ends with `/token`, on any branch of the repo at `cwd` */
15
+ export function onceAPath(cwd: string, token: string): boolean {
16
+ try {
17
+ const p = Bun.spawnSync([gitBin(), 'log', '-1', '--format=%h', '--all', '--', `:(glob)**/${token}`, `:(glob)${token}`], { cwd, stdout: 'pipe', stderr: 'ignore' })
18
+ return p.exitCode === 0 && p.stdout.toString().trim() !== ''
19
+ } catch {
20
+ return false
21
+ }
22
+ }
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') {
@@ -0,0 +1,6 @@
1
+ // a signal as a process reports it: bun gives its name or its number
2
+ import { constants } from 'os'
3
+
4
+ /** the signal's name; null when the process ended by itself */
5
+ export const signalName = (signal: string | number | null | undefined): string | null =>
6
+ signal == null ? null : typeof signal === 'string' ? signal : (Object.entries(constants.signals).find(([, n]) => n === signal)?.[0] ?? `SIG${signal}`)
@@ -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
+ }
@@ -15,6 +15,7 @@
15
15
  // git common dir and reused while it is young: rule SK031 in
16
16
  // the health pass pays for it, and the fix pass that applies it reads it.
17
17
  import { mkdirSync, writeFileSync } from 'fs'
18
+ import { isTransient } from './transient.ts'
18
19
  import { dirname, isAbsolute, posix, relative, resolve, sep } from 'path'
19
20
  import type { RepoConfig } from '../repo-config.ts'
20
21
  import { composeChecks } from '../ledger/gate-checks.ts'
@@ -26,6 +27,7 @@ import { SUITE_SELECT_ENV } from '../suite/reads-env.ts'
26
27
  import { gitBin } from './git-bin.ts'
27
28
  import { auditReportPath, auditedExtras, ignoredFor, pendingByTask, readAuditReport, type AuditReport, type AuditTask, type IgnoredInputs } from './audit-report.ts'
28
29
  import { addIgnoredInputs } from './ignored-block.ts'
30
+ import { runLeakGuard } from '../hooks/leak-guard.ts'
29
31
  import { loadRepoConfig } from '../repo-config.ts'
30
32
 
31
33
  /** how long an audit answers for the tree: about a day, like SK030 */
@@ -89,8 +91,15 @@ function inTree(p: string, declared: string[], extras: string[]): boolean {
89
91
  /** the fewest entries that cover what was read: each file by itself, or a
90
92
  * dir by content once more than three files under it were read (its own
91
93
  * 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[] {
94
+ * `dir/**`, the outermost one only, unless a content entry covers it.
95
+ * An entry `leaks` refuses (the commit leak guard, which reads the config
96
+ * the fix pass writes) becomes its nearest parent it lets through, in the
97
+ * same form; one with no such parent below the root is left out */
98
+ export function proposeInputs(contentRead: string[], listedRead: string[], leaks: (entry: string) => boolean = () => false): string[] {
99
+ // a write in flight is no input: a build's `.dist.tmp-<pid>` names one run, and a line that pins it is stale at once
100
+ const kept = (p: string): boolean => !p.split('/').some(isTransient)
101
+ const content = contentRead.filter(kept)
102
+ const listed = listedRead.filter(kept)
94
103
  const minimal = (xs: string[]): string[] => {
95
104
  const sorted = [...new Set(xs)].sort()
96
105
  return sorted.filter((x) => !sorted.some((y) => y !== x && under(x, y)))
@@ -106,7 +115,15 @@ export function proposeInputs(content: string[], listed: string[]): string[] {
106
115
  const again = new Map<string, string[]>()
107
116
  for (const [d, f] of regroup) again.set(d, [...(again.get(d) ?? []), f])
108
117
  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()
118
+ const lifted = (entry: string, names: boolean): string | null => {
119
+ const form = (d: string): string => (names ? `${d}/**` : d)
120
+ let d = entry
121
+ while (d !== '.' && leaks(form(d))) d = posix.dirname(d)
122
+ return d === '.' ? null : d
123
+ }
124
+ const byContent = minimal(bytes.map((b) => lifted(b, false)).filter((b): b is string => b != null))
125
+ const byNames = minimal(tops.map((t) => lifted(t, true)).filter((t): t is string => t != null)).filter((d) => !byContent.some((b) => under(d, b)))
126
+ return [...byContent, ...byNames.map((d) => `${d}/**`)].sort()
110
127
  }
111
128
 
112
129
  /** the dirs a task depends on as dirs: every one it listed, and every one a
@@ -131,6 +148,7 @@ export async function traceAudit(root: string, config: RepoConfig, o: { fresh?:
131
148
  if (off != null) return { at: now, skipped: off, tasks: [] }
132
149
  const tasks: AuditTask[] = []
133
150
  const toolkit = toolkitDir(root)
151
+ 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
152
  for (const g of await composeChecks(root, config)) {
135
153
  const u = g.runnable
136
154
  if (u.body.cmd == null || g.row.runs.off != null || !g.row.runs.onCi || g.row.decl.inputs == null) continue
@@ -159,7 +177,7 @@ export async function traceAudit(root: string, config: RepoConfig, o: { fresh?:
159
177
  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
178
  const missF = files.filter((p) => (ignored.has(p) ? !covered(p, false, extras) : outside.has(p)))
161
179
  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) })
180
+ tasks.push({ id: u.id, status: 'audited', uncovered: [...missF, ...missD].sort(), propose: proposeInputs(missF, missD, leaks) })
163
181
  } finally {
164
182
  dropTrace(t.dir)
165
183
  }
@@ -0,0 +1,6 @@
1
+ // a write in flight: an atomic write's temp file or folder (`x.tmp`, `x.tmp.<pid>.<hex>`, `.dist.tmp-<pid>`,
2
+ // `.STATUS.md.tmp-<n>`) or an editor's partial copy (`.!<pid>!x`). Its name is true for one run only, so nothing
3
+ // keeps it: no watch hears it, no key names it.
4
+
5
+ /** true for the name of a path segment that is a write in flight */
6
+ export const isTransient = (name: string): boolean => /\.tmp(?:$|[-.])|^\.!\d+!/.test(name)
package/src/drill/run.ts CHANGED
@@ -212,7 +212,7 @@ export function drillRun(lines: readonly string[], o: { transcript: string; root
212
212
  } else if (e.kind === 'bgend') {
213
213
  const c = pending.get(e.id)
214
214
  if (c != null && (c.bgEnd == null || e.at < c.bgEnd)) c.bgEnd = e.at
215
- } else if (e.kind !== 'prompt') marks.push({ at: e.at, kind: e.kind })
215
+ } else if (e.kind !== 'prompt' && e.kind !== 'hook') marks.push({ at: e.at, kind: e.kind })
216
216
  }
217
217
  }
218
218
  const start = Number.isFinite(first) ? first : 0
@@ -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
@@ -11,7 +11,7 @@
11
11
  // check script, a `*.check.ts` with no check object). The declaration always lives WITH the check, never in a table
12
12
  // over here: a table beside the registry is a second source of truth that
13
13
  // drifts the first time somebody adds one.
14
- import { existsSync } from 'fs'
14
+ import { existsSync, realpathSync } from 'fs'
15
15
  import { join, relative, resolve } from 'path'
16
16
  import type { CheckCtx } from '../core/check-ctx.ts'
17
17
  import { type RepoConfig } from '../repo-config.ts'
@@ -55,6 +55,27 @@ function rawAccessOf(root: string, u: DiscoveredCheck, configs: Map<string, RvtC
55
55
  * asked for the quick tier and one that asked for the full tier are different
56
56
  * questions, and a surface that renders keys without applying it renders a
57
57
  * tier nobody ran. */
58
+ /** true when `file` is this repo's own source: under its root, and no install. By real paths, so a root or a file
59
+ * reached through a link is judged where it is */
60
+ export const hostsFile = (root: string, file: string): boolean => {
61
+ const real = (p: string): string => { try { return realpathSync(p) } catch { return p } }
62
+ const rel = relative(real(root), real(file))
63
+ return !rel.startsWith('..') && !rel.split(/[\\/]/).includes('node_modules')
64
+ }
65
+
66
+ /** a check of the toolkit (it has no path of its own in the repo) whose source lives outside this repo */
67
+ export const toolkitCheckElsewhere = (root: string, u: { rel?: string | null; path: string }): boolean => u.rel == null && !hostsFile(root, u.path)
68
+
69
+ /** what a check that declares cache reads becomes when a module its body reaches touches the disk around `c`.
70
+ * In the repo that holds the check's source it is a refusal: the declaration is wrong, and the gate fails until it
71
+ * is right. A toolkit check seen from another repo is the toolkit's defect, never that repo's: it runs there with
72
+ * no cache and says why, so a red gate still means « this repo is broken » */
73
+ export function rawAccessDecl(raw: string, toolkitCheckElsewhere: boolean): Pick<CheckDecl, 'declError' | 'uncacheable'> {
74
+ return toolkitCheckElsewhere
75
+ ? { uncacheable: `a defect of the toolkit, not of this repo: its check declares cache reads, but ${raw}. It runs here with no cache` }
76
+ : { declError: `declares cache reads, but ${raw}` }
77
+ }
78
+
58
79
  export const FULL_TESTS_ENV = 'SHIPKIT_TEST_FULL'
59
80
 
60
81
  export type TestTier = 'quick' | 'full'
@@ -234,9 +255,9 @@ function derivedRuns(o: { gate: boolean; build: boolean; inputs?: string[]; ttl?
234
255
  }
235
256
 
236
257
  /** 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 } {
258
+ function declOfCache(cache: CacheDecl, env: CheckEnv): { inputs?: string[]; optional?: string[]; ttl?: string; never?: string; key?: string; reads?: boolean } {
238
259
  switch (cache.by) {
239
- case 'files': return { inputs: cache.inputs, key: cache.key?.(env) }
260
+ case 'files': return { inputs: cache.inputs, optional: cache.optional, key: cache.key?.(env) }
240
261
  case 'reads': return { reads: true }
241
262
  case 'ttl': return { ttl: cache.span, key: cache.key?.(env) }
242
263
  case 'fact': return { ttl: FOREVER, key: cache.key(env) }
@@ -412,6 +433,7 @@ export async function composeChecks(root: string, c: RepoConfig, o: ComposeOpts
412
433
  decl: {
413
434
  id: u.id,
414
435
  inputs: cache.inputs,
436
+ optional: cache.optional,
415
437
  code: u.rel == null ? undefined : [u.rel],
416
438
  // a built-in's code is the toolkit's: keyed on its own closure
417
439
  // there, never on the toolkit as a whole
@@ -422,7 +444,7 @@ export async function composeChecks(root: string, c: RepoConfig, o: ComposeOpts
422
444
  extra: cache.reads === true ? `${extra ?? ''}|tier=${full ? 'full' : 'quick'}` : extra,
423
445
  writes: u.def.writes,
424
446
  ...(cache.reads === true && raw == null ? { reads: true } : {}),
425
- ...(raw != null ? { declError: `declares cache reads, but ${raw}` } : {}),
447
+ ...(raw != null ? rawAccessDecl(raw, toolkitCheckElsewhere(root, u)) : {}),
426
448
  },
427
449
  title: u.title,
428
450
  description: u.description,
@@ -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 exists (a submodule
371
+ // with a change of its own, 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 with uncommitted changes, 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 => {