SLOPSHOPPER

worktree-ready

Makes a new git worktree of a Laravel app ready to use with no hands: clones vendor, node_modules and built assets with copy-on-write, links it with Valet over…

guardtoaststatusprocesstimer
A shopper browsing a rack in a slop shop
README

worktree-ready

Make a new git worktree of a Laravel app ready to use with no hands, and tidy it away when you are done.

worktree-ready is a Claude Code mod. When Claude enters a worktree of a Laravel app, it brings the worktree up to the same state as your main checkout, links it as its own .test site over HTTPS, and shows you the URL. When the worktree is exited, it unlinks the site and removes the folder if the work is finished.

Requirements

  • A Claude Code build that loads plugin modules (mods).
  • macOS on APFS. Dependencies are cloned with cp -c, a copy-on-write clone, so the worktree must be on the same volume as the main checkout (worktrees under .claude/worktrees/ always are).
  • Laravel Valet. Without it the worktree is still set up, it just is not linked.
  • composer, and your JS package manager, on the PATH.

What happens when a worktree is entered

The mod only acts in a linked worktree that has an artisan file. Each step is skipped when it has nothing to do.

  1. Clone vendor, node_modules and public/build from the main checkout with copy-on-write. This takes seconds and shares disk blocks until a file changes. public/hot and bootstrap/cache are never cloned.
  2. Copy .env from the main checkout, if the worktree has none. The worktree shares main's database. A sqlite database is shared by pointing DB_DATABASE at main's file.
  3. Install only what changed. composer install runs when composer.lock differs from main's, and the JS install runs when its lockfile differs. The package manager is picked from the lockfile (bun.lock, pnpm-lock.yaml, yarn.lock or package-lock.json).
  4. Build assets only when needed. The build script runs when the worktree's resources/, package.json or Vite, Tailwind, PostCSS or TypeScript config differ from main's working tree, or when main has no public/build.
  5. Link and secure. The site is linked as <project>-<worktree> (for example acme-blue-heron.test), secured, and checked against links. The word worktree is never part of the name. A name that already points at a different folder is left alone and reported. APP_URL in the worktree's .env is set to the new URL, and VITE_DEV_SERVER_KEY and VITE_DEV_SERVER_CERT to the site's certificate, so the Vite dev server runs on https at that host. Without them, laravel-vite-plugin looks for a certificate named after the folder, finds none, and serves plain http assets that an https page blocks.

Claude does not get control back until this finishes, as with a SessionStart hook, so its first command in the worktree already has what it needs. Progress shows under the prompt.

A worktree that a session starts in (claude --worktree) is set up the same way.

What happens when it is exited

Whether the exit keeps or removes the worktree, the site is unsecured and unlinked, and the mod checks that it is gone: from links, from the Sites folder, and that no nginx config or certificate for it is left. Leftover files are deleted and checked again, except an nginx config that proxies (a valet proxy of the same name is never touched). A site that cannot be fully removed is reported, and its worktree is kept until a later session can finish the job.

If the exit kept the worktree, the mod then removes the folder (checking that it is gone) and its branch when there is nothing to lose: no uncommitted changes, and the branch has commits of its own that are merged into the default branch, or a merged PR (found with gh) whose head is the worktree's current commit, which covers squash merges. A worktree on a detached HEAD counts as merged when its commit is in the default branch; it has no branch to delete. A worktree you entered and left without committing is kept. A worktree still locked by a running Claude session, or locked by anything other than Claude, is kept; a lock left by a Claude session that is no longer running is released. Anything else is kept, and you are told why once.

A session that ends while it is inside a worktree (you exit, or the process is stopped) marks it exited, but the time a session has to end is too short to unlink or remove anything. The same check runs for those, and other leftovers, at the start of the next session in any project, not only the one the worktree belongs to. A worktree still marked active whose Claude session has died (a lock naming a process that no longer runs) is treated the same way; one whose session is running is left alone.

Valet's links hides a site once its folder is gone, so the same start-of-session pass also reads the Sites folder and removes every site that points under a .claude/worktrees/ folder that no longer exists, whether or not the mod set it up. Only worktrees under a project's .claude/worktrees/ that the mod set up are ever removed.

