rvlib-shipkit 2.23.0 → 2.24.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 (97) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/package.json +1 -1
  3. package/src/agent-time/render.ts +28 -14
  4. package/src/agent-time/report.ts +46 -25
  5. package/src/agent-time/store.ts +30 -10
  6. package/src/agent-time/timeline.ts +43 -15
  7. package/src/asks/asks-queue.ts +32 -11
  8. package/src/checks/SK044-behind-upstream.check.ts +38 -0
  9. package/src/cli/cmd_Asks.ts +2 -0
  10. package/src/cli/cmd_Backup.ts +7 -5
  11. package/src/cli/cmd_Bump.ts +1 -0
  12. package/src/cli/cmd_Capacity.ts +26 -0
  13. package/src/cli/cmd_Check.ts +1 -0
  14. package/src/cli/cmd_Checks.ts +1 -0
  15. package/src/cli/cmd_Ci.ts +1 -0
  16. package/src/cli/cmd_Commands.ts +50 -14
  17. package/src/cli/cmd_Home.ts +0 -29
  18. package/src/cli/cmd_Hooks.ts +1 -0
  19. package/src/cli/cmd_Mv.ts +1 -0
  20. package/src/cli/cmd_Reflect.ts +1 -0
  21. package/src/cli/cmd_Releases.ts +1 -0
  22. package/src/cli/cmd_Review.ts +97 -14
  23. package/src/cli/cmd_Secret.ts +41 -2
  24. package/src/cli/cmd_Shot.ts +1 -0
  25. package/src/cli/cmd_Status.ts +1 -0
  26. package/src/cli/cmd_Time.ts +3 -1
  27. package/src/cli/cmd_Tmp.ts +82 -0
  28. package/src/cli/cmd_Wiki.ts +1 -0
  29. package/src/cli/registry.ts +13 -1
  30. package/src/collections/pings.ts +1 -1
  31. package/src/core/capacity.ts +71 -0
  32. package/src/core/check-runner.ts +86 -15
  33. package/src/core/motherhome.ts +67 -9
  34. package/src/core/slots.ts +49 -12
  35. package/src/core/trace-audit.ts +4 -1
  36. package/src/drill/run.ts +5 -2
  37. package/src/home/gui-app/ShipkitGui.swift +1 -0
  38. package/src/home/home-launchd.ts +11 -3
  39. package/src/home/home-routes.ts +11 -4
  40. package/src/home/machine-host.ts +65 -0
  41. package/src/home/machine-stores.ts +19 -17
  42. package/src/home/machine-temp.ts +493 -0
  43. package/src/home/other-macs.ts +74 -0
  44. package/src/home/run-daemon.ts +10 -2
  45. package/src/home/serve-web.ts +2 -2
  46. package/src/home/via-hub.ts +6 -1
  47. package/src/init-repo.ts +7 -3
  48. package/src/ledger/ledger.ts +6 -0
  49. package/src/ledger/store.ts +6 -0
  50. package/src/media-store/backup/keys.ts +21 -6
  51. package/src/media-store/backup/manifest.ts +52 -11
  52. package/src/media-store/backup/restore.ts +17 -10
  53. package/src/media-store/backup/run.ts +5 -2
  54. package/src/media-store/backup/sources.ts +2 -1
  55. package/src/mv/mv-md.ts +121 -42
  56. package/src/reflect/transcript.ts +56 -11
  57. package/src/releases/from-card.ts +45 -3
  58. package/src/releases/model.ts +6 -0
  59. package/src/releases/store.ts +8 -1
  60. package/src/repo-config.ts +5 -3
  61. package/src/review/cells.ts +24 -3
  62. package/src/review/format.ts +33 -9
  63. package/src/review/media-kind.ts +14 -11
  64. package/src/review/media-read.ts +6 -5
  65. package/src/review/model.ts +71 -3
  66. package/src/review/paste.ts +2 -1
  67. package/src/review/previews.ts +123 -36
  68. package/src/review/routes.ts +29 -18
  69. package/src/review/store.ts +74 -12
  70. package/src/review/threads.ts +7 -5
  71. package/src/secrets/copy.ts +110 -0
  72. package/src/secrets/list.ts +17 -7
  73. package/src/serve/hub-app/home-strip.css +5 -0
  74. package/src/serve/hub-app/home-strip.tsx +18 -0
  75. package/src/serve/hub-app/hub-app.tsx +2 -1
  76. package/src/serve/hub-app/hub.css +14 -0
  77. package/src/serve/hub-app/inbox.css +1 -0
  78. package/src/serve/hub-app/pull-refresh.tsx +88 -0
  79. package/src/serve/hub-app/review/review-cells.tsx +52 -13
  80. package/src/serve/hub-app/review/review-list.tsx +6 -1
  81. package/src/serve/hub-app/review/review-st.ts +6 -5
  82. package/src/serve/hub-app/review/review-thread.tsx +3 -1
  83. package/src/serve/hub-app/review/review-views.tsx +18 -11
  84. package/src/serve/hub-app/review/thread-st.ts +82 -14
  85. package/src/serve/hub-app/review.css +15 -2
  86. package/src/serve/hub-runtime.ts +2 -1
  87. package/src/serve/run-serve.ts +4 -2
  88. package/src/serve/serve-hub.ts +9 -2
  89. package/src/suite/child-tools.ts +45 -0
  90. package/src/suite/judge-suites.ts +10 -22
  91. package/src/suite/select.ts +83 -8
  92. package/src/suite/suite-cli.ts +38 -14
  93. package/src/suite/suite-cores.ts +68 -0
  94. package/src/suite/suite-reads-preload.ts +8 -6
  95. package/src/ts/config.ts +44 -0
  96. package/src/ts/rename.ts +11 -1
  97. package/src/home/claude-temp.ts +0 -139
