agentlane 0.0.0 → 0.4.0-rc.2

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 (146) hide show
  1. package/CHANGELOG.md +118 -0
  2. package/LICENSE +27 -0
  3. package/README.md +167 -2
  4. package/dist/agents/claude-plugin.js +79 -0
  5. package/dist/agents/cli.js +258 -0
  6. package/dist/agents/detect.js +88 -0
  7. package/dist/agents/init.js +251 -0
  8. package/dist/agents/launcher.js +32 -0
  9. package/dist/agents/package.js +119 -0
  10. package/dist/agents/skills.js +59 -0
  11. package/dist/agents/toml.js +325 -0
  12. package/dist/agents/wiring-check.js +117 -0
  13. package/dist/agents/wiring.js +374 -0
  14. package/dist/bench/host.js +104 -0
  15. package/dist/bench/live.js +511 -0
  16. package/dist/bench/mcp-client.js +91 -0
  17. package/dist/bench/model.js +15 -0
  18. package/dist/bench/report.js +162 -0
  19. package/dist/bench/run.js +121 -0
  20. package/dist/bench/schedule.js +140 -0
  21. package/dist/bench/stats.js +59 -0
  22. package/dist/bench-cli.js +167 -0
  23. package/dist/browser/aria.js +184 -0
  24. package/dist/browser/control.js +203 -0
  25. package/dist/browser/env.js +118 -0
  26. package/dist/browser/evidence.js +44 -0
  27. package/dist/browser/install.js +361 -0
  28. package/dist/browser/kinds.js +10 -0
  29. package/dist/browser/lane-browser.js +224 -0
  30. package/dist/browser/libraries.js +56 -0
  31. package/dist/browser/paths.js +29 -0
  32. package/dist/browser/release.js +121 -0
  33. package/dist/browser/screen.js +19 -0
  34. package/dist/browser/signin.js +154 -0
  35. package/dist/browser/stop.js +163 -0
  36. package/dist/browser/tools.js +25 -0
  37. package/dist/cache/build.js +154 -0
  38. package/dist/cache/config.js +186 -0
  39. package/dist/cache/index.js +4 -0
  40. package/dist/cache/key.js +196 -0
  41. package/dist/cache/store.js +303 -0
  42. package/dist/cli.js +178 -0
  43. package/dist/clock.js +4 -0
  44. package/dist/devices/adb.js +160 -0
  45. package/dist/devices/android.js +214 -0
  46. package/dist/devices/backend.js +7 -0
  47. package/dist/devices/bundler.js +46 -0
  48. package/dist/devices/common.js +51 -0
  49. package/dist/devices/controls.js +65 -0
  50. package/dist/devices/dial.js +56 -0
  51. package/dist/devices/emulator.js +396 -0
  52. package/dist/devices/hygiene.js +202 -0
  53. package/dist/devices/index.js +5 -0
  54. package/dist/devices/launch.js +76 -0
  55. package/dist/devices/simctl.js +119 -0
  56. package/dist/devices/tools.js +1 -0
  57. package/dist/devices/variant.js +99 -0
  58. package/dist/devices/xcrun.js +265 -0
  59. package/dist/driver/absence.js +54 -0
  60. package/dist/driver/caller.js +51 -0
  61. package/dist/driver/client.js +312 -0
  62. package/dist/driver/diff.js +180 -0
  63. package/dist/driver/elements.js +70 -0
  64. package/dist/driver/engine-main.js +13 -0
  65. package/dist/driver/engine.js +499 -0
  66. package/dist/driver/errors.js +11 -0
  67. package/dist/driver/exec.js +66 -0
  68. package/dist/driver/failure.js +156 -0
  69. package/dist/driver/flow.js +94 -0
  70. package/dist/driver/idle.js +100 -0
  71. package/dist/driver/images.js +68 -0
  72. package/dist/driver/install.js +272 -0
  73. package/dist/driver/lock.js +101 -0
  74. package/dist/driver/look.js +223 -0
  75. package/dist/driver/maestro-child.js +194 -0
  76. package/dist/driver/maestro-runs.js +46 -0
  77. package/dist/driver/paths.js +105 -0
  78. package/dist/driver/pixels.js +144 -0
  79. package/dist/driver/plan.js +108 -0
  80. package/dist/driver/release.js +7 -0
  81. package/dist/driver/runner.js +42 -0
  82. package/dist/driver/selector.js +91 -0
  83. package/dist/driver/session.js +474 -0
  84. package/dist/driver/suggest.js +86 -0
  85. package/dist/driver/supervisor.js +251 -0
  86. package/dist/driver/tree.js +426 -0
  87. package/dist/driver-cli.js +865 -0
  88. package/dist/evidence/device.js +177 -0
  89. package/dist/evidence/evidence.js +304 -0
  90. package/dist/evidence/files.js +92 -0
  91. package/dist/hooks/env.js +81 -0
  92. package/dist/hooks/run.js +101 -0
  93. package/dist/mcp/server.js +69 -0
  94. package/dist/mcp/tools.js +246 -0
  95. package/dist/name.js +22 -0
  96. package/dist/plugin/aims.js +465 -0
  97. package/dist/plugin/conventions.js +73 -0
  98. package/dist/plugin/guard.js +163 -0
  99. package/dist/plugin/hook-cli.js +216 -0
  100. package/dist/plugin/session-name.js +28 -0
  101. package/dist/plugin/shell.js +254 -0
  102. package/dist/processes.js +77 -0
  103. package/dist/project/config.js +316 -0
  104. package/dist/project/schema.js +335 -0
  105. package/dist/project/validate.js +224 -0
  106. package/dist/registry/config.js +142 -0
  107. package/dist/registry/format.js +22 -0
  108. package/dist/registry/owner.js +265 -0
  109. package/dist/registry/paths.js +50 -0
  110. package/dist/registry/ports.js +26 -0
  111. package/dist/registry/prune.js +160 -0
  112. package/dist/registry/refusal.js +53 -0
  113. package/dist/registry/registry.js +1027 -0
  114. package/dist/registry/resources.js +117 -0
  115. package/dist/registry/rows.js +115 -0
  116. package/dist/registry/status.js +85 -0
  117. package/dist/registry/store.js +274 -0
  118. package/dist/registry/types.js +1 -0
  119. package/dist/registry-cli.js +544 -0
  120. package/dist/services/services.js +268 -0
  121. package/dist/services/system.js +189 -0
  122. package/dist/up/deps.js +1 -0
  123. package/dist/up/doctor.js +424 -0
  124. package/dist/up/exec.js +133 -0
  125. package/dist/up/lane-files.js +75 -0
  126. package/dist/up/lane-services.js +38 -0
  127. package/dist/up/maestro-env.js +172 -0
  128. package/dist/up/preflight.js +232 -0
  129. package/dist/up/release.js +148 -0
  130. package/dist/up/resources.js +178 -0
  131. package/dist/up/restart.js +87 -0
  132. package/dist/up/setup.js +28 -0
  133. package/dist/up/up.js +610 -0
  134. package/dist/up-cli.js +258 -0
  135. package/dist/usage.js +16 -0
  136. package/package.json +58 -3
  137. package/schema/agentlane.schema.json +675 -0
  138. package/skills/create-verification-skill/LICENSE +21 -0
  139. package/skills/create-verification-skill/SKILL.md +88 -0
  140. package/skills/dev-loop/LICENSE +21 -0
  141. package/skills/dev-loop/SKILL.md +61 -0
  142. package/skills/device/SKILL.md +8 -0
  143. package/skills/drive/SKILL.md +64 -0
  144. package/skills/maintain-verification-skill/LICENSE +21 -0
  145. package/skills/maintain-verification-skill/SKILL.md +42 -0
  146. package/skills/setup/SKILL.md +80 -0
