worktree-compose 0.2.0 → 1.0.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 (94) hide show
  1. package/README.md +458 -140
  2. package/SKILL.md +113 -0
  3. package/dist/cli.js +94 -33
  4. package/dist/commands/clean.d.ts +2 -1
  5. package/dist/commands/clean.js +8 -48
  6. package/dist/commands/doctor.d.ts +3 -0
  7. package/dist/commands/doctor.js +30 -0
  8. package/dist/commands/list.d.ts +4 -1
  9. package/dist/commands/list.js +62 -44
  10. package/dist/commands/promote.d.ts +3 -1
  11. package/dist/commands/promote.js +4 -34
  12. package/dist/commands/prune.d.ts +2 -0
  13. package/dist/commands/prune.js +7 -0
  14. package/dist/commands/restart.d.ts +2 -1
  15. package/dist/commands/restart.js +11 -5
  16. package/dist/commands/skill.d.ts +4 -0
  17. package/dist/commands/skill.js +10 -0
  18. package/dist/commands/start.d.ts +2 -1
  19. package/dist/commands/start.js +7 -34
  20. package/dist/commands/stop.d.ts +1 -1
  21. package/dist/commands/stop.js +6 -23
  22. package/dist/compose/detect.d.ts +1 -2
  23. package/dist/compose/detect.js +1 -10
  24. package/dist/compose/engine.d.ts +61 -0
  25. package/dist/compose/engine.js +129 -0
  26. package/dist/compose/isolation.d.ts +15 -0
  27. package/dist/compose/isolation.js +62 -0
  28. package/dist/compose/parse.d.ts +5 -0
  29. package/dist/compose/parse.js +89 -11
  30. package/dist/compose/status.d.ts +84 -0
  31. package/dist/compose/status.js +227 -0
  32. package/dist/compose/types.d.ts +20 -0
  33. package/dist/config.d.ts +31 -0
  34. package/dist/config.js +23 -6
  35. package/dist/context.d.ts +89 -3
  36. package/dist/context.js +278 -45
  37. package/dist/core/clean.d.ts +91 -0
  38. package/dist/core/clean.js +343 -0
  39. package/dist/core/compose.d.ts +30 -0
  40. package/dist/core/compose.js +45 -0
  41. package/dist/core/doctor.d.ts +28 -0
  42. package/dist/core/doctor.js +277 -0
  43. package/dist/core/list.d.ts +42 -0
  44. package/dist/core/list.js +94 -0
  45. package/dist/core/promote.d.ts +40 -0
  46. package/dist/core/promote.js +117 -0
  47. package/dist/core/prune.d.ts +32 -0
  48. package/dist/core/prune.js +75 -0
  49. package/dist/core/restart.d.ts +14 -0
  50. package/dist/core/restart.js +18 -0
  51. package/dist/core/start.d.ts +31 -0
  52. package/dist/core/start.js +99 -0
  53. package/dist/core/stop.d.ts +32 -0
  54. package/dist/core/stop.js +57 -0
  55. package/dist/core/teardown.d.ts +121 -0
  56. package/dist/core/teardown.js +298 -0
  57. package/dist/core/types.d.ts +15 -0
  58. package/dist/core/types.js +1 -0
  59. package/dist/git/promote.d.ts +49 -2
  60. package/dist/git/promote.js +160 -38
  61. package/dist/git/repo.d.ts +72 -0
  62. package/dist/git/repo.js +167 -0
  63. package/dist/git/status.d.ts +8 -0
  64. package/dist/git/status.js +25 -0
  65. package/dist/git/worktree.d.ts +63 -3
  66. package/dist/git/worktree.js +173 -29
  67. package/dist/mcp/server.d.ts +2 -0
  68. package/dist/mcp/server.js +230 -115
  69. package/dist/ports/allocate.d.ts +14 -3
  70. package/dist/ports/allocate.js +20 -4
  71. package/dist/selectors.d.ts +10 -0
  72. package/dist/selectors.js +106 -0
  73. package/dist/skill.d.ts +13 -0
  74. package/dist/skill.js +28 -0
  75. package/dist/state/registry.d.ts +194 -0
  76. package/dist/state/registry.js +595 -0
  77. package/dist/sync/env.d.ts +77 -2
  78. package/dist/sync/env.js +151 -32
  79. package/dist/sync/files.d.ts +15 -1
  80. package/dist/sync/files.js +126 -38
  81. package/dist/utils/exec.d.ts +69 -4
  82. package/dist/utils/exec.js +221 -15
  83. package/dist/utils/log.d.ts +37 -0
  84. package/dist/utils/log.js +68 -4
  85. package/dist/utils/paths.d.ts +61 -0
  86. package/dist/utils/paths.js +163 -0
  87. package/dist/utils/sanitize.d.ts +7 -0
  88. package/dist/utils/sanitize.js +12 -0
  89. package/dist/version.d.ts +1 -0
  90. package/dist/version.js +3 -0
  91. package/dist/workspaces/resolve.d.ts +21 -0
  92. package/dist/workspaces/resolve.js +235 -0
  93. package/package.json +18 -14
  94. package/wtc.schema.json +62 -0