@@ -9,20 +9,21 @@
9
9
  import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
10
10
  import { availableParallelism, tmpdir } from 'os'
11
11
  import { machineLoad } from '../core/budget.ts'
12
- import { join, posix } from 'path'
12
+ import { basename, join, posix } from 'path'
13
13
  import { FULL_TESTS_ENV } from '../ledger/gate-checks.ts'
14
14
  import { CHECK_ID_ENV, recordSuites, type SuitePhase } from '../ledger/suite-log.ts'
15
15
  import { killTree } from '../core/spawn-timeout.ts'
16
16
  import { parallelCap } from '../core/parallel.ts'
17
- import { poolDir, poolOccupancy } from '../core/slots.ts'
17
+ import { poolDir, SLOT_CORES_ENV, SLOT_HELD_ENV, slotsLine, takeFreeSlots } from '../core/slots.ts'
18
+ import { keptWorkMs, mostWorkers, workersFor, workersToStart } from './suite-cores.ts'
18
19
  import { keepTimings, seedTimings, timingsHome } from './kept-timings.ts'
19
20
  import { SUITE_READS_ENV, SUITE_ROOT_ENV, SUITE_SELECT_ENV } from './reads-env.ts'
20
- import { changedKeys, dropStaticEdges, extras, isBunSuite, envFilesOf, foldReads, loadErrorModules, loadState, preloadsOf, saveState, selectStatePath, selectSuites, snapshot, suiteFiles, taintedSuites, walkGraph, type GraphEntry, type Selection, type SelectState } from './select.ts'
21
+ import { baseAfter, changedKeys, dropStaticEdges, extras, isBunSuite, envFilesOf, foldReads, loadErrorModules, loadState, preloadsOf, saveState, selectStatePath, selectSuites, suiteFiles, taintedSuites, treeSnapshot, walkGraph, type GraphEntry, type Selection, type SelectState } from './select.ts'
21
22
  import { gitRoot } from '../core/git-root.ts'
22
23
  import { runReaches, type TestRun } from './test-units.ts'
23
24
  import { loadConfig } from '../ts/config.ts'
24
25
  import { conversionRate, machineRate } from './calibrate.ts'
25
- import { aloneRunsNeeded, bunfigTest, coreMs, cpuAllowance, loadShare, type SuiteWork, type BunfigTest, readPhaseCpu, SUITE_CPU_ENV, type AloneRun, type Confirmed, confirmOver, crashedWorkers, interruptedSuites, overWords, ranAs, retryAlone, smallerRun, stallWords, DEFAULT_BUDGET_MS, FULL_CEILING_MS, failedSuites, failLines, judgeSuites, normSuitePath, parseSuiteFlags, planPhases, QUICK_CEILING_MS, poolWorkers, redWords } from './judge-suites.ts'
26
+ import { aloneRunsNeeded, bunfigTest, coreMs, cpuAllowance, loadShare, type SuiteWork, type BunfigTest, readPhaseCpu, SUITE_CPU_ENV, type AloneRun, type Confirmed, confirmOver, crashedWorkers, interruptedSuites, overWords, ranAs, retryAlone, smallerRun, stallWords, DEFAULT_BUDGET_MS, FULL_CEILING_MS, failedSuites, failLines, judgeSuites, normSuitePath, parseSuiteFlags, planPhases, QUICK_CEILING_MS, redWords } from './judge-suites.ts'
26
27
 
27
28
  type Phase = { code: number; signal: string | null; stalled: boolean; out: string; timings: Record<string, number>; cpuMs: number | null }
28
29
 
