emd-agents 0.0.0-stage → 0.14.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 (77) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +121 -2
  4. package/dist/adapters/expo/index.d.ts +3 -0
  5. package/dist/adapters/expo/index.js +55 -0
  6. package/dist/bin.d.ts +2 -0
  7. package/dist/bin.js +11 -0
  8. package/dist/cli/main.d.ts +1 -0
  9. package/dist/cli/main.js +265 -0
  10. package/dist/core/adapter.d.ts +32 -0
  11. package/dist/core/adapter.js +3 -0
  12. package/dist/core/check.d.ts +20 -0
  13. package/dist/core/check.js +214 -0
  14. package/dist/core/checkrecord.d.ts +22 -0
  15. package/dist/core/checkrecord.js +34 -0
  16. package/dist/core/detect.d.ts +2 -0
  17. package/dist/core/detect.js +27 -0
  18. package/dist/core/device/axe.d.ts +10 -0
  19. package/dist/core/device/axe.js +66 -0
  20. package/dist/core/device/backend.d.ts +43 -0
  21. package/dist/core/device/backend.js +72 -0
  22. package/dist/core/device/maestro.d.ts +4 -0
  23. package/dist/core/device/maestro.js +86 -0
  24. package/dist/core/device/screen.d.ts +9 -0
  25. package/dist/core/device/screen.js +7 -0
  26. package/dist/core/doctor.d.ts +12 -0
  27. package/dist/core/doctor.js +70 -0
  28. package/dist/core/evidence.d.ts +9 -0
  29. package/dist/core/evidence.js +107 -0
  30. package/dist/core/gc.d.ts +22 -0
  31. package/dist/core/gc.js +172 -0
  32. package/dist/core/index.d.ts +17 -0
  33. package/dist/core/index.js +16 -0
  34. package/dist/core/input.d.ts +15 -0
  35. package/dist/core/input.js +59 -0
  36. package/dist/core/isolate.d.ts +4 -0
  37. package/dist/core/isolate.js +43 -0
  38. package/dist/core/jobs.d.ts +21 -0
  39. package/dist/core/jobs.js +114 -0
  40. package/dist/core/jobstore.d.ts +21 -0
  41. package/dist/core/jobstore.js +45 -0
  42. package/dist/core/launch.d.ts +8 -0
  43. package/dist/core/launch.js +273 -0
  44. package/dist/core/log.d.ts +5 -0
  45. package/dist/core/log.js +54 -0
  46. package/dist/core/logs.d.ts +19 -0
  47. package/dist/core/logs.js +122 -0
  48. package/dist/core/owned.d.ts +19 -0
  49. package/dist/core/owned.js +91 -0
  50. package/dist/core/probe.d.ts +2 -0
  51. package/dist/core/probe.js +14 -0
  52. package/dist/core/process.d.ts +10 -0
  53. package/dist/core/process.js +32 -0
  54. package/dist/core/project.d.ts +6 -0
  55. package/dist/core/project.js +76 -0
  56. package/dist/core/registry.d.ts +3 -0
  57. package/dist/core/registry.js +13 -0
  58. package/dist/core/result.d.ts +248 -0
  59. package/dist/core/result.js +147 -0
  60. package/dist/core/run.d.ts +15 -0
  61. package/dist/core/run.js +22 -0
  62. package/dist/core/setup.d.ts +29 -0
  63. package/dist/core/setup.js +202 -0
  64. package/dist/core/simulator.d.ts +21 -0
  65. package/dist/core/simulator.js +107 -0
  66. package/dist/core/state.d.ts +2 -0
  67. package/dist/core/state.js +9 -0
  68. package/dist/core/tool.d.ts +5 -0
  69. package/dist/core/tool.js +54 -0
  70. package/dist/core/version.d.ts +1 -0
  71. package/dist/core/version.js +5 -0
  72. package/dist/core/workspace.d.ts +1 -0
  73. package/dist/core/workspace.js +109 -0
  74. package/dist/mcp/server.d.ts +1 -0
  75. package/dist/mcp/server.js +188 -0
  76. package/package.json +58 -4
  77. package/skills/emd/SKILL.md +35 -0
