agentpath 0.0.0-stage → 0.1.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +105 -0
- package/README.md +101 -2
- package/THIRD_PARTY_NOTICES +12 -0
- package/apps/demo-site/dist/site.js +92 -0
- package/apps/studio/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
- package/apps/studio/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
- package/apps/studio/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
- package/apps/studio/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
- package/apps/studio/dist/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
- package/apps/studio/dist/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
- package/apps/studio/dist/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
- package/apps/studio/dist/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
- package/apps/studio/dist/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
- package/apps/studio/dist/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
- package/apps/studio/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
- package/apps/studio/dist/assets/index-DH4wJPHm.js +67 -0
- package/apps/studio/dist/assets/index-DrnNh2ip.css +1 -0
- package/apps/studio/dist/index.html +14 -0
- package/audit.md +173 -0
- package/autonomous-mode.md +104 -0
- package/ci.md +118 -0
- package/coding-agents.md +143 -0
- package/concepts.md +145 -0
- package/contracts.md +356 -0
- package/examples/tasks/ambiguous.json +98 -0
- package/examples/tasks/assertion-failure.json +98 -0
- package/examples/tasks/broken.json +98 -0
- package/examples/tasks/fixed.json +98 -0
- package/examples/tasks/recovery.json +19 -0
- package/images/compare-recovery-desktop.jpg +0 -0
- package/images/compare-variants-desktop.jpg +0 -0
- package/images/overview-desktop.jpg +0 -0
- package/images/run-autonomous-passed-desktop.jpg +0 -0
- package/images/run-failed-desktop.jpg +0 -0
- package/images/run-failed-mobile.jpg +0 -0
- package/images/run-missing-artifact-desktop.jpg +0 -0
- package/images/task-editor-laptop.jpg +0 -0
- package/installation.md +102 -0
- package/ledger.md +62 -0
- package/licenses/-fontsource-variable-geist-mono.txt +93 -0
- package/licenses/-fontsource-variable-geist.txt +93 -0
- package/licenses/lucide-react.txt +43 -0
- package/licenses/react-dom.txt +21 -0
- package/licenses/react.txt +21 -0
- package/licenses/scheduler.txt +21 -0
- package/licenses/tailwindcss.txt +21 -0
- package/licenses/zod.txt +21 -0
- package/package.json +165 -4
- package/packages/cli/bin/agentpath.js +39 -0
- package/packages/cli/dist/audit-rerun.js +384 -0
- package/packages/cli/dist/audit.js +387 -0
- package/packages/cli/dist/change-summaries.js +87 -0
- package/packages/cli/dist/ci-report.js +88 -0
- package/packages/cli/dist/demo.js +88 -0
- package/packages/cli/dist/doctor.js +265 -0
- package/packages/cli/dist/explain.js +89 -0
- package/packages/cli/dist/git.js +7 -0
- package/packages/cli/dist/inspect.js +118 -0
- package/packages/cli/dist/ledger.js +509 -0
- package/packages/cli/dist/local.js +102 -0
- package/packages/cli/dist/main.js +708 -0
- package/packages/cli/dist/mcp.js +231 -0
- package/packages/cli/dist/paths.js +6 -0
- package/packages/cli/dist/playwright-fixture.js +185 -0
- package/packages/cli/dist/playwright-reporter.js +49 -0
- package/packages/cli/dist/tasks.js +37 -0
- package/packages/cli/dist/test-source.js +283 -0
- package/packages/cli/dist/watch.js +96 -0
- package/packages/contracts/dist/agent-settings.js +18 -0
- package/packages/contracts/dist/agent.js +175 -0
- package/packages/contracts/dist/audit.js +115 -0
- package/packages/contracts/dist/guidance.js +339 -0
- package/packages/contracts/dist/index.js +14 -0
- package/packages/contracts/dist/inspect.js +63 -0
- package/packages/contracts/dist/ledger.js +80 -0
- package/packages/contracts/dist/local.js +171 -0
- package/packages/contracts/dist/outcomes.js +94 -0
- package/packages/contracts/dist/platform.js +105 -0
- package/packages/contracts/dist/playwright-live.js +76 -0
- package/packages/contracts/dist/policy.js +93 -0
- package/packages/contracts/dist/run.js +178 -0
- package/packages/contracts/dist/task-issues.js +39 -0
- package/packages/contracts/dist/task.js +185 -0
- package/packages/contracts/dist/watch.js +57 -0
- package/packages/core/dist/action-feedback.js +103 -0
- package/packages/core/dist/actions.js +160 -0
- package/packages/core/dist/agent-loop.js +122 -0
- package/packages/core/dist/artifacts.js +156 -0
- package/packages/core/dist/assertions.js +120 -0
- package/packages/core/dist/autonomous.js +1 -0
- package/packages/core/dist/browser.js +196 -0
- package/packages/core/dist/compare.js +141 -0
- package/packages/core/dist/control-state.js +62 -0
- package/packages/core/dist/diagnostics.js +134 -0
- package/packages/core/dist/evidence-diff.js +93 -0
- package/packages/core/dist/evidence.js +203 -0
- package/packages/core/dist/index.js +22 -0
- package/packages/core/dist/inspect.js +257 -0
- package/packages/core/dist/integrity.js +176 -0
- package/packages/core/dist/liveness.js +114 -0
- package/packages/core/dist/local-files.js +61 -0
- package/packages/core/dist/locators.js +214 -0
- package/packages/core/dist/model-provider.js +88 -0
- package/packages/core/dist/observation.js +257 -0
- package/packages/core/dist/playwright-live.js +519 -0
- package/packages/core/dist/playwright-results.js +543 -0
- package/packages/core/dist/policy.js +182 -0
- package/packages/core/dist/privacy.js +93 -0
- package/packages/core/dist/recovery.js +54 -0
- package/packages/core/dist/retention.js +204 -0
- package/packages/core/dist/run-index.js +177 -0
- package/packages/core/dist/run-plan.js +28 -0
- package/packages/core/dist/run-repository.js +518 -0
- package/packages/core/dist/runner.js +913 -0
- package/packages/core/dist/storage.js +63 -0
- package/packages/core/dist/task-fingerprint.js +36 -0
- package/packages/core/dist/test-change-rerun.js +84 -0
- package/packages/core/dist/test-changes.js +896 -0
- package/packages/core/dist/timing.js +41 -0
- package/packages/core/dist/watch.js +165 -0
- package/packages/server/dist/index.js +265 -0
- package/packages/server/dist/task-store.js +103 -0
- package/quickstart.md +85 -0
- package/security.md +136 -0
- package/try-on-your-repo.md +54 -0
- package/understanding-results.md +159 -0
- package/writing-tasks.md +196 -0
|
@@ -0,0 +1,543 @@
|
|
|
1
|
+
import { lstat, open, readdir, readFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { inflateRawSync } from "node:zlib";
|
|
4
|
+
import { FAILED_REQUEST_LIMIT, FAILED_REQUEST_PATH_LIMIT, guidanceFor } from "#agentpath/contracts";
|
|
5
|
+
import { liveFindingSchema, messageKey, nameDifference, SCHEMA_VERSION, semanticRoleSchema } from "#agentpath/contracts";
|
|
6
|
+
import { findNearMatches, snapshotRoleEntries, snapshotTargets } from "./locators.js";
|
|
7
|
+
/** Reads the fixture's file for one test; anything that does not parse is "unreadable", never trusted. */
|
|
8
|
+
export function readLiveFinding(text) {
|
|
9
|
+
try {
|
|
10
|
+
const parsed = liveFindingSchema.safeParse(JSON.parse(text));
|
|
11
|
+
return parsed.success ? parsed.data : "unreadable";
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return "unreadable";
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
const FILE_LIMIT = 2 * 1024 * 1024;
|
|
18
|
+
const TRACE_LIMIT = 512 * 1024 * 1024;
|
|
19
|
+
const ENTRY_LIMIT = 64 * 1024 * 1024;
|
|
20
|
+
/** Total inflated bytes across the entries read from one trace, so many large entries cannot add up unbounded. */
|
|
21
|
+
const INFLATED_LIMIT = 128 * 1024 * 1024;
|
|
22
|
+
const DIRECTORY_LIMIT = 5_000;
|
|
23
|
+
/**
|
|
24
|
+
* Trace format versions whose network entries were checked field by field (the fields read below): 10 is
|
|
25
|
+
* Playwright 1.65, 8 is Playwright 1.61. A version not checked, 9 included, is reported as unreadable.
|
|
26
|
+
*/
|
|
27
|
+
const TRACE_VERSIONS = new Set([8, 10]);
|
|
28
|
+
const roles = new Set(semanticRoleSchema.options);
|
|
29
|
+
const stripAnsi = (value) => value.replace(/\u001b\[[0-9;]*m/g, "");
|
|
30
|
+
/**
|
|
31
|
+
* The fenced blocks of a markdown section, as the pattern /```([a-z]*)\n([\s\S]*?)\n```/g would find them, in
|
|
32
|
+
* linear time. Page text reaches these sections (a failed expect() prints what it received), and the regular
|
|
33
|
+
* expression backtracks quadratically on many unclosed fences: 2 MiB took about two minutes.
|
|
34
|
+
*/
|
|
35
|
+
function fencedBlocks(text, limit = Infinity) {
|
|
36
|
+
const blocks = [];
|
|
37
|
+
let from = 0;
|
|
38
|
+
while (blocks.length < limit) {
|
|
39
|
+
const open = text.indexOf("```", from);
|
|
40
|
+
if (open < 0)
|
|
41
|
+
break;
|
|
42
|
+
let newline = open + 3;
|
|
43
|
+
while (newline < text.length && text.charCodeAt(newline) >= 97 && text.charCodeAt(newline) <= 122)
|
|
44
|
+
newline++;
|
|
45
|
+
if (text[newline] !== "\n") {
|
|
46
|
+
from = open + 1;
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
const close = text.indexOf("\n```", newline + 1);
|
|
50
|
+
// No closing fence after this opening means none after any later one either.
|
|
51
|
+
if (close < 0)
|
|
52
|
+
break;
|
|
53
|
+
blocks.push({ language: text.slice(open + 3, newline), body: text.slice(newline + 1, close) });
|
|
54
|
+
from = close + 4;
|
|
55
|
+
}
|
|
56
|
+
return blocks;
|
|
57
|
+
}
|
|
58
|
+
/** Sections of an `error-context.md`, by heading. */
|
|
59
|
+
export function parseErrorContext(markdown) {
|
|
60
|
+
const text = stripAnsi(markdown);
|
|
61
|
+
const section = (heading) => {
|
|
62
|
+
const start = text.indexOf(`\n# ${heading}\n`);
|
|
63
|
+
if (start < 0)
|
|
64
|
+
return undefined;
|
|
65
|
+
const rest = text.slice(start + heading.length + 4);
|
|
66
|
+
const next = rest.search(/\n# [A-Z]/);
|
|
67
|
+
return next < 0 ? rest : rest.slice(0, next);
|
|
68
|
+
};
|
|
69
|
+
// The error details can hold several blocks, such as a test timeout followed by the locator error it cut
|
|
70
|
+
// short. A failed expect() adds a yaml block there: the aria snapshot it took, in place of a Page snapshot.
|
|
71
|
+
const details = fencedBlocks(section("Error details") ?? "");
|
|
72
|
+
const errors = details.filter((block) => block.language !== "yaml").map((block) => block.body);
|
|
73
|
+
const expectSnapshot = details.find((block) => block.language === "yaml")?.body;
|
|
74
|
+
const info = section("Test info") ?? "";
|
|
75
|
+
return {
|
|
76
|
+
test: /^- Name: (.+)$/m.exec(info)?.[1]?.trim(),
|
|
77
|
+
location: /^- Location: (.+)$/m.exec(info)?.[1]?.trim(),
|
|
78
|
+
error: errors.length ? errors.join("\n") : undefined,
|
|
79
|
+
snapshot: fencedBlocks(section("Page snapshot") ?? "", 1)[0]?.body ?? expectSnapshot,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
// A JavaScript single- or double-quoted string literal as Playwright prints it.
|
|
83
|
+
const literal = String.raw `'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"`;
|
|
84
|
+
const unquote = (value) => {
|
|
85
|
+
const body = value.slice(1, -1);
|
|
86
|
+
return body.replace(/\\(.)/g, (_, character) => character);
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* The failed locator from Playwright's error text. Only a page-level `getByRole` with a string name or a
|
|
90
|
+
* `getByLabel` with a string label is supported: a chained, scoped, regular-expression or other locator
|
|
91
|
+
* returns undefined with the reason, because AgentPath would otherwise compare a different target.
|
|
92
|
+
*/
|
|
93
|
+
export function parseFailedLocator(error) {
|
|
94
|
+
const text = stripAnsi(error);
|
|
95
|
+
const line = /(?:waiting for |Locator: )(\S.*)$/m.exec(text)?.[1]?.trim();
|
|
96
|
+
if (!line)
|
|
97
|
+
return { reason: "The error text names no locator." };
|
|
98
|
+
const role = new RegExp(String.raw `^getByRole\((${literal})(?:, \{ name: (${literal})(, exact: true)? \})?\)$`).exec(line);
|
|
99
|
+
if (role) {
|
|
100
|
+
const roleName = unquote(role[1]);
|
|
101
|
+
if (!roles.has(roleName))
|
|
102
|
+
return { text: line, reason: `The role ${JSON.stringify(roleName)} is not one AgentPath targets.` };
|
|
103
|
+
if (role[2] === undefined)
|
|
104
|
+
return { text: line, reason: "A role without a name cannot be compared with names on the page." };
|
|
105
|
+
return { text: line, locator: { by: "role", role: roleName, name: unquote(role[2]), exact: Boolean(role[3]) } };
|
|
106
|
+
}
|
|
107
|
+
const label = new RegExp(String.raw `^getByLabel\((${literal})(, \{ exact: true \})?\)$`).exec(line);
|
|
108
|
+
if (label)
|
|
109
|
+
return { text: line, locator: { by: "label", label: unquote(label[1]), exact: Boolean(label[2]) } };
|
|
110
|
+
return { text: line, reason: "Only a page-level getByRole with a string name, or getByLabel with a string, is supported; chained, scoped and regular-expression locators are not." };
|
|
111
|
+
}
|
|
112
|
+
function errorKind(error) {
|
|
113
|
+
if (/strict mode violation/i.test(error))
|
|
114
|
+
return "strict";
|
|
115
|
+
if (/Timeout \d+ms exceeded|Test timeout of \d+ms exceeded/i.test(error))
|
|
116
|
+
return "missing";
|
|
117
|
+
if (/expect\(/.test(error) || /element\(s\) not found/i.test(error))
|
|
118
|
+
return "expect";
|
|
119
|
+
return "other";
|
|
120
|
+
}
|
|
121
|
+
const LABELLED = new Set(["textbox", "searchbox", "combobox", "listbox", "checkbox", "radio", "switch", "spinbutton", "slider"]);
|
|
122
|
+
/** Whether Playwright's own matching rule would find the locator among the snapshot's targets. */
|
|
123
|
+
export function matchesInSnapshot(locator, snapshot) {
|
|
124
|
+
const wanted = locator.by === "role" ? locator.name : locator.label;
|
|
125
|
+
const same = (name) => locator.exact ? name === wanted : fold(name).includes(fold(wanted));
|
|
126
|
+
// getByLabel finds labelled controls, so a heading or button that contains the label text does not count.
|
|
127
|
+
return snapshotRoleEntries(snapshot).some((entry) => entry.name !== undefined
|
|
128
|
+
&& (locator.by === "label" ? LABELLED.has(entry.role) : entry.role === locator.role) && same(entry.name));
|
|
129
|
+
}
|
|
130
|
+
// ---- trace.zip: only the network log is read ------------------------------------------------------------
|
|
131
|
+
/** Entries of a zip archive whose names pass `wanted`, inflated with a size limit. Zip64 is not supported. */
|
|
132
|
+
export function readZipEntries(archive, wanted) {
|
|
133
|
+
const result = new Map();
|
|
134
|
+
let inflated = 0;
|
|
135
|
+
let end = -1;
|
|
136
|
+
for (let i = archive.length - 22; i >= Math.max(0, archive.length - 65_557); i--) {
|
|
137
|
+
if (archive.readUInt32LE(i) === 0x06054b50) {
|
|
138
|
+
end = i;
|
|
139
|
+
break;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (end < 0)
|
|
143
|
+
throw new Error("not a zip archive");
|
|
144
|
+
const count = archive.readUInt16LE(end + 10);
|
|
145
|
+
let offset = archive.readUInt32LE(end + 16);
|
|
146
|
+
for (let entry = 0; entry < count; entry++) {
|
|
147
|
+
if (offset + 46 > archive.length || archive.readUInt32LE(offset) !== 0x02014b50)
|
|
148
|
+
throw new Error("bad central directory");
|
|
149
|
+
const method = archive.readUInt16LE(offset + 10);
|
|
150
|
+
const compressed = archive.readUInt32LE(offset + 20);
|
|
151
|
+
const nameLength = archive.readUInt16LE(offset + 28);
|
|
152
|
+
const extraLength = archive.readUInt16LE(offset + 30);
|
|
153
|
+
const commentLength = archive.readUInt16LE(offset + 32);
|
|
154
|
+
const local = archive.readUInt32LE(offset + 42);
|
|
155
|
+
const name = archive.subarray(offset + 46, offset + 46 + nameLength).toString("utf8");
|
|
156
|
+
offset += 46 + nameLength + extraLength + commentLength;
|
|
157
|
+
if (!wanted(name))
|
|
158
|
+
continue;
|
|
159
|
+
if (local + 30 > archive.length || archive.readUInt32LE(local) !== 0x04034b50)
|
|
160
|
+
throw new Error("bad local header");
|
|
161
|
+
const start = local + 30 + archive.readUInt16LE(local + 26) + archive.readUInt16LE(local + 28);
|
|
162
|
+
const data = archive.subarray(start, start + compressed);
|
|
163
|
+
const content = method === 0 ? data : method === 8 ? inflateRawSync(data, { maxOutputLength: ENTRY_LIMIT }) : undefined;
|
|
164
|
+
if (!content)
|
|
165
|
+
throw new Error("unsupported compression");
|
|
166
|
+
inflated += content.length;
|
|
167
|
+
if (inflated > INFLATED_LIMIT)
|
|
168
|
+
throw new Error("trace entries too large");
|
|
169
|
+
result.set(name, content);
|
|
170
|
+
}
|
|
171
|
+
return result;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Failed requests from a trace's network log, limited to the hosts of the test's own page loads (document
|
|
175
|
+
* requests), so third-party noise does not point at the site under test. Paths exclude the query.
|
|
176
|
+
*/
|
|
177
|
+
export function traceFailedRequests(archive) {
|
|
178
|
+
// The format is undocumented; a version this reader was not written for is reported, not parsed. The
|
|
179
|
+
// version is on the first line of every trace file; the test runner's own file is the small one.
|
|
180
|
+
const files = readZipEntries(archive, (name) => name.endsWith(".network") || name === "test.trace" || name === "0-trace.trace");
|
|
181
|
+
const header = files.get("test.trace") ?? files.get("0-trace.trace");
|
|
182
|
+
const firstLine = header?.subarray(0, header.indexOf("\n") < 0 ? header.length : header.indexOf("\n")).toString("utf8");
|
|
183
|
+
if (!firstLine || !TRACE_VERSIONS.has(JSON.parse(firstLine).version))
|
|
184
|
+
throw new Error("unsupported trace version");
|
|
185
|
+
const entries = [];
|
|
186
|
+
for (const [name, data] of files) {
|
|
187
|
+
if (!name.endsWith(".network"))
|
|
188
|
+
continue;
|
|
189
|
+
for (const line of data.toString("utf8").split("\n")) {
|
|
190
|
+
if (!line.trim())
|
|
191
|
+
continue;
|
|
192
|
+
try {
|
|
193
|
+
entries.push(JSON.parse(line));
|
|
194
|
+
}
|
|
195
|
+
catch { /* one bad line does not hide the rest */ }
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
const url = (value) => { try {
|
|
199
|
+
return value ? new URL(value) : undefined;
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
return undefined;
|
|
203
|
+
} };
|
|
204
|
+
const appHosts = new Set(entries.filter((entry) => entry.snapshot?._resourceType === "document")
|
|
205
|
+
.map((entry) => url(entry.snapshot?.request?.url)?.host).filter((host) => Boolean(host)));
|
|
206
|
+
const failed = new Map();
|
|
207
|
+
for (const entry of entries) {
|
|
208
|
+
const snapshot = entry.snapshot;
|
|
209
|
+
const target = url(snapshot?.request?.url);
|
|
210
|
+
if (!snapshot || !target || !appHosts.has(target.host))
|
|
211
|
+
continue;
|
|
212
|
+
const status = snapshot.response?.status ?? 0;
|
|
213
|
+
const failureText = snapshot.response?._failureText ?? "";
|
|
214
|
+
// A received HTTP status decides, even when the body was then aborted (Chromium aborts a script after a
|
|
215
|
+
// 500, for example). Without a status, as in task runs: navigations and teardown abort in-flight requests,
|
|
216
|
+
// which are not failures of the site, and a request with no failure text was still pending at the end.
|
|
217
|
+
let network = false;
|
|
218
|
+
if (status > 0) {
|
|
219
|
+
if (status < 400)
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
if (!failureText || /ERR_ABORTED|ERR_BLOCKED_BY_CLIENT/.test(failureText))
|
|
224
|
+
continue;
|
|
225
|
+
network = true;
|
|
226
|
+
}
|
|
227
|
+
const method = (snapshot.request?.method ?? "GET").slice(0, 16);
|
|
228
|
+
const path = target.pathname.slice(0, FAILED_REQUEST_PATH_LIMIT) || "/";
|
|
229
|
+
const resourceType = (snapshot._resourceType ?? "other").slice(0, 32);
|
|
230
|
+
const key = `${method} ${target.host}${path} ${network ? "network" : status}`;
|
|
231
|
+
const known = failed.get(key);
|
|
232
|
+
if (known)
|
|
233
|
+
known.count++;
|
|
234
|
+
else
|
|
235
|
+
failed.set(key, { host: target.host, path, method, resourceType, ...(network ? { failure: "network" } : { status: Math.min(status, 599) }), count: 1 });
|
|
236
|
+
}
|
|
237
|
+
return [...failed.values()].slice(0, FAILED_REQUEST_LIMIT);
|
|
238
|
+
}
|
|
239
|
+
// ---- the explanation ---------------------------------------------------------------------------------
|
|
240
|
+
const js = (value) => `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
|
|
241
|
+
function locatorCode(target) {
|
|
242
|
+
return target.by === "label" ? `getByLabel(${js(target.label)}, { exact: true })`
|
|
243
|
+
: `getByRole(${js(target.role)}${target.name === undefined ? "" : `, { name: ${js(target.name)}, exact: true }`})`;
|
|
244
|
+
}
|
|
245
|
+
/** Playwright's action names, as far as which roles can stand in for the target is concerned. */
|
|
246
|
+
function guidanceAction(action) {
|
|
247
|
+
if (!action)
|
|
248
|
+
return undefined;
|
|
249
|
+
if (["fill", "type", "pressSequentially", "clear"].includes(action))
|
|
250
|
+
return "fill";
|
|
251
|
+
if (action === "selectOption")
|
|
252
|
+
return "select";
|
|
253
|
+
if (["click", "dblclick", "tap", "check", "uncheck", "setChecked", "press"].includes(action))
|
|
254
|
+
return "click";
|
|
255
|
+
return undefined;
|
|
256
|
+
}
|
|
257
|
+
const fold = (value) => value.normalize("NFKC").toLowerCase().replace(/\s+/g, " ").trim();
|
|
258
|
+
/** A label with the requested text that labels nothing. Only a label whose own text is the requested text counts: one that merely contains it may be another label. */
|
|
259
|
+
function labelDetached(label, exact, detached) {
|
|
260
|
+
return (detached ?? []).some((text) => exact ? text === label : fold(text) === fold(label));
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Whether Playwright's page snapshot shows the requested label text as a plain text entry directly beside a form
|
|
264
|
+
* field that has no accessible name: before any field, or after a checkbox, radio or switch, at the same depth.
|
|
265
|
+
* The snapshot cannot say whether the text is a <label> element, so the finding says what it shows: a field with
|
|
266
|
+
* no name next to the text the test reads as its label. Only text equal to the requested label counts.
|
|
267
|
+
*/
|
|
268
|
+
export function unnamedFieldBesideText(label, exact, snapshot) {
|
|
269
|
+
const entries = snapshot.split("\n").map((raw) => /^(\s*)- (.*)$/.exec(raw)).filter((match) => match !== null)
|
|
270
|
+
.map((match) => ({ depth: match[1].length, line: match[2] }));
|
|
271
|
+
const textOf = (line) => {
|
|
272
|
+
const match = /^text: (.*)$/.exec(line);
|
|
273
|
+
if (!match)
|
|
274
|
+
return undefined;
|
|
275
|
+
const value = match[1].trim();
|
|
276
|
+
if (value.startsWith('"')) {
|
|
277
|
+
try {
|
|
278
|
+
return JSON.parse(value);
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
return undefined;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
return value.startsWith("'") && value.endsWith("'") ? value.slice(1, -1).replaceAll("''", "'") : value;
|
|
285
|
+
};
|
|
286
|
+
const unnamed = (line) => /^([a-z]+)(?: \[[^\]]*\])*:?$/.exec(line)?.[1];
|
|
287
|
+
const same = (text) => exact ? text === label : fold(text) === fold(label);
|
|
288
|
+
for (let index = 0; index + 1 < entries.length; index++) {
|
|
289
|
+
const [first, second] = [entries[index], entries[index + 1]];
|
|
290
|
+
if (first.depth !== second.depth)
|
|
291
|
+
continue;
|
|
292
|
+
const before = textOf(first.line);
|
|
293
|
+
const field = unnamed(second.line);
|
|
294
|
+
if (before !== undefined && field && LABELLED.has(field) && same(before))
|
|
295
|
+
return true;
|
|
296
|
+
const after = textOf(second.line);
|
|
297
|
+
const box = unnamed(first.line);
|
|
298
|
+
if (after !== undefined && box && ["checkbox", "radio", "switch"].includes(box) && same(after))
|
|
299
|
+
return true;
|
|
300
|
+
}
|
|
301
|
+
return false;
|
|
302
|
+
}
|
|
303
|
+
/** Explanation from the fixture's record of the live page: the chain as rebuilt, step counts and the late check. */
|
|
304
|
+
function explainLive(base, live, chain, kind, failedRequests, traceState) {
|
|
305
|
+
const stopped = chain.stoppedAt;
|
|
306
|
+
const finalCount = chain.steps.at(-1)?.count;
|
|
307
|
+
const target = stopped !== undefined ? live.target : undefined;
|
|
308
|
+
const locator = target
|
|
309
|
+
? target.by === "role" ? { by: "role", role: target.role, name: target.name, exact: target.exact } : { by: "label", label: target.label, exact: target.exact }
|
|
310
|
+
: undefined;
|
|
311
|
+
const detached = target?.by === "label" && labelDetached(target.label, target.exact, live.detachedLabels);
|
|
312
|
+
const failure = {
|
|
313
|
+
category: kind === "strict" ? "TARGET_AMBIGUOUS" : "TARGET_NOT_FOUND",
|
|
314
|
+
location: { phase: "step", index: 0, action: "click" },
|
|
315
|
+
expected: "a target matching the locator", observed: stopped !== undefined ? "no element matched the locator" : "see the Playwright error",
|
|
316
|
+
observation: { ...(stopped !== undefined ? { matchCount: 0 } : {}), ...(live.nearMatches?.length ? { nearMatches: live.nearMatches } : {}),
|
|
317
|
+
...(detached ? { labelState: "detached" } : {}) },
|
|
318
|
+
evidence: [{ kind: "failure", path: "agentpath-live.json" }],
|
|
319
|
+
};
|
|
320
|
+
const browser = failedRequests?.length
|
|
321
|
+
? { schemaVersion: SCHEMA_VERSION, pageErrors: 0, consoleErrors: 0, failedRequests } : undefined;
|
|
322
|
+
// The action and assertion apply to the chain's last step. A step before it is a scope: its stand-in only
|
|
323
|
+
// has to be the same kind of element (a widget or not), whatever the test then does inside it.
|
|
324
|
+
const last = stopped === chain.steps.length - 1 || chain.steps.slice((stopped ?? 0) + 1).every((step) => /^(?:first|last|nth|filter)\(/.test(step.code));
|
|
325
|
+
const action = last ? guidanceAction(live.action) : undefined;
|
|
326
|
+
const where = target
|
|
327
|
+
? { path: "/locator", kind: last && live.action === "expect" ? "assertion" : "step", ...(action ? { action } : {}),
|
|
328
|
+
target: target.by === "role" ? { by: "role", role: target.role, name: target.name } : { by: "label", label: target.label } }
|
|
329
|
+
: undefined;
|
|
330
|
+
const guidance = guidanceFor(where, failure, browser);
|
|
331
|
+
const facts = [];
|
|
332
|
+
if (stopped !== undefined) {
|
|
333
|
+
const step = chain.steps[stopped];
|
|
334
|
+
const before = stopped > 0 ? chain.steps[stopped - 1] : undefined;
|
|
335
|
+
facts.push({ pointsTo: "unclear", statement: before
|
|
336
|
+
? `The chain matched ${before.count ?? "an unknown number of"} element${before.count === 1 ? "" : "s"} up to ${before.code}, and nothing from ${step.code} on, at the end of the test.`
|
|
337
|
+
: `Nothing on the page matched ${step.code} at the end of the test.` });
|
|
338
|
+
}
|
|
339
|
+
else if (kind === "strict" && finalCount !== undefined) {
|
|
340
|
+
facts.push({ pointsTo: "unclear", statement: `The locator matched ${finalCount} elements at the end of the test, where one was required.` });
|
|
341
|
+
}
|
|
342
|
+
else if (finalCount !== undefined && finalCount > 0) {
|
|
343
|
+
facts.push({ pointsTo: "unclear", statement: `The locator matched ${finalCount} element${finalCount === 1 ? "" : "s"} at the end of the test, so the failure concerns its state or text, which AgentPath does not check here.` });
|
|
344
|
+
}
|
|
345
|
+
const late = live.lateCheck;
|
|
346
|
+
if (late?.outcome === "passed-later") {
|
|
347
|
+
facts.push({ pointsTo: "task", statement: `Without acting, the locator matched a visible element ${late.afterMs ?? 0} ms after AgentPath began observing at the end of the test. The page was slower than the test's timeout allowed.` });
|
|
348
|
+
}
|
|
349
|
+
else if (late?.outcome === "still-failing") {
|
|
350
|
+
facts.push({ pointsTo: "unclear", statement: `Without acting, the locator still matched no visible element during a further ${late.windowMs ?? 0} ms. A longer timeout alone is unlikely to fix this.` });
|
|
351
|
+
}
|
|
352
|
+
const stepCode = (replacement) => chain.steps.map((step, index) => index === stopped ? locatorCode(replacement) : step.code).join(".");
|
|
353
|
+
// A step that names a value (placeholder, test id, title, alt text, text): the same guards as for names. A value
|
|
354
|
+
// that differs by an identifier or a whole word, or is shaped like a message key, is a fact; evidence that points
|
|
355
|
+
// to the site suppresses every suggestion.
|
|
356
|
+
const valueSuggestions = [];
|
|
357
|
+
const value = stopped !== undefined && !target ? live.valueTarget : undefined;
|
|
358
|
+
if (value && live.similarValues?.length) {
|
|
359
|
+
const others = [];
|
|
360
|
+
const keys = [];
|
|
361
|
+
for (const match of live.similarValues) {
|
|
362
|
+
if (nameDifference(value.value, match.value)) {
|
|
363
|
+
others.push(JSON.stringify(match.value));
|
|
364
|
+
continue;
|
|
365
|
+
}
|
|
366
|
+
if (messageKey(match.value) && !messageKey(value.value)) {
|
|
367
|
+
keys.push(JSON.stringify(match.value));
|
|
368
|
+
continue;
|
|
369
|
+
}
|
|
370
|
+
const exact = value.method === "getByTestId" ? "" : ", { exact: true }";
|
|
371
|
+
valueSuggestions.push(chain.steps.map((step, index) => index === stopped ? `${value.method}(${js(match.value)}${exact})` : step.code).join("."));
|
|
372
|
+
}
|
|
373
|
+
if (others.length)
|
|
374
|
+
facts.push({ pointsTo: "unclear", statement: `The page has ${others.join(", ")}, which ${others.length === 1 ? "differs" : "differ"} from the requested value by an identifier or a whole word, so ${others.length === 1 ? "it is" : "they are"} not suggested.` });
|
|
375
|
+
if (keys.length)
|
|
376
|
+
facts.push({ pointsTo: "unclear", statement: `The page has ${keys.join(", ")}, shaped like an untranslated message key where a readable value is requested, so ${keys.length === 1 ? "it is" : "they are"} not suggested.` });
|
|
377
|
+
if (valueSuggestions.length && !guidance.findings.some((finding) => finding.pointsTo === "site")) {
|
|
378
|
+
facts.push({ pointsTo: "task", statement: "The page has a target close to the requested one. If the page's current naming is intended, the test's locator is out of date; if not, the page changed." });
|
|
379
|
+
}
|
|
380
|
+
else
|
|
381
|
+
valueSuggestions.length = 0;
|
|
382
|
+
}
|
|
383
|
+
const suggestedLocators = locator && stopped !== undefined ? guidance.suggestedChanges.flatMap((change) => {
|
|
384
|
+
if (change.path === "/locator/target")
|
|
385
|
+
return [stepCode(change.value)];
|
|
386
|
+
if (change.path === "/locator/target/name" && locator.by === "role")
|
|
387
|
+
return [stepCode({ by: "role", role: locator.role, name: String(change.value) })];
|
|
388
|
+
if (change.path === "/locator/target/role" && locator.by === "role")
|
|
389
|
+
return [stepCode({ by: "role", role: String(change.value), name: locator.name })];
|
|
390
|
+
return [];
|
|
391
|
+
}) : [];
|
|
392
|
+
suggestedLocators.push(...valueSuggestions.slice(0, 3));
|
|
393
|
+
const compared = Boolean(locator) || Boolean(value && live.similarValues !== undefined) || Boolean(value && !(value.method === "getByText" && stopped === 0));
|
|
394
|
+
return { ...base, status: "explained", comparison: compared ? "compared" : "located-only", ...(locator ? { locator } : {}), errorKind: kind, chain, ...(late ? { lateCheck: late } : {}),
|
|
395
|
+
...(live.nearMatches?.length && locator ? { nearMatches: live.nearMatches } : {}), ...(failedRequests?.length ? { failedRequests } : {}), trace: traceState, live: "read",
|
|
396
|
+
guidance: { ...guidance, findings: [...facts, ...guidance.findings] }, ...(suggestedLocators.length ? { suggestedLocators } : {}) };
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* Explains one failed test from its `error-context.md` text and, when present, its trace archive and the
|
|
400
|
+
* AgentPath fixture's record of the live page. The fixture's chain, when it rebuilt one, takes precedence.
|
|
401
|
+
*/
|
|
402
|
+
export function explainFailedTest(directory, markdown, trace, liveRecord) {
|
|
403
|
+
const result = explainOne(directory, markdown, trace, liveRecord);
|
|
404
|
+
return liveRecord !== "unreadable" && liveRecord?.noPage && liveRecord.reason ? { ...result, liveReason: liveRecord.reason } : result;
|
|
405
|
+
}
|
|
406
|
+
function explainOne(directory, markdown, trace, liveRecord) {
|
|
407
|
+
const context = parseErrorContext(markdown);
|
|
408
|
+
const base = { directory, ...(context.test ? { test: context.test } : {}), ...(context.location ? { location: context.location } : {}) };
|
|
409
|
+
const liveState = liveRecord === undefined ? "absent" : liveRecord === "unreadable" ? "unreadable" : liveRecord.noPage ? "no-page" : "read";
|
|
410
|
+
const live = liveRecord === "unreadable" ? undefined : liveRecord;
|
|
411
|
+
let failedRequests;
|
|
412
|
+
let traceState = trace === undefined ? "absent" : "read";
|
|
413
|
+
if (trace === "unreadable")
|
|
414
|
+
traceState = "unreadable";
|
|
415
|
+
else if (trace) {
|
|
416
|
+
try {
|
|
417
|
+
failedRequests = traceFailedRequests(trace);
|
|
418
|
+
}
|
|
419
|
+
catch {
|
|
420
|
+
traceState = "unreadable";
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
// The trace sees every page of the test; the fixture sees its page. Use the fixture's only without a trace.
|
|
424
|
+
if (traceState !== "read" && live?.failedRequests?.length)
|
|
425
|
+
failedRequests = live.failedRequests;
|
|
426
|
+
if (!context.error)
|
|
427
|
+
return { ...base, status: "unreadable", trace: traceState, live: liveState, reason: "error-context.md has no error details." };
|
|
428
|
+
const kind = errorKind(context.error);
|
|
429
|
+
if (live?.chain)
|
|
430
|
+
return explainLive(base, live, live.chain, kind, failedRequests, traceState);
|
|
431
|
+
// Playwright's snapshot shows one page; with several, it may not be the page the locator ran on.
|
|
432
|
+
if (live?.otherPages) {
|
|
433
|
+
return { ...base, status: "several-pages", errorKind: kind, trace: traceState, live: liveState, ...(live.lateCheck ? { lateCheck: live.lateCheck } : {}),
|
|
434
|
+
...(failedRequests?.length ? { failedRequests } : {}), reason: live.reason ?? "The test used more than one page." };
|
|
435
|
+
}
|
|
436
|
+
const lateCheck = live?.lateCheck ? { lateCheck: live.lateCheck } : {};
|
|
437
|
+
const parsed = parseFailedLocator(context.error);
|
|
438
|
+
if (!parsed.locator) {
|
|
439
|
+
return { ...base, status: parsed.text ? "unsupported-locator" : "no-locator", errorKind: kind, trace: traceState, live: liveState, ...lateCheck,
|
|
440
|
+
...(failedRequests?.length ? { failedRequests } : {}), reason: live?.reason && parsed.text ? `${parsed.reason} ${live.reason}` : parsed.reason };
|
|
441
|
+
}
|
|
442
|
+
const locator = parsed.locator;
|
|
443
|
+
const snapshot = context.snapshot;
|
|
444
|
+
const present = snapshot === undefined ? undefined : matchesInSnapshot(locator, snapshot);
|
|
445
|
+
// Near matches explain a missing target only. A present one, or a strict-mode failure, has other causes.
|
|
446
|
+
const nearMatches = snapshot !== undefined && !present && kind !== "strict" ? findNearMatches(locator, snapshotTargets(snapshot)) : [];
|
|
447
|
+
// A test that timed out has no locator while the page is open, but the fixture lists labels that label nothing.
|
|
448
|
+
const detached = locator.by === "label" && present !== true && labelDetached(locator.label, locator.exact, live?.detachedLabels);
|
|
449
|
+
const failure = {
|
|
450
|
+
category: kind === "strict" ? "TARGET_AMBIGUOUS" : "TARGET_NOT_FOUND",
|
|
451
|
+
location: { phase: "step", index: 0, action: "click" },
|
|
452
|
+
expected: "a target matching the locator", observed: present === false ? "no matching target in the page snapshot" : "see the Playwright error",
|
|
453
|
+
observation: { ...(present === false ? { matchCount: 0 } : {}), ...(nearMatches.length ? { nearMatches } : {}), ...(detached ? { labelState: "detached" } : {}) },
|
|
454
|
+
evidence: [{ kind: "failure", path: "error-context.json" }],
|
|
455
|
+
};
|
|
456
|
+
const browser = failedRequests?.length
|
|
457
|
+
? { schemaVersion: SCHEMA_VERSION, pageErrors: 0, consoleErrors: 0, failedRequests } : undefined;
|
|
458
|
+
const target = locator.by === "role" ? { by: "role", role: locator.role, name: locator.name } : { by: "label", label: locator.label };
|
|
459
|
+
const computed = guidanceFor({ path: "/locator", kind: "step", target }, failure, browser);
|
|
460
|
+
// Without the fixture, the snapshot can still show the field the label text sits beside, with no accessible name.
|
|
461
|
+
const unnamed = !detached && locator.by === "label" && present === false && snapshot !== undefined && unnamedFieldBesideText(locator.label, locator.exact, snapshot);
|
|
462
|
+
const guidance = unnamed ? { ...computed, suggestedChanges: [], findings: [{ pointsTo: "site",
|
|
463
|
+
statement: `The page shows the text ${JSON.stringify(locator.label)} directly beside a form field that has no accessible name, so nothing on the page is labelled ${JSON.stringify(locator.label)}. The field lost its accessible label.` }, ...computed.findings] } : computed;
|
|
464
|
+
const suggestedLocators = guidance.suggestedChanges.flatMap((change) => {
|
|
465
|
+
if (change.path === "/locator/target")
|
|
466
|
+
return [locatorCode(change.value)];
|
|
467
|
+
if (change.path === "/locator/target/name" && locator.by === "role")
|
|
468
|
+
return [locatorCode({ by: "role", role: locator.role, name: String(change.value) })];
|
|
469
|
+
if (change.path === "/locator/target/role" && locator.by === "role")
|
|
470
|
+
return [locatorCode({ by: "role", role: String(change.value), name: locator.name })];
|
|
471
|
+
return [];
|
|
472
|
+
});
|
|
473
|
+
return { ...base, status: "explained", comparison: "compared", locator, errorKind: kind, ...(present === undefined ? {} : { presentInSnapshot: present }),
|
|
474
|
+
...(nearMatches.length ? { nearMatches } : {}), ...(failedRequests?.length ? { failedRequests } : {}), trace: traceState, live: liveState, ...lateCheck,
|
|
475
|
+
guidance, ...(suggestedLocators.length ? { suggestedLocators } : {}) };
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Explains every failed test under a Playwright output directory (`test-results` by default). Symbolic
|
|
479
|
+
* links are not followed; each directory is read on its own, so one unreadable file is reported, not fatal.
|
|
480
|
+
*/
|
|
481
|
+
export async function explainPlaywrightResults(root) {
|
|
482
|
+
const results = [];
|
|
483
|
+
const pending = [""];
|
|
484
|
+
let visited = 0;
|
|
485
|
+
while (pending.length && visited < DIRECTORY_LIMIT) {
|
|
486
|
+
const relative = pending.shift();
|
|
487
|
+
visited++;
|
|
488
|
+
let entries;
|
|
489
|
+
try {
|
|
490
|
+
entries = await readdir(join(root, relative), { withFileTypes: true });
|
|
491
|
+
}
|
|
492
|
+
catch (error) {
|
|
493
|
+
if (!relative)
|
|
494
|
+
throw error;
|
|
495
|
+
results.push({ directory: relative, status: "unreadable", trace: "absent", live: "absent", reason: "The directory could not be read." });
|
|
496
|
+
continue;
|
|
497
|
+
}
|
|
498
|
+
for (const entry of entries)
|
|
499
|
+
if (entry.isDirectory() && !entry.isSymbolicLink())
|
|
500
|
+
pending.push(relative ? join(relative, entry.name) : entry.name);
|
|
501
|
+
if (!entries.some((entry) => entry.isFile() && entry.name === "error-context.md"))
|
|
502
|
+
continue;
|
|
503
|
+
const directory = relative || ".";
|
|
504
|
+
try {
|
|
505
|
+
const file = join(root, relative, "error-context.md");
|
|
506
|
+
if ((await lstat(file)).size > FILE_LIMIT)
|
|
507
|
+
throw new Error("too large");
|
|
508
|
+
const markdown = await readFile(file, "utf8");
|
|
509
|
+
let trace;
|
|
510
|
+
const tracePath = join(root, relative, "trace.zip");
|
|
511
|
+
if (entries.some((entry) => entry.isFile() && entry.name === "trace.zip")) {
|
|
512
|
+
try {
|
|
513
|
+
const handle = await open(tracePath, "r");
|
|
514
|
+
try {
|
|
515
|
+
const { size } = await handle.stat();
|
|
516
|
+
trace = size > TRACE_LIMIT ? "unreadable" : await handle.readFile();
|
|
517
|
+
}
|
|
518
|
+
finally {
|
|
519
|
+
await handle.close();
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
catch {
|
|
523
|
+
trace = "unreadable";
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
let live;
|
|
527
|
+
if (entries.some((entry) => entry.isFile() && entry.name === "agentpath-live.json")) {
|
|
528
|
+
try {
|
|
529
|
+
const file = join(root, relative, "agentpath-live.json");
|
|
530
|
+
live = (await lstat(file)).size > FILE_LIMIT ? "unreadable" : readLiveFinding(await readFile(file, "utf8"));
|
|
531
|
+
}
|
|
532
|
+
catch {
|
|
533
|
+
live = "unreadable";
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
results.push(explainFailedTest(directory, markdown, trace, live));
|
|
537
|
+
}
|
|
538
|
+
catch {
|
|
539
|
+
results.push({ directory, status: "unreadable", trace: "absent", live: "absent", reason: "error-context.md could not be read." });
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
return results.sort((a, b) => a.directory.localeCompare(b.directory));
|
|
543
|
+
}
|