@@ -90,6 +91,21 @@ const lastCount = (out: string, re: RegExp): number => Number([...out.matchAll(r
90
91
  /** what the selection carries from before the run to after it */
91
92
  type SelectCtx = { sel: Selecting | null; /** the suites that ran and passed, time included */ ran: string[]; tier: 'quick' | 'full'; /** every suite ran to its end, red or green: no phase stalled or was killed */ complete: boolean; /** what every phase printed */ out: string }
92
93
 
94
+ /** the workers the parallel phase starts and the slots behind them. Inside a check the runner already holds them
95
+ * (SHIPKIT_SLOT_CORES). A run someone started by hand takes the free ones itself and never waits */
96
+ function coresFor(p: { need: number; who: { repo: string; check: string } }): { workers: number; release: () => void } {
97
+ if (process.env[SLOT_HELD_ENV] === '1') {
98
+ const granted = Number(process.env[SLOT_CORES_ENV])
99
+ const slots = Number.isInteger(granted) && granted >= 1 ? granted : 1
100
+ // the runner sized the slots on the whole unit; this run says what the suites it starts use, and gives
101
+ // the rest back once the phase ended (the serial phase and a lone rerun run one suite at a time)
102
+ if (slots > 1) console.log(slotsLine(Math.min(slots, p.need)))
103
+ return { workers: workersToStart(p.need, slots), release: () => { if (slots > 1) console.log(slotsLine(1)) } }
104
+ }
105
+ const own = takeFreeSlots({ dir: poolDir(), size: parallelCap(), load: machineLoad }, p.who, p.need)
106
+ return { workers: workersToStart(p.need, own.count), release: own.release }
107
+ }
108
+
93
109
  export async function suiteCli(argv: string[]): Promise<number> {
94
110
  const ctx: SelectCtx = { sel: null, ran: [], tier: 'quick', complete: false, out: '' }
95
111
  try {
@@ -131,12 +147,10 @@ async function runSuites(argv: string[], ctx: SelectCtx): Promise<number> {
131
147
  // bun drops these the moment any ignore reaches its command line
132
148
  const bunfig = bunfigTest(existsSync('bunfig.toml') ? readFileSync('bunfig.toml', 'utf8') : null)
133
149
  if (bunfig.error != null) { console.log(`FAIL: ${bunfig.error}`); return 1 }
134
- // the pool is read, never taken: this process runs on its check's slot
150
+ // the plan names the most a run asks for; the count it starts is set once the suites to run are known (coresFor)
135
151
  const cores = availableParallelism()
136
- const held = parallel ? poolOccupancy({ dir: poolDir(), size: parallelCap() }).held.length : 0
137
- const pool = parallel ? poolWorkers({ cores, size: parallelCap(), held }) : undefined
138
- const plan = planPhases({ tests, tier, rawArgs, parallel, noIsolate: helpText.includes('--no-isolate'), configIgnores: bunfig.ignores, workers: pool })
139
- const { workers } = plan
152
+ const plan = planPhases({ tests, tier, rawArgs, parallel, noIsolate: helpText.includes('--no-isolate'), configIgnores: bunfig.ignores, workers: parallel ? mostWorkers(cores) : undefined })
153
+ let workers = plan.workers
140
154
  const dir = mkdtempSync(join(tmpdir(), 'shipkit-suite-'))
141
155
  const tmp = join(dir, 'temp')
142
156
  mkdirSync(tmp)
@@ -189,8 +203,15 @@ async function runSuites(argv: string[], ctx: SelectCtx): Promise<number> {
189
203
  return files.length === 0 ? null : [...plan.alone, ...files]
190
204
  })()
191
205
  const parallelEmpty = pickedSet != null && parallelArgs.length === plan.parallel.length
206
+ // the workers follow the suites this phase starts, and the slots held for them
207
+ const held = plan.workers == null || parallelEmpty ? null : coresFor({
208
+ need: Math.min(plan.workers, workersFor(kept == null ? null : keptWorkMs(join(dir, 'parallel.json'), pickedSet == null ? undefined : new Set([...pickedSet].filter((f) => !serialSet.has(f)))), cores)),
209
+ who: { repo: basename(process.cwd()), check: process.env[CHECK_ID_ENV] ?? (unit === '' ? 'test' : `test:${unit}`) },
210
+ })
211
+ if (held != null) workers = held.workers
212
+ const phaseArgs = held == null ? parallelArgs : parallelArgs.map((a) => (/^--parallel(=\d+)?$/.test(a) ? `--parallel=${held.workers}` : a))
192
213
  const p1At = Date.now()
193
- const p1 = parallelEmpty ? { ...NO_PHASE } : await runPhase(parallelArgs, timed ? join(dir, 'parallel.json') : null, ceilingMs, tmp, true, cpuFile, rec)
214
+ const p1 = parallelEmpty ? { ...NO_PHASE } : await runPhase(phaseArgs, timed ? join(dir, 'parallel.json') : null, ceilingMs, tmp, true, cpuFile, rec).finally(() => held?.release())
194
215
  const p1Ms = Date.now() - p1At
195
216
  // bun merges what it read into what it writes, so a suite deleted since
196
217
  // the last run is judged and kept only if the workers say it ran here
@@ -335,7 +356,7 @@ async function runSuites(argv: string[], ctx: SelectCtx): Promise<number> {
335
356
  if (fails.length > 0) { console.log(fails[0]); return 1 }
336
357
  const serialCount = serialArgs != null ? phaseFiles(serialArgs, rawArgs).length : 0
337
358
  const chosen = ctx.sel?.picked != null ? `, the ${ctx.sel.picked.length} of ${ctx.sel.total} a change reaches` : ''
338
- console.log(`ok: Ran ${ran} tests across ${Object.keys(timings).length || '?'} suites${chosen}, ${parallel ? `parallel on ${workers} workers` : 'one at a time'}${serialCount > 0 ? ` then ${serialCount} serial` : ''}, ${tier} tier, ${ranAs(plan.parallel, rawArgs)}${slowest}`)
359
+ console.log(`ok: Ran ${ran} tests across ${Object.keys(timings).length || '?'} suites${chosen}, ${parallel ? `parallel on ${workers} workers` : 'one at a time'}${serialCount > 0 ? ` then ${serialCount} serial` : ''}, ${tier} tier, ${ranAs(phaseArgs, rawArgs)}${slowest}`)
339
360
  return 0
340
361
  } finally {
341
362
  rmSync(dir, { recursive: true, force: true })
@@ -349,6 +370,8 @@ type Selecting = {
349
370
  rec: Recording
350
371
  statePath: string
351
372
  state: SelectState
373
+ /** what git saw when the run started, the part of `now` no read names */
374
+ tree: Record<string, string>
352
375
  now: Record<string, string>
353
376
  graph: Record<string, GraphEntry>
354
377
  preloads: string[]
@@ -408,9 +431,10 @@ function prepareSelection(o: { tests: TestsConfigLike; tier: 'quick' | 'full'; r
408
431
  const loads = Object.values(state.modules).flatMap((m) => m.l ?? [])
409
432
  const graph = walkGraph(cfg, [...suites.map(toTop), ...preloads, ...loads], state.graph)
410
433
  const started = Date.now()
411
- const now = snapshot(top, state.modules)
434
+ const tree = treeSnapshot(top)
435
+ const now = { ...tree, ...extras(top, state.modules, tree) }
412
436
  const rec: Recording = { file: join(tmpdir(), `shipkit-reads-${process.pid}-${Date.now()}.tsv`), top }
413
- const base = { rec, statePath, state, now, started, graph, preloads, cwdRel, allSuites: suites.map(toTop), total: suites.length, notes, changed: 0 }
437
+ const base = { rec, statePath, state, tree, now, started, graph, preloads, cwdRel, allSuites: suites.map(toTop), total: suites.length, notes, changed: 0 }
414
438
  if (o.tier !== 'quick') return { ...base, picked: null }
415
439
  const pos = positional(o.rawArgs)
416
440
  if (pos != null) { notes.push(`note: every suite runs: the test script names ${pos}, which a selection would override`); return { ...base, picked: null } }
@@ -455,7 +479,7 @@ function finishSelection(sel: Selecting, passed: string[], replace: boolean, out
455
479
  const dirty = [...new Set([...before, ...picked.filter((s) => !ok.has(s) || tainted.has(s))])].sort()
456
480
  // a read first recorded by this run joins the snapshot it started from,
457
481
  // unless its path moved since the start
458
- const base = { ...sel.now, ...extras(sel.rec.top, modules, sel.now, sel.started) }
482
+ const base = baseAfter(sel.tree, sel.now, modules, (have) => extras(sel.rec.top, modules, have, sel.started))
459
483
  saveState(sel.statePath, { ...sel.state, base, dirty, modules, recorded, graph: sel.graph, bun: Bun.version })
460
484
  return null
461
485
  } catch (e) {
@@ -0,0 +1,68 @@
1
+ // HOW MANY WORKERS A SUITE RUN STARTS, and how many slots of the machine pool
2
+ // it asks for (core/slots.ts: a slot is one core's worth of work). The count
3
+ // follows the work: the kept durations of the suites the run will start. A
4
+ // worker pays its own start and its own load of the import closure, so a
5
+ // short run on many workers burns more CPU for the same wall.
6
+ //
7
+ // The one constraint a reader breaks first: a run starts the workers it holds
8
+ // slots for, and at least two when its work asks for two. bun fixes the count
9
+ // for the whole run, and a long suite left on one worker sets the gate's time
10
+ // alone (a phase bound by process spawns took 20 to 46s on two workers, 7.6s
11
+ // on four).
12
+ import { readFileSync } from 'fs'
13
+ import { availableParallelism } from 'os'
14
+ import { normSuitePath } from './judge-suites.ts'
15
+ import { timingsHome } from './kept-timings.ts'
16
+
17
+ /** the suite time one worker is worth starting for */
18
+ export const WORKER_WORK_MS = 4000
19
+
20
+ /** the most workers one run asks for: half the cores. Measured on 8 cores: two workers 12.2s, four 7.6s, eight 7.0s */
21
+ export const mostWorkers = (cores: number): number => Math.max(1, Math.floor(cores / 2))
22
+
23
+ /** the workers this much suite time asks for. null: nothing kept yet, so the most */
24
+ export function workersFor(workMs: number | null, cores: number): number {
25
+ const most = mostWorkers(cores)
26
+ return workMs == null ? most : Math.max(1, Math.min(most, Math.ceil(workMs / WORKER_WORK_MS)))
27
+ }
28
+
29
+ /** the workers a run starts: what it holds slots for, never more than its work asks, and two when it asks for two */
30
+ export const workersToStart = (need: number, slots: number): number => Math.max(Math.min(need, Math.max(1, slots)), Math.min(2, need))
31
+
32
+ /** the kept durations summed, over every suite or over `only`. null when nothing readable is kept. A suite of
33
+ * `only` with no kept duration counts as one worker's worth: it is new, and nobody knows what it costs */
34
+ export function keptWorkMs(file: string, only?: ReadonlySet<string>): number | null {
35
+ let files: Record<string, unknown>
36
+ try {
37
+ const parsed = JSON.parse(readFileSync(file, 'utf8')) as { files?: unknown }
38
+ if (parsed?.files == null || typeof parsed.files !== 'object' || Array.isArray(parsed.files)) return null
39
+ files = parsed.files as Record<string, unknown>
40
+ } catch {
41
+ return null
42
+ }
43
+ const ms = new Map<string, number>()
44
+ for (const [f, v] of Object.entries(files)) {
45
+ const n = typeof v === 'number' ? v : Number((v as { ms?: unknown } | null)?.ms)
46
+ if (Number.isFinite(n)) ms.set(normSuitePath(f), n)
47
+ }
48
+ if (only == null) return ms.size === 0 ? null : [...ms.values()].reduce((a, b) => a + b, 0)
49
+ let sum = 0
50
+ for (const f of only) sum += ms.get(normSuitePath(f)) ?? WORKER_WORK_MS
51
+ return sum
52
+ }
53
+
54
+ /** the unit a suite runner command runs (`''` for the root), null when the command is not the suite runner */
55
+ export function suiteUnitOf(cmd: readonly string[] | undefined): string | null {
56
+ if (cmd == null) return null
57
+ const at = cmd.findIndex((a) => /(?:^|\/)suite-cli\.ts$/.test(a))
58
+ if (at < 0) return null
59
+ for (let i = at + 1; i < cmd.length && cmd[i] !== '--'; i++) if (cmd[i] === '--unit') return cmd[i + 1] ?? ''
60
+ return ''
61
+ }
62
+
63
+ /** the slots a check asks the pool for: the workers its whole unit asks for when it runs the suite runner, else one */
64
+ export function slotsWanted(cmd: readonly string[] | undefined, cwd: string, cores: number = availableParallelism()): number {
65
+ const unit = suiteUnitOf(cmd)
66
+ if (unit == null) return 1
67
+ try { return workersFor(keptWorkMs(timingsHome(cwd, unit)), cores) } catch { return mostWorkers(cores) }
68
+ }
@@ -29,6 +29,7 @@ import * as cpLive from 'node:child_process'
29
29
  import { appendFileSync, realpathSync } from 'node:fs'
30
30
  import { isAbsolute, join, relative, resolve, sep } from 'node:path'
31
31
  import { fileURLToPath } from 'node:url'
32
+ import { childCwd, readsNoFile } from './child-tools.ts'
32
33
  import { SUITE_OWNER_ENV, SUITE_READS_ENV, SUITE_ROOT_ENV } from './reads-env.ts'
33
34
 
34
35
  const out = process.env[SUITE_READS_ENV]
@@ -174,7 +175,7 @@ function install(outFile: string, rootDir: string): void {
174
175
  }
175
176
  const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'fish', 'env', 'xargs', 'nice', 'time', 'timeout'])
176
177
  // tools that read only the files their arguments name, nothing they find through them
177
- const FILE_TOOLS = new Set(['true', 'false', 'echo', 'sleep', 'kill', 'rm', 'mkdir', 'touch', 'cwebp', 'dwebp'])
178
+ const FILE_TOOLS = new Set(['true', 'false', 'echo', 'sleep', 'kill', 'rm', 'mkdir', 'touch', 'chmod', 'mkfifo', 'cp', 'cwebp', 'dwebp'])
178
179
  const isBun = (bin: unknown): boolean => typeof bin === 'string' && (bin === 'bun' || bin === process.execPath || /(^|\/)bun$/.test(bin))
179
180
  const childEnv = (env: unknown): Record<string, string | undefined> => {
180
181
  const base = (typeof env === 'object' && env != null ? env : process.env) as Record<string, string | undefined>
@@ -188,14 +189,15 @@ function install(outFile: string, rootDir: string): void {
188
189
  }
189
190
  }
190
191
  // a child that is not bun reads what nobody records. It is trusted only
191
- // when it runs outside the repo and names nothing in it (git in a temp
192
- // repo); a tool known to read only the files it names (cwebp) records
193
- // them; any other child in or about the repo makes its module opaque
192
+ // when it opens no file at all (ps, lsof of a port), when it runs outside
193
+ // the repo and names nothing in it (git in a temp repo, or `git -C` one);
194
+ // a tool known to read only the files it names (cwebp) records them; any
195
+ // other child in or about the repo makes its module opaque
194
196
  const spawned = (cmd: unknown, cwdOpt: unknown): void => {
195
197
  const argv = (Array.isArray(cmd) ? cmd : typeof cmd === 'string' ? [cmd] : []).map(String)
196
- if (isBun(argv[0])) return
198
+ if (isBun(argv[0]) || readsNoFile(argv)) return
197
199
  const tool = (argv[0] ?? '?').split('/').pop() ?? '?'
198
- const cwd = typeof cwdOpt === 'string' ? resolve(cwdOpt) : cwdOpt instanceof URL ? fileURLToPath(cwdOpt) : process.cwd()
200
+ const cwd = childCwd(argv, typeof cwdOpt === 'string' ? resolve(cwdOpt) : cwdOpt instanceof URL ? fileURLToPath(cwdOpt) : process.cwd())
199
201
  const shell = SHELLS.has(tool)
200
202
  const words = argv.slice(1).flatMap((a) => (shell ? a.split(/[\s;&|<>()'"`=]+/) : [a.replace(/^--?[\w-]+=/, '')])).filter((w) => w !== '' && !w.startsWith('-'))
201
203
  const inRepo: string[] = []
package/src/ts/config.ts CHANGED
@@ -117,6 +117,50 @@ function discoverPackages(root: string, roots: string[], skip: string[], vendore
117
117
  return found.sort((a, b) => b.dir.length - a.dir.length)
118
118
  }
119
119
 
120
+ // the package.json `workspaces` (an array, or `{ packages }`), each a dir or a glob of dirs, with each one's `exports`:
121
+ // a workspace outside the roots is still imported by its name, and the test selection's graph follows that edge
122
+ export function workspacePackages(root: string, vendored: readonly string[] = []): (RvtPackage & { exports?: unknown })[] {
123
+ let globs: string[] = []
124
+ try {
125
+ const w = (JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { workspaces?: string[] | { packages?: string[] } }).workspaces
126
+ globs = Array.isArray(w) ? w : w?.packages ?? []
127
+ } catch {
128
+ return []
129
+ }
130
+ const dirs = (pattern: string): string[] => {
131
+ let at = ['']
132
+ for (const seg of pattern.replace(/\/+$/, '').split('/')) {
133
+ if (!seg.includes('*')) {
134
+ at = at.map((d) => (d === '' ? seg : `${d}/${seg}`))
135
+ continue
136
+ }
137
+ const re = new RegExp(`^${seg.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*')}$`)
138
+ at = at.flatMap((d) => {
139
+ try {
140
+ return readdirSync(join(root, d), { withFileTypes: true }).filter((e) => e.isDirectory() && re.test(e.name)).map((e) => (d === '' ? e.name : `${d}/${e.name}`))
141
+ } catch {
142
+ return []
143
+ }
144
+ })
145
+ }
146
+ return at
147
+ }
148
+ const out: (RvtPackage & { exports?: unknown })[] = []
149
+ for (const g of globs) {
150
+ if (g.startsWith('!')) continue
151
+ for (const dir of dirs(g)) {
152
+ if (isVendored(dir, vendored)) continue
153
+ try {
154
+ const m = JSON.parse(readFileSync(join(root, dir, 'package.json'), 'utf8')) as { name?: string; exports?: unknown }
155
+ if (m.name != null && m.name !== '') out.push({ name: m.name, dir, ...(m.exports !== undefined ? { exports: m.exports } : {}) })
156
+ } catch {
157
+ // no named manifest: not a package
158
+ }
159
+ }
160
+ }
161
+ return out
162
+ }
163
+
120
164
  export function loadConfig(cwd: string = process.cwd()): RvtConfig {
121
165
  const root = findRepoRoot(cwd)
122
166
  let roots: string[] = []
package/src/ts/rename.ts CHANGED
@@ -251,6 +251,16 @@ function relativeRewrites(file: string, content: string, movedTo: (rel: string)
251
251
  return out
252
252
  }
253
253
 
254
+ /** the next occurrence of a path that ENDS there: `server/staged` inside
255
+ * `server/staged.ts` or `server/staged-x` names another file, never the folder */
256
+ function pathAt(text: string, needle: string, from: number): number {
257
+ for (let idx = text.indexOf(needle, from); idx !== -1; idx = text.indexOf(needle, idx + 1)) {
258
+ const next = text.slice(idx + needle.length, idx + needle.length + 2)
259
+ if (!/^[\w-]/.test(next) && !/^\.\w/.test(next)) return idx
260
+ }
261
+ return -1
262
+ }
263
+
254
264
  // simultaneous multi-needle replace: earliest match wins (longest needle on a
255
265
  // tie) and the scan continues PAST the replacement — sequential split/join
256
266
  // would let one pair's output feed the next (the package form is a substring
@@ -264,7 +274,7 @@ function scanPairs(text: string, pairs: { from: string; to: string }[]): { text:
264
274
  let hit: { from: string; to: string } | null = null
265
275
  for (const p of pairs) {
266
276
  if (p.from.length === 0) continue
267
- const idx = text.indexOf(p.from, i)
277
+ const idx = pathAt(text, p.from, i)
268
278
  if (idx === -1) continue
269
279
  if (at === -1 || idx < at || (idx === at && p.from.length > (hit?.from.length ?? 0))) {
270
280
  at = idx
@@ -1,139 +0,0 @@
1
- // claude code's per session scratch, `<temp root>/<project>/<session>/`: nothing
2
- // trims it but a reboot. A pass of the retention sweep (machine-stores.ts) keeps
3
- // every session written in the last guard hours, then the newest idle ones while
4
- // they fit under the cap, and deletes the rest, oldest first.
5
- //
6
- // the one constraint a reader breaks first: this deletes for real (the Trash is
7
- // on the same disk). Nothing outside the checked root, and no link is followed:
8
- // lstat everywhere, a link is removed as a link.
9
- import { lstatSync, readdirSync, realpathSync, rmSync } from 'node:fs'
10
- import { homedir } from 'node:os'
11
- import { basename, join, sep } from 'node:path'
12
- import { machineGet, machineSet } from '../core/machine-db.ts'
13
-
14
- /** what the idle sessions may hold together */
15
- export const CLAUDE_TEMP_MAX_BYTES = 5e9
16
- /** a session written this recently is never touched, whatever its size */
17
- export const CLAUDE_TEMP_GUARD_MS = 24 * 60 * 60 * 1000
18
-
19
- const AUTO_KEY = 'claude-temp-auto'
20
- /** the owner's switch, off until it is turned on: the daemon's sweep deletes nothing before */
21
- export const claudeTempAuto = (): boolean => machineGet<boolean>(AUTO_KEY) === true
22
- export const setClaudeTempAuto = (on: boolean): boolean => machineSet(AUTO_KEY, on)
23
-
24
- /** where claude code keeps it on this machine: its own override, else /tmp, then one folder per uid */
25
- export function claudeTempRoot(env: Record<string, string | undefined> = process.env): string | null {
26
- const uid = process.getuid?.()
27
- return uid == null ? null : join(env.CLAUDE_CODE_TMPDIR || '/tmp', `claude-${uid}`)
28
- }
29
-
30
- /** the root, resolved once and checked; null when it does not exist; throws on any other shape */
31
- export function checkedRoot(root: string): string | null {
32
- const uid = process.getuid?.()
33
- if (uid == null) throw new Error('no uid on this platform: the claude temp pass does not run')
34
- if (root.split(/[\\/]/).includes('..')) throw new Error(`${root}: a path with .. is refused`)
35
- let real: string
36
- try { real = realpathSync(root) } catch (e) {
37
- if ((e as { code?: string }).code === 'ENOENT') return null
38
- throw e
39
- }
40
- const s = lstatSync(real)
41
- if (real === sep || real === homedir() || !s.isDirectory()) throw new Error(`${real}: not a temp folder of its own`)
42
- if (s.uid !== uid) throw new Error(`${real}: owned by uid ${s.uid}, not ${uid}`)
43
- if (basename(real) !== `claude-${uid}`) throw new Error(`${real}: not named claude-${uid}`)
44
- return real
45
- }
46
-
47
- export type Unit = { path: string; at: number; bytes: number }
48
- export type Plan = { root: string; keep: Unit[]; drop: Unit[] }
49
-
50
- /** newest mtime and size of a tree, lstat only; null once an entry is newer than `fresh` or unreadable */
51
- function scan(top: string, fresh: number, printErr: (l: string) => void): { at: number; bytes: number } | null {
52
- let at = 0
53
- let bytes = 0
54
- const stack = [top]
55
- while (stack.length > 0) {
56
- const p = stack.pop()!
57
- let s
58
- try { s = lstatSync(p) } catch { continue }
59
- at = Math.max(at, s.mtimeMs)
60
- bytes += s.size
61
- if (at >= fresh) return null
62
- if (!s.isDirectory()) continue
63
- try { for (const n of readdirSync(p)) stack.push(join(p, n)) } catch (e) {
64
- printErr(`WARN claude temp: ${p} unreadable (${(e as Error).message}), its session kept`)
65
- return null
66
- }
67
- }
68
- return { at, bytes }
69
- }
70
-
71
- const names = (d: string, printErr: (l: string) => void): string[] => {
72
- try { return readdirSync(d) } catch (e) {
73
- printErr(`WARN claude temp: ${d} unreadable (${(e as Error).message}), skipped`)
74
- return []
75
- }
76
- }
77
-
78
- /** every idle unit under the root: newest first under the cap kept, the rest dropped, oldest first */
79
- export function planClaudeTemp(root: string, o: { now: number; capBytes?: number; guardMs?: number; printErr: (l: string) => void }): Plan | null {
80
- const real = checkedRoot(root)
81
- if (real == null) return null
82
- const fresh = o.now - (o.guardMs ?? CLAUDE_TEMP_GUARD_MS)
83
- const units: (Unit & { loose: boolean })[] = []
84
- const loose = (path: string): void => {
85
- try {
86
- const s = lstatSync(path)
87
- if (s.mtimeMs < fresh) units.push({ path, at: s.mtimeMs, bytes: s.size, loose: true })
88
- } catch { /* raced: gone */ }
89
- }
90
- for (const project of names(real, o.printErr)) {
91
- const pp = join(real, project)
92
- if (!isDir(pp)) { loose(pp); continue }
93
- for (const session of names(pp, o.printErr)) {
94
- const sp = join(pp, session)
95
- if (!isDir(sp)) { loose(sp); continue }
96
- const r = scan(sp, fresh, o.printErr)
97
- if (r != null) units.push({ path: sp, ...r, loose: false })
98
- }
99
- }
100
- // a loose file ranks as the oldest unit: it belongs to no session
101
- units.sort((a, b) => (b.loose ? -Infinity : b.at) - (a.loose ? -Infinity : a.at))
102
- const keep: Unit[] = []
103
- const drop: Unit[] = []
104
- let total = 0
105
- for (const u of units) {
106
- const unit = { path: u.path, at: u.at, bytes: u.bytes }
107
- if (drop.length === 0 && total + u.bytes <= (o.capBytes ?? CLAUDE_TEMP_MAX_BYTES)) { total += u.bytes; keep.push(unit) } else drop.push(unit)
108
- }
109
- return { root: real, keep, drop: drop.reverse() }
110
- }
111
-
112
- const isDir = (p: string): boolean => {
113
- try { return lstatSync(p).isDirectory() } catch { return false }
114
- }
115
-
116
- export const gb = (n: number): string => `${(n / 1e9).toFixed(2)} GB`
117
- const days = (ms: number): string => `${(ms / 86_400_000).toFixed(1)}d`
118
-
119
- /** one pass: each dropped unit removed (or only named, `dry`), one line each; the bytes freed */
120
- export function trimClaudeTemp(root: string, o: { now: number; dry?: boolean; capBytes?: number; guardMs?: number; print: (l: string) => void; printErr: (l: string) => void }): number {
121
- const plan = planClaudeTemp(root, o)
122
- if (plan == null) return 0
123
- let freed = 0
124
- for (const u of plan.drop) {
125
- if (!u.path.startsWith(plan.root + sep) || u.path.split(sep).includes('..')) throw new Error(`${u.path}: outside ${plan.root}, the pass stops`)
126
- const line = `${u.path.slice(plan.root.length + 1)} idle ${days(o.now - u.at)} ${gb(u.bytes)}`
127
- if (o.dry !== true) {
128
- try { rmSync(u.path, { recursive: true, force: true }) } catch (e) {
129
- o.printErr(`WARN claude temp: ${u.path} not deleted (${(e as Error).message})`)
130
- continue
131
- }
132
- }
133
- freed += u.bytes
134
- o.print(`claude temp: ${o.dry === true ? 'would delete' : 'deleted'} ${line}`)
135
- }
136
- const kept = plan.keep.reduce((n, u) => n + u.bytes, 0)
137
- if (o.dry === true || plan.drop.length > 0) o.print(`claude temp: ${o.dry === true ? 'would free' : 'freed'} ${gb(freed)} in ${plan.drop.length} units; kept ${plan.keep.length} idle units, ${gb(kept)} of ${gb(o.capBytes ?? CLAUDE_TEMP_MAX_BYTES)}, and every session written in the last ${(o.guardMs ?? CLAUDE_TEMP_GUARD_MS) / 3_600_000} h`)
138
- return freed
139
- }