agentlane 0.4.1 → 0.5.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 (74) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/dist/agents/claude-plugin.js +54 -8
  3. package/dist/agents/cli.js +11 -4
  4. package/dist/agents/hook-check.js +290 -0
  5. package/dist/agents/launcher.js +34 -6
  6. package/dist/agents/wiring-check.js +10 -4
  7. package/dist/agents/wiring.js +6 -33
  8. package/dist/browser/env.js +27 -7
  9. package/dist/browser/install.js +144 -6
  10. package/dist/browser/lane-browser.js +6 -3
  11. package/dist/browser/stop.js +2 -17
  12. package/dist/cache/key.js +23 -11
  13. package/dist/cli.js +63 -23
  14. package/dist/devices/backend.js +6 -0
  15. package/dist/devices/emulator.js +15 -5
  16. package/dist/devices/simctl.js +15 -3
  17. package/dist/disk-limits.js +134 -0
  18. package/dist/driver/caller.js +21 -6
  19. package/dist/driver/client.js +9 -5
  20. package/dist/driver/engine.js +29 -14
  21. package/dist/driver/install.js +88 -36
  22. package/dist/driver/paths.js +15 -11
  23. package/dist/driver/session.js +4 -1
  24. package/dist/driver/superseded.js +378 -0
  25. package/dist/driver-cli.js +32 -23
  26. package/dist/evidence/device.js +4 -0
  27. package/dist/evidence/evidence.js +4 -2
  28. package/dist/evidence/files.js +68 -0
  29. package/dist/evidence/strays.js +107 -0
  30. package/dist/hooks/env.js +2 -1
  31. package/dist/mcp/server.js +15 -0
  32. package/dist/mcp/tools.js +9 -1
  33. package/dist/plugin/guard.js +30 -0
  34. package/dist/plugin/hook-cli.js +101 -6
  35. package/dist/plugin/hook-mark.js +73 -0
  36. package/dist/plugin/hook-once.js +78 -0
  37. package/dist/plugin/shell.js +109 -8
  38. package/dist/processes.js +52 -2
  39. package/dist/registry/config.js +12 -8
  40. package/dist/registry/holds.js +37 -0
  41. package/dist/registry/leases.js +109 -0
  42. package/dist/registry/owner-checks.js +55 -0
  43. package/dist/registry/owner.js +18 -0
  44. package/dist/registry/parks.js +60 -0
  45. package/dist/registry/paths.js +28 -4
  46. package/dist/registry/ports.js +5 -1
  47. package/dist/registry/prune.js +643 -24
  48. package/dist/registry/refusal.js +1 -0
  49. package/dist/registry/registry.js +1258 -235
  50. package/dist/registry/rows.js +18 -4
  51. package/dist/registry/status.js +51 -8
  52. package/dist/registry/store.js +63 -1
  53. package/dist/registry/touch.js +180 -0
  54. package/dist/registry-cli.js +197 -36
  55. package/dist/services/services.js +223 -54
  56. package/dist/services/system.js +2 -1
  57. package/dist/up/answers.js +124 -0
  58. package/dist/up/doctor.js +27 -3
  59. package/dist/up/exec.js +29 -4
  60. package/dist/up/lane-files.js +26 -8
  61. package/dist/up/lane-services.js +8 -3
  62. package/dist/up/park.js +146 -0
  63. package/dist/up/preflight.js +2 -10
  64. package/dist/up/release.js +20 -24
  65. package/dist/up/restart.js +9 -2
  66. package/dist/up/sweep.js +437 -0
  67. package/dist/up/up.js +33 -12
  68. package/dist/up/wake.js +124 -0
  69. package/dist/up/waker.js +49 -0
  70. package/dist/up-cli.js +6 -1
  71. package/package.json +2 -2
  72. package/skills/dev-loop/SKILL.md +7 -5
  73. package/skills/drive/SKILL.md +4 -0
  74. package/skills/setup/SKILL.md +2 -2
@@ -2,25 +2,29 @@ import { spawnSync } from 'node:child_process';
2
2
  import crypto from 'node:crypto';
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
+ import { envName } from "../name.js";
5
6
  import { diskNames, lanesRoot } from "../registry/paths.js";
6
7
  import { DriverError } from "./errors.js";
7
8
  import { isAlive } from "./exec.js";
8
9
  import { lockHolder } from "./lock.js";
9
10
  // sockaddr_un.sun_path holds 104 bytes on macOS and 108 on Linux, terminator included.
10
11
  export const SUN_PATH_LIMIT = 100;
12
+ export const USER_TEMP_ENV = envName('USER_TEMP');
11
13
  let cachedTemp;
