qualiow-exploratory-testing 1.3.0 → 2.2.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 (106) hide show
  1. package/.claude-plugin/marketplace.json +26 -0
  2. package/.claude-plugin/plugin.json +22 -0
  3. package/.env.example +27 -0
  4. package/CHANGELOG.md +259 -0
  5. package/README.md +472 -204
  6. package/agents/qa-diff-indexer-agent.md +81 -0
  7. package/agents/qa-gather-agent.md +41 -0
  8. package/agents/qa-page-mapper-agent.md +74 -0
  9. package/agents/qa-reporting-agent.md +103 -0
  10. package/{scripts → bin}/doctor-mobile.sh +57 -18
  11. package/bin/mcli +15 -9
  12. package/bin/mobile-cli.mjs +574 -286
  13. package/bin/qualiow +30 -0
  14. package/{scripts → bin}/setup-mobile.sh +56 -19
  15. package/bin/wadb +10 -4
  16. package/bin/wk-ios +29 -17
  17. package/bin/wkeval.mjs +7 -1
  18. package/data/domains/_default.yml +1 -1
  19. package/data/knowledge/changelog.yml +30 -12
  20. package/data/knowledge/manifest.yml +355 -127
  21. package/data/knowledge/releases/v0.1.0/entries/technique-business-logic-race-conditions.yml +1 -1
  22. package/data/knowledge/releases/v0.1.0/release.yml +8 -1
  23. package/data/knowledge/releases/v0.6.0/entries/technique-async-callback-contracts.yml +98 -0
  24. package/data/knowledge/releases/v0.6.0/entries/technique-exactly-once-verification.yml +116 -0
  25. package/data/knowledge/releases/v0.6.0/release.yml +30 -0
  26. package/data/security/SECURITY-POLICY.md +273 -0
  27. package/data/targets/_default.yml +1 -1
  28. package/data/targets/_example-api-only.yml +80 -0
  29. package/data/targets/_example-mobile-emulation.yml +2 -2
  30. package/data/targets/_example-native-mobile.yml +2 -2
  31. package/data/targets/_example-sim-android-chrome.yml +1 -1
  32. package/data/targets/_example-sim-ios-safari.yml +1 -1
  33. package/data/templates/api-probe-matrix.md +3 -3
  34. package/data/templates/bug-report.md +29 -151
  35. package/data/templates/coverage-map.md +9 -6
  36. package/data/templates/expected-behaviour.md +3 -2
  37. package/data/templates/session-charter.md +3 -0
  38. package/data/templates/session-report.md +57 -80
  39. package/dist/cli/index.js +2286 -701
  40. package/dist/index.d.ts +637 -81
  41. package/dist/index.js +2058 -228
  42. package/docs/BACKEND-VERIFICATION.md +39 -9
  43. package/docs/GETTING-STARTED.md +300 -121
  44. package/docs/MOBILE-SETUP.md +149 -18
  45. package/hooks/hooks.json +27 -0
  46. package/hooks/scripts/read-guard.mjs +95 -0
  47. package/hooks/scripts/secret-patterns.d.mts +8 -0
  48. package/hooks/scripts/secret-patterns.mjs +136 -0
  49. package/hooks/scripts/write-guard.mjs +87 -0
  50. package/package.json +33 -18
  51. package/skills/qa-explore/SKILL.md +32 -25
  52. package/skills/qa-explore/phases/00-setup.md +76 -42
  53. package/skills/qa-explore/phases/01-auth.md +32 -15
  54. package/skills/qa-explore/phases/02-charter.md +16 -5
  55. package/skills/qa-explore/phases/03-discovery.md +93 -27
  56. package/skills/qa-explore/phases/04-journeys.md +2 -2
  57. package/skills/qa-explore/phases/05-features.md +39 -24
  58. package/skills/qa-explore/phases/06-edge-cases.md +24 -13
  59. package/skills/qa-explore/phases/07-reporting.md +102 -142
  60. package/skills/qa-explore/references/context-integration.md +1 -1
  61. package/skills/qa-explore/references/delegation-rules.md +82 -0
  62. package/skills/qa-explore/references/output-contract.md +192 -0
  63. package/skills/qa-explore/references/paths.md +108 -0
  64. package/skills/qa-explore/references/playwright-agents-integration.md +61 -84
  65. package/skills/qa-explore/references/security-rules.md +70 -25
  66. package/skills/qa-explore/references/session-rules.md +2 -1
  67. package/skills/qa-explore/references/severity-guide.md +31 -4
  68. package/skills/qa-explore-cleanup/SKILL.md +51 -15
  69. package/skills/qa-explore-feedback/SKILL.md +23 -5
  70. package/skills/qa-explore-mobile/SKILL.md +86 -64
  71. package/skills/qa-explore-mobile/phases/00-setup.md +71 -62
  72. package/skills/qa-explore-mobile/phases/01-auth.md +28 -31
  73. package/skills/qa-explore-mobile/phases/02-charter.md +8 -4
  74. package/skills/qa-explore-mobile/phases/03-discovery.md +17 -11
  75. package/skills/qa-explore-mobile/phases/04-journeys.md +6 -6
  76. package/skills/qa-explore-mobile/phases/05-features.md +9 -9
  77. package/skills/qa-explore-mobile/phases/06-edge-cases.md +35 -40
  78. package/skills/qa-explore-mobile/phases/07-reporting.md +108 -60
  79. package/skills/qa-explore-mobile/references/mobile-edges.md +26 -26
  80. package/skills/qa-explore-quick/SKILL.md +71 -26
  81. package/skills/qa-explore-report/SKILL.md +65 -35
  82. package/skills/qa-gather/SKILL.md +44 -8
  83. package/skills/qa-knowledge-add/SKILL.md +25 -9
  84. package/skills/qa-knowledge-list/SKILL.md +37 -40
  85. package/skills/qa-target-setup/SKILL.md +63 -41
  86. package/skills/qa-verify-backend/SKILL.md +31 -19
  87. package/skills/qa-verify-backend/phases/00-setup.md +57 -12
  88. package/skills/qa-verify-backend/phases/01-ac-decomposition.md +2 -2
  89. package/skills/qa-verify-backend/phases/02-static-review.md +11 -0
  90. package/skills/qa-verify-backend/phases/03-live-verification.md +5 -3
  91. package/skills/qa-verify-backend/phases/03b-api-verification.md +24 -9
  92. package/skills/qa-verify-backend/phases/04-e2e-trigger.md +18 -2
  93. package/skills/qa-verify-backend/phases/05-reporting.md +72 -12
  94. package/skills/qa-verify-backend/references/api-probes.md +28 -1
  95. package/skills/qa-verify-backend/references/payload-verification.md +1 -1
  96. package/skills/qa-verify-backend/references/release-readiness.md +1 -1
  97. package/skills/qa-verify-backend/references/safety-rules.md +13 -8
  98. package/data/domains/_default.md +0 -181
  99. package/data/domains/ecommerce.md +0 -192
  100. package/data/domains/fintech.md +0 -200
  101. package/data/domains/identity.md +0 -88
  102. package/data/domains/marketing.md +0 -194
  103. package/data/domains/saas.md +0 -197
  104. package/dist/cli/index.d.ts +0 -1
  105. package/dist/cli/index.js.map +0 -1
  106. package/dist/index.js.map +0 -1
@@ -2,50 +2,112 @@
2
2
  // mobile-cli — Maestro-backed shim mimicking the playwright-cli command surface
3
3
  // used by qualiow exploratory testing skills, adapted for iOS/Android.
4
4
  //
5
- // State persists in $MOBILE_CLI_STATE (default ~/.mobile-cli/state.json):
6
- // { device, platform, appId, refs: { e1: {id, text, x, y, bounds, class} }, capturedAt }
5
+ // State file (first match wins):
6
+ // --state <file> | $MOBILE_CLI_STATE | ~/.mobile-cli/current (pointer written by
7
+ // set-device to a per-device file ~/.mobile-cli/<device>.json) | ~/.mobile-cli/state.json
8
+ // { device, deviceName, platform, appId, refs: { e1: {id, text, x, y, bounds, class, kind} }, capturedAt }
7
9
  //
8
10
  // Commands:
9
- // set-device <udid|emulator-5554> persist target device
11
+ // set-device <id> [--platform ios|android] persist target device: adb serial, sim UDID or sim name
10
12
  // set-app <bundleOrPackage> persist app id
11
- // info show resolved state
12
- // launch cold-start the app
13
- // stop force-stop the app
14
- // relaunch-clean stop+clear+launch (android only)
15
- // snapshot [--full] write refs, print ref'd tree
16
- // click <ref> tap element by ref
17
- // fill <ref> <text...> tap then inputText
18
- // press <key> BACK | ENTER | HOME
19
- // screenshot <path> save PNG
13
+ // info show resolved state and the state file in use
14
+ // boot <avd|sim-name|udid> boot an Android AVD or iOS simulator, then set-device it
15
+ // launch | stop | relaunch-clean app lifecycle (relaunch-clean is android-only)
16
+ // snapshot [--full] write refs, print ref'd tree (on-screen nodes only)
17
+ // click <ref> tap element by ref (refs expire after MCLI_REF_TTL_MS, default 60s)
18
+ // fill <ref> <text...> tap then inputText (Maestro flow)
19
+ // clear <ref> tap then erase the field's text (Maestro eraseText)
20
+ // tap-id <testID> tap by testID directly (no snapshot needed)
21
+ // fill-id <testID> <text...> tapOn id + inputText in one Maestro flow
22
+ // wait-text <substring> [timeout-sec] poll hierarchy for text to appear, default 10s
23
+ // press <BACK|ENTER|HOME|TAB|ESCAPE> (iOS: ENTER + HOME only)
24
+ // screenshot <path> save PNG (no app required)
20
25
  // logs [--since <sec>] [--errors] dump device logs (logcat / simctl log)
