worktree-compose 0.2.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +501 -143
  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 +26 -0
  27. package/dist/compose/isolation.js +91 -0
  28. package/dist/compose/override.d.ts +152 -0
  29. package/dist/compose/override.js +542 -0
  30. package/dist/compose/parse.d.ts +12 -0
  31. package/dist/compose/parse.js +199 -29
  32. package/dist/compose/status.d.ts +84 -0
  33. package/dist/compose/status.js +227 -0
  34. package/dist/compose/types.d.ts +43 -0
  35. package/dist/config.d.ts +31 -0
  36. package/dist/config.js +23 -6
  37. package/dist/context.d.ts +104 -3
  38. package/dist/context.js +299 -45
  39. package/dist/core/clean.d.ts +91 -0
  40. package/dist/core/clean.js +347 -0
  41. package/dist/core/compose.d.ts +92 -0
  42. package/dist/core/compose.js +195 -0
  43. package/dist/core/doctor.d.ts +29 -0
  44. package/dist/core/doctor.js +342 -0
  45. package/dist/core/list.d.ts +46 -0
  46. package/dist/core/list.js +101 -0
  47. package/dist/core/promote.d.ts +40 -0
  48. package/dist/core/promote.js +117 -0
  49. package/dist/core/prune.d.ts +32 -0
  50. package/dist/core/prune.js +79 -0
  51. package/dist/core/restart.d.ts +14 -0
  52. package/dist/core/restart.js +18 -0
  53. package/dist/core/start.d.ts +33 -0
  54. package/dist/core/start.js +113 -0
  55. package/dist/core/stop.d.ts +32 -0
  56. package/dist/core/stop.js +58 -0
  57. package/dist/core/teardown.d.ts +123 -0
  58. package/dist/core/teardown.js +305 -0
  59. package/dist/core/types.d.ts +15 -0
  60. package/dist/core/types.js +1 -0
  61. package/dist/git/promote.d.ts +49 -2
  62. package/dist/git/promote.js +160 -38
  63. package/dist/git/repo.d.ts +72 -0
  64. package/dist/git/repo.js +167 -0
  65. package/dist/git/status.d.ts +8 -0
  66. package/dist/git/status.js +25 -0
  67. package/dist/git/worktree.d.ts +63 -3
  68. package/dist/git/worktree.js +173 -29
  69. package/dist/mcp/server.d.ts +2 -0
  70. package/dist/mcp/server.js +230 -115
  71. package/dist/ports/allocate.d.ts +39 -5
  72. package/dist/ports/allocate.js +96 -16
  73. package/dist/ports/extract.d.ts +12 -0
  74. package/dist/ports/extract.js +48 -4
  75. package/dist/ports/types.d.ts +12 -1
  76. package/dist/selectors.d.ts +10 -0
  77. package/dist/selectors.js +106 -0
  78. package/dist/skill.d.ts +13 -0
  79. package/dist/skill.js +28 -0
  80. package/dist/state/registry.d.ts +194 -0
  81. package/dist/state/registry.js +595 -0
  82. package/dist/sync/env.d.ts +93 -2
  83. package/dist/sync/env.js +169 -32
  84. package/dist/sync/files.d.ts +15 -1
  85. package/dist/sync/files.js +126 -38
  86. package/dist/utils/exec.d.ts +69 -4
  87. package/dist/utils/exec.js +221 -15
  88. package/dist/utils/log.d.ts +37 -0
  89. package/dist/utils/log.js +68 -4
  90. package/dist/utils/paths.d.ts +61 -0
  91. package/dist/utils/paths.js +163 -0
  92. package/dist/utils/sanitize.d.ts +7 -0
  93. package/dist/utils/sanitize.js +12 -0
  94. package/dist/version.d.ts +1 -0
  95. package/dist/version.js +3 -0
  96. package/dist/workspaces/resolve.d.ts +21 -0
  97. package/dist/workspaces/resolve.js +235 -0
  98. package/package.json +20 -16
  99. package/wtc.schema.json +62 -0