@@ -0,0 +1,544 @@
1
+ import { stopEndedBrowsers } from "./browser/lane-browser.js";
2
+ import { realBrowserTools } from "./browser/tools.js";
3
+ import { spawnSync } from 'node:child_process';
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { parseArgs } from 'node:util';
7
+ import { DeviceBackendError } from "./devices/backend.js";
8
+ import { laneVariables } from "./hooks/env.js";
9
+ import { CLI, TOOL } from "./name.js";
10
+ import { describeStart } from "./processes.js";
11
+ import { formatAge, formatTime, shellQuote } from "./registry/format.js";
12
+ import { DEVICE_MEMORY_MB } from "./registry/config.js";
13
+ import { describeOwner, describeState, isProven, ownerKey, resolveOwner } from "./registry/owner.js";
14
+ import { databasePath, stateDir } from "./registry/paths.js";
15
+ import { describePruneResult, listPrunable, renderPruneListing } from "./registry/prune.js";
16
+ import { NotClaimed, Refusal, UsageError } from "./registry/refusal.js";
17
+ import { readRegistryStatus, Registry } from "./registry/registry.js";
18
+ import { realServiceSystem } from "./services/system.js";
19
+ import { pruneEndedLaneFiles } from "./up/lane-files.js";
20
+ import { stopEndedLanes, tearDownLane } from "./up/release.js";
21
+ import { tearDownEndedResources } from "./up/resources.js";
22
+ import { systemClock } from "./clock.js";
23
+ import { claudeSessionName } from "./plugin/session-name.js";
24
+ import { groupUsage, helpOf } from "./usage.js";
25
+ export const REGISTRY_COMMANDS = ['claim', 'release', 'status', 'lanes', 'touch', 'prune'];
26
+ export const REGISTRY_HELP = {
27
+ title: 'Lanes:',
28
+ entries: {
29
+ claim: ` claim Claim a lane for this session and folder: ports, and a pool simulator or emulator.
30
+ Prints shell exports on stdout: eval "$(${TOOL} claim)".
31
+ --services <list> comma-separated name[:type]; default metro,api,web; 'none' for no ports
32
+ --no-device claim ports only
33
+ --platform <name> ios (default) or android; an Android lane always boots its emulator
34
+ --device-type <name> default: the newest iPhone the runtime supports; on Android, pixel_8
35
+ --runtime <name> default: the newest installed iOS runtime; on Android, the newest
36
+ installed Google APIs system image for this Mac's CPU
37
+ --strict take only the exact device type and runtime; without it, a full pool
38
+ hands over a free device of another type
39
+ --boot boot the simulator and wait until it is ready
40
+ --timeout <seconds> how long to queue when the pool is full (default 600; 0 = don't wait)
41
+ --worktree <dir> the folder the lane is for (default: this git worktree)
42
+ --json print the lane as JSON instead of exports
43
+ `,
44
+ release: ` release Release this session's lane for this folder: stop the services up started
45
+ (each verified by pid and start time), clear the bundler pin, run the teardown hook,
46
+ then each resource's teardown. A teardown that fails is kept, and the next release
47
+ or reap on this Mac tries it again.
48
+ release <id> releases a lane by id: yours, or one whose owner is proven gone. For a
49
+ lane that has ended, it runs the teardowns still pending for it.
50
+ --worktree <dir> the folder whose lane to release (default: this git worktree)
51
+ --lane <id> the same as release <id>
52
+ --force with an id: release it even if its owner is alive or can't be judged;
53
+ for an ended lane, drop the record of a teardown that fails again
54
+ `,
55
+ status: ` status Every lane on this Mac: owner, folder, start, idle time, last action.
56
+ `,
57
+ lanes: ` lanes --json: the same as status, as JSON for tools.
58
+ `,
59
+ touch: ` touch Record activity on this session's lane (--action <text>).
60
+ `,
61
+ prune: ` prune List the pool simulators and emulators no lane holds, 0.2.x's included; --yes
62
+ deletes them to free their disk. Each deletion takes the registry's lock and checks
63
+ again that no lane holds the device, so one claimed meanwhile is kept. A device the
64
+ registry has no record of is never deleted, even one named like a pool device.
65
+ --yes delete them; without it, prune only lists
66
+ --json print the listing, and with --yes each result, as JSON
67
+ `,
68
+ },
69
+ };
70
+ export const REGISTRY_USAGE = groupUsage(REGISTRY_HELP);
71
+ const EXIT_REFUSED = 3;
72
+ const EXIT_USAGE = 2;
73
+ function git(dir, args) {
74
+ const result = spawnSync('git', ['-C', dir, ...args], { encoding: 'utf8' });
75
+ return result.status === 0 ? result.stdout.trim() : null;
76
+ }
77
+ export function resolveFolder(start) {
78
+ let dir;
79
+ try {
80
+ dir = fs.realpathSync(start);
81
+ }
82
+ catch {
83
+ throw new UsageError(`${start} does not exist`, 'pass --worktree with an existing folder');
84
+ }
85
+ const top = git(dir, ['rev-parse', '--show-toplevel']);
86
+ const worktree = top ? fs.realpathSync(top) : dir;
87
+ const common = git(dir, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
88
+ if (!common)
89
+ return { worktree, projectRoot: worktree };
90
+ const real = fs.realpathSync(common);
91
+ return { worktree, projectRoot: path.basename(real) === '.git' ? path.dirname(real) : real };
92
+ }
93
+ function parseServices(raw) {
94
+ if (raw.trim() === 'none')
95
+ return [];
96
+ return raw
97
+ .split(',')
98
+ .map(s => s.trim())
99
+ .filter(s => s !== '')
100
+ .map(entry => {
101
+ const [name = '', type = name] = entry.split(':');
102
+ if (!/^[a-z][a-z0-9-]*$/.test(name) || !/^[a-z][a-z0-9-]*$/.test(type)) {
103
+ throw new UsageError(`'${entry}' is not a service`, 'write services as name[:type], e.g. --services metro,api,admin:web');
104
+ }
105
+ return { name, type };
106
+ });
107
+ }
108
+ function parseSeconds(raw, flag) {
109
+ const seconds = Number(raw);
110
+ if (!Number.isFinite(seconds) || seconds < 0)
111
+ throw new UsageError(`${flag} ${raw} is not a number of seconds`, `pass ${flag} 600`);
112
+ return seconds * 1000;
113
+ }
114
+ export function laneEnv(lane) {
115
+ return laneVariables(lane, null, null);
116
+ }
117
+ function describeEnded(e, now) {
118
+ const where = `${e.owner} in ${e.worktree}`;
119
+ switch (e.reason) {
120
+ case 'taken-over':
121
+ return `took over idle lane ${e.id} of ${where}: last used ${formatTime(e.lastUsedAt)} (${formatAge(now - e.lastUsedAt)} ago, ${e.lastAction})`;
122
+ case 'released':
123
+ case 'forced':
124
+ return `${e.reason} lane ${e.id} of ${where}`;
125
+ default:
126
+ return `freed lane ${e.id} of ${where}: ${describeState(e.reason)}`;
127
+ }
128
+ }
129
+ function describeLane(lane) {
130
+ const parts = [];
131
+ if (lane.device)
132
+ parts.push(`${lane.device.name} (${lane.device.deviceTypeName}, ${lane.device.runtimeName}, ${lane.device.serial ?? lane.device.id})`);
133
+ if (lane.browser)
134
+ parts.push(`a ${lane.browser.driver} browser (session ${lane.browser.session})`);
135
+ if (lane.ports.length > 0)
136
+ parts.push(`ports ${lane.ports.map(p => `${p.service} ${String(p.port)}`).join(', ')}`);
137
+ return parts.join('; ') || 'nothing';
138
+ }
139
+ function renderOutcome(outcome, now, deps, json) {
140
+ const { lane } = outcome;
141
+ if (json) {
142
+ deps.stdout(`${JSON.stringify({ ...outcome, env: laneEnv(lane) }, null, 2)}\n`);
143
+ return;
144
+ }
145
+ for (const e of outcome.freed)
146
+ deps.stderr(`${TOOL}: ${describeEnded(e, now)}\n`);
147
+ for (const e of outcome.tookOver)
148
+ deps.stderr(`${TOOL}: ${describeEnded(e, now)}\n`);
149
+ for (const note of outcome.notes)
150
+ deps.stderr(`${TOOL}: ${note}\n`);
151
+ const verb = outcome.created ? 'claimed lane' : 'reusing lane';
152
+ deps.stderr(`${TOOL}: ${verb} ${lane.id} for ${describeOwner(lane.owner)} in ${lane.worktree}: ${describeLane(lane)}\n`);
153
+ for (const [key, value] of Object.entries(laneEnv(lane)))
154
+ deps.stdout(`export ${key}=${shellQuote(value)}\n`);
155
+ }
156
+ function laneLines(c, sessionName) {
157
+ const state = c.ownerState === 'alive' ? 'alive' : describeState(c.ownerState).toUpperCase();
158
+ const name = sessionName(c);
159
+ const lines = [
160
+ ` ${c.id} ${describeOwner(c.owner)}${name ? ` "${name}"` : ''} [${state}]`,
161
+ ` folder ${c.worktree}${c.projectRoot !== c.worktree ? ` (project ${c.projectRoot})` : ''}`,
162
+ ` started ${formatTime(c.createdAt)} idle ${formatAge(c.idleMs)} last action: ${c.lastAction}`,
163
+ ];
164
+ if (c.device) {
165
+ lines.push(` device ${c.device.name} (${c.device.deviceTypeName}, ${c.device.runtimeName}) ${c.device.serial ?? c.device.id} ${c.deviceState ?? ''}`);
166
+ }
167
+ if (c.browser) {
168
+ lines.push(` browser ${c.browser.driver}, session ${c.browser.session}, debugging port ${String(c.browser.debugPort)}${c.browser.streamPort === null ? '' : `, stream port ${String(c.browser.streamPort)}`}`);
169
+ }
170
+ if (c.ports.length > 0)
171
+ lines.push(` ports ${c.ports.map(p => `${p.service} ${String(p.port)}`).join(', ')}`);
172
+ if (c.resources.length > 0) {
173
+ const shown = c.resources.map(r => r.exports === null
174
+ ? `${r.name} (create did not finish)`
175
+ : `${r.name}${Object.keys(r.exports).length > 0 ? ` (${Object.keys(r.exports).join(', ')})` : ''}`);
176
+ lines.push(` resources ${shown.join(', ')}`);
177
+ }
178
+ for (const p of c.processes)
179
+ lines.push(` process ${p.service} pid ${String(p.pid)} (started ${describeStart(p.start)})`);
180
+ if (c.ownerState === 'cant-tell')
181
+ lines.push(` left alone: its owner can't be judged; ${CLI} release --lane ${c.id} --force frees it`);
182
+ return lines;
183
+ }
184
+ function poolLine(report) {
185
+ const { config } = report;
186
+ const count = (platform) => report.pool.filter(d => d.platform === platform).length;
187
+ const claimed = report.lanes.flatMap(c => (c.device ? [c.device.platform] : []));
188
+ const used = claimed.reduce((sum, platform) => sum + DEVICE_MEMORY_MB[platform], 0);
189
+ return `${String(count('ios'))} of ${String(config.poolSize)} simulators, ${String(count('android'))} of ${String(config.emulatorPoolSize)} emulators; claimed devices use ${String(used / 1000)} of ${String(config.memoryBudgetMb / 1000)} GB`;
190
+ }
191
+ export function renderStatus(report, sessionName = () => null) {
192
+ const { config } = report;
193
+ const lines = [
194
+ `${TOOL} registry: ${report.stateDir}`,
195
+ `pool: ${poolLine(report)}; idle lanes are reclaimable after ${formatAge(config.idleMs)} when the pool is full`,
196
+ `ports: ${Object.entries(config.blocks)
197
+ .map(([type, b]) => `${type} ${String(b.first)}-${String(b.last)}`)
198
+ .join(', ')}`,
199
+ '',
200
+ ];
201
+ if (report.lanes.length === 0)
202
+ lines.push('no lanes');
203
+ else {
204
+ lines.push(`lanes (${String(report.lanes.length)}):`);
205
+ for (const c of report.lanes)
206
+ lines.push(...laneLines(c, sessionName));
207
+ }
208
+ if (report.queue.length > 0) {
209
+ lines.push('', 'queue:');
210
+ for (const q of report.queue)
211
+ lines.push(` ${String(q.ticket)} ${q.owner} in ${q.worktree}, waiting since ${formatTime(q.enqueuedAt)} (pid ${String(q.waiterPid)})`);
212
+ }
213
+ if (report.pool.length > 0) {
214
+ lines.push('', 'pool devices:');
215
+ for (const d of report.pool) {
216
+ lines.push(` ${d.name} ${d.deviceTypeName}, ${d.runtimeName} ${d.id ?? ''} ${d.laneId ? `lane ${d.laneId}` : 'free'} ${d.state}`);
217
+ }
218
+ }
219
+ if (report.teardowns.length > 0) {
220
+ lines.push('', `teardowns pending (${CLI} release <id> runs them now):`);
221
+ for (const t of report.teardowns) {
222
+ const tried = t.attempts === 0
223
+ ? 'not tried yet'
224
+ : `failed ${String(t.attempts)} time${t.attempts === 1 ? '' : 's'}, last at ${formatTime(t.lastAttemptAt ?? 0)}: ${t.problem ?? ''}`;
225
+ lines.push(` ${t.lane} resource ${t.name} of ${t.worktree}, created ${formatTime(t.createdAt)}; ${tried}`);
226
+ }
227
+ }
228
+ if (report.recent.length > 0) {
229
+ lines.push('', 'ended in the last day:');
230
+ for (const e of report.recent) {
231
+ lines.push(` ${formatTime(e.endedAt)} ${describeEnded(e, report.now)}${e.by === e.owner ? '' : ` (by ${e.by})`}`);
232
+ }
233
+ }
234
+ return `${lines.join('\n')}\n`;
235
+ }
236
+ function reportError(error, deps) {
237
+ if (error instanceof Refusal || error instanceof NotClaimed) {
238
+ deps.stderr(`${TOOL}: ${error.message}\n`);
239
+ return EXIT_REFUSED;
240
+ }
241
+ if (error instanceof UsageError) {
242
+ deps.stderr(`${TOOL}: ${error.message}\n`);
243
+ return EXIT_USAGE;
244
+ }
245
+ if (error instanceof DeviceBackendError) {
246
+ deps.stderr(`${TOOL}: ${error.message}\n`);
247
+ return 1;
248
+ }
249
+ throw error;
250
+ }
251
+ export async function runRegistryCommand(command, args, deps) {
252
+ try {
253
+ return await dispatch(command, args, deps);
254
+ }
255
+ catch (error) {
256
+ if (error instanceof TypeError && error.code?.startsWith('ERR_PARSE_ARGS')) {
257
+ deps.stderr(`${TOOL} ${command}: ${error.message}\n\n${helpOf(REGISTRY_HELP, command) ?? REGISTRY_USAGE}`);
258
+ return EXIT_USAGE;
259
+ }
260
+ return reportError(error, deps);
261
+ }
262
+ }
263
+ function open(deps) {
264
+ return Registry.open({
265
+ dir: stateDir(deps.env),
266
+ processes: deps.processes,
267
+ ports: deps.ports,
268
+ devices: deps.devices,
269
+ ...(deps.clock ? { clock: deps.clock } : {}),
270
+ ...(deps.pollMs !== undefined ? { pollMs: deps.pollMs } : {}),
271
+ });
272
+ }
273
+ function teardownDeps(deps) {
274
+ return {
275
+ env: deps.env,
276
+ sim: deps.sim ?? null,
277
+ system: deps.system ?? realServiceSystem,
278
+ clock: deps.clock ?? systemClock,
279
+ processes: deps.processes,
280
+ browser: deps.browser ?? realBrowserTools,
281
+ ...(deps.evidence ? { evidence: deps.evidence } : {}),
282
+ ...(deps.adb ? { adb: deps.adb } : {}),
283
+ };
284
+ }
285
+ async function tearDownTargets(deps, who, target) {
286
+ const dir = stateDir(deps.env);
287
+ const report = readRegistryStatus({
288
+ dir,
289
+ processes: deps.processes,
290
+ devices: deps.devices,
291
+ ...(deps.clock ? { clock: deps.clock } : {}),
292
+ });
293
+ const key = ownerKey(who);
294
+ const targets = report.lanes.filter(c => {
295
+ if (target.id !== null)
296
+ return c.id === target.id && (c.ownerKey === key || isProven(c.ownerState) || target.force);
297
+ return c.ownerKey === key && (target.folder === null || c.worktree === target.folder);
298
+ });
299
+ const teardowns = [];
300
+ for (const lane of targets)
301
+ teardowns.push(await tearDownLane(teardownDeps(deps), dir, lane));
302
+ return teardowns;
303
+ }
304
+ function merged(teardowns) {
305
+ const byLane = new Map();
306
+ for (const t of teardowns) {
307
+ const into = byLane.get(t.lane) ?? { lane: t.lane, notes: [], problems: [] };
308
+ into.notes.push(...t.notes);
309
+ into.problems.push(...t.problems);
310
+ byLane.set(t.lane, into);
311
+ }
312
+ return [...byLane.values()];
313
+ }
314
+ function printTeardowns(deps, teardowns, own) {
315
+ for (const t of teardowns) {
316
+ const which = own(t.lane) ? `lane ${t.lane}` : `ended lane ${t.lane}`;
317
+ for (const line of t.notes)
318
+ deps.stderr(`${TOOL}: ${which}: ${line}\n`);
319
+ for (const line of t.problems)
320
+ deps.stderr(`${TOOL}: ${which}: PROBLEM: ${line}\n`);
321
+ }
322
+ }
323
+ async function pendingRelease(deps, registry, target, json) {
324
+ const teardowns = await tearDownEndedResources(teardownDeps(deps), registry, stateDir(deps.env), {
325
+ ...(target.id !== null ? { lane: target.id } : {}),
326
+ force: target.force,
327
+ });
328
+ if (json)
329
+ deps.stdout(`${JSON.stringify({ released: [], notes: [], teardowns }, null, 2)}\n`);
330
+ else {
331
+ printTeardowns(deps, teardowns, () => true);
332
+ if (teardowns.length === 0) {
333
+ deps.stderr(`${TOOL}: lane ${target.id ?? ''} has ended, and another ${TOOL} run is tearing down its resources now\n`);
334
+ }
335
+ }
336
+ return teardowns.some(t => t.problems.length > 0 && !target.force) ? 1 : 0;
337
+ }
338
+ async function releaseLanes(deps, who, target, json) {
339
+ const teardowns = await tearDownTargets(deps, who, target);
340
+ const registry = open(deps);
341
+ const notes = [];
342
+ try {
343
+ if (target.id !== null && registry.pendingTeardowns().some(t => t.lane === target.id)) {
344
+ return await pendingRelease(deps, registry, target, json);
345
+ }
346
+ const ended = target.id !== null
347
+ ? [registry.releaseById(target.id, who, target.force, notes)]
348
+ : registry.releaseOwn(who, target.folder, notes);
349
+ const at = now(deps);
350
+ const released = new Set(ended.map(e => e.id));
351
+ const own = (lane) => released.has(lane);
352
+ const all = merged([
353
+ ...teardowns,
354
+ ...(await stopEndedBrowsers(teardownDeps(deps).browser, registry, stateDir(deps.env), teardownDeps(deps).clock)),
355
+ ...(await tearDownEndedResources(teardownDeps(deps), registry, stateDir(deps.env))),
356
+ ]);
357
+ const problems = all.filter(t => own(t.lane)).flatMap(t => t.problems);
358
+ if (json)
359
+ deps.stdout(`${JSON.stringify({ released: ended, notes, teardowns: all }, null, 2)}\n`);
360
+ else {
361
+ printTeardowns(deps, all, own);
362
+ for (const note of notes)
363
+ deps.stderr(`${TOOL}: ${note}\n`);
364
+ if (ended.length === 0)
365
+ deps.stderr(`${TOOL}: ${describeOwner(who)} holds no lane here; nothing to release\n`);
366
+ for (const e of ended)
367
+ deps.stderr(`${TOOL}: ${describeEnded(e, at)}\n`);
368
+ }
369
+ return problems.length > 0 ? 1 : 0;
370
+ }
371
+ finally {
372
+ registry.close();
373
+ }
374
+ }
375
+ export function releaseEveryLaneOf(deps, who) {
376
+ return releaseLanes(deps, who, { id: null, force: false, folder: null }, false);
377
+ }
378
+ function releaseId(positionals, flag) {
379
+ const [bare, ...extra] = positionals;
380
+ if (extra.length > 0)
381
+ throw new UsageError(`unexpected ${extra.join(' ')}`, `pass one lane id: ${CLI} release <id>`);
382
+ if (bare !== undefined && flag !== undefined && bare !== flag)
383
+ throw new UsageError(`release ${bare} and --lane ${flag} name two lanes`, `pass one: ${CLI} release <id>`);
384
+ return bare ?? flag ?? null;
385
+ }
386
+ function prune(deps, yes, json) {
387
+ const dir = stateDir(deps.env);
388
+ const registry = fs.existsSync(databasePath(dir)) ? open(deps) : null;
389
+ try {
390
+ const listing = registry ? registry.prunable() : listPrunable(null, dir, deps.devices);
391
+ if (!json)
392
+ deps.stdout(renderPruneListing(listing, yes));
393
+ const results = [];
394
+ if (yes && registry) {
395
+ for (const device of listing.free) {
396
+ const result = registry.pruneDevice(device);
397
+ results.push(result);
398
+ if (json)
399
+ continue;
400
+ if (result.outcome === 'failed')
401
+ deps.stderr(`${TOOL}: ${describePruneResult(result)}\n`);
402
+ else
403
+ deps.stdout(`${describePruneResult(result)}\n`);
404
+ }
405
+ }
406
+ if (json)
407
+ deps.stdout(`${JSON.stringify({ ...listing, ...(yes ? { results } : {}) }, null, 2)}\n`);
408
+ return results.some(r => r.outcome === 'failed') ? 1 : 0;
409
+ }
410
+ finally {
411
+ registry?.close();
412
+ }
413
+ }
414
+ function now(deps) {
415
+ return deps.clock ? deps.clock.now() : Date.now();
416
+ }
417
+ async function dispatch(command, args, deps) {
418
+ const owner = () => resolveOwner(deps.env, deps.processes, deps.selfPid);
419
+ switch (command) {
420
+ case 'claim': {
421
+ const { values } = parseArgs({
422
+ args,
423
+ strict: true,
424
+ options: {
425
+ services: { type: 'string', default: 'metro,api,web' },
426
+ 'no-device': { type: 'boolean', default: false },
427
+ platform: { type: 'string', default: 'ios' },
428
+ 'device-type': { type: 'string' },
429
+ runtime: { type: 'string' },
430
+ strict: { type: 'boolean', default: false },
431
+ boot: { type: 'boolean', default: false },
432
+ timeout: { type: 'string', default: '600' },
433
+ worktree: { type: 'string' },
434
+ json: { type: 'boolean', default: false },
435
+ },
436
+ });
437
+ if (values.platform !== 'ios' && values.platform !== 'android') {
438
+ throw new UsageError(`--platform ${values.platform} is not a platform`, 'pass --platform ios or --platform android');
439
+ }
440
+ const folder = resolveFolder(values.worktree ?? deps.cwd);
441
+ const who = owner();
442
+ const registry = open(deps);
443
+ const stop = deps.onCancel?.(() => registry.cancelPending());
444
+ try {
445
+ const outcome = await registry.claim({
446
+ owner: who,
447
+ worktree: folder.worktree,
448
+ projectRoot: folder.projectRoot,
449
+ services: parseServices(values.services),
450
+ device: values['no-device']
451
+ ? null
452
+ : {
453
+ platform: values.platform,
454
+ deviceType: values['device-type'],
455
+ runtime: values.runtime,
456
+ strict: values.strict,
457
+ },
458
+ waitMs: parseSeconds(values.timeout, '--timeout'),
459
+ boot: values.boot,
460
+ });
461
+ renderOutcome(outcome, now(deps), deps, values.json);
462
+ const state = stateDir(deps.env);
463
+ const stopped = [
464
+ ...(await stopEndedLanes(teardownDeps(deps), state, [...outcome.freed, ...outcome.tookOver])),
465
+ ...(await stopEndedBrowsers(teardownDeps(deps).browser, registry, state, teardownDeps(deps).clock)),
466
+ ...(await tearDownEndedResources(teardownDeps(deps), registry, state)),
467
+ ];
468
+ for (const t of stopped)
469
+ for (const line of [...t.notes, ...t.problems])
470
+ deps.stderr(`${TOOL}: lane ${t.lane}: ${line}\n`);
471
+ pruneEndedLaneFiles(state, new Set([...registry.status().lanes.map(c => c.id), ...registry.pendingTeardowns().map(t => t.lane)]), now(deps), deps.env);
472
+ return 0;
473
+ }
474
+ finally {
475
+ stop?.();
476
+ registry.close();
477
+ }
478
+ }
479
+ case 'release': {
480
+ const { values, positionals } = parseArgs({
481
+ args,
482
+ strict: true,
483
+ allowPositionals: true,
484
+ options: {
485
+ lane: { type: 'string' },
486
+ force: { type: 'boolean', default: false },
487
+ worktree: { type: 'string' },
488
+ json: { type: 'boolean', default: false },
489
+ },
490
+ });
491
+ const id = releaseId(positionals, values.lane);
492
+ if (values.force && id === null)
493
+ throw new UsageError('--force needs a lane id', `pass ${CLI} release <id> --force`);
494
+ const who = owner();
495
+ const folder = id === null ? resolveFolder(values.worktree ?? deps.cwd).worktree : null;
496
+ return releaseLanes(deps, who, { id, force: values.force, folder }, values.json);
497
+ }
498
+ case 'status':
499
+ case 'lanes': {
500
+ const { values } = parseArgs({ args, strict: true, options: { json: { type: 'boolean', default: false } } });
501
+ if (command === 'lanes' && !values.json) {
502
+ throw new UsageError(`'${CLI} lanes' is for tools`, `run '${CLI} lanes --json', or '${CLI} status' for people`);
503
+ }
504
+ const report = readRegistryStatus({
505
+ dir: stateDir(deps.env),
506
+ processes: deps.processes,
507
+ devices: deps.devices,
508
+ ...(deps.clock ? { clock: deps.clock } : {}),
509
+ });
510
+ const names = c => claudeSessionName(c.owner, deps.env);
511
+ deps.stdout(values.json
512
+ ? `${JSON.stringify({ version: 2, ...report, lanes: report.lanes.map(c => ({ ...c, sessionName: names(c) })) }, null, 2)}\n`
513
+ : renderStatus(report, names));
514
+ return 0;
515
+ }
516
+ case 'touch': {
517
+ const { values } = parseArgs({
518
+ args,
519
+ strict: true,
520
+ options: { action: { type: 'string', default: 'touch' }, worktree: { type: 'string' } },
521
+ });
522
+ const who = owner();
523
+ const registry = open(deps);
524
+ try {
525
+ const lane = registry.touchOwn(who, resolveFolder(values.worktree ?? deps.cwd).worktree, values.action);
526
+ deps.stderr(`${TOOL}: touched lane ${lane.id} (${lane.lastAction})\n`);
527
+ return 0;
528
+ }
529
+ finally {
530
+ registry.close();
531
+ }
532
+ }
533
+ case 'prune': {
534
+ const { values } = parseArgs({
535
+ args,
536
+ strict: true,
537
+ options: { yes: { type: 'boolean', default: false }, json: { type: 'boolean', default: false } },
538
+ });
539
+ return prune(deps, values.yes, values.json);
540
+ }
541
+ default:
542
+ throw new UsageError(`'${command}' is not a lanes command`, `run ${TOOL} --help`);
543
+ }
544
+ }