@@ -0,0 +1,595 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { composeProjectName } from "../utils/sanitize.js";
5
+ import { escapesRoot } from "../utils/paths.js";
6
+ import { isCandidate, worktreeAdminDir } from "../git/worktree.js";
7
+ export const STATE_VERSION = 1;
8
+ const LOCK_RETRY_MS = 50;
9
+ const LOCK_TIMEOUT_MS = 10_000;
10
+ /**
11
+ * A lock whose holder still runs is broken only after this long. The
12
+ * critical section is file I/O plus one `git worktree list` (container
13
+ * calls happen before the lock is taken), so a holder this old is wedged —
14
+ * or its PID was reused.
15
+ */
16
+ const LOCK_MAX_AGE_MS = 10 * 60_000;
17
+ const RETIRED_LIMIT = 200;
18
+ const ID_FILE = "wtc-id";
19
+ export function stateDir(commonDir) {
20
+ return path.join(commonDir, "wtc");
21
+ }
22
+ export function stateFile(commonDir) {
23
+ return path.join(stateDir(commonDir), "state.json");
24
+ }
25
+ function lockFile(commonDir) {
26
+ return path.join(stateDir(commonDir), "state.lock");
27
+ }
28
+ function sleepSync(ms) {
29
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
30
+ }
31
+ function readText(file) {
32
+ try {
33
+ return fs.readFileSync(file, "utf-8");
34
+ }
35
+ catch {
36
+ return null;
37
+ }
38
+ }
39
+ /** The holder PID of a lock's `<pid>:<token>` content, or null when unreadable. */
40
+ function lockPid(content) {
41
+ const m = /^(\d+):\S+\s*$/.exec(content ?? "");
42
+ const pid = m ? Number(m[1]) : NaN;
43
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
44
+ }
45
+ /** Only ESRCH proves a process is gone; EPERM means it exists but is not ours to signal. */
46
+ function processIsGone(pid) {
47
+ try {
48
+ process.kill(pid, 0);
49
+ return false;
50
+ }
51
+ catch (err) {
52
+ return err.code === "ESRCH";
53
+ }
54
+ }
55
+ /**
56
+ * Break the lock if it is stale. Returns true when the caller should retry
57
+ * acquiring right away (lock broken, or released meanwhile).
58
+ *
59
+ * A lock is stale only when its holder PID no longer exists, or when it is
60
+ * older than 10 minutes. Age alone never breaks a live holder sooner — an
61
+ * age rule of 30 s let a waiter steal the lock from a process still inside
62
+ * its critical section. The stale lock is renamed aside and its content
63
+ * (unique token) compared, so a fresh lock that replaced it between our
64
+ * read and the rename is put back, not lost.
65
+ */
66
+ function breakStaleLock(lock) {
67
+ const content = readText(lock);
68
+ if (content === null)
69
+ return true;
70
+ let mtimeMs;
71
+ try {
72
+ mtimeMs = fs.statSync(lock).mtimeMs;
73
+ }
74
+ catch {
75
+ return true;
76
+ }
77
+ const pid = lockPid(content);
78
+ const stale = Date.now() - mtimeMs > LOCK_MAX_AGE_MS || (pid !== null && processIsGone(pid));
79
+ if (!stale)
80
+ return false;
81
+ const aside = `${lock}.stale-${process.pid}-${randomUUID()}`;
82
+ try {
83
+ fs.renameSync(lock, aside);
84
+ }
85
+ catch {
86
+ return true;
87
+ }
88
+ try {
89
+ if (readText(aside) !== content) {
90
+ // A fresh lock replaced the stale one: restore it.
91
+ try {
92
+ fs.linkSync(aside, lock);
93
+ }
94
+ catch {
95
+ // Yet another lock already took its place; nothing to restore into.
96
+ }
97
+ }
98
+ }
99
+ finally {
100
+ fs.rmSync(aside, { force: true });
101
+ }
102
+ return true;
103
+ }
104
+ /**
105
+ * Run `fn` holding an exclusive lock on the registry. The CLI and the MCP
106
+ * server (or two agents) may reconcile at the same moment; without the lock
107
+ * both could hand out the same index. `fn` must never call a container
108
+ * engine — a slow daemon would hold every other wtc process up.
109
+ *
110
+ * The lock holds `<pid>:<random token>`; on release it is removed only if
111
+ * it still holds our token, so a holder never deletes another's lock.
112
+ */
113
+ export function withStateLock(commonDir, fn, opts = {}) {
114
+ const lock = lockFile(commonDir);
115
+ fs.mkdirSync(path.dirname(lock), { recursive: true });
116
+ const content = `${process.pid}:${randomUUID()}`;
117
+ const deadline = Date.now() + (opts.timeoutMs ?? LOCK_TIMEOUT_MS);
118
+ for (;;) {
119
+ let fd;
120
+ try {
121
+ fd = fs.openSync(lock, "wx");
122
+ }
123
+ catch (err) {
124
+ if (err.code !== "EEXIST")
125
+ throw err;
126
+ const broken = breakStaleLock(lock);
127
+ if (Date.now() >= deadline) {
128
+ const pid = lockPid(readText(lock));
129
+ throw new Error(`Timed out waiting for the wtc state lock (${lock})` +
130
+ (pid !== null ? `, held by process ${pid}` : "") +
131
+ `. Another wtc command is running; retry when it finishes. ` +
132
+ `If no wtc process is running at all, delete that file.`);
133
+ }
134
+ if (!broken)
135
+ sleepSync(LOCK_RETRY_MS);
136
+ continue;
137
+ }
138
+ try {
139
+ fs.writeSync(fd, content);
140
+ }
141
+ catch (err) {
142
+ fs.closeSync(fd);
143
+ fs.rmSync(lock, { force: true });
144
+ throw err;
145
+ }
146
+ fs.closeSync(fd);
147
+ break;
148
+ }
149
+ try {
150
+ return fn();
151
+ }
152
+ finally {
153
+ // Not ours any more (broken as stale by a waiter): leave it alone.
154
+ if (readText(lock) === content)
155
+ fs.rmSync(lock, { force: true });
156
+ }
157
+ }
158
+ function isRecord(value) {
159
+ if (!value || typeof value !== "object")
160
+ return false;
161
+ const r = value;
162
+ return (typeof r.path === "string" &&
163
+ typeof r.project === "string" &&
164
+ typeof r.branch === "string" &&
165
+ typeof r.createdAt === "string" &&
166
+ Number.isInteger(r.index) &&
167
+ r.index > 0 &&
168
+ (r.id === undefined || typeof r.id === "string") &&
169
+ (r.envFiles === undefined ||
170
+ (Array.isArray(r.envFiles) && r.envFiles.every((f) => typeof f === "string"))));
171
+ }
172
+ /** Thrown for a state file written by a newer wtc: never discard it. */
173
+ export class NewerStateError extends Error {
174
+ constructor(file, version) {
175
+ super(`${file} was written by a newer wtc (state version ${version}); upgrade wtc.`);
176
+ this.name = "NewerStateError";
177
+ }
178
+ }
179
+ function emptyState() {
180
+ return { version: STATE_VERSION, worktrees: [], retired: [] };
181
+ }
182
+ function parseState(file, text) {
183
+ let doc;
184
+ try {
185
+ doc = JSON.parse(text);
186
+ }
187
+ catch (err) {
188
+ return { ok: false, problem: `invalid JSON (${err instanceof Error ? err.message : String(err)})` };
189
+ }
190
+ if (!doc || typeof doc !== "object" || Array.isArray(doc)) {
191
+ return { ok: false, problem: "not a JSON object" };
192
+ }
193
+ const d = doc;
194
+ if (Number.isInteger(d.version) && d.version > STATE_VERSION) {
195
+ // A newer wtc (e.g. the global CLI) shares this file with an older one
196
+ // (e.g. a cached MCP server). Resetting it would renumber every stack.
197
+ throw new NewerStateError(file, d.version);
198
+ }
199
+ if (d.version !== STATE_VERSION) {
200
+ return { ok: false, problem: `unsupported state version ${JSON.stringify(d.version)}` };
201
+ }
202
+ if (!Array.isArray(d.worktrees)) {
203
+ return { ok: false, problem: `"worktrees" is not an array` };
204
+ }
205
+ const valid = d.worktrees.filter(isRecord);
206
+ const retired = Array.isArray(d.retired)
207
+ ? d.retired.filter((p) => typeof p === "string")
208
+ : [];
209
+ const mainCheckout = typeof d.mainCheckout === "string" && path.isAbsolute(d.mainCheckout) ? d.mainCheckout : undefined;
210
+ return {
211
+ ok: true,
212
+ state: { version: STATE_VERSION, worktrees: valid, retired, ...(mainCheckout ? { mainCheckout } : {}) },
213
+ malformed: d.worktrees.length - valid.length,
214
+ };
215
+ }
216
+ /**
217
+ * Read the registry without side effects: `null` when there is none or it
218
+ * is unreadable. Throws NewerStateError for a newer format.
219
+ */
220
+ export function peekState(commonDir) {
221
+ const file = stateFile(commonDir);
222
+ const text = readText(file);
223
+ if (text === null)
224
+ return null;
225
+ const parsed = parseState(file, text);
226
+ return parsed.ok ? parsed.state : null;
227
+ }
228
+ /**
229
+ * Read the registry. A corrupt file is moved aside as
230
+ * `state.json.bak-<epoch>` (never silently overwritten) and replaced by an
231
+ * empty registry, with a warning; malformed records are dropped after a
232
+ * backup copy. With `readOnly`, nothing is moved or copied — the problem is
233
+ * only reported. A file from a newer wtc is never touched: NewerStateError.
234
+ */
235
+ export function readState(commonDir, warnings = [], opts = {}) {
236
+ const file = stateFile(commonDir);
237
+ const text = readText(file);
238
+ if (text === null)
239
+ return emptyState();
240
+ const parsed = parseState(file, text);
241
+ if (parsed.ok) {
242
+ if (parsed.malformed > 0) {
243
+ if (opts.readOnly) {
244
+ warnings.push(`Ignoring ${parsed.malformed} malformed record(s) in ${file}.`);
245
+ }
246
+ else {
247
+ const backup = `${file}.bak-${Date.now()}`;
248
+ fs.copyFileSync(file, backup);
249
+ warnings.push(`Ignored ${parsed.malformed} malformed record(s) in ${file} (backup: ${backup}).`);
250
+ }
251
+ }
252
+ return parsed.state;
253
+ }
254
+ if (opts.readOnly) {
255
+ warnings.push(`wtc state file is unreadable (${parsed.problem}): ${file}. Left in place; ` +
256
+ `the next command that changes anything moves it aside and starts fresh.`);
257
+ return emptyState();
258
+ }
259
+ const backup = `${file}.bak-${Date.now()}`;
260
+ fs.renameSync(file, backup);
261
+ warnings.push(`wtc state file was unreadable (${parsed.problem}); moved it to ${backup} and started fresh.`);
262
+ return emptyState();
263
+ }
264
+ /** Atomic write: temp file in the same directory, then rename over the target. */
265
+ export function writeState(commonDir, state) {
266
+ const file = stateFile(commonDir);
267
+ fs.mkdirSync(path.dirname(file), { recursive: true });
268
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
269
+ const retired = [...new Set(state.retired ?? [])].slice(-RETIRED_LIMIT);
270
+ const doc = {
271
+ version: STATE_VERSION,
272
+ worktrees: state.worktrees,
273
+ retired,
274
+ ...(state.mainCheckout ? { mainCheckout: state.mainCheckout } : {}),
275
+ };
276
+ fs.writeFileSync(tmp, JSON.stringify(doc, null, 2) + "\n", "utf-8");
277
+ fs.renameSync(tmp, file);
278
+ }
279
+ function lowestFreeIndex(used) {
280
+ let i = 1;
281
+ while (used.has(i))
282
+ i++;
283
+ return i;
284
+ }
285
+ /** The stable id stored in a worktree's admin dir, if it has one yet. */
286
+ export function readWorktreeId(adminDir) {
287
+ if (!adminDir)
288
+ return undefined;
289
+ const id = readText(path.join(adminDir, ID_FILE))?.trim();
290
+ return id || undefined;
291
+ }
292
+ /** Create the worktree's id file; `undefined` when its admin dir is not writable. */
293
+ function createWorktreeId(adminDir) {
294
+ if (!adminDir)
295
+ return undefined;
296
+ const id = randomUUID();
297
+ try {
298
+ fs.writeFileSync(path.join(adminDir, ID_FILE), id + "\n", { flag: "wx" });
299
+ return id;
300
+ }
301
+ catch {
302
+ return readWorktreeId(adminDir);
303
+ }
304
+ }
305
+ /**
306
+ * Is `record` the record of the live worktree `wt`? Its id matches, or —
307
+ * for a record without an id, or a worktree that cannot hold one (no admin
308
+ * dir) — its path does. A path match whose ids differ (or a fresh admin
309
+ * dir with no id yet) is a *different* worktree created at a reused path.
310
+ */
311
+ function isRecordOf(record, wt) {
312
+ if (record.id !== undefined && record.id === wt.id)
313
+ return true;
314
+ return pathMatches(record, wt);
315
+ }
316
+ function pathMatches(record, wt) {
317
+ return (path.resolve(record.path) === path.resolve(wt.path) &&
318
+ (record.id === undefined || record.id === wt.id || (wt.id === undefined && !wt.adminDir)));
319
+ }
320
+ /**
321
+ * Match live worktrees to their records, assigning new identities as needed.
322
+ *
323
+ * - Records match by path, then by stable id: a moved worktree keeps its
324
+ * index and project (the stored path is updated); a new worktree at a
325
+ * reused path does not inherit the old one's (see isRecordOf).
326
+ * - Records with no live worktree are orphans. They keep their index — their
327
+ * stack may still hold its ports — until `wtc prune` / `wtc clean`.
328
+ * - A worktree without a record adopts a running stack's identity
329
+ * (`adoptable`) when its index is free. Otherwise an empty registry
330
+ * (fresh install, 0.2 upgrade, corrupt file) assigns positional indices
331
+ * in `git worktree list` order — exactly the old naming, so 0.2 stacks are
332
+ * adopted, not duplicated — and a non-empty one the lowest index no
333
+ * record (live or orphaned) holds.
334
+ */
335
+ export function reconcileWorktrees(opts) {
336
+ if (opts.readOnly) {
337
+ const warnings = [];
338
+ const listed = opts.listWorktrees();
339
+ const state = readState(opts.commonDir, warnings, { readOnly: true });
340
+ return assignIdentities(opts, listed, state, warnings, false);
341
+ }
342
+ if (!fs.existsSync(stateFile(opts.commonDir))) {
343
+ const pre = opts.listWorktrees();
344
+ if (!pre.some(isCandidate)) {
345
+ // Nothing to record and nothing recorded: don't create .git/wtc at all.
346
+ return { worktrees: [], orphans: [], unavailable: [], warnings: [], listed: pre };
347
+ }
348
+ if (opts.adoptable === undefined) {
349
+ // A fresh registry without a stack probe is computed, never persisted,
350
+ // so nothing is written — not even the lock.
351
+ const warnings = [];
352
+ const state = readState(opts.commonDir, warnings, { readOnly: true });
353
+ return assignIdentities(opts, pre, state, warnings, false);
354
+ }
355
+ }
356
+ return withStateLock(opts.commonDir, () => {
357
+ const listed = opts.listWorktrees();
358
+ const warnings = [];
359
+ const state = readState(opts.commonDir, warnings);
360
+ const persist = state.worktrees.length > 0 || opts.adoptable !== undefined;
361
+ return assignIdentities(opts, listed, state, warnings, persist);
362
+ });
363
+ }
364
+ function assignIdentities(opts, listed, state, warnings, persist) {
365
+ const now = opts.now ?? (() => new Date());
366
+ const fresh = state.worktrees.length === 0;
367
+ const records = state.worktrees;
368
+ let changed = false;
369
+ const live = listed.filter(isCandidate).map((wt) => ({
370
+ ...wt,
371
+ path: path.resolve(wt.path),
372
+ id: readWorktreeId(wt.adminDir),
373
+ }));
374
+ // 1. Match records to live worktrees: by path, then by id.
375
+ const matched = new Map();
376
+ const claimed = new Set();
377
+ const claim = (wt, record) => {
378
+ matched.set(wt, record);
379
+ claimed.add(record);
380
+ };
381
+ for (const wt of live) {
382
+ const record = records.find((r) => !claimed.has(r) && pathMatches(r, wt));
383
+ if (record)
384
+ claim(wt, record);
385
+ }
386
+ for (const wt of live) {
387
+ if (matched.has(wt) || wt.id === undefined)
388
+ continue;
389
+ const record = records.find((r) => !claimed.has(r) && r.id === wt.id);
390
+ if (!record)
391
+ continue;
392
+ record.path = wt.path; // `git worktree move`: same worktree, new path.
393
+ changed = true;
394
+ claim(wt, record);
395
+ }
396
+ // Worktrees git still lists but wtc cannot start keep their records too:
397
+ // locked ones missing on disk, and one that became the main checkout.
398
+ const unavailable = [];
399
+ for (const entry of listed) {
400
+ if (!holdsRecord(entry) || isCandidate(entry))
401
+ continue;
402
+ const wt = { ...entry, path: path.resolve(entry.path), id: readWorktreeId(entry.adminDir) };
403
+ const record = records.find((r) => !claimed.has(r) && pathMatches(r, wt)) ??
404
+ (wt.id === undefined ? undefined : records.find((r) => !claimed.has(r) && r.id === wt.id));
405
+ if (!record)
406
+ continue;
407
+ if (record.path !== wt.path) {
408
+ record.path = wt.path;
409
+ changed = true;
410
+ }
411
+ claimed.add(record);
412
+ unavailable.push({ ...record, reason: entry.missing ? "missing" : "main" });
413
+ }
414
+ // Stamp ids on records written before ids existed.
415
+ for (const [wt, record] of matched) {
416
+ if (record.id !== undefined)
417
+ continue;
418
+ const id = wt.id ?? (persist ? createWorktreeId(wt.adminDir) : undefined);
419
+ if (id) {
420
+ record.id = id;
421
+ changed = true;
422
+ }
423
+ }
424
+ // 2. Every record keeps its index: orphans are only forgotten by prune/clean.
425
+ const orphans = records.filter((r) => !claimed.has(r));
426
+ const used = new Set(records.map((r) => r.index));
427
+ const projects = new Set(records.map((r) => r.project));
428
+ // 3. Worktrees without a record adopt their running stack's identity.
429
+ const adopted = new Map();
430
+ for (const wt of live) {
431
+ if (matched.has(wt))
432
+ continue;
433
+ const stack = opts.adoptable?.get(wt.path);
434
+ if (!stack || used.has(stack.index) || projects.has(stack.project))
435
+ continue;
436
+ adopted.set(wt, stack);
437
+ used.add(stack.index);
438
+ projects.add(stack.project);
439
+ }
440
+ // 4. Number the rest.
441
+ const kept = [...records];
442
+ const resolved = [];
443
+ // ≤0.2 numbered every non-main entry (prunable ones included) 1..N.
444
+ let legacyPosition = 0;
445
+ const byPath = new Map(live.map((wt) => [wt.path, wt]));
446
+ for (const entry of listed) {
447
+ if (entry.isMain || entry.bare)
448
+ continue;
449
+ legacyPosition++;
450
+ if (!isCandidate(entry))
451
+ continue;
452
+ const wt = byPath.get(path.resolve(entry.path));
453
+ if (!wt)
454
+ continue;
455
+ let record = matched.get(wt);
456
+ if (!record) {
457
+ const stack = adopted.get(wt);
458
+ const index = stack
459
+ ? stack.index
460
+ : fresh && !used.has(legacyPosition)
461
+ ? legacyPosition
462
+ : lowestFreeIndex(used);
463
+ record = {
464
+ path: wt.path,
465
+ index,
466
+ project: stack ? stack.project : composeProjectName(opts.repoName, index, wt.branch),
467
+ branch: wt.branch,
468
+ createdAt: now().toISOString(),
469
+ };
470
+ const id = wt.id ?? (persist ? createWorktreeId(wt.adminDir) : undefined);
471
+ if (id)
472
+ record.id = id;
473
+ used.add(index);
474
+ kept.push(record);
475
+ changed = true;
476
+ }
477
+ resolved.push({
478
+ ...wt,
479
+ index: record.index,
480
+ project: record.project,
481
+ id: record.id,
482
+ envFiles: record.envFiles,
483
+ });
484
+ }
485
+ let mainCheckout = state.mainCheckout;
486
+ if (opts.mainCheckout !== undefined && mainCheckout !== path.resolve(opts.mainCheckout)) {
487
+ mainCheckout = path.resolve(opts.mainCheckout);
488
+ changed = true;
489
+ }
490
+ if (persist && changed) {
491
+ writeState(opts.commonDir, {
492
+ version: STATE_VERSION,
493
+ worktrees: kept,
494
+ retired: state.retired,
495
+ ...(mainCheckout ? { mainCheckout } : {}),
496
+ });
497
+ }
498
+ orphans.sort((a, b) => a.index - b.index);
499
+ unavailable.sort((a, b) => a.index - b.index);
500
+ return { worktrees: resolved, orphans, unavailable, warnings, listed };
501
+ }
502
+ /**
503
+ * Entries whose records stay theirs: every linked worktree git still lists
504
+ * — managed ones, locked ones missing on disk, and one marked main — but
505
+ * not the first entry (main checkout, bare repo or git dir) nor ones git
506
+ * reports gone (prunable).
507
+ */
508
+ function holdsRecord(wt) {
509
+ return !wt.bare && !wt.prunable && (!wt.isMain || wt.markedMain === true);
510
+ }
511
+ /**
512
+ * True when a record's worktree still exists in `listed` (same identity
513
+ * rules as reconcile): any linked worktree git still lists counts —
514
+ * including a locked one missing on disk and one marked main — not only
515
+ * those wtc can start. Clean and prune re-check this right before tearing
516
+ * an orphan down: another process may have registered or moved its
517
+ * worktree since, and `down -v` must never hit a worktree that exists.
518
+ */
519
+ export function recordIsLive(record, listed) {
520
+ return listed
521
+ .filter(holdsRecord)
522
+ .some((wt) => isRecordOf(record, { ...wt, path: path.resolve(wt.path), id: readWorktreeId(wt.adminDir) }));
523
+ }
524
+ /** True when the live worktree `wt` already has a record in `state`. */
525
+ export function hasRecord(state, wt) {
526
+ if (!state)
527
+ return false;
528
+ const live = { ...wt, id: readWorktreeId(wt.adminDir) };
529
+ return state.worktrees.some((r) => isRecordOf(r, live));
530
+ }
531
+ /**
532
+ * Drop records by compose project (unique per record) — used by clean and
533
+ * prune after teardown. Keyed by project, not path: a reused path can hold
534
+ * both an orphan's record and a new worktree's. An unreadable registry is
535
+ * left alone rather than moved aside.
536
+ */
537
+ export function forgetRecords(commonDir, projects) {
538
+ if (projects.length === 0)
539
+ return;
540
+ if (!fs.existsSync(stateFile(commonDir)))
541
+ return;
542
+ const drop = new Set(projects);
543
+ withStateLock(commonDir, () => {
544
+ const state = peekState(commonDir);
545
+ if (!state)
546
+ return;
547
+ const kept = state.worktrees.filter((r) => !drop.has(r.project));
548
+ if (kept.length !== state.worktrees.length) {
549
+ const retired = [...(state.retired ?? []), ...projects];
550
+ writeState(commonDir, { ...state, worktrees: kept, retired });
551
+ }
552
+ });
553
+ }
554
+ /**
555
+ * Remember env files wtc wrote into the worktree at `wtPath` (absolute, or
556
+ * relative to the worktree), merged with — and deduplicated against — those
557
+ * already recorded. Stored repo-relative with `/` separators. Clean treats
558
+ * exactly these as wtc's own changes, so they never make a worktree dirty.
559
+ * A worktree without a record (registry not persisted yet) is skipped.
560
+ */
561
+ export function recordEnvFiles(commonDir, wtPath, files) {
562
+ if (!fs.existsSync(stateFile(commonDir)))
563
+ return;
564
+ const root = path.resolve(wtPath);
565
+ const rel = files
566
+ .map((f) => (path.isAbsolute(f) ? path.relative(root, f) : path.normalize(f)))
567
+ .filter((f) => f !== "" && f !== "." && !escapesRoot(f))
568
+ .map((f) => f.split(path.sep).join("/"));
569
+ if (rel.length === 0)
570
+ return;
571
+ // Identify the worktree before locking (may ask git).
572
+ const adminDir = worktreeAdminDir(root);
573
+ const wt = {
574
+ path: root,
575
+ branch: "",
576
+ isMain: false,
577
+ bare: false,
578
+ detached: false,
579
+ locked: false,
580
+ prunable: false,
581
+ adminDir,
582
+ id: readWorktreeId(adminDir),
583
+ };
584
+ withStateLock(commonDir, () => {
585
+ const state = peekState(commonDir);
586
+ const record = state?.worktrees.find((r) => isRecordOf(r, wt));
587
+ if (!state || !record)
588
+ return;
589
+ const merged = [...new Set([...(record.envFiles ?? []), ...rel])];
590
+ if (record.envFiles && merged.length === record.envFiles.length)
591
+ return;
592
+ record.envFiles = merged;
593
+ writeState(commonDir, state);
594
+ });
595
+ }
@@ -1,5 +1,80 @@
1
1
  import type { PortAllocation } from "../ports/types.js";