21
26
  // logs-clear clear device log buffer (android)
22
27
  // deep-link <url> open a deep link in the app
23
28
  // open-url <url> open a URL in the device browser (alias of deep-link)
24
29
  // running which activity / app is foreground
25
- // record-start <path> begin video recording
26
- // record-stop stop video recording
27
-
28
- import { execFileSync, execSync, spawn } from 'node:child_process';
29
- import { createWriteStream, existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync } from 'node:fs';
30
- import { homedir } from 'node:os';
30
+ // record-start <path.mp4> begin video recording (mp4 container on both platforms)
31
+ // record-stop stop video recording and pull the file
32
+ // version print the mobile-cli version
33
+ //
34
+ // Exit codes: 0 ok · 1 command failed · 2 usage · 3 stale/unknown ref · 4 no device/app set
35
+ //
36
+ // Every Maestro flow is generated by buildFlow(), which serialises each scalar with
37
+ // JSON.stringify — a JSON string is a valid YAML double-quoted scalar, so quotes,
38
+ // newlines and backslashes in typed text can never inject extra flow steps.
39
+
40
+ import { execFileSync, spawn } from 'node:child_process';
41
+ import {
42
+ existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, unlinkSync, writeFileSync,
43
+ } from 'node:fs';
44
+ import { homedir, tmpdir } from 'node:os';
31
45
  import { dirname, join } from 'node:path';
46
+ import { fileURLToPath, pathToFileURL } from 'node:url';
47
+
48
+ const HERE = dirname(fileURLToPath(import.meta.url));
49
+ const MCLI_DIR = join(homedir(), '.mobile-cli');
50
+ const CURRENT_POINTER = join(MCLI_DIR, 'current');
32
51
 
33
- const STATE_PATH = process.env.MOBILE_CLI_STATE || join(homedir(), '.mobile-cli', 'state.json');
34
- const REC_PID_PATH = STATE_PATH.replace(/\.json$/, '.rec.pid');
52
+ export const EXIT = { OK: 0, FAILED: 1, USAGE: 2, REF: 3, NO_DEVICE: 4 };
53
+ export const REF_TTL_MS =
54
+ Number(process.env.MCLI_REF_TTL_MS) > 0 ? Number(process.env.MCLI_REF_TTL_MS) : 60_000;
55
+
56
+ export class CliError extends Error {
57
+ constructor(message, exitCode = EXIT.FAILED) {
58
+ super(message);
59
+ this.exitCode = exitCode;
60
+ }
61
+ }
35
62
 
36
63
  // Maestro prints an analytics banner on first run, corrupting parsed output
37
64
  // (e.g. the hierarchy JSON). Opt out for every maestro child process.
38
65
  process.env.MAESTRO_CLI_NO_ANALYTICS = process.env.MAESTRO_CLI_NO_ANALYTICS || '1';
39
66
 
40
- function loadState() {
41
- if (!existsSync(STATE_PATH)) return {};
42
- try { return JSON.parse(readFileSync(STATE_PATH, 'utf8')); } catch { return {}; }
67
+ // ---- state file ----
68
+ let STATE_PATH = join(MCLI_DIR, 'state.json');
69
+ let STATE_PATH_EXPLICIT = false; // --state flag or $MOBILE_CLI_STATE: never auto-switched per device
70
+
71
+ export function parseGlobalFlags(argv) {
72
+ const args = [];
73
+ let statePath = null;
74
+ for (let i = 0; i < argv.length; i++) {
75
+ const a = argv[i];
76
+ if (a === '--state') {
77
+ statePath = argv[++i];
78
+ if (!statePath) throw new CliError('--state needs a file path', EXIT.USAGE);
79
+ } else if (a.startsWith('--state=')) {
80
+ statePath = a.slice('--state='.length);
81
+ } else {
82
+ args.push(a);
83
+ }
84
+ }
85
+ return { args, statePath };
86
+ }
87
+
88
+ export function resolveStatePath(flagPath, env = process.env) {
89
+ if (flagPath) return { path: flagPath, explicit: true };
90
+ if (env.MOBILE_CLI_STATE) return { path: env.MOBILE_CLI_STATE, explicit: true };
91
+ if (existsSync(CURRENT_POINTER)) {
92
+ const p = readFileSync(CURRENT_POINTER, 'utf8').trim();
93
+ if (p) return { path: p, explicit: false };
94
+ }
95
+ return { path: join(MCLI_DIR, 'state.json'), explicit: false };
96
+ }
97
+
98
+ function loadStateFrom(path) {
99
+ if (!existsSync(path)) return {};
100
+ try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return {}; }
43
101
  }
102
+ function loadState() { return loadStateFrom(STATE_PATH); }
44
103
  function saveState(s) {
45
104
  mkdirSync(dirname(STATE_PATH), { recursive: true });
46
105
  writeFileSync(STATE_PATH, JSON.stringify(s, null, 2));
47
106
  }
107
+ function recPath() { return STATE_PATH.replace(/\.json$/, '') + '.rec.json'; }
108
+ export function sanitizeDeviceId(id) { return String(id).replace(/[^A-Za-z0-9._-]+/g, '_'); }
48
109
 
110
+ // ---- process helpers ----
49
111
  function run(cmd, args, opts = {}) {
50
112
  return execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], ...opts });
51
113
  }
@@ -53,32 +115,147 @@ function runOk(cmd, args, opts = {}) {
53
115
  try { return { ok: true, out: run(cmd, args, opts) }; }
54
116
  catch (e) { return { ok: false, out: e.stdout?.toString() || '', err: e.stderr?.toString() || e.message }; }
55
117
  }
56
-
57
- function platformFromDevice(device) {
58
- // emulator-* or NNNN.NNNN.NNNN style or starts with 'R' → android adb; UDID with hyphens → ios
59
- if (!device) return null;
60
- if (device.startsWith('emulator-') || /^[0-9A-F]{8}$/i.test(device) || device.length < 16) return 'android';
61
- return 'ios';
118
+ export function sleep(ms) {
119
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Math.max(0, ms));
62
120
  }
63
121
 
64
122
  function reqDevice(s) {
65
- if (!s.device) throw new Error('No device set. Run: mobile-cli set-device <udid|emulator-5554>');
123
+ if (!s.device || !s.platform) throw new CliError('No device set. Run: mobile-cli set-device <serial|udid|sim-name> [--platform ios|android]', EXIT.NO_DEVICE);
66
124
  return s;
67
125
  }
68
126
  function reqApp(s) {
69
127
  reqDevice(s);
70
- if (!s.appId) throw new Error('No app set. Run: mobile-cli set-app <bundleId|package>');
128
+ if (!s.appId) throw new CliError('No app set. Run: mobile-cli set-app <bundleId|package>', EXIT.NO_DEVICE);
71
129
  return s;
72
130
  }
73
131
 