14
+ function findPerUserTemp() {
15
+ const override = process.env[USER_TEMP_ENV];
16
+ if (override && path.isAbsolute(override))
17
+ return override;
18
+ if (process.platform !== 'darwin')
19
+ return '/tmp';
20
+ const result = spawnSync('getconf', ['DARWIN_USER_TEMP_DIR'], { encoding: 'utf8' });
21
+ const found = result.status === 0 ? result.stdout.trim() : '';
22
+ return found || '/tmp';
23
+ }
24
+ /** The folder for sockets whose path in the state dir would be too long: macOS's per-user temp folder, or /tmp. */
12
25
  export function perUserTemp() {
13
- if (cachedTemp !== undefined)
14
- return cachedTemp;
15
- let dir = '/tmp';
16
- if (process.platform === 'darwin') {
17
- const result = spawnSync('getconf', ['DARWIN_USER_TEMP_DIR'], { encoding: 'utf8' });
18
- const found = result.status === 0 ? result.stdout.trim() : '';
19
- if (found)
20
- dir = found;
21
- }
22
- cachedTemp = dir;
23
- return dir;
26
+ cachedTemp ??= findPerUserTemp();
27
+ return cachedTemp;
24
28
  }
25
29
  export function ensurePrivateDir(dir) {
26
30
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
@@ -1,5 +1,6 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import { keepNewestLinesAsSoleWriter } from "../disk-limits.js";
3
4
  import { checkAbsent, readIn, treeBound } from "./absence.js";
4
5
  import { diffScreens, renderDiff, volatileBetween } from "./diff.js";
5
6
  import { messageOf } from "./errors.js";
@@ -16,6 +17,7 @@ import { parseInspectScreen } from "./tree.js";
16
17
  export const PIXEL_CHECK_WIDTH = 200;
17
18
  const VOLATILE_TTL_MS = 5 * 60_000;
18
19
  const RECENT_READ_MS = 5000;
20
+ export const RECORDED_STEPS_LIMIT = { maxBytes: 1024 * 1024, keepBytes: 512 * 1024 };
19
21
  const RESPAWN_NOTE = "Maestro's session was rebuilt for this call";
20
22
  /** Turns a `run` reply into its error text: per-flow errors from a file run, the plain message from inline YAML. */
21
23
  export function flowError(reply) {
@@ -337,7 +339,8 @@ export class DriverSession {
337
339
  if (run.passed === 0)
338
340
  return;
339
341
  fs.mkdirSync(path.dirname(this.stepsFile), { recursive: true, mode: 0o700 });
340
- fs.appendFileSync(this.stepsFile, `${JSON.stringify(run)}\n`);
342
+ fs.appendFileSync(this.stepsFile, `${JSON.stringify({ ...run, at: Date.now() })}\n`);
343
+ keepNewestLinesAsSoleWriter(this.stepsFile, RECORDED_STEPS_LIMIT);
341
344
  }
342
345
  async run(args) {
343
346
  const started = Date.now();
@@ -0,0 +1,378 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { DatabaseSync } from 'node:sqlite';
6
+ import { FORMER, TOOL } from "../name.js";
7
+ import { environmentOf } from "../processes.js";
8
+ import { databasePath, lanesRoot, STATE_DIR_ENV } from "../registry/paths.js";
9
+ import { bestEffort, tryLock, unlock } from "./lock.js";
10
+ /**
11
+ * The processes in `ps -o pid=,args=` output; undefined unless it shows pid 1's arguments, so it can't see every
12
+ * process. macOS ps prints a process's name in parentheses in place of arguments it may not read.
13
+ */
14
+ export function commandLinesOf(output) {
15
+ const rows = output
16
+ .split('\n')
17
+ .map(line => /^\s*(\d+)\s?(.*)$/.exec(line))
18
+ .filter(row => row !== null);
19
+ if (!rows.some(([, pid, args = '']) => pid === '1' && args.startsWith('/')))
20
+ return undefined;
21
+ return rows.map(([, pid = '', args = '']) => ({ pid: Number(pid), args })).filter(row => row.args.trim() !== '');
22
+ }
23
+ export const systemCommandLines = () => {
24
+ const result = spawnSync('ps', ['-A', '-ww', '-o', 'pid=,args='], {
25
+ encoding: 'utf8',
26
+ env: { PATH: '/bin:/usr/bin', LC_ALL: 'C' },
27
+ timeout: 10_000,
28
+ maxBuffer: 64 * 1024 * 1024,
29
+ });
30
+ if (result.error || result.status !== 0)
31
+ return undefined;
32
+ return commandLinesOf(result.stdout)?.map(({ pid, args }) => ({ args, environment: () => environmentOf(pid) }));
33
+ };
34
+ function registryDirs(env) {
35
+ const xdg = env.XDG_STATE_HOME;
36
+ const base = xdg && path.isAbsolute(xdg) ? xdg : path.join(env.HOME ?? os.homedir(), '.local', 'state');
37
+ const override = env[STATE_DIR_ENV];
38
+ return [...new Set([...(override ? [path.resolve(override)] : []), path.join(base, TOOL), path.join(base, FORMER.tool)])];
39
+ }
40
+ function recordedLaneIds(dir) {
41
+ if (!fs.existsSync(databasePath(dir)))
42
+ return [];
43
+ try {
44
+ const db = new DatabaseSync(databasePath(dir), { readOnly: true, timeout: 1000 });
45
+ try {
46
+ return db
47
+ .prepare('SELECT id FROM claims')
48
+ .all()
49
+ .map(row => String(row.id));
50
+ }
51
+ finally {
52
+ db.close();
53
+ }
54
+ }
55
+ catch {
56
+ return undefined;
57
+ }
58
+ }
59
+ function absent(error) {
60
+ const code = error.code;
61
+ return code === 'ENOENT' || code === 'ENOTDIR';
62
+ }
63
+ function linkTarget(link) {
64
+ try {
65
+ return path.resolve(path.dirname(link), fs.readlinkSync(link));
66
+ }
67
+ catch (error) {
68
+ if (absent(error) || error.code === 'EINVAL')
69
+ return undefined;
70
+ throw error;
71
+ }
72
+ }
73
+ function realPath(file) {
74
+ try {
75
+ return fs.realpathSync(file);
76
+ }
77
+ catch (error) {
78
+ if (absent(error))
79
+ return undefined;
80
+ throw error;
81
+ }
82
+ }
83
+ function targetsOf(file) {
84
+ return [linkTarget(file), realPath(file)].filter(target => target !== undefined);
85
+ }
86
+ function laneFiles(lane) {
87
+ const bin = path.join(lane, 'bin');
88
+ let names = [];
89
+ try {
90
+ names = fs.readdirSync(bin);
91
+ }
92
+ catch (error) {
93
+ if (!absent(error))
94
+ throw error;
95
+ }
96
+ const files = names.map(name => {
97
+ const file = path.join(bin, name);
98
+ const texts = targetsOf(file);
99
+ try {
100
+ texts.push(fs.readFileSync(file, 'utf8'));
101
+ }
102
+ catch (error) {
103
+ if (!absent(error))
104
+ throw error;
105
+ }
106
+ return texts;
107
+ });
108
+ return [...files, targetsOf(path.join(lane, 'browser', 'ffmpeg', 'ffmpeg'))];
109
+ }
110
+ /**
111
+ * What every lane recorded in this version's registry or 0.2.x's runs. Each registry is opened read-only, which never
112
+ * changes its data, though SQLite creates the database's `-shm` and `-wal` files beside it when they are missing.
113
+ */
114
+ export function laneToolsOf(env) {
115
+ return () => {
116
+ const files = [];
117
+ for (const dir of registryDirs(env)) {
118
+ const ids = recordedLaneIds(dir);
119
+ if (ids === undefined)
120
+ return undefined;
121
+ for (const id of ids) {
122
+ try {
123
+ files.push(...laneFiles(path.join(lanesRoot(dir), id)));
124
+ }
125
+ catch {
126
+ return undefined;
127
+ }
128
+ }
129
+ }
130
+ return files;
131
+ };
132
+ }
133
+ const BUILD_TAGS = [FORMER.tool.replaceAll('-', ''), TOOL];
134
+ function parseVersion(version) {
135
+ const [plain = ''] = version.split('+');
136
+ const tagged = new RegExp(`^(.*)-(${BUILD_TAGS.join('|')})\\.([0-9A-Za-z-]+)$`).exec(plain);
137
+ const core = tagged?.[1] ?? plain;
138
+ const dash = core.indexOf('-');
139
+ return {
140
+ release: (dash === -1 ? core : core.slice(0, dash)).split('.'),
141
+ prerelease: dash === -1 ? undefined : core.slice(dash + 1).split('.'),
142
+ build: tagged ? [BUILD_TAGS.indexOf(tagged[2] ?? ''), tagged[3] ?? ''] : undefined,
143
+ };
144
+ }
145
+ function compareParts(x, y) {
146
+ const numeric = /^\d+$/;
147
+ if (numeric.test(x) && numeric.test(y))
148
+ return Number(x) - Number(y);
149
+ if (numeric.test(x))
150
+ return -1;
151
+ if (numeric.test(y))
152
+ return 1;
153
+ return x === y ? 0 : x < y ? -1 : 1;
154
+ }
155
+ function compareLists(left, right) {
156
+ for (let i = 0; i < Math.max(left.length, right.length); i++) {
157
+ const x = left[i];
158
+ const y = right[i];
159
+ if (x === y)
160
+ continue;
161
+ if (x === undefined)
162
+ return -1;
163
+ if (y === undefined)
164
+ return 1;
165
+ const order = compareParts(x, y);
166
+ if (order !== 0)
167
+ return order;
168
+ }
169
+ return 0;
170
+ }
171
+ /**
172
+ * Orders versions as semver does, a prerelease before its release, with this toolkit's own builds of a release after
173
+ * it: 1.65.0-alpha < 1.65.0 < 1.65.0-agentenv.3 < 1.65.0-agentlane.1 < 1.65.0-agentlane.2 < 1.66.0.
174
+ */
175
+ export function compareVersions(a, b) {
176
+ const left = parseVersion(a);
177
+ const right = parseVersion(b);
178
+ const release = compareLists(left.release, right.release);
179
+ if (release !== 0)
180
+ return release;
181
+ if (left.prerelease === undefined || right.prerelease === undefined) {
182
+ if (left.prerelease !== right.prerelease)
183
+ return left.prerelease === undefined ? 1 : -1;
184
+ }
185
+ else {
186
+ const prerelease = compareLists(left.prerelease, right.prerelease);
187
+ if (prerelease !== 0)
188
+ return prerelease;
189
+ }
190
+ if (left.build === undefined || right.build === undefined) {
191
+ return left.build === right.build ? 0 : left.build === undefined ? -1 : 1;
192
+ }
193
+ return left.build[0] - right.build[0] || compareParts(left.build[1], right.build[1]);
194
+ }
195
+ const REMOVING = '.removing-';
196
+ /** The ways a file can spell a folder: as given, by its real path, and each as a single-quoted shell word quotes it. */
197
+ function spellingsOf(dir) {
198
+ const names = [dir];
199
+ bestEffort(() => {
200
+ names.push(fs.realpathSync(dir));
201
+ });
202
+ return [...new Set(names.flatMap(name => [name, name.replaceAll("'", "'\\''")]))];
203
+ }
204
+ function mentions(spellings, texts) {
205
+ return texts.some(text => spellings.some(name => text.includes(`${name}${path.sep}`) || text.endsWith(name)));
206
+ }
207
+ function inUse(dir, texts) {
208
+ return mentions(spellingsOf(dir), texts);
209
+ }
210
+ /** Whether an environment, as ps or /proc shows it, sets a variable to a path inside one of a folder's spellings. */
211
+ function setsInside(environment, variable, spellings) {
212
+ return spellings.some(name => ` ${environment}`.includes(` ${variable}=${name}${path.sep}`));
213
+ }
214
+ /**
215
+ * What the launchers' users keep, with why: what a running process's environment says it launches and what the
216
+ * launcher puts on its PATH, and everything a launcher needs while a process or lane file runs it without naming what it
217
+ * launches. Each process and each file is judged on its own.
218
+ */
219
+ function launched(launchers, commands, files) {
220
+ const needed = new Map();
221
+ for (const launcher of launchers) {
222
+ const name = path.basename(launcher.dir);
223
+ const tool = spellingsOf(launcher.dir);
224
+ const launches = launcher.launches.map(dir => ({ dir, spellings: spellingsOf(dir) }));
225
+ const names = (texts) => launches.some(launch => mentions(launch.spellings, texts));
226
+ let unnamed = files.some(file => mentions(tool, file) && !names(file));
227
+ for (const command of commands) {
228
+ if (!mentions(tool, [command.args]) || names([command.args]))
229
+ continue;
230
+ const environment = command.environment();
231
+ const chosen = environment === undefined ? [] : launches.filter(launch => setsInside(environment, launcher.variable, launch.spellings));
232
+ if (chosen.length === 0)
233
+ unnamed = true;
234
+ for (const launch of chosen)
235
+ needed.set(launch.dir, `which a running ${name} launches`);
236
+ for (const dir of chosen.length > 0 ? (launcher.onPath ?? []) : [])
237
+ needed.set(dir, `which a running ${name} may run from PATH`);
238
+ }
239
+ if (unnamed)
240
+ for (const dir of launcher.needs)
241
+ needed.set(dir, `which ${name} may run`);
242
+ }
243
+ return needed;
244
+ }
245
+ /** Folders a removal was interrupted in, under the folders the versions sit in. */
246
+ function sweepInterrupted(parents) {
247
+ for (const parent of parents) {
248
+ let names;
249
+ try {
250
+ names = fs.readdirSync(parent);
251
+ }
252
+ catch {
253
+ continue;
254
+ }
255
+ for (const name of names.filter(n => n.startsWith(REMOVING))) {
256
+ bestEffort(() => {
257
+ fs.rmSync(path.join(parent, name), { recursive: true, force: true });
258
+ });
259
+ }
260
+ }
261
+ }
262
+ function lockFor(lock, options) {
263
+ try {
264
+ return tryLock(lock, options.me, options.processes).acquired;
265
+ }
266
+ catch {
267
+ return false;
268
+ }
269
+ }
270
+ export function realOrResolved(file) {
271
+ try {
272
+ return fs.realpathSync(file);
273
+ }
274
+ catch {
275
+ return path.resolve(file);
276
+ }
277
+ }
278
+ function inside(root, dir) {
279
+ return [
280
+ [path.resolve(root), path.resolve(dir)],
281
+ [realOrResolved(root), realOrResolved(dir)],
282
+ ].every(([r = '', d = '']) => {
283
+ const relative = path.relative(r, d);
284
+ return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative);
285
+ });
286
+ }
287
+ /**
288
+ * Removes the older versions that no running process names on its command line, no recorded lane's files name,
289
+ * no other process is installing, no kept version needs, no launcher may run and no folder that stays holds. Returns the
290
+ * folders removed.
291
+ */
292
+ export function removeOlderVersions(candidates, options) {
293
+ if (candidates.length === 0)
294
+ return [];
295
+ const { root } = options;
296
+ if (root === undefined) {
297
+ options.log(`kept ${candidates.map(v => v.dir).join(', ')}: neither HOME nor XDG_DATA_HOME is set`);
298
+ return [];
299
+ }
300
+ const older = candidates.filter(version => inside(root, version.dir));
301
+ sweepInterrupted(new Set(older.map(version => path.dirname(version.dir))));
302
+ if (older.length === 0)
303
+ return [];
304
+ const commands = options.commandLines();
305
+ if (commands === undefined) {
306
+ options.log(`kept ${older.map(v => v.dir).join(', ')}: ps could not say whether a running process uses them`);
307
+ return [];
308
+ }
309
+ const lanes = options.laneTools();
310
+ if (lanes === undefined) {
311
+ options.log(`kept ${older.map(v => v.dir).join(', ')}: a registry could not say whether a lane uses them`);
312
+ return [];
313
+ }
314
+ const needed = launched(options.launchers ?? [], commands, lanes);
315
+ const neededBy = (version) => {
316
+ for (const dir of version.needs ?? [])
317
+ needed.set(dir, 'which a kept version runs');
318
+ };
319
+ const keep = (version, why) => {
320
+ neededBy(version);
321
+ options.log(`kept ${version.dir}, ${why}`);
322
+ };
323
+ const commandTexts = commands.map(command => command.args);
324
+ const laneTexts = lanes.flat();
325
+ const removed = [];
326
+ const remove = (version) => {
327
+ if (version.lock !== undefined && !lockFor(version.lock, options)) {
328
+ keep(version, 'which another process is installing');
329
+ return;
330
+ }
331
+ const aside = path.join(path.dirname(version.dir), `${REMOVING}${path.basename(version.dir)}-${String(process.pid)}`);
332
+ const moved = bestEffort(() => {
333
+ fs.renameSync(version.dir, aside);
334
+ });
335
+ if (version.lock !== undefined)
336
+ unlock(version.lock, options.me);
337
+ if (!moved) {
338
+ neededBy(version);
339
+ return;
340
+ }
341
+ bestEffort(() => {
342
+ fs.rmSync(aside, { recursive: true, force: true });
343
+ });
344
+ removed.push(version.dir);
345
+ options.log(`removed ${version.dir}, which this version supersedes`);
346
+ };
347
+ const held = [];
348
+ for (const version of [...older.filter(v => v.needs), ...older.filter(v => !v.needs)]) {
349
+ const why = needed.get(version.dir);
350
+ if (why !== undefined) {
351
+ options.log(`kept ${version.dir}, ${why}`);
352
+ continue;
353
+ }
354
+ if (inUse(version.dir, commandTexts)) {
355
+ keep(version, 'which a running process uses');
356
+ continue;
357
+ }
358
+ if (inUse(version.dir, laneTexts)) {
359
+ keep(version, 'which a lane that is up runs');
360
+ continue;
361
+ }
362
+ if ((version.heldBy ?? []).length > 0)
363
+ held.push(version);
364
+ else
365
+ remove(version);
366
+ }
367
+ for (const version of held) {
368
+ const why = needed.get(version.dir);
369
+ const holder = version.heldBy?.find(dir => fs.existsSync(dir));
370
+ if (why !== undefined)
371
+ options.log(`kept ${version.dir}, ${why}`);
372
+ else if (holder !== undefined)
373
+ options.log(`kept ${version.dir}, since ${holder} stays`);
374
+ else
375
+ remove(version);
376
+ }
377
+ return removed;
378
+ }
@@ -25,9 +25,10 @@ import { MAESTRO_RELEASE } from "./driver/release.js";
25
25
  import { serveMcp } from "./mcp/server.js";
26
26
  import { createToolHandler, TOOLS } from "./mcp/tools.js";
27
27
  import { CLI, TOOL } from "./name.js";
28
- import { tcpProbe } from "./registry/ports.js";
29
28
  import { NotClaimed, Refusal, UsageError } from "./registry/refusal.js";
30
- import { Registry } from "./registry/registry.js";
29
+ import { touchLane } from "./registry/touch.js";
30
+ import { SWEEP_INTERVAL_MS } from "./up/sweep.js";
31
+ import { enterLane } from "./up/wake.js";
31
32
  import { groupUsage, helpOf } from "./usage.js";
32
33
  export const DRIVER_COMMANDS = ['look', 'run', 'screenshot', 'record', 'evidence', 'driver', 'browser', 'device', 'mcp'];
33
34
  export const DRIVER_HELP = {
@@ -101,6 +102,14 @@ function stamp() {
101
102
  function laneFor(deps, worktree, need = 'device') {
102
103
  return resolveCallerLane({ env: deps.env, cwd: deps.cwd, worktree, processes: deps.processes, need });
103
104
  }
105
+ /** The caller's lane for a call on it: the call is recorded, and a parked lane is brought back first. */
106
+ async function enter(deps, worktree, need = 'device') {
107
+ const resolved = resolveCallerLane({ env: deps.env, cwd: deps.cwd, worktree, processes: deps.processes, need, counts: true });
108
+ const lane = await enterLane({ stateDir: resolved.stateDir, processes: deps.processes }, resolved.lane, resolved.park, deps.wake, line => {
109
+ deps.stderr(`${TOOL}: ${line}\n`);
110
+ });
111
+ return { ...resolved, lane, park: null };
112
+ }
104
113
  /** The lane's browser when asked for, or when the lane holds no device; else null, for the device. */
105
114
  function browserTarget(deps, resolved, asked) {
106
115
  const { lane } = resolved;
@@ -194,16 +203,16 @@ async function look(args, deps) {
194
203
  throw new UsageError(`--depth ${values.depth} is not a level count`, 'pass --depth 2');
195
204
  lookArgs.depth = depth;
196
205
  }
197
- const resolved = laneFor(deps, values.worktree, values.device ? 'device' : values.browser ? 'browser' : 'either');
206
+ const resolved = await enter(deps, values.worktree, values.device ? 'device' : values.browser ? 'browser' : 'either');
198
207
  const browser = values.device ? null : browserTarget(deps, resolved, values.browser);
199
208
  if (browser) {
200
209
  notOnBrowser({ bounds: values.bounds, raw: values.raw }, 'look');
210
+ touch(deps, resolved, 'look: browser');
201
211
  const page = await lookAtBrowser(browser, {
202
212
  interactiveOnly: values.interactive,
203
213
  ...(lookArgs.within === undefined ? {} : { within: lookArgs.within }),
204
214
  ...(lookArgs.depth === undefined ? {} : { depth: lookArgs.depth }),
205
215
  });
206
- touch(deps, resolved, 'look: browser');
207
216
  if (values.json) {
208
217
  deps.stdout(`${JSON.stringify({ ok: true, text: page.text, url: page.url, title: page.title, driver: page.driver, shown: page.shown, interactive: page.interactive }, null, 2)}\n`);
209
218
  }
@@ -265,7 +274,7 @@ async function run(args, deps) {
265
274
  throw new UsageError(`no flow file at ${file}`, 'pass the path of a Maestro flow');
266
275
  runArgs.file = file;
267
276
  }
268
- const resolved = laneFor(deps, values.worktree);
277
+ const resolved = await enter(deps, values.worktree);
269
278
  const driverLogFrom = sizeOf(enginePaths(resolved.stateDir, resolved.lane.id).log);
270
279
  const response = await callEngine(targetOf(deps, resolved), { op: 'run', args: runArgs });
271
280
  let screenshot;
@@ -310,12 +319,12 @@ async function screenshot(args, deps) {
310
319
  }
311
320
  if (values.crop !== undefined)
312
321
  shotArgs.crop = parseCrop(values.crop);
313
- const resolved = laneFor(deps, values.worktree, values.device ? 'device' : values.browser ? 'browser' : 'either');
322
+ const resolved = await enter(deps, values.worktree, values.device ? 'device' : values.browser ? 'browser' : 'either');
314
323
  const browser = values.device ? null : browserTarget(deps, resolved, values.browser);
315
324
  if (browser) {
316
325
  notOnBrowser({ scale: values.scale, crop: values.crop }, 'screenshot');
317
- const file = await screenshotBrowser(browser, values.out === undefined ? undefined : path.resolve(deps.cwd, values.out));
318
326
  touch(deps, resolved, 'screenshot: browser');
327
+ const file = await screenshotBrowser(browser, values.out === undefined ? undefined : path.resolve(deps.cwd, values.out));
319
328
  if (values.json)
320
329
  deps.stdout(`${JSON.stringify({ ok: true, file, mimeType: 'image/png' }, null, 2)}\n`);
321
330
  else
@@ -342,7 +351,7 @@ async function record(args, deps) {
342
351
  (action === 'save') !== (file !== undefined)) {
343
352
  throw new UsageError('record takes save <file>, show or clear', `${CLI} record save flows/probe.yaml`);
344
353
  }
345
- const resolved = laneFor(deps, values.worktree);
354
+ const resolved = await enter(deps, values.worktree);
346
355
  const response = await callEngine(targetOf(deps, resolved), {
347
356
  op: 'record',
348
357
  args: { action, ...(file === undefined ? {} : { file: path.resolve(deps.cwd, file) }) },
@@ -390,7 +399,7 @@ async function driver(args, deps) {
390
399
  return 0;
391
400
  }
392
401
  case 'start': {
393
- const resolved = laneFor(deps, values.worktree);
402
+ const resolved = await enter(deps, values.worktree);
394
403
  const started = Date.now();
395
404
  const response = await callEngine(targetOf(deps, resolved), { op: 'look', args: { interactiveOnly: true } });
396
405
  const seconds = (Date.now() - started) / 1000;
@@ -422,6 +431,7 @@ async function driver(args, deps) {
422
431
  }
423
432
  case 'stop': {
424
433
  const resolved = laneFor(deps, values.worktree);
434
+ touch(deps, resolved, 'driver stop');
425
435
  const stopped = await stopEngine(resolved.stateDir, resolved.lane);
426
436
  deps.stdout(stopped ? `Stopped the driver for lane ${resolved.lane.id}.\n` : `No driver ran for lane ${resolved.lane.id}.\n`);
427
437
  return 0;
@@ -483,7 +493,9 @@ async function evidence(args, deps) {
483
493
  if (rest.length > 0)
484
494
  throw new UsageError(`unexpected ${rest.join(' ')}`, EVIDENCE_FIX);
485
495
  const asked = values.browser ? 'browser' : values.device ? 'device' : undefined;
486
- const resolved = laneFor(deps, values.worktree, asked ?? 'either');
496
+ const resolved = what === 'list' ? laneFor(deps, values.worktree, asked ?? 'either') : await enter(deps, values.worktree, asked ?? 'either');
497
+ if (what !== 'list')
498
+ touch(deps, resolved, `evidence ${what}${action ? ` ${action}` : ''}`);
487
499
  const ctx = evidenceContext(deps, resolved);
488
500
  const folder = laneEvidence(resolved.stateDir, resolved.lane.id);
489
501
  let kept;
@@ -530,7 +542,6 @@ async function evidence(args, deps) {
530
542
  default:
531
543
  throw new UsageError(`'evidence ${what}' is not an evidence command`, EVIDENCE_FIX);
532
544
  }
533
- touch(deps, resolved, `evidence ${what}${action ? ` ${action}` : ''}`);
534
545
  if (values.json)
535
546
  deps.stdout(`${JSON.stringify({ ok: kept.problems.length === 0, ...kept }, null, 2)}\n`);
536
547
  else {
@@ -603,7 +614,8 @@ async function device(args, deps) {
603
614
  options: { worktree: { type: 'string' } },
604
615
  });
605
616
  const [control, ...rest] = positionals;
606
- const resolved = laneFor(deps, values.worktree);
617
+ const resolved = await enter(deps, values.worktree);
618
+ touch(deps, resolved, control === undefined ? 'device' : `device ${control}`);
607
619
  const claimed = resolved.lane.device;
608
620
  if (claimed?.platform === 'android') {
609
621
  if (!claimed.serial)
@@ -611,7 +623,6 @@ async function device(args, deps) {
611
623
  const adb = adbTools(deps, claimed.serial);
612
624
  await requireEmulatorBooted(adb);
613
625
  const said = await androidControl(adb, positionals);
614
- touch(deps, resolved, `device ${control ?? ''}`);
615
626
  deps.stdout(`${said}\n`);
616
627
  return 0;
617
628
  }
@@ -685,7 +696,6 @@ async function device(args, deps) {
685
696
  const [action, ...words] = rest;
686
697
  if (action === 'get' && words.length === 0) {
687
698
  deps.stdout(await controls.readClipboard(udid));
688
- touch(deps, resolved, 'device clipboard');
689
699
  return 0;
690
700
  }
691
701
  if (action !== 'set' || words.length === 0)
@@ -709,7 +719,6 @@ async function device(args, deps) {
709
719
  default:
710
720
  notAControl(positionals, `${CLI} device location|permission|appearance|push|clipboard|open ...`);
711
721
  }
712
- touch(deps, resolved, `device ${control}`);
713
722
  deps.stdout(`${said}\n`);
714
723
  return 0;
715
724
  }
@@ -798,13 +807,7 @@ async function androidControl(adb, positionals) {
798
807
  }
799
808
  }
800
809
  function touch(deps, resolved, action) {
801
- const registry = Registry.open({ dir: resolved.stateDir, processes: deps.processes, ports: tcpProbe, devices: {} });
802
- try {
803
- registry.touch({ id: resolved.lane.id, token: resolved.lane.token }, action);
804
- }
805
- finally {
806
- registry.close();
807
- }
810
+ touchLane({ dir: resolved.stateDir, processes: deps.processes }, { id: resolved.lane.id, token: resolved.lane.token }, action);
808
811
  }
809
812
  async function mcp(args, deps) {
810
813
  if (args.length > 0)
@@ -814,7 +817,13 @@ async function mcp(args, deps) {
814
817
  output: deps.output,
815
818
  info: { name: TOOL, version: packageVersion() },
816
819
  tools: TOOLS,
817
- call: createToolHandler({ env: deps.env, cwd: deps.cwd, processes: deps.processes }),
820
+ call: createToolHandler({
821
+ env: deps.env,
822
+ cwd: deps.cwd,
823
+ processes: deps.processes,
824
+ ...(deps.wake ? { wake: deps.wake } : {}),
825
+ }),
826
+ ...(deps.sweep ? { every: { ms: SWEEP_INTERVAL_MS, ...deps.sweep } } : {}),
818
827
  });
819
828
  return 0;
820
829
  }
@@ -3,6 +3,7 @@ import fs from 'node:fs';
3
3
  import { DriverError } from "../driver/errors.js";
4
4
  import { isAlive, runCommand, tail } from "../driver/exec.js";
5
5
  import { TOOL } from "../name.js";
6
+ import { runningStartTimes } from "../processes.js";
6
7
  export const realEvidenceSystem = {
7
8
  run: (command, args, timeoutMs) => runCommand(command, args, { timeoutMs }),
8
9
  start(command, args, log) {
@@ -27,6 +28,7 @@ export const realEvidenceSystem = {
27
28
  });
28
29
  return result.status === 0 && result.stdout.trim() !== '' ? result.stdout.trim() : undefined;
29
30
  },
31
+ startTimes: runningStartTimes,
30
32
  signal(pid, signal) {
31
33
  try {
32
34
  process.kill(pid, signal);
@@ -70,6 +72,7 @@ export async function startDeviceVideo(system, target, file, clock) {
70
72
  const said = fs.existsSync(log) ? tail(fs.readFileSync(log, 'utf8'), 6) : '';
71
73
  throw new DriverError(`the screen recording stopped as it started${said ? `:\n${said}` : ''}`, target.platform === 'ios' ? 'check that the simulator is booted' : 'check that the emulator is booted');
72
74
  }
75
+ const start = system.startTimes([pid])?.get(pid);
73
76
  return {
74
77
  version: 1,
75
78
  target: 'device',
@@ -77,6 +80,7 @@ export async function startDeviceVideo(system, target, file, clock) {
77
80
  file,
78
81
  pid,
79
82
  command: running,
83
+ ...(start === undefined ? {} : { start }),
80
84
  platform: target.platform,
81
85
  device: target.device,
82
86
  ...(target.platform === 'android' ? { remote } : {}),
@@ -9,7 +9,7 @@ import { CLI } from "../name.js";
9
9
  import { UsageError } from "../registry/refusal.js";
10
10
  import { laneDir, readUpRecord } from "../up/lane-files.js";
11
11
  import { startDeviceVideo, stopDeviceVideo, writeDeviceLog } from "./device.js";
12
- import { clearInProgress, copyNewer, newEvidenceFile, newEvidenceFolder, readFrom, readInProgress, sizeOf, writeInProgress, } from "./files.js";
12
+ import { clearInProgress, copyNewer, inodeOf, newEvidenceFile, newEvidenceFolder, readFrom, readInProgress, runsSince, sizeOf, writeInProgress, } from "./files.js";
13
13
  export function laneEvidence(stateDir, laneId) {
14
14
  return evidenceDir(laneDir(stateDir, laneId));
15
15
  }
@@ -134,12 +134,14 @@ export async function startTrace(ctx, target) {
134
134
  return { path: evidence, files: [], notes: [`tracing the ${control.driver} browser's actions`], problems: [] };
135
135
  }
136
136
  const files = driverFiles(ctx);
137
+ const stepsIno = inodeOf(files.steps);
137
138
  writeInProgress(evidence, 'trace', {
138
139
  version: 1,
139
140
  target,
140
141
  startedAt,
141
142
  driverLogBytes: sizeOf(files.log),
142
143
  stepsBytes: sizeOf(files.steps),
144
+ ...(stepsIno === undefined ? {} : { stepsIno }),
143
145
  });
144
146
  return { path: evidence, files: [], notes: ["tracing the driver's calls, the flows run and the device's log"], problems: [] };
145
147
  }
@@ -187,7 +189,7 @@ export async function stopTrace(ctx, target) {
187
189
  kept.files.push(file);
188
190
  };
189
191
  write('driver.log', readFrom(files.log, started.driverLogBytes ?? 0));
190
- write('flows.jsonl', readFrom(files.steps, started.stepsBytes ?? 0));
192
+ write('flows.jsonl', runsSince(files.steps, { bytes: started.stepsBytes ?? 0, ino: started.stepsIno, startedAt: started.startedAt }));
191
193
  kept.files.push(...copyNewer(files.shots, path.join(dir, 'screenshots'), started.startedAt));
192
194
  try {
193
195
  const file = path.join(dir, 'device.log');