Limits

  • A worktree whose branch was squash-merged without a PR, or with gh missing or signed out, is reported as not merged. It stays until you remove it.
  • A session that is killed outright (SIGKILL, a crash) never ends cleanly. Its worktree stays marked active until a later session sees that the lock's process has died; a worktree with no Claude session lock is kept.
  • A worktree entered and left without a commit is kept, on a branch or a detached HEAD, even though its commit is in the default branch.
  • Valet is the only supported site tool.
  • The enter and exit flows were tested against a faked machine. The start-of-session site cleanup was also run against a real Valet.

Development

The pure helpers (link names, .env edits, the links table, lockfile and asset checks) are in hooks/lib.ts, and the enter and exit flows in hooks/register.ts. Both are covered by tests that fake the file system, git, composer, the package manager and Valet:

claude plugin validate plugins/worktree-ready
claude plugin test plugins/worktree-ready

License

MIT

Source 2 files
hooks/register.ts 628 lines
1import type { EngineInterface, Register } from 'claude-code'
2
3import { ASSET_INPUTS, CLONES, JS_LOCK_FILES, SCAN_SITES, basename, certBase, inWorktrees, isProxy, jsPlan, linkName, lockOf, parseLinks, parseSiteScan, parseWorktree, setEnv, shareSqlite, siteFiles, siteLink, sitesDir, underWorktrees } from './lib'
4import type { Link, Tool, WorktreeInfo, WorktreeRecord } from './lib'
5
6const PLUGIN = 'worktree-ready'
7const PREFIX = 'wt:'
8const LONG_MS = 600_000
9const SITE_MS = 120_000
10const STALE_LOCK_MS = 1_800_000
11const NOT_LINKED = { url: null, linked: false }
12
13type Outcome = { exitCode: number; stdout: string; stderr: string }
14
15async function run($: EngineInterface, argv: string[], cwd?: string, timeoutMs?: number): Promise<Outcome> {
16  try {
17    return await $.process.run(argv, { ...(cwd ? { cwd } : {}), ...(timeoutMs ? { timeoutMs } : {}) })
18  } catch (error) {
19    return { exitCode: 127, stdout: '', stderr: String(error) }
20  }
21}
22
23const passed = (outcome: Outcome): boolean => outcome.exitCode === 0
24
25const deniedOrFailed = (result: unknown): boolean => {
26  const shape = result as { deny?: unknown; isError?: unknown } | undefined
27
28  return shape?.deny !== undefined || shape?.isError === true
29}
30
31const outcomeOf = (result: unknown): { worktreePath?: string; action?: string } | undefined => {
32  const inner = (result as { result?: unknown } | undefined)?.result
33
34  return typeof inner === 'object' && inner !== null ? (inner as { worktreePath?: string; action?: string }) : undefined
35}
36
37function must(outcome: Outcome, what: string) {
38  if (!passed(outcome)) {
39    throw new Error(`${what}: ${outcome.stderr.trim().slice(0, 160) || `exit ${outcome.exitCode}`}`)
40  }
41}
42
43const say = ($: EngineInterface, text?: string) => $.ui.status(text)
44
45const toast = ($: EngineInterface, text: string, timeoutMs = 6000) => $.ui.toast(text, { timeoutMs })
46
47const has = ($: EngineInterface, root: string, rel: string) => $.fs.exists(`${root}/${rel}`)
48
49const recordKey = (path: string) => `${PREFIX}${path}`
50
51async function readRecord($: EngineInterface, path: string): Promise<WorktreeRecord | null> {
52  return ((await $.store.get(recordKey(path))) as WorktreeRecord | undefined) ?? null
53}
54
55async function saveRecord($: EngineInterface, record: WorktreeRecord) {
56  await $.store.set(recordKey(record.path), record)
57}
58
59async function worktreeAt($: EngineInterface, dir: string): Promise<WorktreeInfo | null> {
60  const rev = await run($, ['git', 'rev-parse', '--path-format=absolute', '--show-toplevel', '--git-dir', '--git-common-dir'], dir)
61
62  return passed(rev) ? parseWorktree(rev.stdout) : null
63}
64
65async function findTool($: EngineInterface): Promise<Tool | null> {
66  return passed(await run($, ['sh', '-c', 'command -v valet'])) ? 'valet' : null
67}
68
69async function listLinks($: EngineInterface, tool: Tool): Promise<Link[] | null> {
70  const listed = await run($, [tool, 'links'])
71
72  return passed(listed) ? parseLinks(listed.stdout) : null
73}
74
75async function copyEnv($: EngineInterface, { main, top }: WorktreeInfo) {
76  if ((await has($, top, '.env')) || !(await has($, main, '.env'))) {
77    return
78  }
79
80  await $.fs.write(`${top}/.env`, String(await $.fs.read(`${main}/.env`)))
81}
82
83async function editEnv($: EngineInterface, top: string, change: (text: string) => string) {
84  if (!(await has($, top, '.env'))) {
85    return
86  }
87
88  const text = String(await $.fs.read(`${top}/.env`))
89  const next = change(text)
90
91  if (next !== text) {
92    await $.fs.write(`${top}/.env`, next)
93  }
94}
95
96async function shareDatabase($: EngineInterface, { main, top }: WorktreeInfo) {
97  const database = `${main}/database/database.sqlite`
98
99  if (await $.fs.exists(database)) {
100    await editEnv($, top, text => shareSqlite(text, database))
101  }
102}
103
104const setAppUrl = ($: EngineInterface, top: string, url: string) => editEnv($, top, text => setEnv(text, 'APP_URL', url))
105
106const homeDir = async ($: EngineInterface) => (await run($, ['printenv', 'HOME'])).stdout.trim()
107
108async function useSiteCert($: EngineInterface, top: string, url: string) {
109  const home = await homeDir($)
110  const base = certBase(home, new URL(url).hostname)
111
112  if (!home || !(await $.fs.exists(`${base}.key`)) || !(await $.fs.exists(`${base}.crt`))) {
113    return
114  }
115
116  await editEnv($, top, text => setEnv(setEnv(text, 'VITE_DEV_SERVER_KEY', `${base}.key`), 'VITE_DEV_SERVER_CERT', `${base}.crt`))
117}
118
119async function lockDiffers($: EngineInterface, { main, top }: WorktreeInfo, file: string): Promise<boolean> {
120  return !passed(await run($, ['cmp', '-s', `${main}/${file}`, `${top}/${file}`]))
121}
122
123async function hasBuildScript($: EngineInterface, top: string): Promise<boolean> {
124  if (!(await has($, top, 'package.json'))) {
125    return false
126  }
127
128  try {
129    const scripts = (JSON.parse(String(await $.fs.read(`${top}/package.json`))) as { scripts?: Record<string, unknown> }).scripts
130
131    return typeof scripts?.build === 'string'
132  } catch {
133    return false
134  }
135}
136
137async function needsBuild($: EngineInterface, { main, top }: WorktreeInfo): Promise<boolean> {
138  if (!(await has($, top, 'public/build'))) {
139    return true
140  }
141
142  const head = await run($, ['git', 'rev-parse', 'HEAD'], top)
143
144  if (!passed(head)) {
145    return true
146  }
147
148  // Main's working tree is what its public/build was built from, so that is what the worktree's commit is compared with.
149  return !passed(await run($, ['git', '-C', main, 'diff', '--quiet', head.stdout.trim(), '--', ...ASSET_INPUTS]))
150}
151
152async function link($: EngineInterface, tool: Tool, name: string, top: string): Promise<{ url: string | null; linked: boolean }> {
153  const clash = (await listLinks($, tool))?.find(site => site.name === name)
154
155  if (clash && clash.path !== top) {
156    toast($, `${name} already points at ${clash.path}, so it was not linked`, 10_000)
157
158    return NOT_LINKED
159  }
160
161  if (!clash && !passed(await run($, [tool, 'link', name], top, SITE_MS))) {
162    toast($, `${tool} link ${name} failed`, 10_000)
163
164    return NOT_LINKED
165  }
166
167  await run($, [tool, 'secure', name], top, SITE_MS)
168
169  const site = (await listLinks($, tool))?.find(entry => entry.name === name && entry.path === top)
170
171  if (!site?.secure) {
172    toast($, `${name} is linked but not secure`, 10_000)
173  }
174
175  return { url: site?.url ?? null, linked: true }
176}
177
178async function setUp($: EngineInterface, info: WorktreeInfo): Promise<string | null> {
179  const { top, main } = info
180  const earlier = await readRecord($, top)
181
182  say($, 'cloning dependencies')
183
184  for (const dir of CLONES) {
185    if ((await has($, main, dir)) && !(await has($, top, dir))) {
186      await run($, ['cp', '-c', '-R', `${main}/${dir}`, `${top}/${dir}`], undefined, LONG_MS)
187    }
188  }
189
190  await copyEnv($, info)
191  await shareDatabase($, info)
192
193  if ((await has($, top, 'composer.lock')) && ((await lockDiffers($, info, 'composer.lock')) || !(await has($, top, 'vendor')))) {
194    say($, 'composer install')
195    must(await run($, ['composer', 'install', '--no-interaction'], top, LONG_MS), 'composer install failed')
196  }
197
198  if ((await has($, main, 'public/storage')) && !(await has($, top, 'public/storage'))) {
199    await run($, ['php', 'artisan', 'storage:link'], top)
200  }
201
202  const locks: string[] = []
203
204  for (const file of JS_LOCK_FILES) {
205    if (await has($, top, file)) {
206      locks.push(file)
207    }
208  }
209
210  const plan = jsPlan(locks, await hasBuildScript($, top))
211
212  if (plan.install && plan.lock && ((await lockDiffers($, info, plan.lock)) || !(await has($, top, 'node_modules')))) {
213    say($, `${plan.install[0]} install`)
214    must(await run($, plan.install, top, LONG_MS), `${plan.install[0]} install failed`)
215  }
216
217  if (plan.build && (await needsBuild($, info))) {
218    say($, 'building assets')
219    must(await run($, plan.build, top, LONG_MS), 'asset build failed')
220  }
221
222  const project = basename(main)
223  const name = linkName(project, basename(top), top)
224  const tool = await findTool($)
225  const site = tool ? await link($, tool, name, top) : NOT_LINKED
226
227  if (site.url) {
228    await setAppUrl($, top, site.url)
229  }
230
231  if (site.url && tool) {
232    await useSiteCert($, top, site.url)
233  }
234
235  const branch = (await run($, ['git', 'rev-parse', '--abbrev-ref', 'HEAD'], top)).stdout.trim()
236  const head = (await run($, ['git', 'rev-parse', 'HEAD'], top)).stdout.trim()
237
238  await saveRecord($, { path: top, main, project, branch, base: earlier?.base ?? head, tool, link: site.linked ? name : null, state: 'active', notified: false })
239  toast($, site.url ? `Worktree ready at ${site.url}` : 'Worktree ready', 15_000)
240
241  if (site.url) {
242    $.ui.log(`${basename(top)} is served at ${site.url}`)
243  }
244
245  return site.url
246}
247
248async function claimLock($: EngineInterface, lock: string): Promise<boolean> {
249  if (passed(await run($, ['mkdir', lock]))) {
250    return true
251  }
252
253  const made = Number((await run($, ['stat', '-f', '%m', lock])).stdout.trim())
254
255  if (!(made > 0) || (await $.clock.now()) - made * 1000 < STALE_LOCK_MS) {
256    return false
257  }
258
259  await run($, ['rmdir', lock])
260
261  return passed(await run($, ['mkdir', lock]))
262}
263
264async function provision($: EngineInterface, dir: string): Promise<string | null> {
265  const info = await worktreeAt($, dir)
266
267  if (!info || !(await has($, info.top, 'artisan'))) {
268    return null
269  }
270
271  const lock = `${info.gitDir}/${PLUGIN}.lock`
272
273  if (!(await claimLock($, lock))) {
274    toast($, `another setup is running at ${lock}`, 10_000)
275
276    return null
277  }
278
279  try {
280    return await setUp($, info)
281  } catch (error) {
282    toast($, String(error instanceof Error ? error.message : error), 12_000)
283
284    return null
285  } finally {
286    say($)
287    await run($, ['rmdir', lock])
288  }
289}
290
291const isSymlink = async ($: EngineInterface, path: string) => passed(await run($, ['test', '-L', path]))
292
293async function removeLeftovers($: EngineInterface, name: string, host: string): Promise<string | null> {
294  const home = await homeDir($)
295
296  if (!home) {
297    return null
298  }
299
300  const link = siteLink(home, name)
301
302  if (await isSymlink($, link)) {
303    await run($, ['rm', '-f', link])
304
305    if (await isSymlink($, link)) {
306      return `${link} could not be removed`
307    }
308  }
309
310  const { nginx, certs } = siteFiles(home, host)
311  const leftovers: string[] = []
312
313  if ((await $.fs.exists(nginx)) && !isProxy(String(await $.fs.read(nginx)))) {
314    leftovers.push(nginx)
315  }
316
317  for (const cert of certs) {
318    if (await $.fs.exists(cert)) {
319      leftovers.push(cert)
320    }
321  }
322
323  if (leftovers.length === 0) {
324    return null
325  }
326
327  await run($, ['rm', '-f', ...leftovers])
328
329  for (const file of leftovers) {
330    if (await $.fs.exists(file)) {
331      return `${file} could not be removed`
332    }
333  }
334
335  return null
336}
337
338async function dropSite($: EngineInterface, tool: Tool, name: string): Promise<string | null> {
339  const listed = (await listLinks($, tool))?.find(site => site.name === name)
340  const host = listed ? new URL(listed.url).hostname : `${name}.test`
341
342  await run($, [tool, 'unsecure', name], undefined, SITE_MS)
343  await run($, [tool, 'unlink', name], undefined, SITE_MS)
344
345  const after = await listLinks($, tool)
346
347  if (!after) {
348    return `${tool} links failed, so ${name} could not be checked`
349  }
350
351  if (after.some(site => site.name === name)) {
352    return `${name} is still linked after unlink`
353  }
354
355  return removeLeftovers($, name, host)
356}
357
358async function unlink($: EngineInterface, record: WorktreeRecord): Promise<WorktreeRecord> {
359  if (!record.link || !record.tool) {
360    return record
361  }
362
363  const problem = await dropSite($, record.tool, record.link)
364
365  if (problem) {
366    toast($, problem, 10_000)
367
368    return record
369  }
370
371  return { ...record, link: null }
372}
373
374const detached = (record: WorktreeRecord): boolean => !record.branch || record.branch === 'HEAD'
375
376async function isMerged($: EngineInterface, record: WorktreeRecord): Promise<boolean> {
377  const head = await run($, ['git', 'rev-parse', 'HEAD'], record.path)
378
379  if (!passed(head) || (record.base !== undefined && head.stdout.trim() === record.base)) {
380    return false
381  }
382
383  const tip = head.stdout.trim()
384  const origin = await run($, ['git', '-C', record.main, 'symbolic-ref', '--short', 'refs/remotes/origin/HEAD'])
385
386  for (const ref of [...(passed(origin) ? [origin.stdout.trim()] : []), 'main', 'master']) {
387    if (passed(await run($, ['git', '-C', record.main, 'merge-base', '--is-ancestor', detached(record) ? tip : record.branch, ref]))) {
388      return true
389    }
390  }
391
392  return detached(record) ? false : prMerged($, record, tip)
393}
394
395async function prMerged($: EngineInterface, record: WorktreeRecord, head: string): Promise<boolean> {
396  const listed = await run($, ['gh', 'pr', 'list', '--head', record.branch, '--state', 'merged', '--json', 'headRefOid'], record.main, SITE_MS)
397
398  if (!passed(listed)) {
399    return false
400  }
401
402  try {
403    return (JSON.parse(listed.stdout) as { headRefOid?: string }[]).some(pr => pr.headRefOid === head)
404  } catch {
405    return false
406  }
407}
408
409async function unlocked($: EngineInterface, record: WorktreeRecord): Promise<boolean> {
410  const listed = await run($, ['git', '-C', record.main, 'worktree', 'list', '--porcelain'])
411  const lock = passed(listed) ? lockOf(listed.stdout, record.path) : { kind: 'other' as const }
412
413  if (lock.kind === 'none') {
414    return true
415  }
416
417  if (lock.kind === 'session' && !passed(await run($, ['kill', '-0', String(lock.pid)]))) {
418    return passed(await run($, ['git', '-C', record.main, 'worktree', 'unlock', record.path]))
419  }
420
421  if (!record.notified) {
422    toast($, `${basename(record.path)} was kept: ${lock.kind === 'session' ? 'a running session still holds it' : 'it is locked'}`, 10_000)
423    await saveRecord($, { ...record, notified: true })
424  }
425
426  return false
427}
428
429async function tryRemove($: EngineInterface, record: WorktreeRecord) {
430  const forget = () => $.store.delete(recordKey(record.path))
431
432  if (!underWorktrees(record.main, record.path)) {
433    await forget()
434
435    return
436  }
437
438  if (!(await $.fs.exists(record.path))) {
439    await forget()
440
441    return
442  }
443
444  const status = await run($, ['git', 'status', '--porcelain'], record.path)
445  const dirty = !passed(status) || status.stdout.trim() !== ''
446
447  if (dirty || !(await isMerged($, record))) {
448    if (!record.notified) {
449      toast($, `${basename(record.path)} was kept: ${dirty ? 'it has uncommitted changes' : 'its work is not merged into the default branch'}`, 10_000)
450      await saveRecord($, { ...record, notified: true })
451    }
452
453    return
454  }
455
456  if (!(await unlocked($, record))) {
457    return
458  }
459
460  if (!passed(await run($, ['git', '-C', record.main, 'worktree', 'remove', record.path])) || (await $.fs.exists(record.path))) {
461    toast($, `${basename(record.path)} could not be removed`, 10_000)
462
463    return
464  }
465
466  await forget()
467
468  if (detached(record)) {
469    toast($, `Removed the finished worktree ${basename(record.path)}`, 10_000)
470
471    return
472  }
473
474  const branchDropped = passed(await run($, ['git', '-C', record.main, 'branch', '-d', record.branch]))
475
476  toast($, branchDropped ? `Removed the finished worktree ${basename(record.path)}` : `Removed ${basename(record.path)}, but its branch ${record.branch} was kept`, 10_000)
477}
478
479async function retire($: EngineInterface, top: string, removedByTool: boolean) {
480  const record = await readRecord($, top)
481
482  if (!record) {
483    return
484  }
485
486  // Unlinking goes by site name, so it works after the tool has deleted the directory.
487  const unlinked = await unlink($, record)
488
489  const exited: WorktreeRecord = { ...unlinked, state: 'exited' }
490
491  if (removedByTool && !exited.link) {
492    await $.store.delete(recordKey(top))
493
494    return
495  }
496
497  await saveRecord($, exited)
498
499  if (!removedByTool && !exited.link) {
500    await tryRemove($, exited)
501  }
502}
503
504async function markExited($: EngineInterface) {
505  const here = await $.session.cwd()
506
507  for (const key of (await $.store.keys()).filter(key => key.startsWith(PREFIX))) {
508    const record = (await $.store.get(key)) as WorktreeRecord | undefined
509
510    if (record?.state === 'active' && (here === record.path || here.startsWith(`${record.path}/`))) {
511      await saveRecord($, { ...record, state: 'exited' })
512    }
513  }
514}
515
516async function sessionDied($: EngineInterface, record: WorktreeRecord): Promise<boolean> {
517  const listed = await run($, ['git', '-C', record.main, 'worktree', 'list', '--porcelain'])
518  const lock = passed(listed) ? lockOf(listed.stdout, record.path) : { kind: 'other' as const }
519
520  return lock.kind === 'session' && !passed(await run($, ['kill', '-0', String(lock.pid)]))
521}
522
523async function sweep($: EngineInterface) {
524  const here = await $.session.cwd()
525
526  for (const key of (await $.store.keys()).filter(key => key.startsWith(PREFIX))) {
527    const record = (await $.store.get(key)) as WorktreeRecord | undefined
528
529    if (!record || here === record.path || here.startsWith(`${record.path}/`)) {
530      continue
531    }
532
533    if (record.state === 'exited' || !(await $.fs.exists(record.path)) || (await sessionDied($, record))) {
534      const exited: WorktreeRecord = { ...(await unlink($, record)), state: 'exited' }
535
536      await saveRecord($, exited)
537
538      if (!exited.link) {
539        await tryRemove($, exited)
540      }
541    }
542  }
543}
544
545async function reconcile($: EngineInterface) {
546  const tool = await findTool($)
547  const home = await homeDir($)
548
549  if (!tool || !home) {
550    return
551  }
552
553  const scan = await run($, ['sh', '-c', SCAN_SITES, '_', sitesDir(home)])
554
555  if (!passed(scan)) {
556    return
557  }
558
559  let dropped = 0
560
561  for (const site of parseSiteScan(scan.stdout).filter(entry => inWorktrees(entry.path))) {
562    if (await $.fs.exists(site.path)) {
563      continue
564    }
565
566    const problem = await dropSite($, tool, site.name)
567
568    if (problem) {
569      toast($, problem, 10_000)
570    } else {
571      dropped++
572    }
573  }
574
575  if (dropped > 0) {
576    toast($, `Removed ${dropped} ${dropped === 1 ? 'site' : 'sites'} whose worktree folder no longer exists`, 10_000)
577  }
578}
579
580export const register: Register = on => {
581  on('session.start', async ($, e, next) => {
582    await provision($, await $.session.cwd()).catch(() => undefined)
583
584    $.clock.after(0, () => {
585      void sweep($).then(() => reconcile($)).catch(() => undefined)
586    })
587
588    return next(e)
589  })
590
591  // session.end has about 1.5 s for every hook, too short for unlinking or `git worktree remove`; the next session's sweep does those.
592  on('session.end', async ($, e, next) => {
593    if (e.reason !== 'clear') {
594      await markExited($).catch(() => undefined)
595    }
596
597    return next(e)
598  })
599
600  on('tool.call', { tool: 'EnterWorktree' }, async ($, e, next) => {
601    const result = await next(e)
602    const entered = outcomeOf(result)?.worktreePath
603
604    if (!entered || deniedOrFailed(result)) {
605      return result
606    }
607
608    const url = await provision($, entered).catch(() => null)
609
610    if (!url) {
611      return result
612    }
613
614    return { ...result, context: [...((result as { context?: readonly string[] }).context ?? []), `This worktree is served at ${url}. Tell the user this URL.`] }
615  })
616
617  on('tool.call', { tool: 'ExitWorktree' }, async ($, e, next) => {
618    const result = await next(e)
619    const left = outcomeOf(result)
620
621    if (left?.worktreePath) {
622      await retire($, left.worktreePath, (left.action ?? (e as { action?: string }).action) === 'remove').catch(error => toast($, String(error), 10_000))
623    }
624
625    return result
626  })
627}
628
hooks/lib.ts 155 lines
1export type Tool = 'valet'
2
3export type Link = { name: string; secure: boolean; url: string; path: string }
4
5export type WorktreeInfo = { top: string; gitDir: string; main: string }
6
7export type WorktreeRecord = {
8  path: string
9  main: string
10  project: string
11  branch: string
12  base?: string
13  tool: Tool | null
14  link: string | null
15  state: 'active' | 'exited'
16  notified: boolean
17}
18
19export type JsPlan = { lock: string | null; install: string[] | null; build: string[] | null }
20
21// Never add public/hot or bootstrap/cache: they carry main's dev-server URL and its cached config.
22export const CLONES = ['vendor', 'node_modules', 'public/build']
23
24const ANSI = /\u001b\[[0-9;]*m/g
25
26const JS_LOCKS: [string, string[], string[]][] = [
27  ['bun.lock', ['bun', 'install', '--frozen-lockfile'], ['bun', 'run', 'build']],
28  ['bun.lockb', ['bun', 'install', '--frozen-lockfile'], ['bun', 'run', 'build']],
29  ['pnpm-lock.yaml', ['pnpm', 'install', '--frozen-lockfile'], ['pnpm', 'run', 'build']],
30  ['yarn.lock', ['yarn', 'install', '--frozen-lockfile'], ['yarn', 'run', 'build']],
31  ['package-lock.json', ['npm', 'ci'], ['npm', 'run', 'build']],
32]
33
34export const JS_LOCK_FILES = JS_LOCKS.map(([lock]) => lock)
35
36export const ASSET_INPUTS = ['resources', 'package.json', ...JS_LOCK_FILES, 'vite.config.*', 'tailwind.config.*', 'postcss.config.*', 'tsconfig.json']
37
38const slug = (text: string): string =>
39  text
40    .toLowerCase()
41    .replace(/[^a-z0-9]+/g, '-')
42    .replace(/^-+|-+$/g, '')
43
44const parts = (text: string): string[] => slug(text).replaceAll('worktree', '').split('-').filter(Boolean)
45
46const hash = (text: string): string => {
47  let value = 5381
48
49  for (const char of text) {
50    value = ((value * 33) ^ char.charCodeAt(0)) >>> 0
51  }
52
53  return value.toString(36).slice(0, 6)
54}
55
56export const linkName = (project: string, worktree: string, path: string): string => {
57  const own = parts(worktree)
58  const name = [...parts(project), ...(own.length > 0 ? own : [hash(path)])].join('-')
59
60  return name.slice(0, 60).replace(/-+$/, '')
61}
62
63export const parseLinks = (stdout: string): Link[] =>
64  stdout
65    .replace(ANSI, '')
66    .split('\n')
67    .filter(line => line.trim().startsWith('|'))
68    .map(line => line.split('|').slice(1, -1).map(cell => cell.trim()))
69    .filter(cells => cells.length >= 4 && cells[0] !== 'Site')
70    .map(([name = '', ssl = '', url = '', path = '']) => ({ name, secure: ssl !== '', url, path }))
71
72export const parseWorktree = (revParse: string): WorktreeInfo | null => {
73  const [top, gitDir, commonDir] = revParse.split('\n').map(line => line.trim())
74
75  if (!top || !gitDir || !commonDir || gitDir === commonDir) {
76    return null
77  }
78
79  return { top, gitDir, main: commonDir.replace(/\/\.git\/?$/, '') }
80}
81
82export const basename = (path: string): string => path.split('/').filter(Boolean).pop() ?? path
83
84export type WorktreeLock = { kind: 'none' } | { kind: 'session'; pid: number } | { kind: 'other' }
85
86export const lockOf = (porcelain: string, path: string): WorktreeLock => {
87  const block = porcelain.split('\n\n').find(entry => entry.split('\n')[0] === `worktree ${path}`)
88  const locked = block?.split('\n').find(line => line === 'locked' || line.startsWith('locked '))
89
90  if (locked === undefined) {
91    return { kind: 'none' }
92  }
93
94  const pid = /^locked claude session .*\(pid (\d+)\b/.exec(locked)?.[1]
95
96  return pid ? { kind: 'session', pid: Number(pid) } : { kind: 'other' }
97}
98
99export const underWorktrees =(main: string, path: string): boolean => path.startsWith(`${main}/.claude/worktrees/`)
100
101export const jsPlan = (files: string[], hasBuild: boolean): JsPlan => {
102  const found = JS_LOCKS.find(([lock]) => files.includes(lock))
103
104  if (!found) {
105    return { lock: null, install: null, build: null }
106  }
107
108  return { lock: found[0], install: found[1], build: hasBuild ? found[2] : null }
109}
110
111export const sitesDir = (home: string): string => `${home}/.config/valet/Sites`
112
113export const certBase = (home: string, host: string): string => `${home}/.config/valet/Certificates/${host}`
114
115export const siteFiles = (home: string, host: string): { nginx: string; certs: string[] } => ({
116  nginx: `${home}/.config/valet/Nginx/${host}`,
117  certs: ['crt', 'key', 'csr', 'conf'].map(extension => `${certBase(home, host)}.${extension}`),
118})
119
120export const siteLink = (home: string, name: string): string => `${sitesDir(home)}/${name}`
121
122export const SCAN_SITES = 'for l in "$1"/*; do [ -L "$l" ] && printf "%s\\t%s\\n" "${l##*/}" "$(readlink "$l")"; done; true'
123
124export const parseSiteScan = (stdout: string): { name: string; path: string }[] =>
125  stdout
126    .split('\n')
127    .filter(line => line.includes('\t'))
128    .map(line => {
129      const [name = '', path = ''] = line.split('\t')
130
131      return { name, path }
132    })
133
134export const isProxy =(nginxConfig: string): boolean => nginxConfig.includes('proxy_pass')
135
136export const inWorktrees = (path: string): boolean => path.includes('/.claude/worktrees/')
137
138export const setEnv = (text: string, key: string, value: string): string => {
139  const line = `${key}=${/\s/.test(value) ? `"${value}"` : value}`
140  const pattern = new RegExp(`^${key}=.*$`, 'm')
141
142  if (pattern.test(text)) {
143    return text.replace(pattern, () => line)
144  }
145
146  return `${text}${text === '' || text.endsWith('\n') ? '' : '\n'}${line}\n`
147}
148
149export const shareSqlite = (text: string, mainDatabase: string): string => {
150  const sqlite = /^DB_CONNECTION=["']?sqlite/m.test(text)
151  const absolute = /^DB_DATABASE=["']?\//m.test(text)
152
153  return sqlite && !absolute ? setEnv(text, 'DB_DATABASE', mainDatabase) : text
154}
155