emd-agents 0.14.0 → 0.16.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.
package/README.md CHANGED
@@ -1,50 +1,24 @@
1
1
  # EMD: Everything Mobile Development
2
2
 
3
- EMD is an MCP server and CLI. It lets a coding agent launch an Expo app on the iOS simulator, check it, and collect evidence.
3
+ <!-- Intro rule: one category line, the job in two or three sentences, then the agents it works with. Nothing else. Add a "used by" line only with a public link for each name. Details go in the sections below. -->
4
4
 
5
- Status: early.
5
+ An MCP server, CLI and agent skill for coding agents that change mobile apps.
6
6
 
7
- ## What works today
7
+ Your coding agent shouldn't grade its own mobile work. EMD builds the app, launches it on the iOS simulator, and passes or fails each change from the app's own log lines and screen. It keeps the evidence: checks, log lines and screenshots.
8
8
 
9
- Stack: Expo (React Native). `detect` reports iOS and Android. `launch` runs on the iOS simulator only.
9
+ `setup` registers EMD with Claude Code, Codex and Cursor. Tested end to end in Claude Code.
10
10
 
11
- MCP tools (`emd mcp`):
12
-
13
- - `detect`: finds the stack, platforms, app IDs, run commands and package manager of a folder. At a workspace root, it lists the app folders instead (`apps`).
14
- - `launch`: builds the app, installs and opens it on an iOS simulator, and keeps its dev server running. Returns a job at once.
15
- - `job_status`: the state of a job (queued, running, succeeded, failed) and, at the end, its result.
16
- - `logs`: the `[EMD:<tag>]` lines that the app wrote during the run of a launch job.
17
- - `tap`, `type`, `swipe`: act on the launched app. `tap` takes a testID, a visible text or a point. Each says which tool did it (AXe or Maestro).
18
- - `check`: passes or fails a run from tagged log lines and on-screen elements (by testID or text). Returns a job.
19
- - `evidence`: puts the checks, log lines, screenshots and Maestro flows of a run in one folder.
20
-
21
- CLI commands (`npx -y emd-agents@latest <command>`, or `node dist/bin.js <command>` in a clone; below, `emd` means either):
22
-
23
- - `detect [dir]`: same as the tool.
24
- - `launch [dir] [--device X] [--timeout N]`: same as the tool, but waits for the result.
25
- - `job status <id>`: reads a job.
26
- - `logs <jobId> [--tag T] [--limit N]`: same as the tool.
27
- - `check <jobId> [--log TAG[=TEXT]] [--element id=X|text=Y] [--name N] [--agent pass|fail]`: same as the tool, but waits.
28
- - `check reset [dir]`: clears the failed-check count. A person must type `reset` at a terminal.
29
- - `evidence <jobId>`: same as the tool.
30
- - `gc [--apply]`: lists, then removes, what EMD made for app folders that no longer exist.
31
- - `tap <jobId> --id X|--text Y|--x N --y N`, `type <jobId> <text>`, `swipe <jobId> up|down|left|right`: same as the tools.
32
- - `setup [--dry-run] [--yes] [--agent X]`: registers EMD with your agents and installs the skill (see below).
33
- - `doctor`: checks that this Mac has what EMD needs (Node, macOS, Xcode, an iPhone simulator, AXe or Maestro) and says how to add what is missing.
34
- - `mcp`: starts the MCP server on stdio.
11
+ Status: early. Expo apps on the iOS simulator only.
35
12
 
36
13
  ## Requirements
37
14
 
38
- - An Expo app with `expo` in package.json and `ios.bundleIdentifier` in its app config (app.json, app.config.js or app.config.ts). EMD reads it with the app's own `expo config`. Without the ID, `launch` stops: "No iOS app ID found".
39
- - The app's dependencies, installed. EMD does not install them.
40
- - macOS. On other systems `detect` works, and `launch` returns "iOS simulators need macOS."
41
- - Xcode, tested with Xcode 26 and 27. Expo SDK 58 apps need Xcode 26 or newer. Without Xcode, `launch` fails: "Could not set up this worktree's simulator and build folders."
42
- - An iOS simulator runtime and at least one shut-down iPhone simulator. EMD clones it once per app folder, as `emd-<key>`. Without one, `launch` fails: "No shut-down iPhone simulator is available to clone."
15
+ - A Mac with Xcode 26 or 27 and at least one iPhone simulator.
43
16
  - Node 22 or newer.