@@ -2,7 +2,11 @@ const ENV_VAR_PATTERN = /^\$\{([A-Z_][A-Z0-9_]*):-(\d+)\}$/;
2
2
  function stripProtocol(port) {
3
3
  return port.replace(/\/(tcp|udp|sctp)$/i, "");
4
4
  }
5
- function splitPortString(raw) {
5
+ /**
6
+ * Split a `ports:` string into its `:`-separated segments, keeping `${…}`
7
+ * interpolations whole. The protocol suffix (`/tcp`) is stripped first.
8
+ */
9
+ export function portSegments(raw) {
6
10
  const cleaned = stripProtocol(raw);
7
11
  const segments = [];
8
12
  let current = "";
@@ -32,6 +36,10 @@ function splitPortString(raw) {
32
36
  current += ch;
33
37
  }
34
38
  segments.push(current);
39
+ return segments;
40
+ }
41
+ function splitPortString(raw) {
42
+ const segments = portSegments(raw);
35
43
  if (segments.length === 1)
36
44
  return null;
37
45
  if (segments.length === 2)
@@ -46,9 +54,20 @@ function resolveEnvVar(segment) {
46
54
  return null;
47
55
  return { envVar: match[1], defaultPort: parseInt(match[2], 10) };
48
56
  }
57
+ /** `8000-8010`: a port range, which no single allocated port can replace. */
58
+ function rangeOf(segment) {
59
+ const m = /^\s*(\d+)\s*-\s*(\d+)\s*$/.exec(segment);
60
+ return m ? [Number(m[1]), Number(m[2])] : null;
61
+ }
62
+ /**
63
+ * A port number, or the first port of a range. Anything else — `${VAR}`
64
+ * without a default, `8000-${END:-8010}` — is null: its numeric prefix is
65
+ * not the port compose publishes.
66
+ */
49
67
  function resolvePort(segment) {
50
- const n = parseInt(segment, 10);
51
- return isNaN(n) ? null : n;
68
+ if (/^\s*\d+\s*$/.test(segment))
69
+ return Number(segment.trim());
70
+ return rangeOf(segment)?.[0] ?? null;
52
71
  }
53
72
  export function extractPortMappings(services) {
54
73
  const mappings = [];
@@ -73,13 +92,17 @@ export function extractPortMappings(services) {
73
92
  }
74
93
  else {
75
94
  const hostPort = resolvePort(split.host);
76
- if (hostPort !== null) {
95
+ const hostRange = rangeOf(split.host);
96
+ // Host port 0 asks the engine for any free port: it never collides.
97
+ if (hostPort !== null && hostPort !== 0) {
77
98
  mappings.push({
78
99
  serviceName: svc.name,
79
100
  envVar: null,
80
101
  defaultPort: hostPort,
81
102
  containerPort,
82
103
  raw,
104
+ ...(hostRange || rangeOf(split.container) ? { range: true } : {}),
105
+ ...(hostRange ? { rangeEnd: hostRange[1] } : {}),
83
106
  });
84
107
  }
85
108
  }
@@ -90,3 +113,24 @@ export function extractPortMappings(services) {
90
113
  export function suggestEnvVar(serviceName) {
91
114
  return `${serviceName.toUpperCase().replace(/[^A-Z0-9]/g, "_")}_PORT`;
92
115
  }
116
+ /**
117
+ * A variable name to suggest for each hardcoded mapping: `<SERVICE>_PORT`,
118
+ * or `<SERVICE>_<CONTAINER>_PORT` for a service's further ports, never one
119
+ * the compose file already uses (two ports sharing a name would get the
120
+ * same value).
121
+ */
122
+ export function suggestEnvVars(mappings) {
123
+ const taken = new Set(mappings.flatMap((m) => (m.envVar ? [m.envVar] : [])));
124
+ const out = new Map();
125
+ for (const m of mappings) {
126
+ if (m.envVar !== null)
127
+ continue;
128
+ const base = suggestEnvVar(m.serviceName);
129
+ let name = taken.has(base) ? base.replace(/_PORT$/, `_${m.containerPort}_PORT`) : base;
130
+ for (let n = 2; taken.has(name); n++)
131
+ name = `${base}_${n}`;
132
+ taken.add(name);
133
+ out.set(m, name);
134
+ }
135
+ return out;
136
+ }
@@ -1,13 +1,24 @@
1
1
  export interface PortMapping {
2
2
  serviceName: string;
3
+ /** `VAR` of a `${VAR:-port}` host port; null for a hardcoded host port. */
3
4
  envVar: string | null;
4
5
  defaultPort: number;
5
6
  containerPort: number;
6
7
  raw: string;
8
+ /** A host port range (`8000-8010:8000-8010`): never remapped. */
9
+ range?: boolean;
10
+ /** Last host port of a range (`defaultPort` is the first). */
11
+ rangeEnd?: number;
7
12
  }
8
13
  export interface PortAllocation {
9
14
  serviceName: string;
10
- envVar: string;
15
+ /**
16
+ * The variable the compose file reads this host port from, or null for a
17
+ * hardcoded host port that wtc remaps at runtime (no variable exists).
18
+ */
19
+ envVar: string | null;
11
20
  port: number;
12
21
  containerPort: number;
22
+ /** The host port the compose file publishes in the main checkout. */
23
+ defaultPort: number;
13
24
  }
@@ -0,0 +1,10 @@
1
+ import type { ResolvedWorktree } from "./state/registry.js";
2
+ /** A worktree selector: index, branch name, directory basename, path, or ".". */
3
+ export type WorktreeSelector = number | string;
4
+ /**
5
+ * Resolve selectors to worktrees, preserving request order and dropping
6
+ * duplicates. Each token may be a persistent index (`2`), a branch name
7
+ * (`feat-a`), a directory basename (`myapp-feat-a`), a path, or `.` (the
8
+ * worktree containing `cwd`). An empty selection means every live worktree.
9
+ */
10
+ export declare function selectWorktrees(worktrees: ResolvedWorktree[], selectors: WorktreeSelector[] | undefined, cwd?: string): ResolvedWorktree[];
@@ -0,0 +1,106 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { samePath } from "./git/worktree.js";
4
+ import { isWithin } from "./utils/paths.js";
5
+ function available(worktrees) {
6
+ if (worktrees.length === 0)
7
+ return "none (create one with: git worktree add ../my-branch my-branch)";
8
+ return [...worktrees]
9
+ .sort((a, b) => a.index - b.index)
10
+ .map((w) => `${w.index}:${w.branch}`)
11
+ .join(", ");
12
+ }
13
+ function describe(w) {
14
+ return `${w.index}:${w.branch} (${w.path})`;
15
+ }
16
+ /** A path token that selects `wtPath` from `cwd` (relative, `./`-prefixed when below cwd). */
17
+ function pathHint(wtPath, cwd) {
18
+ const rel = path.relative(realOrResolved(cwd), wtPath);
19
+ if (rel === "")
20
+ return ".";
21
+ if (path.isAbsolute(rel))
22
+ return rel;
23
+ return rel.startsWith("..") ? rel : `./${rel}`;
24
+ }
25
+ /** `p` with symlinks resolved, when it exists (git records worktree paths resolved). */
26
+ function realOrResolved(p) {
27
+ try {
28
+ return fs.realpathSync.native(p);
29
+ }
30
+ catch {
31
+ return path.resolve(p);
32
+ }
33
+ }
34
+ /** The worktree whose directory contains `cwd` (deepest match wins). */
35
+ function containing(worktrees, cwd) {
36
+ const dirs = [path.resolve(cwd), realOrResolved(cwd)];
37
+ const matches = worktrees.filter((w) => dirs.some((d) => isWithin(w.path, d)));
38
+ matches.sort((a, b) => b.path.length - a.path.length);
39
+ return matches[0] ?? null;
40
+ }
41
+ function matchToken(worktrees, token, cwd) {
42
+ const raw = String(token).trim();
43
+ if (raw === ".") {
44
+ const wt = containing(worktrees, cwd);
45
+ if (!wt) {
46
+ throw new Error(`"." does not refer to a linked worktree (cwd: ${cwd}). Available worktrees: ${available(worktrees)}.`);
47
+ }
48
+ return wt;
49
+ }
50
+ // A JSON number (MCP) is always an index — callers can force one.
51
+ if (typeof token === "number") {
52
+ const byIndex = worktrees.find((w) => w.index === token);
53
+ if (byIndex)
54
+ return byIndex;
55
+ throw new Error(`Worktree "${raw}" not found. Available worktrees: ${available(worktrees)}.`);
56
+ }
57
+ const abs = path.resolve(cwd, raw);
58
+ const matches = new Set();
59
+ for (const w of worktrees) {
60
+ // Paths compare through symlinks (macOS /tmp, a symlinked ~/code…):
61
+ // git records the resolved path.
62
+ if (w.branch === raw || path.basename(w.path) === raw || samePath(w.path, abs)) {
63
+ matches.add(w);
64
+ }
65
+ }
66
+ // A numeric string is an index unless it also names a *different*
67
+ // worktree (a branch or directory called "1"): then it is ambiguous
68
+ // rather than silently shadowing that worktree. Passing the index again
69
+ // cannot resolve that clash, so point at names and paths instead.
70
+ if (/^\d+$/.test(raw)) {
71
+ const byIndex = worktrees.find((w) => w.index === Number(raw));
72
+ if (byIndex) {
73
+ const others = [...matches].filter((w) => w !== byIndex);
74
+ if (others.length === 0)
75
+ return byIndex;
76
+ throw new Error(`Worktree "${raw}" is ambiguous: index ${raw} is ${describe(byIndex)}, but "${raw}" also names ${others
77
+ .map(describe)
78
+ .join(", ")}. Pass the branch, the directory name, or a path such as ${pathHint(others[0].path, cwd)} of the worktree you mean.`);
79
+ }
80
+ }
81
+ if (matches.size === 1)
82
+ return [...matches][0];
83
+ if (matches.size > 1) {
84
+ throw new Error(`Worktree "${raw}" is ambiguous: matches ${[...matches]
85
+ .map(describe)
86
+ .join(", ")}. Use the index instead.`);
87
+ }
88
+ throw new Error(`Worktree "${raw}" not found. Available worktrees: ${available(worktrees)}.`);
89
+ }
90
+ /**
91
+ * Resolve selectors to worktrees, preserving request order and dropping
92
+ * duplicates. Each token may be a persistent index (`2`), a branch name
93
+ * (`feat-a`), a directory basename (`myapp-feat-a`), a path, or `.` (the
94
+ * worktree containing `cwd`). An empty selection means every live worktree.
95
+ */
96
+ export function selectWorktrees(worktrees, selectors, cwd = process.cwd()) {
97
+ if (!selectors || selectors.length === 0)
98
+ return worktrees;
99
+ const out = [];
100
+ for (const token of selectors) {
101
+ const wt = matchToken(worktrees, token, cwd);
102
+ if (!out.includes(wt))
103
+ out.push(wt);
104
+ }
105
+ return out;
106
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The agent skill shipped with the package. Resolved relative to this module:
3
+ * `dist/skill.js` → `<package>/SKILL.md` (and `src/skill.ts` → repo root in
4
+ * development), so it works from any install location.
5
+ */
6
+ export declare const SKILL_PATH: string;
7
+ export declare const SKILL_DIR_NAME = "worktree-compose";
8
+ export declare function readSkill(): string;
9
+ /**
10
+ * Write SKILL.md to `<dir>/worktree-compose/SKILL.md` (default dir:
11
+ * `~/.claude/skills`), creating directories. Returns the written path.
12
+ */
13
+ export declare function installSkill(dir?: string): string;
package/dist/skill.js ADDED
@@ -0,0 +1,28 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ /**
6
+ * The agent skill shipped with the package. Resolved relative to this module:
7
+ * `dist/skill.js` → `<package>/SKILL.md` (and `src/skill.ts` → repo root in
8
+ * development), so it works from any install location.
9
+ */
10
+ export const SKILL_PATH = fileURLToPath(new URL("../SKILL.md", import.meta.url));
11
+ export const SKILL_DIR_NAME = "worktree-compose";
12
+ export function readSkill() {
13
+ if (!fs.existsSync(SKILL_PATH)) {
14
+ throw new Error(`Bundled SKILL.md not found at ${SKILL_PATH}.`);
15
+ }
16
+ return fs.readFileSync(SKILL_PATH, "utf-8");
17
+ }
18
+ /**
19
+ * Write SKILL.md to `<dir>/worktree-compose/SKILL.md` (default dir:
20
+ * `~/.claude/skills`), creating directories. Returns the written path.
21
+ */
22
+ export function installSkill(dir) {
23
+ const base = dir ? path.resolve(dir) : path.join(os.homedir(), ".claude", "skills");
24
+ const dest = path.join(base, SKILL_DIR_NAME, "SKILL.md");
25
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
26
+ fs.writeFileSync(dest, readSkill(), "utf-8");
27
+ return dest;
28
+ }
@@ -0,0 +1,194 @@
1
+ import type { WorktreeInfo } from "../git/worktree.js";
2
+ /**
3
+ * Persistent worktree identity. Each worktree's index (which drives its ports)
4
+ * and compose project name are assigned once, at first sight, and stored in
5
+ * `<git common dir>/wtc/state.json`. Deriving them from the position in
6
+ * `git worktree list` (≤0.2) meant removing worktree #1 renamed #2 → #1, so
7
+ * its running stack was orphaned and a second stack started on new ports.
8
+ * The file lives inside `.git`: never committed, shared by every worktree.
9
+ *
10
+ * A record is tied to its worktree by its path and by a random id kept in
11
+ * the worktree's git admin dir (`.git/worktrees/<name>/wtc-id`):
12
+ * `git worktree move` keeps the admin dir (same id, so the record follows
13
+ * the worktree), while `git worktree remove` deletes it (so a new worktree
14
+ * created at a reused path is a new worktree, not the old one's heir).
15
+ *
16
+ * Records whose worktree is gone (orphans) are never released implicitly:
17
+ * a stack may still hold their ports on a daemon this process cannot see.
18
+ * Only `wtc prune` / `wtc clean` tear them down and forget them. A worktree
19
+ * git still lists is never gone, even when wtc cannot manage it: a locked
20
+ * one whose checkout is missing (an unmounted drive), or one that became
21
+ * the main checkout. Their records are *unavailable*, not orphaned.
22
+ */
23
+ export interface WorktreeRecord {
24
+ path: string;
25
+ index: number;
26
+ project: string;
27
+ branch: string;
28
+ createdAt: string;
29
+ /** Stable worktree id (also stored as `wtc-id` in the worktree's git admin dir). */
30
+ id?: string;
31
+ /** Repo-relative (`/`-separated) env files wtc wrote into the worktree. */
32
+ envFiles?: string[];
33
+ }
34
+ export interface ResolvedWorktree extends WorktreeInfo {
35
+ index: number;
36
+ project: string;
37
+ /** Stable id, when the worktree's admin dir holds one. */
38
+ id?: string;
39
+ /** Env files wtc wrote into the worktree (see WorktreeRecord). */
40
+ envFiles?: string[];
41
+ }
42
+ export interface StateFile {
43
+ version: 1;
44
+ worktrees: WorktreeRecord[];
45
+ /**
46
+ * Projects of records wtc forgot (pruned or cleaned), for diagnosis. Never
47
+ * used to claim a leftover as this repository's: another clone with the
48
+ * same directory name can reuse the very same project name.
49
+ */
50
+ retired?: string[];
51
+ /**
52
+ * The main checkout, recorded in layouts where git cannot locate it from
53
+ * every worktree (see RepoInfo.recordMain).
54
+ */
55
+ mainCheckout?: string;
56
+ }
57
+ export declare const STATE_VERSION = 1;
58
+ export declare function stateDir(commonDir: string): string;
59
+ export declare function stateFile(commonDir: string): string;
60
+ /**
61
+ * Run `fn` holding an exclusive lock on the registry. The CLI and the MCP
62
+ * server (or two agents) may reconcile at the same moment; without the lock
63
+ * both could hand out the same index. `fn` must never call a container
64
+ * engine — a slow daemon would hold every other wtc process up.
65
+ *
66
+ * The lock holds `<pid>:<random token>`; on release it is removed only if
67
+ * it still holds our token, so a holder never deletes another's lock.
68
+ */
69
+ export declare function withStateLock<T>(commonDir: string, fn: () => T, opts?: {
70
+ timeoutMs?: number;
71
+ }): T;
72
+ /** Thrown for a state file written by a newer wtc: never discard it. */
73
+ export declare class NewerStateError extends Error {
74
+ constructor(file: string, version: number);
75
+ }
76
+ /**
77
+ * Read the registry without side effects: `null` when there is none or it
78
+ * is unreadable. Throws NewerStateError for a newer format.
79
+ */
80
+ export declare function peekState(commonDir: string): StateFile | null;
81
+ /**
82
+ * Read the registry. A corrupt file is moved aside as
83
+ * `state.json.bak-<epoch>` (never silently overwritten) and replaced by an
84
+ * empty registry, with a warning; malformed records are dropped after a
85
+ * backup copy. With `readOnly`, nothing is moved or copied — the problem is
86
+ * only reported. A file from a newer wtc is never touched: NewerStateError.
87
+ */
88
+ export declare function readState(commonDir: string, warnings?: string[], opts?: {
89
+ readOnly?: boolean;
90
+ }): StateFile;
91
+ /** Atomic write: temp file in the same directory, then rename over the target. */
92
+ export declare function writeState(commonDir: string, state: StateFile): void;
93
+ /** The stable id stored in a worktree's admin dir, if it has one yet. */
94
+ export declare function readWorktreeId(adminDir: string | undefined): string | undefined;
95
+ /** A running stack a worktree without a record may adopt (see ReconcileOptions.adoptable). */
96
+ export interface AdoptableStack {
97
+ index: number;
98
+ project: string;
99
+ }
100
+ export interface ReconcileOptions {
101
+ commonDir: string;
102
+ repoName: string;
103
+ /**
104
+ * Lists the worktrees in `git worktree list` order (main/bare/prunable
105
+ * entries included; prunable ones count for legacy positions but are
106
+ * never live). Called *inside* the lock, so the worktree set and the
107
+ * registry are read at the same moment: a worktree another process
108
+ * registered meanwhile is never mistaken for an orphan.
109
+ */
110
+ listWorktrees: () => WorktreeInfo[];
111
+ /**
112
+ * Identities of running stacks, keyed by the (resolved) path of the live
113
+ * worktree that is their compose working_dir. A worktree without a
114
+ * record adopts its stack's index and project when that index is free.
115
+ * Computed by the caller *before* reconciling — container calls never run
116
+ * under the lock. `undefined` means no stack probe was available: an
117
+ * empty registry is then not persisted (positional identities are only
118
+ * computed), so the next engine-aware command can adopt running stacks.
119
+ */
120
+ adoptable?: Map<string, AdoptableStack>;
121
+ /**
122
+ * Compute identities without side effects: no lock, no state write, no
123
+ * `wtc-id` created, and a corrupt file is reported rather than moved aside.
124
+ */
125
+ readOnly?: boolean;
126
+ /** Record this path as the main checkout when the registry is written (RepoInfo.recordMain). */
127
+ mainCheckout?: string;
128
+ now?: () => Date;
129
+ }
130
+ /** The record of a worktree git still lists but wtc cannot manage. */
131
+ export interface UnavailableRecord extends WorktreeRecord {
132
+ /**
133
+ * `missing`: locked, and its checkout is missing on disk (an unmounted
134
+ * drive). `main`: it is now the main checkout (bare layouts).
135
+ */
136
+ reason: "missing" | "main";
137
+ }
138
+ export interface ReconcileResult {
139
+ /** Live worktrees, in git order, with their persistent index and project. */
140
+ worktrees: ResolvedWorktree[];
141
+ /** Records whose worktree is gone; their index stays reserved until prune/clean. */
142
+ orphans: WorktreeRecord[];
143
+ /**
144
+ * Records of worktrees git still lists but wtc cannot start (see
145
+ * UnavailableRecord): kept with their index and stack, never orphans —
146
+ * prune and clean leave them alone.
147
+ */
148
+ unavailable: UnavailableRecord[];
149
+ warnings: string[];
150
+ /** The worktree listing the result was computed from. */
151
+ listed: WorktreeInfo[];
152
+ }
153
+ /**
154
+ * Match live worktrees to their records, assigning new identities as needed.
155
+ *
156
+ * - Records match by path, then by stable id: a moved worktree keeps its
157
+ * index and project (the stored path is updated); a new worktree at a
158
+ * reused path does not inherit the old one's (see isRecordOf).
159
+ * - Records with no live worktree are orphans. They keep their index — their
160
+ * stack may still hold its ports — until `wtc prune` / `wtc clean`.
161
+ * - A worktree without a record adopts a running stack's identity
162
+ * (`adoptable`) when its index is free. Otherwise an empty registry
163
+ * (fresh install, 0.2 upgrade, corrupt file) assigns positional indices
164
+ * in `git worktree list` order — exactly the old naming, so 0.2 stacks are
165
+ * adopted, not duplicated — and a non-empty one the lowest index no
166
+ * record (live or orphaned) holds.
167
+ */
168
+ export declare function reconcileWorktrees(opts: ReconcileOptions): ReconcileResult;
169
+ /**
170
+ * True when a record's worktree still exists in `listed` (same identity
171
+ * rules as reconcile): any linked worktree git still lists counts —
172
+ * including a locked one missing on disk and one marked main — not only
173
+ * those wtc can start. Clean and prune re-check this right before tearing
174
+ * an orphan down: another process may have registered or moved its
175
+ * worktree since, and `down -v` must never hit a worktree that exists.
176
+ */
177
+ export declare function recordIsLive(record: WorktreeRecord, listed: WorktreeInfo[]): boolean;
178
+ /** True when the live worktree `wt` already has a record in `state`. */
179
+ export declare function hasRecord(state: StateFile | null, wt: WorktreeInfo): boolean;
180
+ /**
181
+ * Drop records by compose project (unique per record) — used by clean and
182
+ * prune after teardown. Keyed by project, not path: a reused path can hold
183
+ * both an orphan's record and a new worktree's. An unreadable registry is
184
+ * left alone rather than moved aside.
185
+ */
186
+ export declare function forgetRecords(commonDir: string, projects: string[]): void;
187
+ /**
188
+ * Remember env files wtc wrote into the worktree at `wtPath` (absolute, or
189
+ * relative to the worktree), merged with — and deduplicated against — those
190
+ * already recorded. Stored repo-relative with `/` separators. Clean treats
191
+ * exactly these as wtc's own changes, so they never make a worktree dirty.
192
+ * A worktree without a record (registry not persisted yet) is skipped.
193
+ */
194
+ export declare function recordEnvFiles(commonDir: string, wtPath: string, files: string[]): void;