2
+ export declare const DEFAULT_ENV_FILE = ".env";
3
+ /** An env file target: the repo root, or a workspace directory. */
4
+ export interface EnvTarget {
5
+ /** Directory relative to the repo root; `""` means the repo root. */
6
+ dir: string;
7
+ /** Human-readable label used in logs ("root", "workspace server (apps/server)"). */
8
+ label: string;
9
+ /** Env filename to copy and inject (e.g. `.env`, `.env.development`). */
10
+ envFileName: string;
11
+ /** Per-target overrides; `${VAR}` interpolates allocated port values. */
12
+ overrides?: Record<string, string>;
13
+ }
2
14
  export declare function stripOverrideBlock(content: string): string;
15
+ /** Name of the compose project variable wtc writes into the root env file. */
16
+ export declare const PROJECT_NAME_VAR = "COMPOSE_PROJECT_NAME";
17
+ /** Interpolate `${VAR}` placeholders with allocated port values (and the project name). */
18
+ export declare function resolveOverrideValue(value: string, values: Map<string, number | string>): string;
19
+ export interface InjectOptions {
20
+ /** Compose project name; always available to overrides as `${COMPOSE_PROJECT_NAME}`. */
21
+ projectName?: string;
22
+ /**
23
+ * Also write `COMPOSE_PROJECT_NAME=<project>` (root target only), so running
24
+ * `docker compose` by hand inside the worktree addresses the same stack wtc
25
+ * started instead of creating a new one named after the directory.
26
+ */
27
+ writeProjectName?: boolean;
28
+ /**
29
+ * Directory the env file must stay inside (the worktree root). Defaults to
30
+ * the file's own directory, which still protects the final component.
31
+ */
32
+ root?: string;
33
+ /** The pristine env source this file was copied from; never written, even via a hard link. */
34
+ source?: string;
35
+ }
36
+ /**
37
+ * All keys that should be written for a target: the project name (root
38
+ * target), allocated ports, then the target's overrides (already
39
+ * interpolated). Overrides win on key conflicts.
40
+ */
41
+ export declare function buildOverrideEntries(allocations: PortAllocation[], overrides?: Record<string, string>, opts?: InjectOptions): Record<string, string>;
3
42
  export declare function buildOverrideBlock(allocations: PortAllocation[], envOverrides?: Record<string, string>): string;