44
- - AXe or Maestro, for taps, typing, swipes and element checks. EMD tries AXe first, then Maestro.
45
- - AXe (about 40 times faster for checks, 60 for taps): `setup` installs it (below). With Xcode 27, Device Hub must be running.
46
- - Maestro: `curl -fsSL "https://get.maestro.mobile.dev" | bash`. It needs Java 17 or newer, with `JAVA_HOME` set.
47
- - With neither, taps, typing and swipes fail, and a check with elements returns `error`. `launch`, `logs`, log checks and `evidence` still work.
17
+ - An Expo app with its dependencies installed. [Check your app](#check-your-app) shows how to check it.
18
+
19
+ Tested: Expo SDK 58 on Xcode 26 and 27. On Xcode 27, apps below Expo SDK 56 can't build (Expo's bug). Use Xcode 26, or upgrade the app to SDK 56 or newer.
20
+
21
+ More detail: [Requirements in detail](#requirements-in-detail).
48
22
 
49
23
  ## Install
50
24
 
@@ -52,32 +26,39 @@ CLI commands (`npx -y emd-agents@latest <command>`, or `node dist/bin.js <comman
52
26
  npx -y emd-agents@latest setup
53
27
  ```
54
28
 
55
- It finds Claude Code, Codex and Cursor, prints its plan and asks once. On a Mac without AXe, it first installs AXe into `~/.emd/tools/`, from AXe's pinned release archive, checked by SHA-256. Then it registers EMD with each agent and installs EMD's skill, which tells the agent how to use it. It backs up each config to `~/.emd/backups/` first. At the end it runs `doctor` and lists what is still missing. Restart your agents afterwards.
29
+ It finds Claude Code, Codex and Cursor, prints its plan and asks once. On a Mac without AXe, it installs AXe, the tool EMD uses to tap and read the screen. Then it registers EMD with each agent and installs EMD's skill, which tells the agent how to use EMD. It backs up each agent config to `~/.emd/backups/` first.
30
+
31
+ At the end it runs `doctor`. For each check marked `missing`, do what its `fix` says. Then restart your agents.
56
32
 
57
33
  - `--dry-run` prints the plan and changes nothing. `--yes` applies it without asking. `--agent codex` (repeatable) picks agents.
58
- - It registers this exact version, `npx -y emd-agents@<version> mcp`, so the server matches the skill. To upgrade, run the same command again.
59
34
  - It calls two installers, pinned: [add-mcp](https://github.com/neondatabase/add-mcp) for the server and [skills](https://github.com/vercel-labs/skills) for the skill.
60
35
 
61
- ## Install from source
36
+ ## Check your app
37
+
38
+ Run this yourself before you ask your agent:
62
39
 
63
40
  ```sh
64
- git clone https://github.com/andrewhenin/emd.git
65
- cd emd
66
- npm ci
67
- npm run build
68
- node dist/bin.js detect fixtures/expo
41
+ npx -y emd-agents@latest detect /path/to/my-app
69
42
  ```
70
43
 
71
- The last line must print `"verdict":"detected"` and `"appIds":{"ios":"com.emd.sandbox"}`. Then `node dist/bin.js setup` registers this clone's build with your agents.
44
+ It must print `"verdict":"detected"` and no `problem`. For example, `"appIds":{"ios":"com.example.myapp"}`. If the app has no iOS app ID, `detect` says so in `notes`: new Expo apps (from `create-expo-app`) have none, and `launch` lets Expo's build set one in the app config (`ios.bundleIdentifier`). EMD writes nothing to the config. Expo's first `run:ios` also creates the `ios/` folder and points the `ios` and `android` scripts in package.json at `expo run:ios` and `expo run:android`. If `problem` appears, install the app's dependencies: EMD reads the config with the app's own Expo CLI.
72
45
 
73
46
  ## First run
74
47
 
75
- 1. In your app, log an event with a tag, for example `console.log("[EMD:ready] home shown")`. Give a testID to each element that you want to check.
76
- 2. Ask your agent, with the full path of your app:
48
+ Ask your agent for a small change, with the full path of your app:
49
+
50
+ > In /path/to/my-app, add a button that shows "Saved" when tapped. Prove it on the iOS simulator with EMD, then tell me the evidence folder.
51
+
52
+ The agent follows EMD's skill. It adds a tagged log line, such as `console.log("[EMD:saved] button tapped")`, and a testID. Then it launches the app, taps, checks the log line and the screen, and gathers the evidence. A first build takes minutes.
77
53
 
78
- > Use the emd tools on /path/to/my-app. Launch it on the iOS simulator. Check that the `ready` log event fired and that the element with testID `home` is on screen. Then gather the evidence and tell me the folder.
54
+ Each check ends with one verdict:
79
55
 
80
- The agent follows EMD's skill (`skills/emd/SKILL.md`): `launch`, wait for the job with `job_status`, `tap`, read `logs`, `check`, then `evidence`. A check's verdict is `passed`, `failed` (fix and check again), `stopped` (3 failed checks: stop and report) or `error` (the check could not run).
56
+ - `passed`: done.
57
+ - `failed`: the agent fixes the cause and checks again.
58
+ - `stopped`: 3 checks failed in this app folder. Only a person can start over, at a terminal: `npx -y emd-agents@latest check reset /path/to/my-app`.
59
+ - `error`: the check could not run. The result says why.
60
+
61
+ A check name keeps its first expectations. A later check with the same name can add expectations, but not drop them. The evidence lists each check name whose last verdict is not `passed`.
81
62
 
82
63
  Output stays on your Mac:
83
64
 
@@ -85,38 +66,126 @@ Output stays on your Mac:
85
66
  - Jobs are in `$TMPDIR/emd/jobs/<jobId>.json`.
86
67
  - Data that must stay after a restart is in `~/.emd/`: the record of what EMD made (`owned/`), build folders (`derived/`) and failed-check counts (`checks/`).
87
68
 
88
- ## Clean up
69
+ ## Limits today
89
70
 
90
- `gc` removes what EMD made for app folders that no longer exist, for example a deleted git worktree: the simulator clone and its `~/.emd/` folders. It removes only what EMD recorded as its own. For a folder that still exists, it removes nothing. It is a CLI command only, not an MCP tool.
71
+ - Expo apps on the iOS simulator only. No native iOS or Android projects, no Android launch, no physical devices.
72
+ - `launch` leaves the dev server running. The next `launch` of the same folder stops it and starts a new one. A dev server that EMD did not start on that port still blocks `launch` ("Port N already serves a dev server").
73
+ - `EMD_RETRY_LIMIT` (1 to 10) changes the limit of 3 failed checks.
74
+ - A build can take 900 seconds by default (`timeoutSeconds`, or `--timeout` in the CLI). Two cold builds at the same time can take longer.
75
+ - The CLI `launch` waits and does not make a job. `logs`, `check` and `evidence` need the `jobId` of a `launch` that the agent started.
76
+
77
+ ## FAQ
78
+
79
+ ### How is EMD different from agent-device, Argent or MobileBuildMCP?
80
+
81
+ Each project's README says what it does. [agent-device](https://github.com/callstack/agent-device) lets agents inspect, control, debug and verify apps. [Argent](https://github.com/software-mansion/argent) gives agents direct control of simulators, emulators and devices, to interact, debug, profile and record e2e tests. [MobileBuildMCP](https://github.com/getsentry/MobileBuildMCP) gives agents tools for iOS and macOS projects, such as build and test. EMD centers on the verdict:
82
+
83
+ - One check reads the app's own tagged log lines and the elements on screen, and passes or fails on both.
84
+ - A check name keeps its first expectations, so the agent can't pass it by dropping one.
85
+ - After 3 failed checks, every later check returns `stopped` until a person resets the count.
86
+
87
+ For taps and screen reads, EMD uses AXe, with Maestro as the fallback.
88
+
89
+ ### How do I upgrade?
90
+
91
+ Run `npx -y emd-agents@latest setup` again, then restart your agents. Setup registers the exact version it ran from, so EMD's server and skill stay at one version.
92
+
93
+ ### How do I remove EMD?
94
+
95
+ Remove the server from each agent, then the skill:
91
96
 
92
97
  ```sh
93
- emd gc # dry run: lists what it would remove, and the size
94
- emd gc --apply # removes it
98
+ claude mcp remove emd -s user
99
+ codex mcp remove emd
100
+ npx -y skills@1.7.6 remove emd -g -y
95
101
  ```
96
102
 
97
- - It lists `emd-*` simulators that no record names, but it never deletes them.
98
- - It does not touch `$TMPDIR/emd` or a dev server that runs.
103
+ In Cursor, delete the `emd` entry from `~/.cursor/mcp.json`.
99
104
 
100
- ## Limits today
105
+ To remove what EMD made on your Mac:
101
106
 
102
- - Expo apps on the iOS simulator only. No native iOS or Android projects, no Android launch, no physical devices.
103
- - `launch` leaves the dev server running. The next `launch` of the same folder stops it and starts a new one. A dev server that EMD did not start on that port still blocks `launch` ("Port N already serves a dev server").
104
- - After 3 failed checks in one app folder, `check` returns `stopped`. Only a person can start over: `emd check reset /path/to/my-app` at a terminal. `EMD_RETRY_LIMIT` (1 to 10) changes the limit.
105
- - A build can take 900 seconds by default (`timeoutSeconds`, or `--timeout` in the CLI). Two cold builds at the same time can take longer.
106
- - The CLI `launch` waits and does not make a job. `logs`, `check` and `evidence` need the `jobId` of a `launch` that the agent started.
107
+ 1. Delete its simulators. `xcrun simctl list devices | grep emd-` lists them. `xcrun simctl delete <id>` deletes one.
108
+ 2. Delete `~/.emd/`. It holds AXe, build folders, EMD's records and the config backups from setup. Copy a backup first if you want to keep it.
107
109
 
108
110
  ## Report a problem
109
111
 
110
112
  Open an [issue](https://github.com/andrewhenin/emd/issues) with:
111
113
 
112
114
  - What you asked the agent, and the tool or command that failed, with its JSON result.
115
+ - The output of `npx -y emd-agents@latest doctor` and `npx -y emd-agents@latest detect /path/to/my-app`.
113
116
  - Versions: EMD's (the `emd-agents@<version>` in your agent's MCP config, or `node dist/bin.js` and `git rev-parse --short HEAD` in a clone), `sw_vers` (macOS), `xcodebuild -version`, `node --version`, and `axe --version` or `maestro --version` if you use them.
114
- - The output of `emd detect /path/to/my-app`.
115
117
  - From the run folder: `build.log` and `metro.log`, or the lines near the error.
116
118
  - Before you attach logs or screenshots, remove private details: names, tokens, keys, internal URLs and user data.
117
119
 
118
120
  ## Contributing
119
121
 
120
- EMD is open source but not accepting outside pull requests yet. Bug reports and ideas are welcome as issues; report vulnerabilities per [SECURITY.md](SECURITY.md).
122
+ EMD is open source but does not accept pull requests from outside contributors yet. Bug reports and ideas are welcome as issues. If you want to fix something yourself, say so in the issue. Report vulnerabilities per [SECURITY.md](SECURITY.md).
123
+
124
+ ## Reference
125
+
126
+ ### MCP tools
127
+
128
+ `emd mcp` serves these tools:
129
+
130
+ - `detect`: finds the stack, platforms, app IDs, run commands and package manager of a folder. At a workspace root, it lists the app folders instead (`apps`).
131
+ - `launch`: builds the app, installs and opens it on an iOS simulator, and keeps its dev server running. Waits up to 25 s (`waitSeconds`): a reload or relaunch returns its result, a build returns a job.
132
+ - `job_status`: the state of a job (queued, running, succeeded, failed) and, at the end, its result. It waits up to 30 s (`waitSeconds`) and returns when the job ends. In Claude Code, `setup` raises the default wait of `launch`, `check` and `job_status` to 100 s (`EMD_WAIT_SECONDS`), so a build takes fewer calls; a client that cancels a call gets the short waits again.
133
+ - `logs`: the `[EMD:<tag>]` lines that the app wrote during the run of a launch job.
134
+ - `tap`, `type`, `swipe`: act on the launched app. `tap` takes a testID, a visible text or a point. Each says which tool did it (AXe or Maestro).
135
+ - `check`: passes or fails a run from tagged log lines and on-screen elements (by testID or text). Waits up to 25 s (`waitSeconds`) and usually returns the verdict; a longer check returns a job. It can run taps, typing and swipes first (`actions`). Each check rewrites the run's evidence folder and returns its path.
136
+ - `evidence`: puts the checks, log lines, screenshots and Maestro flows of a run in one folder.
137
+
138
+ ### CLI commands
139
+
140
+ Run them as `npx -y emd-agents@latest <command>`, or `node dist/bin.js <command>` in a clone. Below, `emd` means either.
141
+
142
+ - `detect [dir]`: same as the tool.
143
+ - `launch [dir] [--device X] [--timeout N]`: same as the tool, but waits for the result.
144
+ - `job status <id>`: reads a job.
145
+ - `logs <jobId> [--tag T] [--limit N]`: same as the tool.
146
+ - `check <jobId> [--log TAG[=TEXT]] [--element id=X|text=Y] [--name N] [--agent pass|fail]`: same as the tool, but waits.
147
+ - `check reset [dir]`: clears the failed-check count. A person must type `reset` at a terminal.
148
+ - `evidence <jobId>`: same as the tool.
149
+ - `gc [--apply]`: lists, then removes, what EMD made for app folders that no longer exist.
150
+ - `tap <jobId> --id X|--text Y|--x N --y N`, `type <jobId> <text>`, `swipe <jobId> up|down|left|right`: same as the tools.
151
+ - `setup [--dry-run] [--yes] [--agent X]`: registers EMD with your agents and installs the skill.
152
+ - `doctor`: checks that this Mac has what EMD needs (Node, macOS, Xcode, an iPhone simulator, AXe or Maestro) and says how to add what is missing.
153
+ - `mcp`: starts the MCP server on stdio.
154
+
155
+ ### Requirements in detail
156
+
157
+ - An Expo app with `expo` in package.json. EMD reads its app config (app.json, app.config.js or app.config.ts) with the app's own `expo config`. Without `ios.bundleIdentifier`, Expo's build sets one and `launch` reports it (`appIdSet`).
158
+ - The app's dependencies, installed. EMD does not install them.
159
+ - macOS. On other systems `detect` works, and `launch` returns "iOS simulators need macOS."
160
+ - Xcode, tested with Xcode 26 and 27. Expo SDK 58 apps need Xcode 26 or newer. Without Xcode, `launch` fails: "Could not set up this worktree's simulator and build folders."
161
+ - An iOS simulator runtime and at least one shut-down iPhone simulator. EMD clones it once per app folder, as `emd-<key>`. Without one, `launch` fails: "No shut-down iPhone simulator is available to clone."
162
+ - AXe or Maestro, for taps, typing, swipes and element checks. EMD tries AXe first, then Maestro.
163
+ - AXe (about 40 times faster for checks, 60 for taps): `setup` installs it into `~/.emd/tools/`, from AXe's pinned release archive, checked by SHA-256. With Xcode 27, Device Hub must be running.
164
+ - Maestro: `curl -fsSL "https://get.maestro.mobile.dev" | bash`. It needs Java 17 or newer, with `JAVA_HOME` set.
165
+ - With neither, taps, typing and swipes fail, and a check with elements returns `error`. `launch`, `logs`, log checks and `evidence` still work.
166
+
167
+ ### Install from source
168
+
169
+ ```sh
170
+ git clone https://github.com/andrewhenin/emd.git
171
+ cd emd
172
+ npm ci
173
+ npm run build
174
+ node dist/bin.js detect fixtures/expo
175
+ ```
176
+
177
+ The last line must print `"verdict":"detected"` and `"appIds":{"ios":"com.emd.sandbox"}`. Then `node dist/bin.js setup` registers this clone's build with your agents.
178
+
179
+ ### Clean up
180
+
181
+ `gc` removes what EMD made for app folders that no longer exist, for example a deleted git worktree: the simulator clone and its `~/.emd/` folders. It removes only what EMD recorded as its own. For a folder that still exists, it removes nothing. It is a CLI command only, not an MCP tool.
182
+
183
+ ```sh
184
+ emd gc # dry run: lists what it would remove, and the size
185
+ emd gc --apply # removes it
186
+ ```
187
+
188
+ - It lists `emd-*` simulators that no record names, but it never deletes them.
189
+ - It does not touch `$TMPDIR/emd` or a dev server that runs.
121
190
 
122
191
  License: [Apache-2.0](LICENSE)
@@ -1,3 +1,4 @@
1
+ import { existsSync } from "node:fs";
1
2
  import { createRequire } from "node:module";
2
3
  import { join } from "node:path";
3
4
  import { runTool } from "../../core/index.js";
@@ -8,18 +9,30 @@ async function readExpoConfig(dir) {
8
9
  try {
9
10
  const cli = createRequire(join(dir, "package.json")).resolve("expo/bin/cli");
10
11
  const { stdout } = await runTool("expo config", process.execPath, [cli, "config", dir, "--json"], 60);
11
- return JSON.parse(stdout) ?? {};
12
+ return { config: JSON.parse(stdout) ?? {} };
12
13
  }
13
- catch {
14
- return {};
14
+ catch (error) {
15
+ const line = String(error)
16
+ .split("\n")[0]
17
+ ?.replace(/^Error: /, "") ?? "";
18
+ return { config: {}, error: line.slice(0, 200) };
15
19
  }
16
20
  }
21
+ // Expo's own fingerprint, from the project's installed Expo (never downloaded).
22
+ async function expoFingerprint(dir, platform) {
23
+ const fromExpo = createRequire(createRequire(join(dir, "package.json")).resolve("expo/bin/cli"));
24
+ const { createFingerprintAsync } = fromExpo("@expo/fingerprint");
25
+ const { hash } = await createFingerprintAsync(dir, {
26
+ platforms: [platform],
27
+ });
28
+ return hash;
29
+ }
17
30
  const isPlatform = (value) => value === "ios" || value === "android";
18
31
  const nonEmpty = (value) => typeof value === "string" && value !== "" ? value : undefined;
19
32
  const adapter = {
20
33
  id: "expo",
21
34
  async detect(dir, project) {
22
- const config = await readExpoConfig(dir);
35
+ const { config, error } = await readExpoConfig(dir);
23
36
  const declared = Array.isArray(config.platforms)
24
37
  ? [...new Set(config.platforms.filter(isPlatform))]
25
38
  : [];
@@ -31,6 +44,17 @@ const adapter = {
31
44
  appIds.ios = ios;
32
45
  if (android && platforms.includes("android"))
33
46
  appIds.android = android;
47
+ // Expo sets the ID only when it generates ios/, so with ios/ and no ID
48
+ // the build would run for minutes and still find none.
49
+ const noId = platforms.includes("ios") && !appIds.ios && !error;
50
+ const hasIos = existsSync(join(dir, "ios"));
51
+ const atLaunch = "At launch, Expo's build sets ios.bundleIdentifier in the app config.";
52
+ const notes = [];
53
+ if (noId && !hasIos) {
54
+ notes.push(typeof config.bundleIdentifier === "string"
55
+ ? `bundleIdentifier is set directly under expo; Expo reads ios.bundleIdentifier, so the app has no iOS app ID. ${atLaunch}`
56
+ : `The app has no iOS app ID. ${atLaunch}`);
57
+ }
34
58
  const expo = `${project.exec} expo`;
35
59
  const run = {};
36
60
  for (const platform of platforms)
@@ -39,6 +63,14 @@ const adapter = {
39
63
  stack: "expo",
40
64
  platforms,
41
65
  appIds,
66
+ ...(error && {
67
+ problem: `The app config could not be read: ${error}. Install the app's dependencies.`,
68
+ }),
69
+ ...(noId &&
70
+ hasIos && {
71
+ problem: "The app has an ios/ folder and no ios.bundleIdentifier in the app config. Expo sets the ID only when it creates ios/. Set ios.bundleIdentifier in the app config.",
72
+ }),
73
+ ...(notes.length > 0 && { notes }),
42
74
  commands: { run, server: `${expo} start` },
43
75
  };
44
76
  },
@@ -51,5 +83,6 @@ const adapter = {
51
83
  build: `${expo} run:ios --device ${deviceId} --no-bundler`,
52
84
  };
53
85
  },
86
+ fingerprint: expoFingerprint,
54
87
  };
55
88
  export default adapter;
package/dist/cli/main.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createInterface } from "node:readline/promises";
2
2
  import { parseArgs } from "node:util";
3
- import { check, detect, doctor, evidence, gc, jobStatus, launch, logs, resetChecks, runJob, setup, swipe, tap, typeText, version, } from "../core/index.js";
3
+ import { check, detect, doctor, evidence, gc, jobStatus, launchInline, logs, resetChecks, runJob, setup, swipe, tap, typeText, version, } from "../core/index.js";
4
4
  const usage = "Commands: detect [dir], launch [dir] [--device X] [--timeout N], job status <id>, logs <jobId> [--tag T] [--limit N], check <jobId> [--log TAG[=TEXT]] [--element id=X|text=Y] [--name N] [--agent pass|fail], check reset [dir], tap <jobId> --id X|--text Y|--x N --y N, type <jobId> [--] <text>, swipe <jobId> up|down|left|right, evidence <jobId>, gc [--apply], setup [--dry-run] [--yes] [--agent claude-code|codex|cursor], doctor, mcp";
5
5
  // --log smoke or --log smoke=tapped
6
6
  const logSpec = (raw) => {
@@ -71,7 +71,7 @@ export async function run(argv) {
71
71
  console.error(`emd: --timeout must be a number of seconds. ${usage}`);
72
72
  return 2;
73
73
  }
74
- const result = await launch({
74
+ const result = await launchInline({
75
75
  dir: positionals[0],
76
76
  device: values.device,
77
77
  timeoutSeconds,
@@ -12,6 +12,8 @@ export type StackDetection = {
12
12
  stack: StackId;
13
13
  platforms: Platform[];
14
14
  appIds: Partial<Record<Platform, string>>;
15
+ problem?: string;
16
+ notes?: string[];
15
17
  commands: {
16
18
  run: Partial<Record<Platform, string>>;
17
19
  server: string;
@@ -29,4 +31,5 @@ export interface StackAdapter {
29
31
  deviceId: string;
30
32
  port: number;
31
33
  }): LaunchPlan | undefined;
34
+ fingerprint(projectDir: string, platform: Platform): Promise<string>;
32
35
  }
@@ -0,0 +1,8 @@
1
+ export type BuildRecord = {
2
+ fingerprint: string;
3
+ port: number;
4
+ };
5
+ export declare function readBuildRecord(derivedData: string): BuildRecord | undefined;
6
+ export declare function writeBuildRecord(derivedData: string, record: BuildRecord): void;
7
+ export declare function whyBuild(record: BuildRecord | undefined, now: BuildRecord, installed: boolean): string | undefined;
8
+ export declare function builtApp(derivedData: string): string | undefined;
@@ -0,0 +1,45 @@
1
+ import { readdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ const file = (derivedData) => join(derivedData, "emd-build.json");
4
+ export function readBuildRecord(derivedData) {
5
+ try {
6
+ const record = JSON.parse(readFileSync(file(derivedData), "utf8"));
7
+ return typeof record?.fingerprint === "string" &&
8
+ typeof record?.port === "number"
9
+ ? record
10
+ : undefined;
11
+ }
12
+ catch {
13
+ return undefined;
14
+ }
15
+ }
16
+ export function writeBuildRecord(derivedData, record) {
17
+ writeFileSync(file(derivedData), JSON.stringify(record));
18
+ }
19
+ // Why the build must run; undefined when the installed build can be reused.
20
+ // A debug build bakes in the dev server port, so a new port needs a new build.
21
+ export function whyBuild(record, now, installed) {
22
+ if (!record)
23
+ return "no earlier build";
24
+ if (record.fingerprint !== now.fingerprint)
25
+ return "fingerprint changed";
26
+ if (record.port !== now.port)
27
+ return "port changed";
28
+ if (!installed)
29
+ return "app not installed";
30
+ return undefined;
31
+ }
32
+ // The one `.app` an earlier Debug build left in DerivedData (launch builds
33
+ // Debug). Undefined when there is none or more than one.
34
+ export function builtApp(derivedData) {
35
+ const dir = join(derivedData, "Build/Products/Debug-iphonesimulator");
36
+ try {
37
+ const apps = readdirSync(dir).filter((name) => name.endsWith(".app"));
38
+ return apps.length === 1 ? join(dir, apps[0] ?? "") : undefined;
39
+ }
40
+ catch (error) {
41
+ if (error.code === "ENOENT")
42
+ return undefined;
43
+ throw error;
44
+ }
45
+ }
@@ -1,20 +1,32 @@
1
1
  import { type LogSpec } from "./checkrecord.js";
2
2
  import { type ScreenRead } from "./device/backend.js";
3
3
  import { type ElementSpec } from "./device/screen.js";
4
+ import { type TapOptions } from "./input.js";
4
5
  import { type LogsOptions } from "./logs.js";
5
- import type { CheckResult, LogsResult } from "./result.js";
6
+ import type { CheckResult, EvidenceResult, InputResult, LogsResult } from "./result.js";
6
7
  import { type RunRef } from "./run.js";
7
8
  export type CheckOptions = RunRef & {
8
9
  logs?: LogSpec[];
9
10
  elements?: ElementSpec[];
10
11
  name?: string;
11
12
  agentReading?: "pass" | "fail";
13
+ actions?: CheckAction[];
14
+ };
15
+ type CheckAction = {
16
+ tap: Omit<TapOptions, "jobId">;
17
+ } | {
18
+ type: string;
19
+ } | {
20
+ swipe: string;
12
21
  };
13
22
  export type Deps = {
14
23
  logs: (options: Omit<LogsOptions, "limit">) => Promise<LogsResult>;
15
24
  screen: (device: string) => Promise<ScreenRead>;
16
25
  screenshot: (device: string, path: string) => Promise<string | undefined>;
17
26
  recheckSeconds: number;
27
+ evidence: (ref: RunRef) => Promise<EvidenceResult>;
28
+ act: (action: CheckAction, ref: RunRef) => Promise<InputResult>;
18
29
  };
19
30
  export declare const primaryDisplay: (message: string) => string | undefined;
20
31
  export declare function check(options: CheckOptions, report?: (step: string) => void, deps?: Deps): Promise<CheckResult>;
32
+ export {};
@@ -5,17 +5,29 @@ import { axeBackend } from "./device/axe.js";
5
5
  import { detectEnvironment, readScreen, } from "./device/backend.js";
6
6
  import { maestroBackend } from "./device/maestro.js";
7
7
  import { hasElement } from "./device/screen.js";
8
- import { recordCheck } from "./evidence.js";
8
+ import { recordCheck, evidence as writeEvidence } from "./evidence.js";
9
+ import { swipe, tap, typeText } from "./input.js";
9
10
  import { firstLine } from "./log.js";
10
11
  import { allLines, tagPattern, } from "./logs.js";
11
12
  import { worktreeKey } from "./owned.js";
12
13
  import { resolveRun } from "./run.js";
13
14
  import { runTool } from "./tool.js";
15
+ const maxActions = 10;
16
+ // One action through the same code as the tap, type and swipe tools.
17
+ function runAction(action, ref) {
18
+ if ("tap" in action)
19
+ return tap({ ...ref, ...action.tap });
20
+ if ("type" in action)
21
+ return typeText({ ...ref, text: action.type });
22
+ return swipe({ ...ref, direction: action.swipe });
23
+ }
14
24
  const realDeps = {
15
25
  // Measured by the result's `waited` in the e2e log. A tap through AXe
16
26
  // returns at once, and in 2 of 2 e2e runs the check after it waited 5 s.
17
27
  recheckSeconds: 10,
18
28
  logs: allLines,
29
+ evidence: (ref) => writeEvidence(ref),
30
+ act: runAction,
19
31
  screen: async (device) => readScreen(device, await detectEnvironment(), [axeBackend, maestroBackend]),
20
32
  screenshot: async (device, path) => {
21
33
  mkdirSync(dirname(path), { recursive: true });
@@ -58,6 +70,9 @@ export async function check(options, report = () => { }, deps = realDeps) {
58
70
  if (logSpecs.length > maxSpecs || elementSpecs.length > maxSpecs) {
59
71
  return error(`At most ${maxSpecs} expectations of each kind.`);
60
72
  }
73
+ if ((options.actions?.length ?? 0) > maxActions) {
74
+ return error(`At most ${maxActions} actions.`);
75
+ }
61
76
  for (const spec of logSpecs) {
62
77
  if (!tagPattern.test(spec.tag) || (spec.message?.length ?? 0) > maxText) {
63
78
  return error(`A log expectation needs a tag (letters, digits, dot, dash, underscore) and a message of at most ${maxText} characters.`);
@@ -99,6 +114,20 @@ export async function check(options, report = () => { }, deps = realDeps) {
99
114
  if (missing.length > 0) {
100
115
  return error(`Check "${name}" first expected: ${missing.join("; ")}. Keep each of these unchanged; you can add more. For a different moment, use a new name. Only a person can clear this (emd check reset).`);
101
116
  }
117
+ // The actions run first, in order. A failed one stops the rest and the
118
+ // read: the check could not run, so it does not count.
119
+ const actions = [];
120
+ for (const [i, action] of (options.actions ?? []).entries()) {
121
+ const done = await deps.act(action, { jobId: options.jobId });
122
+ actions.push(done);
123
+ if (done.verdict !== "ok") {
124
+ return {
125
+ verdict: "error",
126
+ reason: `Action ${i + 1} (${Object.keys(action)[0]}) failed: ${done.reason ?? "no reason given"}. Nothing was read.`,
127
+ actions,
128
+ };
129
+ }
130
+ }
102
131
  const byTag = new Map();
103
132
  const readLogs = async () => {
104
133
  for (const tag of new Set(logSpecs.map((spec) => spec.tag))) {
@@ -177,6 +206,7 @@ export async function check(options, report = () => { }, deps = realDeps) {
177
206
  : {}),
178
207
  };
179
208
  const evidence = {
209
+ ...(actions.length > 0 ? { actions } : {}),
180
210
  ...(waited > 0 ? { waited } : {}),
181
211
  logs: logResults.length > 0 ? logResults : undefined,
182
212
  elements: elementResults.length > 0 ? elementResults : undefined,
@@ -186,8 +216,10 @@ export async function check(options, report = () => { }, deps = realDeps) {
186
216
  secondOpinion,
187
217
  };
188
218
  // Only a check that read something is a check that ran. It sets the count
189
- // (a pass starts it over) and the name's last verdict.
190
- const ran = (result) => {
219
+ // (a pass starts it over) and the name's last verdict. Then it rewrites the
220
+ // run's evidence folder, so the agent needs no evidence call (#207). A
221
+ // folder that can't be written leaves the result as it was.
222
+ const ran = async (result) => {
191
223
  recordCheck(logDir, name, result);
192
224
  writeRecord(key, {
193
225
  failures: result.verdict === "passed" ? 0 : before + 1,
@@ -196,7 +228,16 @@ export async function check(options, report = () => { }, deps = realDeps) {
196
228
  [name]: { expected: first ?? expected, last: result.verdict },
197
229
  },
198
230
  });
199
- return result;
231
+ const written = await deps
232
+ .evidence({ jobId: options.jobId })
233
+ .catch(() => undefined);
234
+ if (written?.verdict !== "written")
235
+ return result;
236
+ return {
237
+ ...result,
238
+ evidenceDir: written.dir,
239
+ ...(written.notPassed && { notPassed: written.notPassed }),
240
+ };
200
241
  };
201
242
  if (passed)
202
243
  return ran({ verdict: "passed", ...evidence });
@@ -16,12 +16,13 @@ export async function detect(dir = ".") {
16
16
  const found = await (await loadAdapter(id)).detect(root, project);
17
17
  if (!found)
18
18
  return { verdict: "none", root };
19
+ const { notes: appNotes = [], ...rest } = found;
19
20
  return {
20
21
  verdict: "detected",
21
22
  root,
22
- ...found,
23
+ ...rest,
23
24
  packageManager: project.packageManager,
24
25
  maestroFlows,
25
- notes,
26
+ notes: [...appNotes, ...notes],
26
27
  };
27
28
  }
@@ -38,28 +38,30 @@ export function parseAxe(output) {
38
38
  }
39
39
  // The accessibility tree of what is on the simulator's screen now. AXe talks to
40
40
  // the simulator directly, with no driver to start.
41
- async function readScreen(device, bin) {
42
- const { stdout } = await runTool("axe describe-ui", bin, ["describe-ui", "--udid", device], 120);
41
+ async function readScreen(device, bin, seconds = 120) {
42
+ const { stdout } = await runTool("axe describe-ui", bin, ["describe-ui", "--udid", device], seconds);
43
43
  return parseAxe(stdout);
44
44
  }
45
45
  // One AXe command on the simulator. AXe needs no driver, so a gesture takes
46
46
  // about a second (experiments/tap-tools.md).
47
- const run = async (bin, { device }, command, args) => {
48
- await runTool(`axe ${command}`, bin, [command, "--udid", device, ...args], 60);
47
+ const run = async (bin, { device }, command, args, seconds = 60) => {
48
+ await runTool(`axe ${command}`, bin, [command, "--udid", device, ...args], seconds);
49
49
  };
50
- // By testID (AXUniqueId) or label (AXLabel), AXe waits up to 5 s for the
51
- // element to appear, then taps its activation point.
50
+ // By testID (AXUniqueId) or label (AXLabel), AXe waits up to 10 s for the
51
+ // element to appear (the limit `check` reads again for), then taps its
52
+ // activation point.
53
+ const elementWaitSeconds = 10;
52
54
  const targetArgs = (target) => "id" in target
53
- ? ["--id", target.id, "--wait-timeout", "5"]
55
+ ? ["--id", target.id, "--wait-timeout", String(elementWaitSeconds)]
54
56
  : "text" in target
55
- ? ["--label", target.text, "--wait-timeout", "5"]
57
+ ? ["--label", target.text, "--wait-timeout", String(elementWaitSeconds)]
56
58
  : ["-x", String(target.x), "-y", String(target.y)];
57
59
  export const axeBackend = {
58
60
  id: "axe",
59
61
  readScreen,
60
62
  tap: (where, bin, target) => run(bin, where, "tap", targetArgs(target)),
61
63
  // `--` so text that starts with a dash is typed, not read as an option.
62
- type: (where, bin, text) => run(bin, where, "type", ["--", text]),
64
+ type: (where, bin, text, seconds) => run(bin, where, "type", ["--", text], seconds),
63
65
  // AXe's preset scrolls 200 points through the screen's centre, the finger
64
66
  // moving the way named.
65
67
  swipe: (where, bin, direction) => run(bin, where, "gesture", [`scroll-${direction}`]),