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,172 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { RUNNER_TOKEN_ENV } from "../driver/maestro-child.js";
4
+ import { ensureMaestro, MAESTRO_OVERRIDE_ENV } from "../driver/install.js";
5
+ import { maestroRunsDir } from "../driver/maestro-runs.js";
6
+ import { evidenceDir } from "../hooks/env.js";
7
+ import { CLI, CONFIG_FILE, TOOL } from "../name.js";
8
+ import { UsageError } from "../registry/refusal.js";
9
+ import { shellQuote } from "../registry/format.js";
10
+ /** Maestro's root options that take a value (`App` in maestro-cli), so the word after one is not the subcommand. */
11
+ export const MAESTRO_VALUE_OPTIONS = ['-p', '--platform', '--host', '--port', '--driver-host-port', '--device', '--udid'];
12
+ /**
13
+ * The lane's `maestro`: our build, bound to the lane's device. `maestro mcp` takes its device from each tool call, so
14
+ * it can't be bound, and is refused. Unless the caller names its own output folder, `maestro test` writes its output
15
+ * into the lane's evidence folder, which outlives release: `<stamp>-maestro-test-<pid>` when the test passes and
16
+ * `<stamp>-maestro-test-<pid>-failed` when it fails. Each run in it is linked into `runs`, where Maestro would have
17
+ * written it, so tooling that reads Maestro's own folder finds it there too.
18
+ */
19
+ export function maestroShim(lane) {
20
+ const { laneId } = lane;
21
+ return `#!/bin/sh
22
+ # ${TOOL}: the patched Maestro, bound to lane ${laneId}'s device ${lane.device}.
23
+ maestro=${shellQuote(lane.maestro)}
24
+ device=${shellQuote(lane.device)}
25
+ evidence=${shellQuote(lane.evidence)}
26
+ runs=${shellQuote(lane.runs)}
27
+ prev=''
28
+ named=''
29
+ output=''
30
+ value=''
31
+ sub=''
32
+ at=0
33
+ i=0
34
+ for arg in "$@"; do
35
+ i=$((i + 1))
36
+ case "$prev" in --udid|--device) named="$arg" ;; esac
37
+ case "$arg" in
38
+ --udid=*|--device=*) named="\${arg#*=}" ;;
39
+ --debug-output|--debug-output=*|--test-output-dir|--test-output-dir=*) output=given ;;
40
+ esac
41
+ prev="$arg"
42
+ if [ -n "$sub" ]; then continue; fi
43
+ if [ -n "$value" ]; then value=''; continue; fi
44
+ case "$arg" in
45
+ ${MAESTRO_VALUE_OPTIONS.join('|')}) value=1 ;;
46
+ -*) ;;
47
+ *) sub="$arg"; at=$i ;;
48
+ esac
49
+ done
50
+ if [ -n "$named" ] && [ "$named" != "$device" ]; then
51
+ echo "${TOOL}: this maestro drives lane ${laneId}'s device $device, not $named. Drop --udid/--device, or run it from the worktree that holds $named." >&2
52
+ exit 2
53
+ fi
54
+ if [ "$sub" = mcp ]; then
55
+ echo "${TOOL}: maestro mcp takes its device from each tool call, so it can't be held to lane ${laneId}'s device $device. The lane's own MCP server is ${CLI} mcp; look, run and screenshot drive the same device from a shell." >&2
56
+ exit 2
57
+ fi
58
+ run=''
59
+ if [ -z "$output" ] && [ "$sub" = test ]; then
60
+ i=0
61
+ for arg in "$@"; do
62
+ i=$((i + 1))
63
+ if [ "$i" -eq 1 ]; then set --; fi
64
+ set -- "$@" "$arg"
65
+ if [ "$i" -eq "$at" ]; then
66
+ run="$evidence/$(date -u +%Y%m%dT%H%M%SZ)-maestro-test-$$"
67
+ set -- "$@" --debug-output "$run-failed"
68
+ fi
69
+ done
70
+ fi
71
+ if [ -z "$named" ]; then set -- --udid "$device" "$@"; fi
72
+ if [ -z "$run" ]; then exec "$maestro" "$@"; fi
73
+ kept="$run-failed"
74
+ mkdir -p "$kept"
75
+ "$maestro" "$@"
76
+ code=$?
77
+ if [ -z "$(ls -A "$kept")" ]; then
78
+ rmdir "$kept"
79
+ if [ "$code" -ne 0 ]; then echo "${TOOL}: maestro test exited $code before it wrote any output" >&2; fi
80
+ exit "$code"
81
+ fi
82
+ if [ "$code" -eq 0 ] && [ ! -e "$run" ] && mv "$kept" "$run"; then kept="$run"; fi
83
+ linked=''
84
+ for made in "$kept"/.maestro/tests/*; do
85
+ if [ ! -d "$made" ]; then continue; fi
86
+ name="\${made##*/}"
87
+ if [ -e "$runs/$name" ] || [ -L "$runs/$name" ]; then name="$name-$$"; fi
88
+ if mkdir -p "$runs" 2>/dev/null && ln -s "$made" "$runs/$name" 2>/dev/null; then linked="$linked $runs/$name"; fi
89
+ done
90
+ if [ -n "$linked" ]; then linked="; linked where Maestro writes its runs:$linked"; fi
91
+ if [ "$code" -eq 0 ]; then
92
+ echo "${TOOL}: maestro test passed; its output, takeScreenshot files included, is kept (after release too) in $kept$linked" >&2
93
+ else
94
+ echo "${TOOL}: maestro test exited $code; its debug output is kept (after release too) in $kept$linked" >&2
95
+ fi
96
+ exit "$code"
97
+ `;
98
+ }
99
+ /** A `maestro` for a lane that has none of its own: it says why and exits 2, so no other Maestro on PATH runs. */
100
+ export function refusingMaestro(laneId, reason) {
101
+ return `#!/bin/sh
102
+ # ${TOOL}: lane ${laneId} has no Maestro of its own.
103
+ printf '%s\\n' ${shellQuote(`${TOOL}: maestro is off in lane ${laneId}, because ${reason}`)} >&2
104
+ exit 2
105
+ `;
106
+ }
107
+ function writeExecutable(file, content) {
108
+ const temp = `${file}.${String(process.pid)}.tmp`;
109
+ fs.writeFileSync(temp, content, { mode: 0o755 });
110
+ fs.renameSync(temp, file);
111
+ }
112
+ /** The id the lane's Maestro drives, or why the lane can't have its own Maestro, as the problem and its fix. */
113
+ function maestroDevice(config, configProblem, lane) {
114
+ if (configProblem !== null)
115
+ return { refusal: configProblem };
116
+ if (!config) {
117
+ return {
118
+ refusal: `no ${CONFIG_FILE} at or above ${lane.worktree} turns it on\nto fix: add ${CONFIG_FILE} with a driver block ("driver": {})`,
119
+ };
120
+ }
121
+ if (!config.driver)
122
+ return { refusal: `${config.file} has no driver block\nto fix: add "driver": {} to ${config.file}` };
123
+ const held = lane.device;
124
+ if (!held)
125
+ return { refusal: `the lane holds no simulator or emulator\nto fix: ${CLI} release, then ${CLI} up` };
126
+ if (held.platform !== 'android')
127
+ return { device: held.id };
128
+ if (held.serial === null) {
129
+ return {
130
+ refusal: `its emulator ${held.name} isn't running (adb has no serial for it)\nto fix: ${CLI} release, then ${CLI} up`,
131
+ };
132
+ }
133
+ return { device: held.serial };
134
+ }
135
+ /**
136
+ * What a hook or `exec` needs to run `maestro` on the lane's device: our Maestro build first on PATH, bound to the
137
+ * device, JDK 17, an adb that fails fast, and the lane's runner token. When the lane can't have its own Maestro (an
138
+ * invalid config, no `driver` block, no running device), the `maestro` first on PATH says why and runs nothing.
139
+ */
140
+ export async function driverVariables(deps, config, lane, laneDirPath, configProblem = null) {
141
+ const bin = path.join(laneDirPath, 'bin');
142
+ const base = deps.env.PATH ?? '/usr/bin:/bin';
143
+ const target = maestroDevice(config, configProblem, lane);
144
+ if ('refusal' in target) {
145
+ fs.mkdirSync(bin, { recursive: true, mode: 0o700 });
146
+ writeExecutable(path.join(bin, 'maestro'), refusingMaestro(lane.id, target.refusal));
147
+ fs.rmSync(path.join(bin, 'adb'), { force: true });
148
+ return { PATH: [bin, base].join(path.delimiter) };
149
+ }
150
+ const { device } = target;
151
+ const java = await deps.toolchain.findJava17(deps.env);
152
+ if (!java) {
153
+ throw new UsageError('Maestro needs JDK 17, and none was found', `install it ('brew install openjdk@17'), or set JAVA_HOME to a JDK 17 home`);
154
+ }
155
+ const maestro = deps.env[MAESTRO_OVERRIDE_ENV] ?? (await ensureMaestro({ env: { ...deps.env, JAVA_HOME: java.home }, log: deps.log })).binary;
156
+ fs.mkdirSync(bin, { recursive: true, mode: 0o700 });
157
+ writeExecutable(path.join(bin, 'maestro'), maestroShim({
158
+ maestro,
159
+ device,
160
+ laneId: lane.id,
161
+ evidence: evidenceDir(laneDirPath),
162
+ runs: maestroRunsDir(deps.env),
163
+ }));
164
+ writeExecutable(path.join(bin, 'adb'), '#!/bin/sh\nexit 1\n');
165
+ return {
166
+ PATH: [bin, path.join(java.home, 'bin'), base].join(path.delimiter),
167
+ JAVA_HOME: java.home,
168
+ [RUNNER_TOKEN_ENV]: lane.token,
169
+ MAESTRO_CLI_NO_ANALYTICS: '1',
170
+ MAESTRO_DISABLE_UPDATE_CHECK: 'true',
171
+ };
172
+ }
@@ -0,0 +1,232 @@
1
+ import { execFile } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { promisify } from 'node:util';
5
+ import { androidToolchain, CacheKeyError, xcodeVersion } from "../cache/key.js";
6
+ import { findAndroidSdk } from "../devices/emulator.js";
7
+ import { HOOK_LOCALE, JAVA_HOME_ENV } from "../hooks/env.js";
8
+ import { runCheck } from "../hooks/run.js";
9
+ import { TOOL } from "../name.js";
10
+ import { asMobile } from "../project/config.js";
11
+ import { UsageError } from "../registry/refusal.js";
12
+ const execFileAsync = promisify(execFile);
13
+ export class Unmet extends Error {
14
+ finding;
15
+ constructor(finding, elapsedMs) {
16
+ super(`${TOOL} up refused before any build, after ${(elapsedMs / 1000).toFixed(1)} s: ${finding.name}: ${finding.detail}\nto fix: ${finding.fix}`);
17
+ this.name = 'Unmet';
18
+ this.finding = finding;
19
+ }
20
+ }
21
+ async function javaVersion(home) {
22
+ try {
23
+ const { stdout, stderr } = await execFileAsync(path.join(home, 'bin', 'java'), ['-version'], { timeout: 20_000 });
24
+ return /version "([^"]+)"/.exec(`${stderr}${stdout}`)?.[1] ?? null;
25
+ }
26
+ catch {
27
+ return null;
28
+ }
29
+ }
30
+ async function macJavaHome17() {
31
+ try {
32
+ const { stdout } = await execFileAsync('/usr/libexec/java_home', ['-v', '17'], { timeout: 10_000 });
33
+ return stdout.trim() || null;
34
+ }
35
+ catch {
36
+ return null;
37
+ }
38
+ }
39
+ function linuxJvms() {
40
+ try {
41
+ return fs
42
+ .readdirSync('/usr/lib/jvm')
43
+ .filter(name => /(^|-)17(-|\.|$)/.test(name))
44
+ .map(name => path.join('/usr/lib/jvm', name));
45
+ }
46
+ catch {
47
+ return [];
48
+ }
49
+ }
50
+ export async function androidJavaHome(env, toolchain) {
51
+ const named = [env[JAVA_HOME_ENV], env.JAVA_HOME].find(home => home !== undefined && home !== '');
52
+ return named ?? (await toolchain.findJava17(env))?.home ?? null;
53
+ }
54
+ export async function androidBuildEnvironment(env, toolchain) {
55
+ const javaHome = await androidJavaHome(env, toolchain);
56
+ return javaHome === null ? env : { ...env, JAVA_HOME: javaHome };
57
+ }
58
+ export const systemToolchain = {
59
+ xcodeVersion,
60
+ async localeCharmap(locale) {
61
+ try {
62
+ const { stdout } = await execFileAsync('locale', ['charmap'], {
63
+ env: { PATH: process.env.PATH ?? '/usr/bin:/bin', LANG: locale, LC_ALL: locale },
64
+ timeout: 10_000,
65
+ });
66
+ return stdout.trim() || undefined;
67
+ }
68
+ catch {
69
+ return undefined;
70
+ }
71
+ },
72
+ async findJava17(env) {
73
+ const pinned = env[JAVA_HOME_ENV];
74
+ const candidates = pinned
75
+ ? [pinned]
76
+ : [
77
+ env.JAVA_HOME,
78
+ await macJavaHome17(),
79
+ '/opt/homebrew/opt/openjdk@17',
80
+ '/usr/local/opt/openjdk@17',
81
+ ...linuxJvms(),
82
+ ].filter((c) => typeof c === 'string' && c !== '');
83
+ for (const home of new Set(candidates)) {
84
+ const version = await javaVersion(home);
85
+ if (version !== null && /^17(\.|$)/.test(version))
86
+ return { home, version };
87
+ }
88
+ return null;
89
+ },
90
+ async androidToolchain(root, env) {
91
+ const javaHome = await androidJavaHome(env, systemToolchain);
92
+ if (!javaHome)
93
+ throw new CacheKeyError(`no JDK found for the Android build: set JAVA_HOME or ${JAVA_HOME_ENV}`);
94
+ const sdk = findAndroidSdk(env);
95
+ if (!sdk)
96
+ throw new CacheKeyError('no Android SDK found for the Android build: set ANDROID_HOME');
97
+ return androidToolchain({ root, javaHome, sdkRoot: sdk.root });
98
+ },
99
+ };
100
+ function message(error) {
101
+ return error instanceof Error ? (error.message.split('\nto fix:')[0] ?? error.message) : String(error);
102
+ }
103
+ export async function toolchainFindings(config, deps, stopAtFirst) {
104
+ const result = { findings: [], spec: null, java: null };
105
+ const { backend } = deps;
106
+ const mobile = asMobile(config);
107
+ const android = mobile?.platform === 'android';
108
+ const checks = [
109
+ () => Promise.resolve(!mobile || backend
110
+ ? null
111
+ : android
112
+ ? {
113
+ name: 'Android emulators',
114
+ ok: false,
115
+ detail: 'this machine has no Android emulator backend',
116
+ fix: 'install the Android SDK (Android Studio, or the command-line tools with platform-tools and the emulator)',
117
+ }
118
+ : {
119
+ name: 'iOS simulators',
120
+ ok: false,
121
+ detail: 'this machine has no iOS simulators',
122
+ fix: 'run up on a Mac with Xcode installed',
123
+ }),
124
+ () => {
125
+ if (!android)
126
+ return Promise.resolve(null);
127
+ const sdk = findAndroidSdk(deps.env);
128
+ return Promise.resolve({
129
+ name: 'Android SDK',
130
+ ok: sdk !== null,
131
+ detail: sdk
132
+ ? `adb and the emulator in ${sdk.root}`
133
+ : 'no Android SDK with platform-tools and the emulator (looked at ANDROID_HOME, ANDROID_SDK_ROOT and ~/Library/Android/sdk)',
134
+ fix: 'install Android Studio or the SDK command-line tools, then set ANDROID_HOME',
135
+ });
136
+ },
137
+ async () => {
138
+ if (!mobile || android)
139
+ return null;
140
+ try {
141
+ return { name: 'Xcode', ok: true, detail: await deps.toolchain.xcodeVersion(), fix: '' };
142
+ }
143
+ catch (error) {
144
+ return {
145
+ name: 'Xcode',
146
+ ok: false,
147
+ detail: message(error),
148
+ fix: 'install Xcode, then: sudo xcode-select -s /Applications/Xcode.app/Contents/Developer',
149
+ };
150
+ }
151
+ },
152
+ async () => {
153
+ const charmap = await deps.toolchain.localeCharmap(HOOK_LOCALE);
154
+ const ambient = deps.env.LC_ALL ?? deps.env.LANG ?? '(unset)';
155
+ return {
156
+ name: 'hook locale',
157
+ ok: charmap === 'UTF-8',
158
+ detail: charmap === 'UTF-8'
159
+ ? `hooks run with LANG and LC_ALL ${HOOK_LOCALE} (this shell has ${ambient})`
160
+ : `${HOOK_LOCALE} gives charmap ${charmap ?? 'nothing'}, not UTF-8; CocoaPods fails without a UTF-8 locale`,
161
+ fix: `install the ${HOOK_LOCALE} locale (on Linux: locale-gen ${HOOK_LOCALE})`,
162
+ };
163
+ },
164
+ () => {
165
+ if (!backend || !mobile)
166
+ return Promise.resolve(null);
167
+ const runtimeName = android ? 'emulator image' : 'simulator runtime';
168
+ try {
169
+ result.spec = backend.resolveSpec({ deviceType: mobile.app.device.type, runtime: mobile.app.device.runtime });
170
+ return Promise.resolve({
171
+ name: runtimeName,
172
+ ok: true,
173
+ detail: `${result.spec.deviceTypeName} on ${result.spec.runtimeName}`,
174
+ fix: '',
175
+ });
176
+ }
177
+ catch (error) {
178
+ const fix = error instanceof UsageError
179
+ ? error.fix
180
+ : android
181
+ ? 'install a system image: sdkmanager "system-images;android-36;google_apis;arm64-v8a"'
182
+ : 'install an iOS simulator runtime: xcodebuild -downloadPlatform iOS';
183
+ return Promise.resolve({ name: runtimeName, ok: false, detail: message(error), fix });
184
+ }
185
+ },
186
+ async () => {
187
+ if (!config.driver || !mobile)
188
+ return null;
189
+ result.java = await deps.toolchain.findJava17(deps.env);
190
+ const pinned = deps.env[JAVA_HOME_ENV];
191
+ return {
192
+ name: 'Java 17',
193
+ ok: result.java !== null,
194
+ detail: result.java
195
+ ? `java ${result.java.version} at ${result.java.home}`
196
+ : `no JDK 17 found${pinned ? ` at ${JAVA_HOME_ENV}=${pinned}` : ''}; the driver (Maestro) needs it`,
197
+ fix: `install JDK 17 (brew install openjdk@17), or set ${JAVA_HOME_ENV} to a JDK 17 home`,
198
+ };
199
+ },
200
+ ];
201
+ for (const check of checks) {
202
+ const finding = await check();
203
+ if (!finding)
204
+ continue;
205
+ result.findings.push(finding);
206
+ if (!finding.ok && stopAtFirst)
207
+ break;
208
+ }
209
+ return result;
210
+ }
211
+ export async function preconditionFinding(p, cwd, env) {
212
+ const outcome = await runCheck(p.run, { cwd, env });
213
+ const status = outcome.signal ? `was killed by ${outcome.signal}` : `exited ${String(outcome.code)}`;
214
+ const output = outcome.output ? `: ${outcome.output.split('\n').slice(-3).join(' / ')}` : '';
215
+ return {
216
+ name: p.name,
217
+ ok: outcome.code === 0,
218
+ detail: outcome.code === 0 ? `\`${p.run}\` passed` : `\`${p.run}\` ${status}${output}`,
219
+ fix: p.fix,
220
+ };
221
+ }
222
+ export async function projectFindings(config, stage, env, stopAtFirst) {
223
+ const findings = [];
224
+ const applies = (p) => p.before === stage && (p.platforms === null || p.platforms.includes(config.platform));
225
+ for (const p of config.preconditions.filter(applies)) {
226
+ const finding = await preconditionFinding(p, config.dir, env);
227
+ findings.push(finding);
228
+ if (!finding.ok && stopAtFirst)
229
+ break;
230
+ }
231
+ return findings;
232
+ }
@@ -0,0 +1,148 @@
1
+ import { browserOfLane, hasBrowser, stopLaneBrowser } from "../browser/lane-browser.js";
2
+ import { realBrowserTools } from "../browser/tools.js";
3
+ import { adbTools } from "../devices/adb.js";
4
+ import { clearBundlerPin } from "../devices/bundler.js";
5
+ import { stopLaneEngine } from "../driver/client.js";
6
+ import { clearDialDefaults, dialDefaults } from "../devices/dial.js";
7
+ import { realEvidenceSystem } from "../evidence/device.js";
8
+ import { stopRecordings } from "../evidence/evidence.js";
9
+ import { laneEnvironment } from "../hooks/env.js";
10
+ import { runHook } from "../hooks/run.js";
11
+ import { loadLaneConfig, loadProjectConfig } from "../project/config.js";
12
+ import { describeStop, stopService } from "../services/services.js";
13
+ import { laneDir, hookLog, readUpRecord } from "./lane-files.js";
14
+ import { dialArguments } from "./doctor.js";
15
+ function message(error) {
16
+ return error instanceof Error ? error.message : String(error);
17
+ }
18
+ async function stopDriver(deps, stateDir, laneId, into) {
19
+ try {
20
+ if (await stopLaneEngine(stateDir, laneId, { processes: deps.processes, ending: true }))
21
+ into.notes.push('stopped the driver');
22
+ }
23
+ catch (error) {
24
+ into.problems.push(message(error));
25
+ }
26
+ }
27
+ async function browserControl(deps, stateDir, lane, into) {
28
+ const tools = deps.browser ?? realBrowserTools;
29
+ const state = tools.state(lane.browser.driver, deps.env);
30
+ if (state.kind !== 'installed')
31
+ return null;
32
+ try {
33
+ return (await browserOfLane(tools, stateDir, lane, deps.env, state.driver)).control;
34
+ }
35
+ catch (error) {
36
+ into.notes.push(`could not reach the browser's driver (${message(error).split('\n')[0] ?? ''}); stopping its processes`);
37
+ return null;
38
+ }
39
+ }
40
+ async function stopBrowser(deps, stateDir, lane, control, into) {
41
+ const stopped = await stopLaneBrowser(deps.browser ?? realBrowserTools, stateDir, lane.id, lane.browser.session, deps.clock, control);
42
+ into.notes.push(...stopped.notes);
43
+ into.problems.push(...stopped.problems);
44
+ }
45
+ export async function stopRecordedProcesses(deps, processes, into) {
46
+ for (const proc of processes) {
47
+ const outcome = await stopService(deps.system, proc, deps.clock);
48
+ const line = describeStop(proc, outcome);
49
+ if (outcome.kind === 'stopped' || outcome.kind === 'already-gone')
50
+ into.notes.push(line);
51
+ else
52
+ into.problems.push(line);
53
+ }
54
+ }
55
+ export async function tearDownLane(deps, stateDir, lane) {
56
+ const result = { lane: lane.id, notes: [], problems: [] };
57
+ await stopDriver(deps, stateDir, lane.id, result);
58
+ const dir = laneDir(stateDir, lane.id);
59
+ const record = readUpRecord(dir);
60
+ const control = hasBrowser(lane) ? await browserControl(deps, stateDir, lane, result) : null;
61
+ const recordings = await stopRecordings({ stateDir, lane, env: deps.env, clock: deps.clock, system: deps.evidence ?? realEvidenceSystem }, control);
62
+ result.notes.push(...recordings.notes);
63
+ result.problems.push(...recordings.problems);
64
+ if (hasBrowser(lane))
65
+ await stopBrowser(deps, stateDir, lane, control, result);
66
+ await stopRecordedProcesses(deps, lane.processes, result);
67
+ const udid = lane.device?.id;
68
+ if (record?.pinned && record.bundleId !== null && udid && deps.sim) {
69
+ try {
70
+ const device = await deps.sim.device(udid);
71
+ if (device?.state === 'Booted') {
72
+ const cleared = await clearBundlerPin(deps.sim, udid, record.bundleId);
73
+ result.notes.push(cleared.changed ? `cleared the bundler pin of ${record.bundleId}` : `${record.bundleId} had no bundler pin`);
74
+ const keys = dialDefaults(dialArguments(loadProjectConfig(record.config), lane)).map(d => d.key);
75
+ const dials = await clearDialDefaults(deps.sim, udid, record.bundleId, keys);
76
+ if (dials.length > 0)
77
+ result.notes.push(`cleared ${dials.join(', ')} from the defaults of ${record.bundleId}`);
78
+ }
79
+ else {
80
+ result.notes.push(`left the bundler pin of ${record.bundleId}: ${udid} is not booted`);
81
+ }
82
+ }
83
+ catch (error) {
84
+ result.problems.push(`could not clear the bundler pin of ${record.bundleId}: ${message(error)}`);
85
+ }
86
+ }
87
+ const serial = lane.device?.platform === 'android' ? lane.device.serial : null;
88
+ if (record?.reversed && record.reversed.length > 0 && serial) {
89
+ const adb = adbTools(deps, serial);
90
+ const removed = [];
91
+ try {
92
+ const rules = await adb.reverses();
93
+ for (const port of record.reversed) {
94
+ if (!rules.has(port))
95
+ continue;
96
+ await adb.removeReverse(port);
97
+ removed.push(port);
98
+ }
99
+ result.notes.push(removed.length > 0
100
+ ? `removed adb reverse for emulator port${removed.length === 1 ? '' : 's'} ${removed.join(', ')}`
101
+ : 'no adb reverse rule was left to remove');
102
+ }
103
+ catch (error) {
104
+ result.notes.push(`left the adb reverse rules on ${serial}: ${message(error)}`);
105
+ }
106
+ }
107
+ if (record) {
108
+ let teardown = null;
109
+ try {
110
+ const config = loadLaneConfig(record.config, record.platform);
111
+ if (config.hooks.teardown) {
112
+ teardown = {
113
+ command: config.hooks.teardown,
114
+ cwd: config.dir,
115
+ env: laneEnvironment(deps.env, lane, config, dir),
116
+ };
117
+ }
118
+ }
119
+ catch (error) {
120
+ result.problems.push(`skipped the teardown hook: ${message(error)}`);
121
+ }
122
+ if (teardown) {
123
+ try {
124
+ const run = await runHook('teardown', teardown.command, {
125
+ cwd: teardown.cwd,
126
+ env: teardown.env,
127
+ log: hookLog(dir, 'teardown'),
128
+ });
129
+ result.notes.push(`ran the teardown hook (${(run.ms / 1000).toFixed(1)} s)`);
130
+ }
131
+ catch (error) {
132
+ result.problems.push(message(error));
133
+ }
134
+ }
135
+ }
136
+ return result;
137
+ }
138
+ export async function stopEndedLanes(deps, stateDir, ended) {
139
+ const results = [];
140
+ for (const e of ended) {
141
+ const result = { lane: e.id, notes: [], problems: [] };
142
+ await stopDriver(deps, stateDir, e.id, result);
143
+ await stopRecordedProcesses(deps, e.processes ?? [], result);
144
+ if (result.notes.length > 0 || result.problems.length > 0)
145
+ results.push(result);
146
+ }
147
+ return results;
148
+ }