4
- export declare function injectPortOverrides(envPath: string, allocations: PortAllocation[], envOverrides?: Record<string, string>): void;
5
- export declare function copyBaseEnv(repoRoot: string, wtPath: string): void;
43
+ export interface InjectionResult {
44
+ /** Keys whose existing line was rewritten in place. */
45
+ rewritten: string[];
46
+ /** Keys that were not present and were appended in the override block. */
47
+ appended: string[];
48
+ /** A symlink or special file at the path was replaced instead of written through. */
49
+ warnings: string[];
50
+ }
51
+ /**
52
+ * Inject port allocations and overrides into an env file. Existing keys are
53
+ * rewritten in place; missing keys are appended in an idempotent block. The
54
+ * block is stripped before writing, so repeated runs never accumulate.
55
+ */
56
+ export declare function injectPortOverrides(envPath: string, allocations: PortAllocation[], overrides?: Record<string, string>, opts?: InjectOptions): InjectionResult;
57
+ /**
58
+ * Pristine source for a target's env file: `<dir>/<envFileName>` first, then
59
+ * `<dir>/.env.example`. Returns `null` when neither exists.
60
+ */
61
+ export declare function findEnvSource(repoRoot: string, target: EnvTarget): string | null;
62
+ /**
63
+ * Copy the pristine env file from the main checkout into the worktree at the
64
+ * same relative path. Returns the destination path, or `null` when the target
65
+ * is skipped: a workspace with no env file (and no `.env.example`), or a
66
+ * destination wtc refuses to write (reasons pushed onto `warnings`). The
67
+ * repo root otherwise always yields a path — an empty file is created when
68
+ * nothing exists, matching the previous zero-config behavior.
69
+ *
70
+ * The worktree's branch is not trusted: a committed symlink at the env path
71
+ * (`.env -> ../somewhere`) or a symlinked workspace directory would make the
72
+ * copy write the main checkout's secrets — plus the override block — to
73
+ * wherever it points. A symlink at the env path is replaced by a regular
74
+ * copy (symlinking `.env` from main is also a common setup, and writing
75
+ * through it would rewrite main's own `.env`); a directory that resolves
76
+ * outside the worktree is refused. The env source itself is never written:
77
+ * when the destination *is* the source (same realpath or inode — the
78
+ * worktree is the main checkout, or a hard link), the target is skipped.
79
+ */
80
+ export declare function prepareEnvFile(repoRoot: string, wtPath: string, target: EnvTarget, warnings?: string[]): string | null;