@@ -0,0 +1,265 @@
1
+ import { createInterface } from "node:readline/promises";
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";
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
+ // --log smoke or --log smoke=tapped
6
+ const logSpec = (raw) => {
7
+ const at = raw.indexOf("=");
8
+ return at < 0
9
+ ? { tag: raw }
10
+ : { tag: raw.slice(0, at), message: raw.slice(at + 1) };
11
+ };
12
+ // --element id=smoke-button or text=Tapped or '{"id":"x","text":"y"}'
13
+ const elementSpec = (raw) => {
14
+ if (raw.startsWith("{"))
15
+ return JSON.parse(raw);
16
+ const at = raw.indexOf("=");
17
+ const key = raw.slice(0, at);
18
+ if (at < 0 || (key !== "id" && key !== "text")) {
19
+ throw new Error(`--element wants id=X, text=Y or JSON, not "${raw}"`);
20
+ }
21
+ return { [key]: raw.slice(at + 1) };
22
+ };
23
+ const ask = async (question) => {
24
+ const prompt = createInterface({
25
+ input: process.stdin,
26
+ output: process.stdout,
27
+ });
28
+ const answer = await prompt.question(question);
29
+ prompt.close();
30
+ return answer.trim();
31
+ };
32
+ // Only a person at a terminal can start the failure count and the recorded
33
+ // expectations over (decisions 0006, 0010).
34
+ async function resetCommand(dir) {
35
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
36
+ console.error("emd: check reset needs a person at a terminal.");
37
+ return 2;
38
+ }
39
+ const { root } = await detect(dir);
40
+ const typed = await ask(`Clear the failed-check count and recorded expectations for ${root}? Type "reset": `);
41
+ if (typed !== "reset") {
42
+ console.error("emd: not reset.");
43
+ return 1;
44
+ }
45
+ resetChecks(root);
46
+ console.log(JSON.stringify({ verdict: "reset", root }));
47
+ return 0;
48
+ }
49
+ export async function run(argv) {
50
+ const [command, ...args] = argv;
51
+ switch (command) {
52
+ case undefined:
53
+ console.log(`emd ${version()}`);
54
+ return 0;
55
+ case "detect":
56
+ console.log(JSON.stringify(await detect(args[0])));
57
+ return 0;
58
+ case "launch": {
59
+ const { values, positionals } = parseArgs({
60
+ args,
61
+ allowPositionals: true,
62
+ options: {
63
+ device: { type: "string" },
64
+ timeout: { type: "string" },
65
+ },
66
+ });
67
+ const timeoutSeconds = values.timeout
68
+ ? Number(values.timeout)
69
+ : undefined;
70
+ if (timeoutSeconds !== undefined && !(timeoutSeconds > 0)) {
71
+ console.error(`emd: --timeout must be a number of seconds. ${usage}`);
72
+ return 2;
73
+ }
74
+ const result = await launch({
75
+ dir: positionals[0],
76
+ device: values.device,
77
+ timeoutSeconds,
78
+ });
79
+ console.log(JSON.stringify(result));
80
+ return result.verdict === "launched" ? 0 : 1;
81
+ }
82
+ case "job": {
83
+ const [action, id] = args;
84
+ if (action === "run" && id) {
85
+ // Internal: the worker process that a started job runs in.
86
+ await runJob(id);
87
+ return 0;
88
+ }
89
+ if (action === "status" && id) {
90
+ const job = jobStatus(id);
91
+ if (!job) {
92
+ console.error(`emd: no job "${id}".`);
93
+ return 1;
94
+ }
95
+ console.log(JSON.stringify(job));
96
+ return 0;
97
+ }
98
+ console.error(`emd: usage: job status <id>. ${usage}`);
99
+ return 2;
100
+ }
101
+ case "logs": {
102
+ const { values, positionals } = parseArgs({
103
+ args,
104
+ allowPositionals: true,
105
+ options: {
106
+ tag: { type: "string" },
107
+ limit: { type: "string" },
108
+ },
109
+ });
110
+ const jobId = positionals[0];
111
+ if (!jobId) {
112
+ console.error(`emd: usage: logs <jobId>. ${usage}`);
113
+ return 2;
114
+ }
115
+ const result = await logs({
116
+ jobId,
117
+ tag: values.tag,
118
+ limit: values.limit === undefined ? undefined : Number(values.limit),
119
+ });
120
+ console.log(JSON.stringify(result));
121
+ return result.verdict === "ok" ? 0 : 1;
122
+ }
123
+ case "tap": {
124
+ const { values, positionals } = parseArgs({
125
+ args,
126
+ allowPositionals: true,
127
+ options: {
128
+ id: { type: "string" },
129
+ text: { type: "string" },
130
+ x: { type: "string" },
131
+ y: { type: "string" },
132
+ },
133
+ });
134
+ const number = (raw) => raw === undefined ? undefined : Number(raw);
135
+ const result = await tap({
136
+ jobId: positionals[0] ?? "",
137
+ id: values.id,
138
+ text: values.text,
139
+ x: number(values.x),
140
+ y: number(values.y),
141
+ });
142
+ console.log(JSON.stringify(result));
143
+ return result.verdict === "ok" ? 0 : 1;
144
+ }
145
+ case "type":
146
+ case "swipe": {
147
+ const { positionals } = parseArgs({ args, allowPositionals: true });
148
+ const [jobId = "", value = ""] = positionals;
149
+ const result = command === "type"
150
+ ? await typeText({ jobId, text: value })
151
+ : await swipe({ jobId, direction: value });
152
+ console.log(JSON.stringify(result));
153
+ return result.verdict === "ok" ? 0 : 1;
154
+ }
155
+ case "check": {
156
+ if (args[0] === "reset")
157
+ return resetCommand(args[1]);
158
+ const { values, positionals } = parseArgs({
159
+ args,
160
+ allowPositionals: true,
161
+ options: {
162
+ log: { type: "string", multiple: true },
163
+ element: { type: "string", multiple: true },
164
+ agent: { type: "string" },
165
+ name: { type: "string" },
166
+ },
167
+ });
168
+ if (values.agent && values.agent !== "pass" && values.agent !== "fail") {
169
+ console.error(`emd: --agent is pass or fail. ${usage}`);
170
+ return 2;
171
+ }
172
+ let elements;
173
+ try {
174
+ elements = (values.element ?? []).map(elementSpec);
175
+ }
176
+ catch (error) {
177
+ console.error(`emd: ${error.message}`);
178
+ return 2;
179
+ }
180
+ const jobId = positionals[0];
181
+ if (!jobId) {
182
+ console.error(`emd: usage: check <jobId>. ${usage}`);
183
+ return 2;
184
+ }
185
+ const result = await check({
186
+ jobId,
187
+ logs: (values.log ?? []).map(logSpec),
188
+ elements,
189
+ name: values.name,
190
+ agentReading: values.agent,
191
+ });
192
+ console.log(JSON.stringify(result));
193
+ return result.verdict === "passed" ? 0 : 1;
194
+ }
195
+ case "evidence": {
196
+ const jobId = args[0];
197
+ if (!jobId) {
198
+ console.error(`emd: usage: evidence <jobId>. ${usage}`);
199
+ return 2;
200
+ }
201
+ const result = await evidence({ jobId });
202
+ console.log(JSON.stringify(result));
203
+ return result.verdict === "written" ? 0 : 1;
204
+ }
205
+ case "gc": {
206
+ const { values } = parseArgs({
207
+ args,
208
+ options: { apply: { type: "boolean" } },
209
+ });
210
+ const result = await gc({ apply: values.apply });
211
+ console.log(JSON.stringify(result));
212
+ const failed = result.verdict === "failed" ||
213
+ result.entries.some((e) => e.status === "failed");
214
+ return failed ? 1 : 0;
215
+ }
216
+ case "doctor": {
217
+ const result = await doctor();
218
+ console.log(JSON.stringify(result));
219
+ return result.verdict === "ready" ? 0 : 1;
220
+ }
221
+ case "setup": {
222
+ const { values } = parseArgs({
223
+ args,
224
+ options: {
225
+ "dry-run": { type: "boolean" },
226
+ yes: { type: "boolean" },
227
+ agent: { type: "string", multiple: true },
228
+ },
229
+ });
230
+ const only = values.agent;
231
+ const plan = await setup({ only });
232
+ if (plan.verdict !== "planned" || values["dry-run"]) {
233
+ console.log(JSON.stringify(plan));
234
+ return plan.verdict === "failed" ? 1 : 0;
235
+ }
236
+ // One approval for the whole plan (decision 0002). Without a person at a
237
+ // terminal, only --yes applies it.
238
+ let approved = values.yes === true;
239
+ if (!approved && process.stdin.isTTY && process.stdout.isTTY) {
240
+ const axe = plan.axe
241
+ ? `EMD setup will install AXe ${plan.axe.version} into ${plan.axe.dir}, from ${plan.axe.url}, SHA-256 ${plan.axe.sha256}.\n`
242
+ : "";
243
+ console.error(`${axe}EMD setup will run, for ${plan.agents.map((a) => a.id).join(", ")}:\n${plan.steps.map((s) => ` ${s}`).join("\n")}\nIt backs up each config first, in ~/.emd/backups.`);
244
+ approved = !/^n/i.test(await ask("Apply? [Y/n] "));
245
+ }
246
+ if (!approved) {
247
+ console.log(JSON.stringify(plan));
248
+ return 0;
249
+ }
250
+ const result = await setup({ only, apply: true });
251
+ console.log(JSON.stringify(result));
252
+ if (result.restart && process.stderr.isTTY) {
253
+ for (const check of result.doctor?.checks ?? []) {
254
+ if (check.fix)
255
+ console.error(`Missing ${check.name}: ${check.fix}`);
256
+ }
257
+ console.error(`Restart ${result.restart.join(", ")} to load EMD.`);
258
+ }
259
+ return result.verdict === "done" ? 0 : 1;
260
+ }
261
+ default:
262
+ console.error(`emd: unknown command "${command}". ${usage}`);
263
+ return 2;
264
+ }
265
+ }
@@ -0,0 +1,32 @@
1
+ export declare const stackIds: readonly ["expo"];
2
+ export declare const platforms: readonly ["ios", "android"];
3
+ export declare const packageManagers: readonly ["npm", "yarn", "pnpm", "bun"];
4
+ export type StackId = (typeof stackIds)[number];
5
+ export type Platform = (typeof platforms)[number];
6
+ export type PackageManager = (typeof packageManagers)[number];
7
+ export type ProjectInfo = {
8
+ packageManager: PackageManager;
9
+ exec: string;
10
+ };
11
+ export type StackDetection = {
12
+ stack: StackId;
13
+ platforms: Platform[];
14
+ appIds: Partial<Record<Platform, string>>;
15
+ commands: {
16
+ run: Partial<Record<Platform, string>>;
17
+ server: string;
18
+ };
19
+ };
20
+ export type LaunchPlan = {
21
+ server: string;
22
+ build: string;
23
+ };
24
+ export interface StackAdapter {
25
+ id: StackId;
26
+ detect(projectDir: string, project: ProjectInfo): Promise<StackDetection | undefined>;
27
+ launchPlan(project: ProjectInfo, request: {
28
+ platform: Platform;
29
+ deviceId: string;
30
+ port: number;
31
+ }): LaunchPlan | undefined;
32
+ }
@@ -0,0 +1,3 @@
1
+ export const stackIds = ["expo"];
2
+ export const platforms = ["ios", "android"];
3
+ export const packageManagers = ["npm", "yarn", "pnpm", "bun"];
@@ -0,0 +1,20 @@
1
+ import { type LogSpec } from "./checkrecord.js";
2
+ import { type ScreenRead } from "./device/backend.js";
3
+ import { type ElementSpec } from "./device/screen.js";
4
+ import { type LogsOptions } from "./logs.js";
5
+ import type { CheckResult, LogsResult } from "./result.js";
6
+ import { type RunRef } from "./run.js";
7
+ export type CheckOptions = RunRef & {
8
+ logs?: LogSpec[];
9
+ elements?: ElementSpec[];
10
+ name?: string;
11
+ agentReading?: "pass" | "fail";
12
+ };
13
+ export type Deps = {
14
+ logs: (options: Omit<LogsOptions, "limit">) => Promise<LogsResult>;
15
+ screen: (device: string) => Promise<ScreenRead>;
16
+ screenshot: (device: string, path: string) => Promise<string | undefined>;
17
+ recheckSeconds: number;
18
+ };
19
+ export declare const primaryDisplay: (message: string) => string | undefined;
20
+ export declare function check(options: CheckOptions, report?: (step: string) => void, deps?: Deps): Promise<CheckResult>;
@@ -0,0 +1,214 @@
1
+ import { mkdirSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { dropped, readRecord, writeRecord, } from "./checkrecord.js";
4
+ import { axeBackend } from "./device/axe.js";
5
+ import { detectEnvironment, readScreen, } from "./device/backend.js";
6
+ import { maestroBackend } from "./device/maestro.js";
7
+ import { hasElement } from "./device/screen.js";
8
+ import { recordCheck } from "./evidence.js";
9
+ import { firstLine } from "./log.js";
10
+ import { allLines, tagPattern, } from "./logs.js";
11
+ import { worktreeKey } from "./owned.js";
12
+ import { resolveRun } from "./run.js";
13
+ import { runTool } from "./tool.js";
14
+ const realDeps = {
15
+ // Measured by the result's `waited` in the e2e log. A tap through AXe
16
+ // returns at once, and in 2 of 2 e2e runs the check after it waited 5 s.
17
+ recheckSeconds: 10,
18
+ logs: allLines,
19
+ screen: async (device) => readScreen(device, await detectEnvironment(), [axeBackend, maestroBackend]),
20
+ screenshot: async (device, path) => {
21
+ mkdirSync(dirname(path), { recursive: true });
22
+ const shoot = (extra) => runTool("simctl screenshot", "xcrun", ["simctl", "io", device, "screenshot", ...extra, path], 60);
23
+ const attempt = (extra) => shoot(extra).then(() => undefined, (error) => String(error));
24
+ const first = await attempt([]);
25
+ // Xcode 27 simulators have two displays and simctl asks which one.
26
+ // The one it names "(primary)" shows the app (#142).
27
+ const display = first === undefined ? undefined : primaryDisplay(first);
28
+ const error = display === undefined ? first : await attempt([`--display=${display}`]);
29
+ return error === undefined ? undefined : lastLine(error);
30
+ },
31
+ };
32
+ // From simctl's "Specify one with --display" list, the display named
33
+ // "(primary)", not "(primary-1)".
34
+ export const primaryDisplay = (message) => /--display=(\d+)\s.*\(primary\)/m.exec(message)?.[1];
35
+ const lastLine = (error) => `simctl screenshot: ${error.trim().split("\n").at(-1)?.trim() ?? ""}`;
36
+ const defaultRetryLimit = 3;
37
+ const maxRetryLimit = 10;
38
+ const maxSpecs = 20;
39
+ const maxText = 200;
40
+ const maxName = 40;
41
+ // 3 unless a human sets EMD_RETRY_LIMIT; never an agent input.
42
+ function retryLimit() {
43
+ const wanted = Number(process.env.EMD_RETRY_LIMIT);
44
+ return Number.isInteger(wanted) && wanted >= 1 && wanted <= maxRetryLimit
45
+ ? wanted
46
+ : defaultRetryLimit;
47
+ }
48
+ // Independent pass or fail from machine-checkable signals: the tagged log
49
+ // events the run wrote and the elements on the simulator's screen. It counts
50
+ // failed checks per worktree, so fix-and-retry stops at the retry limit.
51
+ export async function check(options, report = () => { }, deps = realDeps) {
52
+ const error = (reason) => ({ verdict: "error", reason });
53
+ const logSpecs = options.logs ?? [];
54
+ const elementSpecs = options.elements ?? [];
55
+ if (logSpecs.length + elementSpecs.length === 0) {
56
+ return error("Give at least one expectation: logs or elements.");
57
+ }
58
+ if (logSpecs.length > maxSpecs || elementSpecs.length > maxSpecs) {
59
+ return error(`At most ${maxSpecs} expectations of each kind.`);
60
+ }
61
+ for (const spec of logSpecs) {
62
+ if (!tagPattern.test(spec.tag) || (spec.message?.length ?? 0) > maxText) {
63
+ return error(`A log expectation needs a tag (letters, digits, dot, dash, underscore) and a message of at most ${maxText} characters.`);
64
+ }
65
+ }
66
+ for (const spec of elementSpecs) {
67
+ const lengths = [spec.id?.length ?? 0, spec.text?.length ?? 0];
68
+ if ((spec.id === undefined && spec.text === undefined) ||
69
+ lengths.some((n) => n > maxText)) {
70
+ return error(`An element expectation needs an id or a text, each at most ${maxText} characters.`);
71
+ }
72
+ }
73
+ // Any other character is stored as a dash, so an agent's first name works.
74
+ const name = (options.name ?? "").replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, maxName) ||
75
+ "default";
76
+ const limit = retryLimit();
77
+ const resolved = resolveRun(options);
78
+ if ("reason" in resolved)
79
+ return error(resolved.reason);
80
+ const { device, root, logDir } = resolved.run;
81
+ // Failed checks count per worktree, across relaunches, because a fix
82
+ // usually means launching again.
83
+ const key = worktreeKey(root);
84
+ const record = readRecord(key);
85
+ const before = record.failures;
86
+ if (before >= limit) {
87
+ return {
88
+ verdict: "stopped",
89
+ attempt: before,
90
+ retryLimit: limit,
91
+ reason: `${before} failed checks already. Stop retrying and report what is still missing. Only a person can start over (emd check reset).`,
92
+ };
93
+ }
94
+ // A name's first expectations are its bar: a later check under the name
95
+ // can add to them but not drop or change one (decision 0010).
96
+ const expected = { logs: logSpecs, elements: elementSpecs };
97
+ const first = record.names[name]?.expected;
98
+ const missing = first ? dropped(first, expected) : [];
99
+ if (missing.length > 0) {
100
+ 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
+ }
102
+ const byTag = new Map();
103
+ const readLogs = async () => {
104
+ for (const tag of new Set(logSpecs.map((spec) => spec.tag))) {
105
+ const got = await deps.logs({ jobId: options.jobId, tag });
106
+ if (got.verdict !== "ok")
107
+ return got.reason ?? "Could not read the logs.";
108
+ byTag.set(tag, got.lines ?? []);
109
+ }
110
+ };
111
+ let screen;
112
+ const readTheScreen = async () => {
113
+ try {
114
+ screen = await deps.screen(device);
115
+ }
116
+ catch (failure) {
117
+ return `Could not read the screen: ${firstLine(failure)}`;
118
+ }
119
+ };
120
+ const judge = () => {
121
+ const logs = logSpecs.map((spec) => ({
122
+ tag: spec.tag,
123
+ ...(spec.message === undefined ? {} : { message: spec.message }),
124
+ found: (byTag.get(spec.tag) ?? []).some((line) => spec.message === undefined || line.message.includes(spec.message)),
125
+ }));
126
+ const elements = elementSpecs.map((spec) => ({
127
+ ...(spec.id === undefined ? {} : { id: spec.id }),
128
+ ...(spec.text === undefined ? {} : { text: spec.text }),
129
+ found: hasElement(screen?.nodes ?? [], spec),
130
+ }));
131
+ return { logs, elements };
132
+ };
133
+ // Read, then read again what is still missing until the limit, so a check
134
+ // run a moment after an action doesn't fail on a line still on its way.
135
+ const started = Date.now();
136
+ let logResults = [];
137
+ let elementResults = [];
138
+ for (let first = true;; first = false) {
139
+ const logsMissing = first || logResults.some((r) => !r.found);
140
+ const screenMissing = first || elementResults.some((r) => !r.found);
141
+ if (logSpecs.length > 0 && logsMissing) {
142
+ report(first ? "reading the logs" : "reading the logs again");
143
+ const failure = await readLogs();
144
+ if (failure)
145
+ return error(failure);
146
+ }
147
+ if (elementSpecs.length > 0 && screenMissing) {
148
+ report(first ? "reading the screen" : "reading the screen again");
149
+ const failure = await readTheScreen();
150
+ if (failure)
151
+ return error(failure);
152
+ }
153
+ ({ logs: logResults, elements: elementResults } = judge());
154
+ const missing = [...logResults, ...elementResults].some((r) => !r.found);
155
+ if (!missing || Date.now() - started >= deps.recheckSeconds * 1000)
156
+ break;
157
+ await new Promise((resolve) => setTimeout(resolve, 1000));
158
+ }
159
+ const waited = Math.round((Date.now() - started) / 1000);
160
+ const nodes = screen?.nodes ?? [];
161
+ const passed = [...logResults, ...elementResults].every((r) => r.found);
162
+ report("taking a screenshot");
163
+ const stamp = Date.now();
164
+ const shotPath = join(logDir, `check-${stamp}.png`);
165
+ const shotError = await deps.screenshot(device, shotPath);
166
+ const shot = shotError === undefined ? shotPath : undefined;
167
+ // What the screen reader got, next to the screenshot, for when they disagree.
168
+ if (screen) {
169
+ mkdirSync(logDir, { recursive: true });
170
+ writeFileSync(join(logDir, `screen-${stamp}.json`), JSON.stringify(nodes));
171
+ }
172
+ const reading = options.agentReading;
173
+ const secondOpinion = {
174
+ ...(shot ? { screenshot: shot } : { screenshotError: shotError }),
175
+ ...(reading
176
+ ? { agent: reading, agrees: (reading === "pass") === passed }
177
+ : {}),
178
+ };
179
+ const evidence = {
180
+ ...(waited > 0 ? { waited } : {}),
181
+ logs: logResults.length > 0 ? logResults : undefined,
182
+ elements: elementResults.length > 0 ? elementResults : undefined,
183
+ // Which backend read the screen, and any it passed over (decision 0004).
184
+ backend: screen?.backend,
185
+ fellBack: screen?.fellBack,
186
+ secondOpinion,
187
+ };
188
+ // 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) => {
191
+ recordCheck(logDir, name, result);
192
+ writeRecord(key, {
193
+ failures: result.verdict === "passed" ? 0 : before + 1,
194
+ names: {
195
+ ...record.names,
196
+ [name]: { expected: first ?? expected, last: result.verdict },
197
+ },
198
+ });
199
+ return result;
200
+ };
201
+ if (passed)
202
+ return ran({ verdict: "passed", ...evidence });
203
+ const failures = before + 1;
204
+ const stopped = failures >= limit;
205
+ return ran({
206
+ verdict: stopped ? "stopped" : "failed",
207
+ attempt: failures,
208
+ retryLimit: limit,
209
+ reason: stopped
210
+ ? `${failures} failed checks. Stop retrying and report what is missing.`
211
+ : `${failures} of ${limit} attempts used. Fix the cause and check again.`,
212
+ ...evidence,
213
+ });
214
+ }
@@ -0,0 +1,22 @@
1
+ import type { ElementSpec } from "./device/screen.js";
2
+ import type { CheckResult } from "./result.js";
3
+ export type LogSpec = {
4
+ tag: string;
5
+ message?: string;
6
+ };
7
+ export type Expected = {
8
+ logs: LogSpec[];
9
+ elements: ElementSpec[];
10
+ };
11
+ type CheckRecord = {
12
+ failures: number;
13
+ names: Record<string, {
14
+ expected: Expected;
15
+ last: CheckResult["verdict"];
16
+ }>;
17
+ };
18
+ export declare function readRecord(key: string): CheckRecord;
19
+ export declare function writeRecord(key: string, record: CheckRecord): void;
20
+ export declare function resetChecks(root: string): void;
21
+ export declare function dropped(first: Expected, now: Expected): string[];
22
+ export {};
@@ -0,0 +1,34 @@
1
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { worktreeKey } from "./owned.js";
4
+ import { homeDir } from "./state.js";
5
+ const recordFile = (key) => join(homeDir(), "checks", `${key}.json`);
6
+ export function readRecord(key) {
7
+ try {
8
+ const { failures, names } = JSON.parse(readFileSync(recordFile(key), "utf8"));
9
+ return {
10
+ failures: Number.isInteger(failures) && failures > 0 ? failures : 0,
11
+ names: typeof names === "object" && names !== null ? names : {},
12
+ };
13
+ }
14
+ catch {
15
+ return { failures: 0, names: {} };
16
+ }
17
+ }
18
+ export function writeRecord(key, record) {
19
+ mkdirSync(dirname(recordFile(key)), { recursive: true });
20
+ writeFileSync(recordFile(key), JSON.stringify(record));
21
+ }
22
+ export function resetChecks(root) {
23
+ rmSync(recordFile(worktreeKey(root)), { force: true });
24
+ }
25
+ // Each first expectation that the new ones leave out or change, in words.
26
+ export function dropped(first, now) {
27
+ const logs = first.logs
28
+ .filter((a) => !now.logs.some((b) => b.tag === a.tag && b.message === a.message))
29
+ .map(({ tag, message }) => message === undefined ? `log ${tag}` : `log ${tag} "${message}"`);
30
+ const elements = first.elements
31
+ .filter((a) => !now.elements.some((b) => b.id === a.id && b.text === a.text))
32
+ .map(({ id, text }) => `element${id === undefined ? "" : ` id=${id}`}${text === undefined ? "" : ` text "${text}"`}`);
33
+ return [...logs, ...elements];
34
+ }
@@ -0,0 +1,2 @@
1
+ import type { DetectResult } from "./result.js";
2
+ export declare function detect(dir?: string): Promise<DetectResult>;
@@ -0,0 +1,27 @@
1
+ import { resolve } from "node:path";
2
+ import { probeStack } from "./probe.js";
3
+ import { inspectProject } from "./project.js";
4
+ import { loadAdapter } from "./registry.js";
5
+ import { workspaceApps } from "./workspace.js";
6
+ export async function detect(dir = ".") {
7
+ const root = resolve(dir);
8
+ const id = await probeStack(root);
9
+ if (!id) {
10
+ const apps = await workspaceApps(root);
11
+ return apps.length > 0
12
+ ? { verdict: "none", root, apps }
13
+ : { verdict: "none", root };
14
+ }
15
+ const { maestroFlows, notes, ...project } = await inspectProject(root);
16
+ const found = await (await loadAdapter(id)).detect(root, project);
17
+ if (!found)
18
+ return { verdict: "none", root };
19
+ return {
20
+ verdict: "detected",
21
+ root,
22
+ ...found,
23
+ packageManager: project.packageManager,
24
+ maestroFlows,
25
+ notes,
26
+ };
27
+ }
@@ -0,0 +1,10 @@
1
+ import type { DeviceBackend } from "./backend.js";
2
+ import type { UiNode } from "./screen.js";
3
+ export declare const axePin: {
4
+ version: string;
5
+ sha256: string;
6
+ url: string;
7
+ };
8
+ export declare const axeDir: () => string;
9
+ export declare function parseAxe(output: string): UiNode[];
10
+ export declare const axeBackend: DeviceBackend;