74
- // ---- maestro wrapper ----
132
+ // ---- device detection (pure parts are exported for tests) ----
133
+ export function parseAdbDevices(out) {
134
+ return String(out || '')
135
+ .split('\n')
136
+ .slice(1)
137
+ .map((l) => l.trim())
138
+ .filter(Boolean)
139
+ .map((l) => l.split(/\s+/))
140
+ .filter(([serial, state]) => serial && state === 'device')
141
+ .map(([serial]) => serial);
142
+ }
143
+
144
+ export function parseSimDevices(jsonText) {
145
+ let j;
146
+ try { j = typeof jsonText === 'string' ? JSON.parse(jsonText) : jsonText; } catch { return []; }
147
+ const out = [];
148
+ for (const [runtime, list] of Object.entries(j?.devices || {})) {
149
+ for (const d of list || []) {
150
+ out.push({ udid: d.udid, name: d.name, state: d.state, available: d.isAvailable !== false, runtime });
151
+ }
152
+ }
153
+ return out;
154
+ }
155
+
156
+ // Resolve an id to { platform, device, deviceName } from what adb and simctl actually
157
+ // list. Never guesses from the shape or length of the string.
158
+ export function detectPlatform(id, { adbSerials = [], simDevices = [] } = {}) {
159
+ if (!id) return null;
160
+ if (adbSerials.includes(id)) return { platform: 'android', device: id };
161
+ const lower = id.toLowerCase();
162
+ const byUdid = simDevices.find((d) => (d.udid || '').toLowerCase() === lower);
163
+ if (byUdid) return { platform: 'ios', device: byUdid.udid, deviceName: byUdid.name };
164
+ const byName = simDevices.filter((d) => d.name === id && d.available);
165
+ if (byName.length) {
166
+ const pick = byName.find((d) => d.state === 'Booted') || byName[0];
167
+ return { platform: 'ios', device: pick.udid, deviceName: pick.name };
168
+ }
169
+ return null;
170
+ }
171
+
172
+ function listAdbSerials() {
173
+ const r = runOk('adb', ['devices']);
174
+ return r.ok ? parseAdbDevices(r.out) : [];
175
+ }
176
+ function listSimDevices() {
177
+ if (process.platform !== 'darwin') return [];
178
+ const r = runOk('xcrun', ['simctl', 'list', 'devices', '-j']);
179
+ return r.ok ? parseSimDevices(r.out) : [];
180
+ }
181
+
182
+ export function resolveDevice(id, { platform } = {}, probes = { adb: listAdbSerials, sim: listSimDevices }) {
183
+ if (!id) throw new CliError('set-device <id> required', EXIT.USAGE);
184
+ if (platform === 'android') return { platform: 'android', device: id };
185
+ if (platform === 'ios') {
186
+ const hit = detectPlatform(id, { simDevices: probes.sim() });
187
+ return hit && hit.platform === 'ios' ? hit : { platform: 'ios', device: id };
188
+ }
189
+ const hit = detectPlatform(id, { adbSerials: probes.adb(), simDevices: probes.sim() });
190
+ if (!hit) {
191
+ throw new CliError(
192
+ `Cannot tell whether '${id}' is an adb serial or an iOS simulator (not listed by \`adb devices\` or \`xcrun simctl list devices\`). Re-run: set-device ${id} --platform ios|android`,
193
+ EXIT.USAGE,
194
+ );
195
+ }
196
+ return hit;
197
+ }
198
+
199
+ // ---- Maestro flow builder: the ONLY producer of flow YAML ----
200
+ function yamlScalar(v) {
201
+ if (typeof v === 'number' || typeof v === 'boolean') return String(v);
202
+ if (v === null || v === undefined) return '""';
203
+ return JSON.stringify(String(v)); // JSON strings are valid YAML double-quoted scalars
204
+ }
205
+ function emitMap(obj, indent) {
206
+ const pad = ' '.repeat(indent);
207
+ const lines = [];
208
+ for (const [k, v] of Object.entries(obj)) {
209
+ if (v && typeof v === 'object' && !Array.isArray(v)) {
210
+ lines.push(`${pad}${k}:`);
211
+ lines.push(...emitMap(v, indent + 2));
212
+ } else {
213
+ lines.push(`${pad}${k}: ${yamlScalar(v)}`);
214
+ }
215
+ }
216
+ return lines;
217
+ }
218
+ export function buildFlow(appId, steps) {
219
+ if (!appId) throw new CliError('buildFlow: appId required', EXIT.NO_DEVICE);
220
+ const out = [`appId: ${yamlScalar(appId)}`, '---'];
221
+ for (const step of steps) {
222
+ if (typeof step === 'string') { out.push(`- ${yamlScalar(step)}`); continue; }
223
+ const entries = Object.entries(step);
224
+ if (entries.length !== 1) throw new CliError('buildFlow: each step must have exactly one command key');
225
+ const [k, v] = entries[0];
226
+ if (v && typeof v === 'object' && !Array.isArray(v)) {
227
+ out.push(`- ${k}:`);
228
+ out.push(...emitMap(v, 4));
229
+ } else {
230
+ out.push(`- ${k}: ${yamlScalar(v)}`);
231
+ }
232
+ }
233
+ return out.join('\n') + '\n';
234
+ }
235
+
236
+ // Maestro CLI has no `input` / `tap-by-id` one-shot commands, so we write a tiny flow
237
+ // to a private temp dir and run it via `maestro test`. Startup is ~3-5s, but avoids
238
+ // char-by-char IME re-renders that adb input text triggers on React Native TextInputs.
239
+ function runFlow(state, steps) {
240
+ reqApp(state);
241
+ const yaml = buildFlow(state.appId, steps);
242
+ const dir = mkdtempSync(join(tmpdir(), 'mcli-')); // 0700
243
+ const flowPath = join(dir, 'flow.yaml');
244
+ try {
245
+ writeFileSync(flowPath, yaml, { mode: 0o600 });
246
+ return runOk('maestro', ['--device', state.device, 'test', flowPath]);
247
+ } finally {
248
+ rmSync(dir, { recursive: true, force: true });
249
+ }
250
+ }
251
+
75
252
  function maestro(state, args) {
76
253
  reqDevice(state);
77
254
  return runOk('maestro', ['--device', state.device, ...args]);
78
255
  }
79
256
 
80
257
  // ---- snapshot: parse maestro hierarchy → ref-numbered text tree ----
81
- function parseBounds(b) {
258
+ export function parseBounds(b) {
82
259
  // "[x1,y1][x2,y2]"
83
260
  const m = /^\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]$/.exec(b || '');
84
261
  if (!m) return null;
@@ -94,86 +271,53 @@ const SYSTEM_ID_PREFIXES = [
94
271
  'android:id/navigationBarBackground',
95
272
  ];
96
273
  function isSystemChrome(id) {
97
- return id && SYSTEM_ID_PREFIXES.some(p => id.startsWith(p));
274
+ return id && SYSTEM_ID_PREFIXES.some((p) => id.startsWith(p));
98
275
  }
99
276
 
100
277
  // Text patterns of dev-only chrome the app renders on top of every screen.
101
- // These traps confuse exploratory agents (one accidental tap = lost in the debug menu).
102
278
  const DEV_CHROME_TEXT_PATTERNS = [
103
- /^Debug tools$/i, // floating bug button (app/sections/debug-menu trigger)
279
+ /^Debug tools$/i, // floating bug button (debug-menu trigger)
104
280
  ];
105
281
  function isDevChrome(text) {
106
- return text && DEV_CHROME_TEXT_PATTERNS.some(p => p.test(text.trim()));
282
+ return text && DEV_CHROME_TEXT_PATTERNS.some((p) => p.test(text.trim()));
107
283
  }
108
284
 
109
285
  // ---- browser-target snapshot tuning ----
110
- // When the "app under test" is actually a mobile browser driving a web app, the a11y
111
- // tree is dominated by the browser's own shell (address bar, tabs, toolbar, on-screen
112
- // keyboard) plus a few wrapper containers around the rendered page. The web content we
113
- // care about lives *inside* those wrappers, so we treat two kinds of nodes specially.
114
- // All of this is gated on the app id being a known browser so native-app snapshots are
115
- // completely unaffected (backward-compatible).
286
+ // When the "app under test" is a mobile browser driving a web app, the a11y tree is
287
+ // dominated by the browser's own shell plus wrapper containers around the rendered page.
288
+ // Gated on the app id being a known browser so native-app snapshots are unaffected.
116
289
  const BROWSER_APP_IDS = [
117
- 'com.apple.mobilesafari', // iOS Safari
118
- 'com.android.chrome', // Android Chrome
119
- 'org.mozilla.firefox', // Firefox (android)
120
- 'com.microsoft.emmx', // Edge (android)
290
+ 'com.apple.mobilesafari', // iOS Safari
291
+ 'com.android.chrome', // Android Chrome
292
+ 'org.mozilla.firefox', // Firefox (android)
293
+ 'com.microsoft.emmx', // Edge (android)
121
294
  ];
122
- function isBrowserApp(appId) {
295
+ export function isBrowserApp(appId) {
123
296
  return !!appId && BROWSER_APP_IDS.includes(appId);
124
297
  }
125
-
126
- // Pass-through wrappers: the browser nests the live web page a few layers deep
127
- // (iOS Safari: SafariWindow > TabDocument > WebView > <page>). We never emit these as
128
- // their own ref, but we DO keep walking into them so the page content surfaces.
298
+ // Pass-through wrappers: never emitted as a ref, but walked into.
129
299
  const BROWSER_PASSTHROUGH_ID_PREFIXES = [
130
- // iOS Safari
131
- 'SafariWindow',
132
- 'TabDocument',
133
- 'WebView',
134
- // Android Chrome — wrappers around the rendered page compositor
300
+ 'SafariWindow', 'TabDocument', 'WebView',
135
301
  'com.android.chrome:id/coordinator',
136
302
  'com.android.chrome:id/compositor_view_holder',
137
303
  'com.android.chrome:id/content',
138
304
  ];
139
305
  function isBrowserPassthrough(id) {
140
- return id && BROWSER_PASSTHROUGH_ID_PREFIXES.some(p => id.startsWith(p));
306
+ return id && BROWSER_PASSTHROUGH_ID_PREFIXES.some((p) => id.startsWith(p));
141
307
  }
142
-
143
- // Browser-own UI subtrees (address/URL bar, tab bar, toolbar, reload/menu buttons,
144
- // on-screen keyboard, input accessory, dimming overlays). None of this is app-under-test
145
- // content — prune the whole subtree like system chrome so web snapshots aren't drowned.
308
+ // Browser-own UI subtrees (address bar, tab bar, toolbar, keyboard, overlays): pruned.
146
309
  const BROWSER_CHROME_ID_PREFIXES = [
147
- // iOS Safari
148
- 'CapsuleViewController', // the entire URL/address bar cluster
149
- 'CapsuleNavigationBar',
150
- 'TabBarItemTitle',
151
- 'BackButton',
152
- 'ReloadButton',
153
- 'MoreMenuButton',
154
- 'PageFormatMenuButton',
155
- 'AdditionalDimmingOverlay',
156
- 'Toolbar',
157
- 'inputView',
158
- 'SystemInputAssistantView',
159
- 'UIKeyboardLayout',
160
- 'UIKeyboard',
161
- 'kb-autofill-key',
162
- // Android Chrome
163
- 'com.android.chrome:id/toolbar',
164
- 'com.android.chrome:id/url_bar',
165
- 'com.android.chrome:id/tab_switcher_button',
166
- 'com.android.chrome:id/menu_button',
167
- 'com.android.chrome:id/control_container',
168
- 'com.android.chrome:id/toolbar_container',
169
- 'com.android.chrome:id/bottom_container',
170
- 'com.android.chrome:id/location_bar',
171
- 'com.android.chrome:id/omnibox',
172
- 'com.android.chrome:id/message', // promo/infobar bubbles ("Open tabs to visit…")
173
- 'com.android.chrome:id/infobar',
310
+ 'CapsuleViewController', 'CapsuleNavigationBar', 'TabBarItemTitle', 'BackButton', 'ReloadButton',
311
+ 'MoreMenuButton', 'PageFormatMenuButton', 'AdditionalDimmingOverlay', 'Toolbar', 'inputView',
312
+ 'SystemInputAssistantView', 'UIKeyboardLayout', 'UIKeyboard', 'kb-autofill-key',
313
+ 'com.android.chrome:id/toolbar', 'com.android.chrome:id/url_bar', 'com.android.chrome:id/tab_switcher_button',
314
+ 'com.android.chrome:id/menu_button', 'com.android.chrome:id/control_container',
315
+ 'com.android.chrome:id/toolbar_container', 'com.android.chrome:id/bottom_container',
316
+ 'com.android.chrome:id/location_bar', 'com.android.chrome:id/omnibox',
317
+ 'com.android.chrome:id/message', 'com.android.chrome:id/infobar',
174
318
  ];
175
319
  function isBrowserChrome(id) {
176
- return id && BROWSER_CHROME_ID_PREFIXES.some(p => id.startsWith(p));
320
+ return id && BROWSER_CHROME_ID_PREFIXES.some((p) => id.startsWith(p));
177
321
  }
178
322
 
179
323
  function isInteresting(attrs) {
@@ -203,43 +347,51 @@ function summarizeClass(cls) {
203
347
  return cls.split('.').pop() || cls;
204
348
  }
205
349
 
206
- function snapshot(state, opts = {}) {
207
- const r = maestro(state, ['hierarchy']);
208
- if (!r.ok) throw new Error('maestro hierarchy failed:\n' + r.err);
209
- let json;
210
- // Tolerate any banner/log lines maestro prints before the JSON payload.
211
- const jsonStart = r.out.indexOf('{');
212
- const raw = jsonStart >= 0 ? r.out.slice(jsonStart) : r.out;
213
- try { json = JSON.parse(raw); } catch (e) { throw new Error('hierarchy not JSON:\n' + r.out.slice(0, 200)); }
350
+ // `maestro hierarchy` is pure JSON since Maestro 2.6; older builds and stray log lines
351
+ // may precede it, so fall back to the first line that starts a JSON object.
352
+ export function parseHierarchy(stdout) {
353
+ const text = String(stdout || '');
354
+ try { return JSON.parse(text.trim()); } catch { /* fall through */ }
355
+ const lines = text.split('\n');
356
+ for (let i = 0; i < lines.length; i++) {
357
+ if (lines[i].trimStart().startsWith('{')) {
358
+ try { return JSON.parse(lines.slice(i).join('\n')); } catch { /* keep scanning */ }
359
+ }
360
+ }
361
+ throw new CliError('hierarchy not JSON:\n' + text.slice(0, 200));
362
+ }
214
363
 
364
+ // Pure: hierarchy JSON → { refs, tree, count }. Nodes whose bounds fall entirely outside
365
+ // the root window get no ref (tapping them would be a silent no-op).
366
+ export function assignRefs(json, opts = {}) {
215
367
  const refs = {};
216
368
  const lines = [];
217
369
  let n = 0;
218
- const browser = isBrowserApp(state.appId);
370
+ const browser = !!opts.browser;
371
+ const rootBounds = parseBounds(json?.attributes?.bounds);
372
+ const win = opts.window || (rootBounds && rootBounds.w > 0 && rootBounds.h > 0 ? rootBounds : null);
373
+ const onScreen = (b) => !win || (b.x2 > win.x1 && b.x1 < win.x2 && b.y2 > win.y1 && b.y1 < win.y2);
219
374
 
220
375
  function walk(node, depth) {
221
376
  if (!node) return;
222
377
  const a = node.attributes || {};
223
378
  const id = (a['resource-id'] || '').trim();
224
- if (isSystemChrome(id)) return; // skip whole systemui/launcher subtrees
225
- if (browser && isBrowserChrome(id)) return; // skip the browser's own URL bar / toolbar / keyboard subtrees
226
- const aText = (a.text || a.accessibilityText || a.hintText || a.label || '').trim();
227
- if (isDevChrome(aText)) return; // skip Debug tools floater and similar dev-only chrome
379
+ if (isSystemChrome(id)) return;
380
+ if (browser && isBrowserChrome(id)) return;
381
+ const text = (a.text || a.accessibilityText || a.hintText || a.label || '').trim();
382
+ if (isDevChrome(text)) return;
228
383
  const bounds = parseBounds(a.bounds);
229
- const text = aText;
230
384
  const kind = summarizeClass(a.class);
231
385
  let show = opts.full ? !!bounds : isInteresting(a);
232
- // Browser page-wrapper nodes (SafariWindow/TabDocument/WebView): don't emit the
233
- // wrapper itself, but keep walking so the web content inside surfaces.
234
386
  if (browser && isBrowserPassthrough(id)) show = false;
235
- if (show && bounds && bounds.w > 0 && bounds.h > 0) {
387
+ if (show && bounds && bounds.w > 0 && bounds.h > 0 && onScreen(bounds)) {
236
388
  n += 1;
237
389
  const ref = 'e' + n;
238
390
  refs[ref] = {
239
391
  id,
240
392
  text,
241
393
  class: a.class || '',
242
- clickable: a.clickable === 'true',
394
+ clickable: a.clickable === 'true' || a.clickable === true,
243
395
  x: bounds.cx, y: bounds.cy,
244
396
  bounds: [bounds.x1, bounds.y1, bounds.x2, bounds.y2],
245
397
  kind,
@@ -252,70 +404,64 @@ function snapshot(state, opts = {}) {
252
404
  for (const child of node.children || []) walk(child, depth + (show ? 1 : 0));
253
405
  }
254
406
  walk(json, 0);
407
+ return { refs, tree: lines.join('\n'), count: n };
408
+ }
255
409
 
410
+ function snapshot(state, opts = {}) {
411
+ const r = maestro(state, ['hierarchy']);
412
+ if (!r.ok) throw new CliError('maestro hierarchy failed:\n' + r.err);
413
+ const json = parseHierarchy(r.out);
414
+ const { refs, tree, count } = assignRefs(json, { full: opts.full, browser: isBrowserApp(state.appId) });
256
415
  state.refs = refs;
257
416
  state.capturedAt = new Date().toISOString();
258
417
  saveState(state);
259
- return { tree: lines.join('\n'), count: n };
260
- }
261
-
262
- function getRef(state, ref) {
263
- if (!state.refs || !state.refs[ref]) throw new Error(`Unknown ref '${ref}'. Run snapshot first.`);
264
- return state.refs[ref];
418
+ return { tree, count };
265
419
  }
266
420
 
267
- // ---- maestro flow runner (one-shot YAML) ----
268
- // Maestro CLI has no `input` / `tap-by-id` one-shot commands, so we write a tiny flow
269
- // to /tmp and run it via `maestro test`. Startup is ~3-5s, but avoids char-by-char IME
270
- // re-renders that adb input text triggers on React Native TextInputs.
271
- function runFlow(state, commandsYaml) {
272
- reqApp(state);
273
- const tmpPath = `/tmp/_mcli_flow_${process.pid}_${Date.now()}.yaml`;
274
- const yaml = `appId: ${state.appId}\n---\n${commandsYaml}\n`;
275
- writeFileSync(tmpPath, yaml);
276
- try {
277
- return runOk('maestro', ['--device', state.device, 'test', tmpPath]);
278
- } finally {
279
- try { unlinkSync(tmpPath); } catch {}
421
+ export function getRef(state, ref, now = Date.now(), ttlMs = REF_TTL_MS) {
422
+ if (!state.refs || !state.refs[ref]) throw new CliError(`Unknown ref '${ref}'. Run snapshot first.`, EXIT.REF);
423
+ const age = now - Date.parse(state.capturedAt || '');
424
+ if (!(age <= ttlMs)) {
425
+ const secs = Number.isFinite(age) ? `${Math.round(age / 1000)}s old` : 'of unknown age';
426
+ throw new CliError(`Ref '${ref}' is from a snapshot ${secs} (limit ${ttlMs / 1000}s) — run snapshot again.`, EXIT.REF);
280
427
  }
428
+ return state.refs[ref];
281
429
  }
282
430
 
283
431
  // ---- actions ----
284
432
  function tap(state, ref) {
433
+ reqDevice(state);
285
434
  const r = getRef(state, ref);
286
435
  if (state.platform === 'android') {
287
436
  return runOk('adb', ['-s', state.device, 'shell', 'input', 'tap', String(r.x), String(r.y)]);
288
437
  }
289
- // iOS sim — simctl has no `io tap`, and current Maestro CLIs have no one-shot
290
- // `tap` command either; run a tiny tapOn-point flow instead.
291
- return runFlow(state, `- tapOn:\n point: "${r.x},${r.y}"`);
438
+ // iOS sim — simctl has no `io tap` and Maestro has no one-shot tap; run a tapOn-point flow.
439
+ return runFlow(state, [{ tapOn: { point: `${r.x},${r.y}` } }]);
292
440
  }
293
-
294
- // Tap by testID directly via Maestro — no snapshot required first.
295
441
  function tapById(state, id) {
296
- return runFlow(state, `- tapOn:\n id: "${id}"`);
442
+ if (!id) throw new CliError('tap-id <testID> required', EXIT.USAGE);
443
+ return runFlow(state, [{ tapOn: { id } }]);
297
444
  }
298
-
299
445
  function fill(state, ref, text) {
300
446
  const tapRes = tap(state, ref);
301
447
  if (!tapRes.ok) return tapRes;
302
448
  sleep(250);
303
- // Use Maestro flow for text input on both platforms — avoids React Native
304
- // per-char re-render hell that makes adb input text crawl on long strings.
305
- // Maestro startup ≈ adb-input-text cost at ~15+ chars, faster above that.
306
- const escaped = String(text).replace(/"/g, '\\"');
307
- return runFlow(state, `- inputText: "${escaped}"`);
449
+ return runFlow(state, [{ inputText: text }]);
308
450
  }
309
-
310
- // Fill by testID — combines tapById + inputText into one Maestro flow (one startup, not two).
311
451
  function fillById(state, id, text) {
312
- const escaped = String(text).replace(/"/g, '\\"');
313
- return runFlow(state, `- tapOn:\n id: "${id}"\n- inputText: "${escaped}"`);
452
+ if (!id) throw new CliError('fill-id <testID> <text...> required', EXIT.USAGE);
453
+ return runFlow(state, [{ tapOn: { id } }, { inputText: text }]);
454
+ }
455
+ function clearField(state, ref) {
456
+ const tapRes = tap(state, ref);
457
+ if (!tapRes.ok) return tapRes;
458
+ sleep(250);
459
+ return runFlow(state, [{ eraseText: 200 }]); // erase up to 200 chars from the focused field
314
460
  }
315
461
 
316
- // Wait until a text substring appears in the visible hierarchy, or timeout.
317
- // Polls every 1s. Returns { ok: true, elapsed_ms } on hit, { ok: false } on timeout.
462
+ // Wait until a text substring appears in the visible hierarchy, or timeout (polls every 1s).
318
463
  function waitText(state, substring, timeoutSec = 10) {
464
+ if (!substring) throw new CliError('wait-text <substring> [timeout-sec] required', EXIT.USAGE);
319
465
  const deadline = Date.now() + timeoutSec * 1000;
320
466
  const start = Date.now();
321
467
  while (Date.now() < deadline) {
@@ -328,34 +474,25 @@ function waitText(state, substring, timeoutSec = 10) {
328
474
  return { ok: false, err: `timeout: "${substring}" not seen in ${timeoutSec}s` };
329
475
  }
330
476
 
477
+ const ANDROID_KEYS = { BACK: 'KEYCODE_BACK', ENTER: 'KEYCODE_ENTER', HOME: 'KEYCODE_HOME', TAB: 'KEYCODE_TAB', ESCAPE: 'KEYCODE_ESCAPE' };
478
+ const IOS_KEYS = { ENTER: 'Enter', HOME: 'Home' };
331
479
  function press(state, key) {
332
- const map = { BACK: 'KEYCODE_BACK', ENTER: 'KEYCODE_ENTER', HOME: 'KEYCODE_HOME', TAB: 'KEYCODE_TAB', ESCAPE: 'KEYCODE_ESCAPE' };
333
- const k = map[key.toUpperCase()];
334
- if (!k) throw new Error(`Unknown key: ${key}. One of: ${Object.keys(map).join(', ')}`);
480
+ const K = String(key || '').toUpperCase();
481
+ const k = ANDROID_KEYS[K];
482
+ if (!k) throw new CliError(`Unknown key: ${key}. One of: ${Object.keys(ANDROID_KEYS).join(', ')}`, EXIT.USAGE);
483
+ reqDevice(state);
335
484
  if (state.platform === 'android') {
336
485
  return runOk('adb', ['-s', state.device, 'shell', 'input', 'keyevent', k]);
337
486
  }
338
- // iOS sim: no hardware keys, but Maestro can synthesize Enter (submit the focused
339
- // field) and Home. BACK still has no iOS equivalent — use an in-app back control.
340
- const iosKey = { ENTER: 'Enter', HOME: 'Home' }[key.toUpperCase()];
341
- if (iosKey) return runFlow(state, `- pressKey: ${iosKey}`);
342
- throw new Error(`press ${key} not supported on iOS sim. Use a UI back button via snapshot+click.`);
343
- }
344
-
345
- // Clear the text of an already-filled input: tap it, then Maestro eraseText.
346
- function clearField(state, ref) {
347
- const tapRes = tap(state, ref);
348
- if (!tapRes.ok) return tapRes;
349
- sleep(250);
350
- return runFlow(state, `- eraseText: 200`); // erase up to 200 chars from the focused field
487
+ // iOS sim: no hardware keys, but Maestro can synthesize Enter and Home.
488
+ if (IOS_KEYS[K]) return runFlow(state, [{ pressKey: IOS_KEYS[K] }]);
489
+ throw new CliError(`press ${K} not supported on iOS sim (only ENTER, HOME). Use an in-app control via snapshot+click.`, EXIT.USAGE);
351
490
  }
352
491
 
353
492
  function launch(state) {
354
493
  reqApp(state);
355
494
  if (state.platform === 'android') {
356
- // Resolve the launcher activity and am start it — the classic `monkey -p <pkg>`
357
- // hack breaks on newer images (API 35 emulator mangles the args). Fall back to
358
- // monkey only if resolution fails.
495
+ // Resolve the launcher activity and am start it; `monkey` breaks on newer images.
359
496
  const res = runOk('adb', ['-s', state.device, 'shell', 'cmd', 'package', 'resolve-activity', '--brief', '-c', 'android.intent.category.LAUNCHER', state.appId]);
360
497
  const comp = (res.out || '').trim().split('\n').pop()?.trim();
361
498
  if (res.ok && comp && comp.includes('/')) {
@@ -372,53 +509,73 @@ function stop(state) {
372
509
  }
373
510
  function relaunchClean(state) {
374
511
  reqApp(state);
375
- if (state.platform !== 'android') throw new Error('relaunch-clean is android-only (use stop+launch on ios).');
512
+ if (state.platform !== 'android') throw new CliError('relaunch-clean is android-only (use stop+launch on ios).', EXIT.USAGE);
376
513
  stop(state);
377
514
  runOk('adb', ['-s', state.device, 'shell', 'pm', 'clear', state.appId]);
378
515
  return launch(state);
379
516
  }
517
+
380
518
  function screenshot(state, path) {
381
- reqApp(state);
519
+ reqDevice(state);
520
+ if (!path) throw new CliError('screenshot <path> required', EXIT.USAGE);
521
+ mkdirSync(dirname(path) || '.', { recursive: true });
382
522
  if (state.platform === 'android') {
383
- const tmp = '/sdcard/_mobile_cli_shot.png';
384
- runOk('adb', ['-s', state.device, 'shell', 'screencap', '-p', tmp]);
385
- const r = runOk('adb', ['-s', state.device, 'pull', tmp, path]);
386
- runOk('adb', ['-s', state.device, 'shell', 'rm', tmp]);
387
- return r;
523
+ try {
524
+ const png = execFileSync('adb', ['-s', state.device, 'exec-out', 'screencap', '-p'], {
525
+ stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 64 * 1024 * 1024,
526
+ });
527
+ writeFileSync(path, png);
528
+ return { ok: true, out: `saved ${path}` };
529
+ } catch (e) {
530
+ return { ok: false, err: e.stderr?.toString() || e.message };
531
+ }
388
532
  }
389
- return runOk('xcrun', ['simctl', 'io', state.device, 'screenshot', path]);
533
+ const r = runOk('xcrun', ['simctl', 'io', state.device, 'screenshot', path]);
534
+ return r.ok ? { ok: true, out: `saved ${path}` } : r;
390
535
  }
536
+
391
537
  function deepLink(state, url) {
392
538
  reqApp(state);
539
+ if (!url) throw new CliError('deep-link|open-url <url> required', EXIT.USAGE);
393
540
  if (state.platform === 'android') {
394
541
  return runOk('adb', ['-s', state.device, 'shell', 'am', 'start', '-W', '-a', 'android.intent.action.VIEW', '-d', url, state.appId]);
395
542
  }
396
543
  return runOk('xcrun', ['simctl', 'openurl', state.device, url]);
397
544
  }
545
+
398
546
  function running(state) {
399
547
  reqDevice(state);
400
548
  if (state.platform === 'android') {
401
- return runOk('adb', ['-s', state.device, 'shell', 'dumpsys', 'window'], {}).out
402
- .split('\n').filter(l => /mCurrentFocus|mFocusedApp/.test(l)).join('\n');
549
+ const r = runOk('adb', ['-s', state.device, 'shell', 'dumpsys', 'window']);
550
+ if (!r.ok) return r;
551
+ return { ok: true, out: r.out.split('\n').filter((l) => /mCurrentFocus|mFocusedApp/.test(l)).join('\n') };
403
552
  }
404
- return run('xcrun', ['simctl', 'listapps', state.device]).slice(0, 400);
553
+ const r = runOk('xcrun', ['simctl', 'listapps', state.device]);
554
+ return r.ok ? { ok: true, out: r.out.slice(0, 400) } : r;
405
555
  }
406
556
 
557
+ export function parseSince(args) {
558
+ const i = args.indexOf('--since');
559
+ if (i < 0) return 60;
560
+ const v = args[i + 1];
561
+ if (!/^\d+$/.test(v || '') || Number(v) <= 0) {
562
+ throw new CliError('--since needs a positive integer number of seconds', EXIT.USAGE);
563
+ }
564
+ return Number(v);
565
+ }
407
566
  function logs(state, args) {
408
567
  reqDevice(state);
409
568
  const errors = args.includes('--errors');
410
- const sinceIdx = args.indexOf('--since');
411
- const since = sinceIdx >= 0 ? parseInt(args[sinceIdx + 1], 10) : 60;
569
+ const since = parseSince(args);
412
570
  if (state.platform === 'android') {
413
- // logcat with time filter; need to compute -T <time>
414
571
  const t = new Date(Date.now() - since * 1000);
415
- const ts = `${String(t.getMonth() + 1).padStart(2, '0')}-${String(t.getDate()).padStart(2, '0')} ${String(t.getHours()).padStart(2, '0')}:${String(t.getMinutes()).padStart(2, '0')}:${String(t.getSeconds()).padStart(2, '0')}.000`;
416
- const lvl = errors ? '*:E' : '*:W';
417
- const out = runOk('adb', ['-s', state.device, 'logcat', '-d', '-T', ts, lvl]).out || '';
418
- return out.split('\n').slice(-400).join('\n');
572
+ const p2 = (x) => String(x).padStart(2, '0');
573
+ const ts = `${p2(t.getMonth() + 1)}-${p2(t.getDate())} ${p2(t.getHours())}:${p2(t.getMinutes())}:${p2(t.getSeconds())}.000`;
574
+ const r = runOk('adb', ['-s', state.device, 'logcat', '-d', '-T', ts, errors ? '*:E' : '*:W']);
575
+ return r.ok ? { ok: true, out: (r.out || '').split('\n').slice(-400).join('\n') } : r;
419
576
  }
420
- const out = runOk('xcrun', ['simctl', 'spawn', state.device, 'log', 'show', '--last', `${since}s`, '--predicate', `processImagePath contains "${state.appId || ''}"`]).out || '';
421
- return out.split('\n').slice(-400).join('\n');
577
+ const r = runOk('xcrun', ['simctl', 'spawn', state.device, 'log', 'show', '--last', `${since}s`, '--predicate', `processImagePath contains "${state.appId || ''}"`]);
578
+ return r.ok ? { ok: true, out: (r.out || '').split('\n').slice(-400).join('\n') } : r;
422
579
  }
423
580
  function logsClear(state) {
424
581
  reqDevice(state);
@@ -426,148 +583,279 @@ function logsClear(state) {
426
583
  return { ok: true, out: '(ios log buffer not clearable)' };
427
584
  }
428
585
 
429
- function recordStart(state, path) {
586
+ // ---- recording ----
587
+ function readRec() {
588
+ if (!existsSync(recPath())) return null;
589
+ try { return JSON.parse(readFileSync(recPath(), 'utf8')); } catch { return null; }
590
+ }
591
+ function recordStart(state, outPath) {
430
592
  reqDevice(state);
431
- if (existsSync(REC_PID_PATH)) throw new Error('Recording already in progress.');
432
- let proc;
593
+ if (!outPath) throw new CliError('record-start <path.mp4> required', EXIT.USAGE);
594
+ if (readRec()) throw new CliError('Recording already in progress (run record-stop first).');
595
+ mkdirSync(dirname(outPath) || '.', { recursive: true });
596
+ const startedAt = new Date().toISOString();
433
597
  if (state.platform === 'android') {
434
- // screenrecord runs on device, then we pull. simpler: use adb screenrecord directly piped to file (max 3min)
435
- proc = spawn('adb', ['-s', state.device, 'exec-out', 'screenrecord', '--output-format=h264', '-'], {
436
- stdio: ['ignore', 'pipe', 'inherit'],
437
- });
438
- const w = createWriteStream(path);
439
- proc.stdout.pipe(w);
440
- } else {
441
- proc = spawn('xcrun', ['simctl', 'io', state.device, 'recordVideo', path], { stdio: 'ignore', detached: true });
442
- }
443
- writeFileSync(REC_PID_PATH, String(proc.pid));
598
+ // Record ON the device into a real mp4 container, pull it at record-stop.
599
+ const devicePath = `/sdcard/_mcli_rec_${process.pid}.mp4`;
600
+ const r = runOk('adb', ['-s', state.device, 'shell',
601
+ `screenrecord --time-limit 180 ${devicePath} </dev/null >/dev/null 2>&1 & echo $!`]);
602
+ const devicePid = parseInt((r.out || '').trim().split('\n').pop(), 10);
603
+ if (!r.ok || !Number.isInteger(devicePid)) throw new CliError('could not start screenrecord: ' + (r.err || r.out));
604
+ writeFileSync(recPath(), JSON.stringify({ platform: 'android', device: state.device, devicePid, devicePath, outPath, startedAt }));
605
+ return { ok: true, out: `recording on device (pid ${devicePid}) → ${outPath} (max 180s)` };
606
+ }
607
+ const proc = spawn('xcrun', ['simctl', 'io', state.device, 'recordVideo', outPath], { stdio: 'ignore', detached: true });
444
608
  proc.unref();
445
- return { ok: true, out: `recording pid=${proc.pid}` };
609
+ writeFileSync(recPath(), JSON.stringify({ platform: 'ios', device: state.device, pid: proc.pid, outPath, startedAt }));
610
+ return { ok: true, out: `recording pid=${proc.pid} → ${outPath}` };
446
611
  }
447
612
  function recordStop() {
448
- if (!existsSync(REC_PID_PATH)) throw new Error('No recording in progress.');
449
- const pid = parseInt(readFileSync(REC_PID_PATH, 'utf8'), 10);
450
- try { process.kill(pid, 'SIGINT'); } catch {}
451
- unlinkSync(REC_PID_PATH);
452
- return { ok: true, out: `stopped pid=${pid}` };
613
+ const rec = readRec();
614
+ if (!rec) throw new CliError('No recording in progress.');
615
+ if (rec.platform === 'android') {
616
+ if (!Number.isInteger(rec.devicePid) || !rec.devicePath || !rec.outPath || !rec.device) {
617
+ throw new CliError(`corrupt recording record — delete ${recPath()} and retry`);
618
+ }
619
+ runOk('adb', ['-s', rec.device, 'shell', 'kill', '-2', String(rec.devicePid)]);
620
+ sleep(1500);
621
+ for (let i = 0; i < 10; i++) { // wait for screenrecord to finalise the file
622
+ const alive = runOk('adb', ['-s', rec.device, 'shell', 'kill', '-0', String(rec.devicePid)]);
623
+ if (!alive.ok) break;
624
+ sleep(500);
625
+ }
626
+ const pull = runOk('adb', ['-s', rec.device, 'pull', rec.devicePath, rec.outPath]);
627
+ runOk('adb', ['-s', rec.device, 'shell', 'rm', '-f', rec.devicePath]);
628
+ unlinkSync(recPath());
629
+ return pull.ok ? { ok: true, out: `saved ${rec.outPath}` } : { ok: false, err: pull.err || pull.out };
630
+ }
631
+ if (!Number.isInteger(rec.pid)) throw new CliError(`corrupt recording record — delete ${recPath()} and retry`);
632
+ let alive = true;
633
+ try { process.kill(rec.pid, 0); } catch { alive = false; }
634
+ if (alive) { try { process.kill(rec.pid, 'SIGINT'); } catch { /* already gone */ } }
635
+ unlinkSync(recPath());
636
+ return alive
637
+ ? { ok: true, out: `stopped pid=${rec.pid} → ${rec.outPath}` }
638
+ : { ok: false, err: `recorder pid=${rec.pid} was not running — ${rec.outPath} may be incomplete` };
639
+ }
640
+
641
+ // ---- boot ----
642
+ function listAvds() {
643
+ const r = runOk('emulator', ['-list-avds']);
644
+ return r.ok ? r.out.split('\n').map((s) => s.trim()).filter((s) => /^[\w.-]+$/.test(s)) : [];
645
+ }
646
+ function boot(name) {
647
+ if (!name) throw new CliError('boot <avd|sim-name|udid> required', EXIT.USAGE);
648
+ const sim = detectPlatform(name, { simDevices: listSimDevices() });
649
+ if (sim) {
650
+ const b = runOk('xcrun', ['simctl', 'boot', sim.device]);
651
+ if (!b.ok && !/already booted|current state: Booted/i.test(b.err || '')) throw new CliError('simctl boot failed: ' + b.err);
652
+ runOk('open', ['-a', 'Simulator']);
653
+ runOk('xcrun', ['simctl', 'bootstatus', sim.device, '-b']);
654
+ return sim;
655
+ }
656
+ const avds = listAvds();
657
+ if (!avds.includes(name)) {
658
+ throw new CliError(`'${name}' is neither an iOS simulator nor an Android AVD (emulator -list-avds: ${avds.join(', ') || 'none'})`, EXIT.USAGE);
659
+ }
660
+ // Adopt an emulator that is already running this AVD instead of spawning a
661
+ // second one (which would wait 180 s for a serial that never boots).
662
+ for (const s of listAdbSerials().filter((x) => x.startsWith('emulator-'))) {
663
+ const r = runOk('adb', ['-s', s, 'emu', 'avd', 'name']);
664
+ const running = (r.out || '').split('\n')[0].trim();
665
+ if (running !== name) continue;
666
+ const done = runOk('adb', ['-s', s, 'shell', 'getprop', 'sys.boot_completed']);
667
+ if ((done.out || '').trim() === '1') return { platform: 'android', device: s, deviceName: name };
668
+ }
669
+ const before = listAdbSerials();
670
+ const proc = spawn('emulator', ['-avd', name, '-no-snapshot', '-no-boot-anim'], { stdio: 'ignore', detached: true });
671
+ proc.unref();
672
+ const deadline = Date.now() + 180_000;
673
+ let serial = null;
674
+ while (Date.now() < deadline) {
675
+ const fresh = listAdbSerials().filter((s) => s.startsWith('emulator-') && !before.includes(s));
676
+ if (fresh.length) {
677
+ const done = runOk('adb', ['-s', fresh[0], 'shell', 'getprop', 'sys.boot_completed']);
678
+ if ((done.out || '').trim() === '1') { serial = fresh[0]; break; }
679
+ }
680
+ sleep(2000);
681
+ }
682
+ if (!serial) throw new CliError('emulator did not finish booting within 180s');
683
+ return { platform: 'android', device: serial, deviceName: name };
684
+ }
685
+
686
+ // Adopt a resolved device: per-device state file (unless --state/$MOBILE_CLI_STATE), refs cleared.
687
+ function adoptDevice(state, res) {
688
+ if (!STATE_PATH_EXPLICIT) {
689
+ STATE_PATH = join(MCLI_DIR, `${sanitizeDeviceId(res.device)}.json`);
690
+ mkdirSync(MCLI_DIR, { recursive: true });
691
+ writeFileSync(CURRENT_POINTER, STATE_PATH);
692
+ const existing = loadStateFrom(STATE_PATH);
693
+ for (const k of Object.keys(state)) delete state[k];
694
+ Object.assign(state, existing);
695
+ }
696
+ state.device = res.device;
697
+ state.deviceName = res.deviceName || null;
698
+ state.platform = res.platform;
699
+ state.refs = {};
700
+ state.capturedAt = null;
701
+ saveState(state);
453
702
  }
454
703
 
455
- function sleep(ms) {
456
- try { execSync(`sleep ${(ms / 1000).toFixed(3)}`); } catch {}
704
+ export function readVersion(here = HERE) {
705
+ const vf = join(here, 'VERSION'); // written by `qualiow init` next to the copied driver
706
+ if (existsSync(vf)) {
707
+ const v = readFileSync(vf, 'utf8').trim();
708
+ if (v) return v;
709
+ }
710
+ const pj = join(here, '..', 'package.json');
711
+ if (existsSync(pj)) {
712
+ try {
713
+ const p = JSON.parse(readFileSync(pj, 'utf8'));
714
+ if (p.name === 'qualiow-exploratory-testing' && p.version) return p.version;
715
+ } catch { /* ignore */ }
716
+ }
717
+ return 'unknown';
457
718
  }
458
719
 
720
+ export const HELP = `mobile-cli — Maestro-backed shim for iOS/Android exploratory testing (native apps and sim browsers)
721
+
722
+ Usage: mobile-cli [--state <file>] <command> [args]
723
+
724
+ Setup:
725
+ set-device <id> [--platform ios|android] adb serial, iOS sim UDID, or iOS sim NAME (resolved via simctl)
726
+ set-app <appId> e.g. com.apple.mobilesafari | com.android.chrome | io.example.app
727
+ boot <avd|sim-name|udid> boot an Android AVD or iOS simulator, wait for it, then set-device it
728
+ info resolved state + the state file in use
729
+ version print the mobile-cli version
730
+
731
+ App lifecycle:
732
+ launch | stop | relaunch-clean (relaunch-clean = stop + pm clear + launch, android only)
733
+ deep-link <url> open a deep link in the app
734
+ open-url <url> open a URL in the device browser — alias of deep-link
735
+ running which activity / app is foreground
736
+
737
+ Interaction (refs come from the last snapshot and expire after MCLI_REF_TTL_MS, default 60s):
738
+ snapshot [--full] print the on-screen a11y tree as refs e1, e2, ...
739
+ click <ref> tap element by ref
740
+ fill <ref> <text...> tap then enter text (Maestro inputText flow — fast on long text)
741
+ clear <ref> tap then erase the field's existing text (Maestro eraseText)
742
+ tap-id <testID> tap by testID directly (skips snapshot)
743
+ fill-id <testID> <text...> tapOn id + inputText in one Maestro flow (fastest combo)
744
+ wait-text <substring> [timeout-sec] poll hierarchy for text to appear, default 10s
745
+ press <BACK|ENTER|HOME|TAB|ESCAPE> (iOS: ENTER + HOME via Maestro pressKey)
746
+
747
+ Evidence:
748
+ screenshot <path> save PNG (no app required)
749
+ logs [--since <sec>] [--errors] device logs (logcat / simctl log), default last 60s
750
+ logs-clear clear the device log buffer (android)
751
+ record-start <path.mp4> | record-stop video recording, mp4 on both platforms (android max 180s)
752
+
753
+ State:
754
+ --state <file> state file for this invocation (also $MOBILE_CLI_STATE);
755
+ otherwise set-device picks ~/.mobile-cli/<device>.json
756
+
757
+ Exit codes: 0 ok · 1 command failed · 2 usage · 3 stale/unknown ref (run snapshot) · 4 no device/app set
758
+ `;
759
+
459
760
  // ---- main ----
460
- function main() {
461
- const [, , cmd, ...args] = process.argv;
761
+ function emit(r, fallback) {
762
+ process.exitCode = r.ok ? EXIT.OK : EXIT.FAILED;
763
+ const text = r.ok ? (r.out || fallback || '') : (r.err || r.out || fallback || 'failed');
764
+ if (text) console.log(text);
765
+ }
766
+
767
+ export function main(argv = process.argv.slice(2)) {
768
+ let parsed;
769
+ try { parsed = parseGlobalFlags(argv); } catch (e) { console.error(`mobile-cli error: ${e.message}`); process.exit(e.exitCode || EXIT.USAGE); }
770
+ const { args: all, statePath: flagPath } = parsed;
771
+ const [cmd, ...args] = all;
462
772
  if (!cmd || cmd === '--help' || cmd === '-h') {
463
- console.log(`mobile-cli — Maestro-backed shim for native iOS/Android exploratory testing
464
-
465
- Commands:
466
- set-device <udid> e.g. emulator-5554 OR iOS sim UDID
467
- set-app <appId> e.g. com.apple.mobilesafari | com.android.chrome | io.example.app
468
- info
469
- launch | stop | relaunch-clean
470
- snapshot [--full]
471
- click <ref> ref = e1, e2, ... from last snapshot
472
- fill <ref> <text...> tap then enter text (uses Maestro flow — fast on long text)
473
- clear <ref> tap then erase the field's existing text (Maestro eraseText)
474
- tap-id <testID> tap by testID directly (skips snapshot — saves a hierarchy call)
475
- fill-id <testID> <text...> tap by id + inputText in one Maestro flow (fastest combo)
476
- wait-text <substring> [timeout-sec] poll hierarchy for text to appear, default 10s
477
- press <BACK|ENTER|HOME|TAB|ESCAPE> (iOS: ENTER + HOME via Maestro; BACK is Android-only)
478
- screenshot <path>
479
- logs [--since <sec>] [--errors]
480
- logs-clear
481
- deep-link <url>
482
- open-url <url> open a URL in the device browser (Safari/Chrome) — alias of deep-link
483
- running
484
- record-start <path> | record-stop
485
- `);
773
+ console.log(HELP);
486
774
  process.exit(0);
487
775
  }
776
+ if (cmd === 'version' || cmd === '--version') { console.log(readVersion()); process.exit(0); }
777
+
778
+ const resolved = resolveStatePath(flagPath);
779
+ STATE_PATH = resolved.path;
780
+ STATE_PATH_EXPLICIT = resolved.explicit;
488
781
  const state = loadState();
489
782
  try {
490
783
  switch (cmd) {
491
784
  case 'set-device': {
492
- state.device = args[0];
493
- state.platform = platformFromDevice(args[0]);
494
- saveState(state);
495
- console.log(`device=${state.device} platform=${state.platform}`);
785
+ const id = args.find((a) => !a.startsWith('--'));
786
+ const pi = args.indexOf('--platform');
787
+ const platform = pi >= 0 ? args[pi + 1] : (args.find((a) => a.startsWith('--platform=')) || '').slice('--platform='.length) || undefined;
788
+ if (platform && !['ios', 'android'].includes(platform)) throw new CliError('--platform must be ios or android', EXIT.USAGE);
789
+ adoptDevice(state, resolveDevice(id, { platform }));
790
+ console.log(`device=${state.device}${state.deviceName ? ` name=${state.deviceName}` : ''} platform=${state.platform} state=${STATE_PATH}`);
791
+ return;
792
+ }
793
+ case 'boot': {
794
+ adoptDevice(state, boot(args[0]));
795
+ console.log(`booted ${state.deviceName || state.device} → device=${state.device} platform=${state.platform} state=${STATE_PATH}`);
496
796
  return;
497
797
  }
498
798
  case 'set-app': {
499
799
  reqDevice(state);
800
+ if (!args[0]) throw new CliError('set-app <appId> required', EXIT.USAGE);
500
801
  state.appId = args[0];
501
802
  saveState(state);
502
803
  console.log(`appId=${state.appId}`);
503
804
  return;
504
805
  }
505
806
  case 'info': {
506
- console.log(JSON.stringify({ device: state.device, platform: state.platform, appId: state.appId, refs: Object.keys(state.refs || {}).length, capturedAt: state.capturedAt }, null, 2));
807
+ console.log(JSON.stringify({
808
+ state_file: STATE_PATH, device: state.device || null, deviceName: state.deviceName || null,
809
+ platform: state.platform || null, appId: state.appId || null,
810
+ refs: Object.keys(state.refs || {}).length, capturedAt: state.capturedAt || null,
811
+ ref_ttl_ms: REF_TTL_MS, recording: readRec() ? readRec().outPath : null,
812
+ }, null, 2));
507
813
  return;
508
814
  }
509
- case 'launch': { const r = launch(state); process.exitCode = r.ok ? 0 : 1; console.log(r.out || r.err); return; }
510
- case 'stop': { const r = stop(state); process.exitCode = r.ok ? 0 : 1; console.log(r.out || r.err); return; }
511
- case 'relaunch-clean': { const r = relaunchClean(state); process.exitCode = r.ok ? 0 : 1; console.log(r.out || r.err); return; }
815
+ case 'launch': return emit(launch(state), 'launched');
816
+ case 'stop': return emit(stop(state), 'stopped');
817
+ case 'relaunch-clean': return emit(relaunchClean(state), 'relaunched');
512
818
  case 'snapshot': {
513
- const full = args.includes('--full');
514
- const { tree, count } = snapshot(state, { full });
819
+ const { tree, count } = snapshot(state, { full: args.includes('--full') });
515
820
  console.log(tree);
516
- console.log(`\n(${count} refs captured)`);
821
+ console.log(`\n(${count} refs captured; valid for ${REF_TTL_MS / 1000}s)`);
517
822
  return;
518
823
  }
519
- case 'click': {
520
- const r = tap(state, args[0]);
521
- process.exitCode = r.ok ? 0 : 1; console.log(r.out || r.err || `tapped ${args[0]}`); return;
522
- }
523
- case 'tap-id': {
524
- const r = tapById(state, args[0]);
525
- process.exitCode = r.ok ? 0 : 1; console.log(r.out || r.err || `tapped id=${args[0]}`); return;
526
- }
527
- case 'fill': {
528
- const ref = args[0]; const text = args.slice(1).join(' ');
529
- const r = fill(state, ref, text);
530
- process.exitCode = r.ok ? 0 : 1; console.log(r.out || r.err || `filled ${ref}`); return;
531
- }
532
- case 'clear': {
533
- const r = clearField(state, args[0]);
534
- process.exitCode = r.ok ? 0 : 1; console.log(r.out || r.err || `cleared ${args[0]}`); return;
535
- }
536
- case 'fill-id': {
537
- const id = args[0]; const text = args.slice(1).join(' ');
538
- const r = fillById(state, id, text);
539
- process.exitCode = r.ok ? 0 : 1; console.log(r.out || r.err || `filled id=${id}`); return;
540
- }
824
+ case 'click': return emit(tap(state, args[0]), `tapped ${args[0]}`);
825
+ case 'tap-id': return emit(tapById(state, args[0]), `tapped id=${args[0]}`);
826
+ case 'fill': return emit(fill(state, args[0], args.slice(1).join(' ')), `filled ${args[0]}`);
827
+ case 'clear': return emit(clearField(state, args[0]), `cleared ${args[0]}`);
828
+ case 'fill-id': return emit(fillById(state, args[0], args.slice(1).join(' ')), `filled id=${args[0]}`);
541
829
  case 'wait-text': {
542
- const r = waitText(state, args[0], args[1] ? parseInt(args[1], 10) : 10);
543
- process.exitCode = r.ok ? 0 : 1; console.log(r.out || r.err); return;
830
+ const t = args[1] ? Number(args[1]) : 10;
831
+ if (!(t > 0)) throw new CliError('wait-text timeout must be a positive number of seconds', EXIT.USAGE);
832
+ return emit(waitText(state, args[0], t));
544
833
  }
545
- case 'press': {
546
- const r = press(state, args[0]);
547
- process.exitCode = r.ok ? 0 : 1; console.log(r.out || r.err || `pressed ${args[0]}`); return;
548
- }
549
- case 'screenshot': {
550
- const r = screenshot(state, args[0]);
551
- process.exitCode = r.ok ? 0 : 1; console.log(r.out || r.err || `saved ${args[0]}`); return;
552
- }
553
- case 'logs': console.log(logs(state, args)); return;
554
- case 'logs-clear': { const r = logsClear(state); console.log(r.out || r.err); return; }
555
- case 'deep-link': { const r = deepLink(state, args[0]); process.exitCode = r.ok ? 0 : 1; console.log(r.out || r.err || `opened ${args[0]}`); return; }
556
- // open-url — ergonomic alias of deep-link for browser targets. simctl openurl /
557
- // am start VIEW already opens any http(s) URL in the device browser; the URL does
558
- // not need to be registered as an app-scoped deep link.
559
- case 'open-url': { const r = deepLink(state, args[0]); process.exitCode = r.ok ? 0 : 1; console.log(r.ok ? `opened ${args[0]}` : (r.err || r.out)); return; }
560
- case 'running': console.log(running(state)); return;
561
- case 'record-start': { const r = recordStart(state, args[0]); console.log(r.out); return; }
562
- case 'record-stop': { const r = recordStop(); console.log(r.out); return; }
834
+ case 'press': return emit(press(state, args[0]), `pressed ${args[0]}`);
835
+ case 'screenshot': return emit(screenshot(state, args[0]), `saved ${args[0]}`);
836
+ case 'logs': return emit(logs(state, args), '(no log lines)');
837
+ case 'logs-clear': return emit(logsClear(state), 'cleared');
838
+ case 'deep-link':
839
+ case 'open-url': return emit(deepLink(state, args[0]), `opened ${args[0]}`);
840
+ case 'running': return emit(running(state), '(nothing in foreground)');
841
+ case 'record-start': return emit(recordStart(state, args[0]));
842
+ case 'record-stop': return emit(recordStop());
563
843
  default:
564
844
  console.error(`Unknown command: ${cmd}. Run with --help.`);
565
- process.exit(2);
845
+ process.exit(EXIT.USAGE);
566
846
  }
567
847
  } catch (e) {
568
848
  console.error(`mobile-cli error: ${e.message}`);
569
- process.exit(1);
849
+ process.exit(e instanceof CliError ? e.exitCode : EXIT.FAILED);
570
850
  }
571
851
  }
572
852
 
573
- main();
853
+ // Only run when executed directly (not when imported by tests). Compare real paths so a
854
+ // symlinked bin entry still counts as a direct invocation.
855
+ function isDirectInvocation() {
856
+ const entry = process.argv[1];
857
+ if (!entry) return false;
858
+ try { return pathToFileURL(realpathSync(entry)).href === import.meta.url; }
859
+ catch { return pathToFileURL(entry).href === import.meta.url; }
860
+ }
861
+ if (isDirectInvocation()) main();