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.
Files changed (127) hide show
  1. package/LICENSE.md +105 -0
  2. package/README.md +101 -2
  3. package/THIRD_PARTY_NOTICES +12 -0
  4. package/apps/demo-site/dist/site.js +92 -0
  5. package/apps/studio/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  6. package/apps/studio/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  7. package/apps/studio/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  8. package/apps/studio/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  9. package/apps/studio/dist/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
  10. package/apps/studio/dist/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
  11. package/apps/studio/dist/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
  12. package/apps/studio/dist/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
  13. package/apps/studio/dist/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
  14. package/apps/studio/dist/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
  15. package/apps/studio/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  16. package/apps/studio/dist/assets/index-DH4wJPHm.js +67 -0
  17. package/apps/studio/dist/assets/index-DrnNh2ip.css +1 -0
  18. package/apps/studio/dist/index.html +14 -0
  19. package/audit.md +173 -0
  20. package/autonomous-mode.md +104 -0
  21. package/ci.md +118 -0
  22. package/coding-agents.md +143 -0
  23. package/concepts.md +145 -0
  24. package/contracts.md +356 -0
  25. package/examples/tasks/ambiguous.json +98 -0
  26. package/examples/tasks/assertion-failure.json +98 -0
  27. package/examples/tasks/broken.json +98 -0
  28. package/examples/tasks/fixed.json +98 -0
  29. package/examples/tasks/recovery.json +19 -0
  30. package/images/compare-recovery-desktop.jpg +0 -0
  31. package/images/compare-variants-desktop.jpg +0 -0
  32. package/images/overview-desktop.jpg +0 -0
  33. package/images/run-autonomous-passed-desktop.jpg +0 -0
  34. package/images/run-failed-desktop.jpg +0 -0
  35. package/images/run-failed-mobile.jpg +0 -0
  36. package/images/run-missing-artifact-desktop.jpg +0 -0
  37. package/images/task-editor-laptop.jpg +0 -0
  38. package/installation.md +102 -0
  39. package/ledger.md +62 -0
  40. package/licenses/-fontsource-variable-geist-mono.txt +93 -0
  41. package/licenses/-fontsource-variable-geist.txt +93 -0
  42. package/licenses/lucide-react.txt +43 -0
  43. package/licenses/react-dom.txt +21 -0
  44. package/licenses/react.txt +21 -0
  45. package/licenses/scheduler.txt +21 -0
  46. package/licenses/tailwindcss.txt +21 -0
  47. package/licenses/zod.txt +21 -0
  48. package/package.json +165 -4
  49. package/packages/cli/bin/agentpath.js +39 -0
  50. package/packages/cli/dist/audit-rerun.js +384 -0
  51. package/packages/cli/dist/audit.js +387 -0
  52. package/packages/cli/dist/change-summaries.js +87 -0
  53. package/packages/cli/dist/ci-report.js +88 -0
  54. package/packages/cli/dist/demo.js +88 -0
  55. package/packages/cli/dist/doctor.js +265 -0
  56. package/packages/cli/dist/explain.js +89 -0
  57. package/packages/cli/dist/git.js +7 -0
  58. package/packages/cli/dist/inspect.js +118 -0
  59. package/packages/cli/dist/ledger.js +509 -0
  60. package/packages/cli/dist/local.js +102 -0
  61. package/packages/cli/dist/main.js +708 -0
  62. package/packages/cli/dist/mcp.js +231 -0
  63. package/packages/cli/dist/paths.js +6 -0
  64. package/packages/cli/dist/playwright-fixture.js +185 -0
  65. package/packages/cli/dist/playwright-reporter.js +49 -0
  66. package/packages/cli/dist/tasks.js +37 -0
  67. package/packages/cli/dist/test-source.js +283 -0
  68. package/packages/cli/dist/watch.js +96 -0
  69. package/packages/contracts/dist/agent-settings.js +18 -0
  70. package/packages/contracts/dist/agent.js +175 -0
  71. package/packages/contracts/dist/audit.js +115 -0
  72. package/packages/contracts/dist/guidance.js +339 -0
  73. package/packages/contracts/dist/index.js +14 -0
  74. package/packages/contracts/dist/inspect.js +63 -0
  75. package/packages/contracts/dist/ledger.js +80 -0
  76. package/packages/contracts/dist/local.js +171 -0
  77. package/packages/contracts/dist/outcomes.js +94 -0
  78. package/packages/contracts/dist/platform.js +105 -0
  79. package/packages/contracts/dist/playwright-live.js +76 -0
  80. package/packages/contracts/dist/policy.js +93 -0
  81. package/packages/contracts/dist/run.js +178 -0
  82. package/packages/contracts/dist/task-issues.js +39 -0
  83. package/packages/contracts/dist/task.js +185 -0
  84. package/packages/contracts/dist/watch.js +57 -0
  85. package/packages/core/dist/action-feedback.js +103 -0
  86. package/packages/core/dist/actions.js +160 -0
  87. package/packages/core/dist/agent-loop.js +122 -0
  88. package/packages/core/dist/artifacts.js +156 -0
  89. package/packages/core/dist/assertions.js +120 -0
  90. package/packages/core/dist/autonomous.js +1 -0
  91. package/packages/core/dist/browser.js +196 -0
  92. package/packages/core/dist/compare.js +141 -0
  93. package/packages/core/dist/control-state.js +62 -0
  94. package/packages/core/dist/diagnostics.js +134 -0
  95. package/packages/core/dist/evidence-diff.js +93 -0
  96. package/packages/core/dist/evidence.js +203 -0
  97. package/packages/core/dist/index.js +22 -0
  98. package/packages/core/dist/inspect.js +257 -0
  99. package/packages/core/dist/integrity.js +176 -0
  100. package/packages/core/dist/liveness.js +114 -0
  101. package/packages/core/dist/local-files.js +61 -0
  102. package/packages/core/dist/locators.js +214 -0
  103. package/packages/core/dist/model-provider.js +88 -0
  104. package/packages/core/dist/observation.js +257 -0
  105. package/packages/core/dist/playwright-live.js +519 -0
  106. package/packages/core/dist/playwright-results.js +543 -0
  107. package/packages/core/dist/policy.js +182 -0
  108. package/packages/core/dist/privacy.js +93 -0
  109. package/packages/core/dist/recovery.js +54 -0
  110. package/packages/core/dist/retention.js +204 -0
  111. package/packages/core/dist/run-index.js +177 -0
  112. package/packages/core/dist/run-plan.js +28 -0
  113. package/packages/core/dist/run-repository.js +518 -0
  114. package/packages/core/dist/runner.js +913 -0
  115. package/packages/core/dist/storage.js +63 -0
  116. package/packages/core/dist/task-fingerprint.js +36 -0
  117. package/packages/core/dist/test-change-rerun.js +84 -0
  118. package/packages/core/dist/test-changes.js +896 -0
  119. package/packages/core/dist/timing.js +41 -0
  120. package/packages/core/dist/watch.js +165 -0
  121. package/packages/server/dist/index.js +265 -0
  122. package/packages/server/dist/task-store.js +103 -0
  123. package/quickstart.md +85 -0
  124. package/security.md +136 -0
  125. package/try-on-your-repo.md +54 -0
  126. package/understanding-results.md +159 -0
  127. package/writing-tasks.md +196 -0
@@ -0,0 +1,387 @@
1
+ import { posix } from "node:path";
2
+ import { parseArgs } from "node:util";
3
+ import { auditReportSchema } from "#agentpath/contracts";
4
+ import { compareParameterised, compareTestFiles, plainText } from "#agentpath/core";
5
+ import { rerunAudit, RerunUsageError } from "./audit-rerun.js";
6
+ import { auditSummary, writeSummary } from "./change-summaries.js";
7
+ import { git } from "./git.js";
8
+ import { CONFIG_FILE, GitUsageError, isTestFile, JSX_TEST_FILE, mayBeTestFile, readSide, resolveCommit, testMatchScopes, usesOtherRunnerSource } from "./test-source.js";
9
+ const MAX_TEST_FILES = 2000;
10
+ // The schema's limits (packages/contracts/src/audit.ts). Anything past them is counted as not read, never dropped silently.
11
+ const MAX_LISTED_FILES = 5000;
12
+ const MAX_NOT_EXAMINED = 5000;
13
+ const MAX_TESTS = 2000;
14
+ const MAX_FINDINGS = 500;
15
+ const MAX_TITLE_PARTS = 64;
16
+ export class AuditUsageError extends GitUsageError {
17
+ }
18
+ /** `git diff --name-status -z` records: "M\0path\0", "R100\0old\0new\0", "C75\0old\0new\0". */
19
+ function parseNameStatus(output) {
20
+ const fields = output.split("\0");
21
+ const changes = [];
22
+ for (let index = 0; index < fields.length && fields[index];) {
23
+ const code = fields[index][0];
24
+ if (code === "R" || code === "C") {
25
+ const previous = fields[index + 1];
26
+ const path = fields[index + 2];
27
+ changes.push(code === "R" ? { status: "renamed", path, previousPath: previous } : { status: "added", path });
28
+ index += 3;
29
+ }
30
+ else {
31
+ const path = fields[index + 1];
32
+ changes.push({ status: code === "A" ? "added" : code === "D" ? "deleted" : "modified", path });
33
+ index += 2;
34
+ }
35
+ }
36
+ return changes;
37
+ }
38
+ export async function auditRepository(cwd, options) {
39
+ let root;
40
+ try {
41
+ root = (await git(cwd, ["rev-parse", "--show-toplevel"])).trim();
42
+ }
43
+ catch {
44
+ throw new AuditUsageError("audit must run inside a git repository.");
45
+ }
46
+ const baseTip = await resolveCommit(root, options.base, "--base");
47
+ const head = await resolveCommit(root, options.head ?? "HEAD", "--head");
48
+ // Compare from where head left base, as a pull request does: tests added on base since then are not head's removals.
49
+ let base;
50
+ try {
51
+ base = (await git(root, ["merge-base", baseTip, head])).trim();
52
+ }
53
+ catch {
54
+ throw new AuditUsageError("--base and --head share no history in this clone. In a shallow clone, fetch the full history first (git fetch --unshallow, or fetch-depth: 0 in CI).");
55
+ }
56
+ const pathspecs = (options.paths ?? []).map((path) => posix.normalize(posix.join(posix.relative(root, cwd) || ".", path)));
57
+ // "." is the repository root: a literal pathspec "." would match nothing.
58
+ const spec = (path) => path === "." ? ":(top)" : `:(top,literal)${path}`;
59
+ // A path that names nothing at either commit is a mistake, not an empty pull request: a misspelled suite would pass.
60
+ for (const path of pathspecs) {
61
+ const found = async (commit) => (await git(root, ["ls-tree", "-r", "--name-only", commit, "--", spec(path)]).catch(() => "")).trim() !== "";
62
+ if (!(await found(base)) && !(await found(head)))
63
+ throw new AuditUsageError(`${plainText(path)} matches no file at the merge base or at --head.`);
64
+ }
65
+ const diff = await git(root, ["diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--name-status", "-z", base, head, "--", ...pathspecs.map(spec)])
66
+ .catch(() => { throw new AuditUsageError("git could not compare the two commits."); });
67
+ // Renames are found with -M in a second pass only among test files, so a moved test keeps its history.
68
+ const renamed = parseNameStatus(await git(root, ["diff", "--no-ext-diff", "--no-textconv", "-M", "--diff-filter=R", "--name-status", "-z", base, head, "--", ...pathspecs.map(spec)]));
69
+ // A configuration's testMatch can select other names than .spec. and .test.: those files are tests too, and where
70
+ // a testMatch cannot be applied, the files it may select are reported as not read, so the gate fails closed.
71
+ // Scopes come from both commits, so a pull request that deletes or narrows a configuration with its tests still
72
+ // has those tests read.
73
+ const treeAt = async (commit) => (await git(root, ["ls-tree", "-r", "-z", "--name-only", commit])).split("\0").filter(Boolean);
74
+ const scopes = [...await testMatchScopes(root, base, await treeAt(base)), ...await testMatchScopes(root, head, await treeAt(head))];
75
+ const isTest = (path) => isTestFile(path, scopes);
76
+ const renames = new Map(renamed.filter((change) => isTest(change.path)).map((change) => [change.path, change.previousPath]));
77
+ const renamedFrom = new Set(renames.values());
78
+ const changes = parseNameStatus(diff);
79
+ const named = changes.filter((change) => isTest(change.path) && !(change.status === "deleted" && renamedFrom.has(change.path)));
80
+ // A test file of another runner on every side that exists (base and head) is listed, never read or gated. Both sides
81
+ // are needed: an import added in the pull request itself cannot move a Playwright test out of the gate.
82
+ const source = (commit, path) => git(root, ["cat-file", "blob", `${commit}:${path}`]).then((text) => text, () => undefined);
83
+ const otherRunner = [];
84
+ const testChanges = [];
85
+ for (const change of named) {
86
+ const basePath = change.status === "added" ? renames.get(change.path) : change.path;
87
+ const sides = [
88
+ ...(basePath !== undefined ? [await source(base, basePath)] : []),
89
+ ...(change.status === "deleted" ? [] : [await source(head, change.path)]),
90
+ ];
91
+ if (sides.length && sides.every((text) => text !== undefined && usesOtherRunnerSource(text)))
92
+ otherRunner.push(plainText(change.path));
93
+ else
94
+ testChanges.push(change);
95
+ }
96
+ otherRunner.sort();
97
+ // With paths given, changed test files outside them are listed (other runners' left out), so a path that leaves out
98
+ // a suite shows instead of passing quietly.
99
+ const outsidePaths = [];
100
+ if (pathspecs.length) {
101
+ const inside = new Set(changes.map((change) => change.path));
102
+ const everything = parseNameStatus(await git(root, ["diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--name-status", "-z", base, head]));
103
+ for (const change of everything.filter((change) => !inside.has(change.path) && isTest(change.path))) {
104
+ const sides = outsidePaths.length >= MAX_TEST_FILES ? [] : [
105
+ ...(change.status === "added" ? [] : [await source(base, change.path)]),
106
+ ...(change.status === "deleted" ? [] : [await source(head, change.path)]),
107
+ ];
108
+ if (!(sides.length && sides.every((text) => text !== undefined && usesOtherRunnerSource(text))))
109
+ outsidePaths.push(plainText(change.path));
110
+ }
111
+ outsidePaths.sort();
112
+ }
113
+ const exempt = new Set(otherRunner);
114
+ const testRoots = new Set(changes.filter((change) => (isTest(change.path) && !exempt.has(plainText(change.path))) || JSX_TEST_FILE.test(change.path)).map((change) => posix.dirname(change.path)));
115
+ const notExamined = changes
116
+ .filter((change) => !isTest(change.path) && !mayBeTestFile(change.path, scopes))
117
+ .filter((change) => JSX_TEST_FILE.test(change.path) || CONFIG_FILE.test(change.path) || [...testRoots].some((dir) => change.path.startsWith(dir === "." ? "" : `${dir}/`)))
118
+ .map((change) => plainText(change.path))
119
+ .sort();
120
+ // Every path the comparison changed, outside the paths given too: a parameter list can live in any imported file.
121
+ let changedAnywhere;
122
+ const stem = (path) => path.replace(/\.[cm]?[jt]sx?$/, "").replace(/\/index$/, "");
123
+ /** Whether a file a test file imports directly, by a relative path, changed between the two commits. */
124
+ const importsChanged = async (sides) => {
125
+ if (sides.every(([, read]) => !read.unreadableTests.length))
126
+ return false;
127
+ changedAnywhere ??= new Set(parseNameStatus(await git(root, ["diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--name-status", "-z", base, head]))
128
+ .map((entry) => stem(entry.path)));
129
+ return sides.some(([path, read]) => read.imports.some((specifier) => specifier.startsWith(".")
130
+ && changedAnywhere.has(stem(posix.normalize(posix.join(posix.dirname(path), specifier))))));
131
+ };
132
+ const files = [];
133
+ for (const change of testChanges.slice(0, MAX_TEST_FILES)) {
134
+ const previousPath = change.status === "added" ? renames.get(change.path) : undefined;
135
+ const status = previousPath ? "renamed" : change.status;
136
+ const basePath = previousPath ?? change.path;
137
+ const before = status === "added" ? undefined : await readSide(root, base, basePath);
138
+ const after = status === "deleted" ? undefined : await readSide(root, head, change.path);
139
+ const problems = [typeof before === "string" ? `base: ${before}` : undefined, typeof after === "string" ? `head: ${after}` : undefined].filter(Boolean);
140
+ const readBefore = typeof before === "string" ? undefined : before;
141
+ const readAfter = typeof after === "string" ? undefined : after;
142
+ // Parameterised tests (a title built at run time) are compared only when nothing outside the compared bodies
143
+ // changed in the file and no helper beside the tests changed, since either could change how many tests run.
144
+ const parameterised = readBefore && readAfter && !notExamined.length
145
+ && !(await importsChanged([[basePath, readBefore], [change.path, readAfter]])) ? compareParameterised(readBefore, readAfter) : undefined;
146
+ const unreadableTests = parameterised ? [] : [
147
+ ...(readBefore?.unreadableTests ?? []).map((line) => ({ side: "base", line })),
148
+ ...(readAfter?.unreadableTests ?? []).map((line) => ({ side: "head", line })),
149
+ ];
150
+ // With one side unreadable, pairing would turn every test into "added" or "removed": report the file instead.
151
+ const compared = problems.length ? [] : [...compareTestFiles(readBefore, readAfter), ...(parameterised ?? [])];
152
+ // Past the schema's limits a file is reported as not fully read, so --fail-on-weakening fails closed.
153
+ const deep = compared.filter((test) => test.title.length > MAX_TITLE_PARTS);
154
+ const tests = compared.filter((test) => test.title.length <= MAX_TITLE_PARTS)
155
+ .map((test) => test.findings.length > MAX_FINDINGS ? { ...test, findings: test.findings.slice(0, MAX_FINDINGS) } : test);
156
+ const limits = [
157
+ deep.length ? `${deep.length} test${deep.length === 1 ? " is" : "s are"} nested more than ${MAX_TITLE_PARTS} levels deep.` : undefined,
158
+ compared.some((test) => test.findings.length > MAX_FINDINGS) ? `A test has more than ${MAX_FINDINGS} findings; the rest are not listed.` : undefined,
159
+ tests.length > MAX_TESTS ? `More than ${MAX_TESTS} tests changed; the rest are not listed.` : undefined,
160
+ unreadableTests.length > MAX_TESTS ? `More than ${MAX_TESTS} tests have titles that are not literals.` : undefined,
161
+ ].filter(Boolean);
162
+ const reasons = [...problems, ...limits];
163
+ files.push({
164
+ path: plainText(change.path), ...(previousPath ? { previousPath: plainText(previousPath) } : {}), status,
165
+ ...(reasons.length ? { unreadable: plainText(reasons.join(" ")).slice(0, 2000) } : {}),
166
+ unreadableTests: unreadableTests.slice(0, MAX_TESTS), tests: tests.slice(0, MAX_TESTS),
167
+ });
168
+ }
169
+ for (const change of testChanges.slice(MAX_TEST_FILES, MAX_LISTED_FILES)) {
170
+ files.push({ path: plainText(change.path), status: change.status, unreadable: `Not read: more than ${MAX_TEST_FILES} test files changed.`, unreadableTests: [], tests: [] });
171
+ }
172
+ for (const change of changes.filter((change) => mayBeTestFile(change.path, scopes)).slice(0, MAX_LISTED_FILES)) {
173
+ const config = scopes.find((scope) => scope.kind === "unapplied" && !scope.defaultNames && (scope.dir === "" || change.path.startsWith(`${scope.dir}/`))).config;
174
+ files.push({ path: plainText(change.path), status: change.status, unreadable: plainText(`Not read: ${config} has a testMatch that audit cannot apply, and it may select this file.`).slice(0, 2000), unreadableTests: [], tests: [] });
175
+ }
176
+ const unlisted = Math.max(0, testChanges.length - MAX_LISTED_FILES);
177
+ const tests = files.flatMap((file) => file.tests);
178
+ const report = {
179
+ schemaVersion: 1,
180
+ base,
181
+ head,
182
+ files,
183
+ notExamined: notExamined.slice(0, MAX_NOT_EXAMINED),
184
+ ...(otherRunner.length ? { otherRunner: otherRunner.slice(0, MAX_NOT_EXAMINED) } : {}),
185
+ ...(outsidePaths.length ? { outsidePaths: outsidePaths.slice(0, MAX_NOT_EXAMINED) } : {}),
186
+ totals: {
187
+ testFiles: testChanges.length,
188
+ testsChanged: tests.length,
189
+ weakened: tests.filter((test) => test.findings.some((finding) => finding.effect === "weakens")).length,
190
+ changed: tests.filter((test) => test.findings.some((finding) => finding.effect === "changes")).length,
191
+ unreadable: unlisted + files.filter((file) => file.unreadable).length + files.reduce((sum, file) => sum + file.unreadableTests.length, 0),
192
+ notExamined: notExamined.length,
193
+ ...(otherRunner.length ? { otherRunner: otherRunner.length } : {}),
194
+ ...(outsidePaths.length ? { outsidePaths: outsidePaths.length } : {}),
195
+ },
196
+ };
197
+ return auditReportSchema.parse(report);
198
+ }
199
+ const EFFECT_ORDER = { weakens: 0, changes: 1, neutral: 2 };
200
+ /** The text report: weakened tests first. Titles, locators and values are quoted from the repository. */
201
+ export function formatAudit(report) {
202
+ const lines = [`Test changes from ${report.base.slice(0, 12)} (where head left base) to ${report.head.slice(0, 12)}`];
203
+ const { totals } = report;
204
+ lines.push(`${totals.testFiles} test file${totals.testFiles === 1 ? "" : "s"} changed, ${totals.testsChanged} test${totals.testsChanged === 1 ? "" : "s"} changed: ${totals.weakened} weakened, ${totals.changed} otherwise changed.`, "");
205
+ const entries = report.files.flatMap((file) => file.tests.map((test) => ({ file, test, rank: Math.min(...test.findings.map((finding) => EFFECT_ORDER[finding.effect])) })));
206
+ for (const [effect, heading] of [[0, "Weakened"], [1, "Changed"], [2, "Added"]]) {
207
+ const group = entries.filter((entry) => entry.rank === effect);
208
+ if (!group.length)
209
+ continue;
210
+ lines.push(`${heading} (${group.length})`);
211
+ for (const { file, test } of group) {
212
+ const line = test.headLine ?? test.baseLine;
213
+ lines.push(` ${file.path}${line ? `:${line}` : ""} ${test.title.map((part) => JSON.stringify(part)).join(" > ")}`);
214
+ for (const finding of [...test.findings].sort((a, b) => EFFECT_ORDER[a.effect] - EFFECT_ORDER[b.effect])) {
215
+ lines.push(` ${finding.effect === "weakens" ? "weakens" : finding.effect === "changes" ? "changes" : "adds"} · ${finding.kind}: ${finding.detail}`);
216
+ }
217
+ if (test.rerun)
218
+ lines.push(...rerunLines(test));
219
+ }
220
+ lines.push("");
221
+ }
222
+ const unreadable = report.files.filter((file) => file.unreadable || file.unreadableTests.length);
223
+ if (unreadable.length || totals.testFiles > report.files.length) {
224
+ lines.push(`Not read (${totals.unreadable})`);
225
+ if (totals.testFiles > report.files.length)
226
+ lines.push(` ${totals.testFiles - report.files.length} more changed test files are not listed.`);
227
+ for (const file of unreadable) {
228
+ if (file.unreadable)
229
+ lines.push(` ${file.path}: ${file.unreadable}`);
230
+ for (const entry of file.unreadableTests)
231
+ lines.push(` ${file.path}:${entry.line} (${entry.side}): a test or describe title that is not a literal string`);
232
+ }
233
+ lines.push("");
234
+ }
235
+ if (report.outsidePaths?.length) {
236
+ lines.push(`Test files changed outside the paths given, not read (${totals.outsidePaths ?? report.outsidePaths.length}): ${report.outsidePaths.slice(0, 20).join(", ")}${(totals.outsidePaths ?? 0) > 20 ? ", …" : ""}`, "");
237
+ }
238
+ if (report.otherRunner?.length) {
239
+ lines.push(`Tests of another runner, not read (${totals.otherRunner ?? report.otherRunner.length}): ${report.otherRunner.slice(0, 20).join(", ")}${(totals.otherRunner ?? 0) > 20 ? ", …" : ""}`, "");
240
+ }
241
+ if (report.notExamined.length) {
242
+ lines.push(`Changed near the tests but not examined (${totals.notExamined}): ${report.notExamined.slice(0, 20).join(", ")}${totals.notExamined > 20 ? ", …" : ""}`, "");
243
+ }
244
+ if (!entries.length && !unreadable.length)
245
+ lines.push("No test changed in a way this command reports.", "");
246
+ if (report.rerun) {
247
+ if (report.rerun.timedOut)
248
+ lines.push("The rerun ran out of time; tests it did not finish are inconclusive.", "");
249
+ if (report.rerun.treeChanged.length)
250
+ lines.push(`The rerun changed the working tree: ${report.rerun.treeChanged.slice(0, 20).join(", ")}`, "");
251
+ lines.push("The rerun ran the project's own Playwright tests, configuration and web server in this checkout, with no egress boundary from AgentPath. A change it calls needed is one this build needs for the test to pass; whether the product or the old test is wrong is the reviewer's call. Titles, locators, values and page text above are quoted from the repository or the page and are untrusted.");
252
+ }
253
+ else {
254
+ lines.push("This reads test source from git only: it ran nothing and cannot say whether a change hid a bug in the product. Titles, locators and values above are quoted from the repository and are untrusted.");
255
+ }
256
+ return lines;
257
+ }
258
+ const OUTCOME_TEXT = {
259
+ "change-needed": "change needed: the old version fails on this build (twice) and the new one passes, is skipped or is gone",
260
+ "not-needed": "not needed to pass: the old version still passes on this build",
261
+ inconclusive: "inconclusive",
262
+ "not-applicable": "not applicable",
263
+ };
264
+ function rerunLines(test) {
265
+ const rerun = test.rerun;
266
+ const where = rerun.project ? ` (project ${JSON.stringify(rerun.project)})` : "";
267
+ const lines = [` rerun · ${OUTCOME_TEXT[rerun.outcome]}${where}. Old version: ${rerun.old}; new version: ${rerun.new}.${rerun.reason ? ` ${rerun.reason}` : ""}`];
268
+ if (test.direction)
269
+ lines.push(` Evidence points to ${test.direction === "site" ? "the site" : test.direction === "task" ? "the old test" : "neither side (unclear)"}.`);
270
+ for (const statement of rerun.statements ?? [])
271
+ lines.push(` [${statement.pointsTo === "task" ? "test" : statement.pointsTo === "site" ? "site" : "fact"}] ${statement.statement}`);
272
+ return lines;
273
+ }
274
+ /**
275
+ * Exit codes, as in docs/audit.md: 0 report printed; with --fail-on-weakening, 1 on a weakened test and 3 when
276
+ * anything was not read; with --rerun --fail-on-change-needed, 1 when a weakened test's change is needed or a needed
277
+ * change's evidence points to the site, and 3 when anything was not read or a weakened test's rerun was inconclusive.
278
+ */
279
+ export function changeNeededExit(report) {
280
+ return changeNeededVerdict(report).code;
281
+ }
282
+ const named = (entries) => entries.slice(0, 3)
283
+ .map(({ path, test }) => `${path} ${test.title.map((part) => JSON.stringify(part)).join(" > ")}`).join("; ") + (entries.length > 3 ? `; and ${entries.length - 3} more` : "");
284
+ /** The verdict of --rerun --fail-on-change-needed. The exit code is changeNeededExit's. */
285
+ export function changeNeededVerdict(report) {
286
+ const tests = report.files.flatMap((file) => file.tests.map((test) => ({ path: file.path, test })));
287
+ const weakened = (test) => test.findings.some((finding) => finding.effect === "weakens");
288
+ if (report.totals.unreadable > 0)
289
+ return { code: 3, reason: `Not decided: ${report.totals.unreadable} test file${report.totals.unreadable === 1 ? " or test was" : "s or tests were"} not read (listed above), so a weakened test could be missed.` };
290
+ if (report.rerun?.timedOut)
291
+ return { code: 3, reason: "Not decided: the rerun ran out of time." };
292
+ if (report.rerun?.treeChanged.length)
293
+ return { code: 3, reason: "Not decided: the rerun changed the working tree." };
294
+ const inconclusive = tests.filter(({ test }) => weakened(test) && test.rerun?.outcome === "inconclusive");
295
+ if (inconclusive.length)
296
+ return { code: 3, reason: `Not decided: the rerun of a weakened test was inconclusive (${named(inconclusive)}).` };
297
+ // test.only needs no rerun to judge: it stops every other test in the run.
298
+ const only = tests.filter(({ test }) => test.findings.some((finding) => finding.kind === "only-added"));
299
+ if (only.length)
300
+ return { code: 1, reason: `Fails: test.only was added, which stops every other test in the run (${named(only)}).` };
301
+ const needed = tests.filter(({ test }) => test.rerun?.outcome === "change-needed");
302
+ const hid = needed.filter(({ test }) => weakened(test));
303
+ if (hid.length)
304
+ return { code: 1, reason: `Fails: a weakened test's change was needed to pass on this build, so the change may hide a failure (${named(hid)}). The old version fails here twice. Fix the product, or have a reviewer accept the change.` };
305
+ const site = needed.filter(({ test }) => test.direction === "site");
306
+ if (site.length)
307
+ return { code: 1, reason: `Fails: a test change was needed to pass on this build, and the evidence from the old version's failure points to the site (${named(site)}). Fix the product, or have a reviewer accept the change.` };
308
+ return { code: 0, reason: needed.length
309
+ ? "Passes: the changes this build needed weaken no test, and their evidence does not point to the site."
310
+ : "Passes: no weakened test's change was needed on this build." };
311
+ }
312
+ /** The verdict of --fail-on-weakening, which reads git only. */
313
+ export function weakeningVerdict(report) {
314
+ if (report.totals.unreadable > 0)
315
+ return { code: 3, reason: `Not decided: ${report.totals.unreadable} test file${report.totals.unreadable === 1 ? " or test was" : "s or tests were"} not read (listed above), so a weakened test could be missed.` };
316
+ const weakened = report.files.flatMap((file) => file.tests.filter((test) => test.findings.some((finding) => finding.effect === "weakens")).map((test) => ({ path: file.path, test })));
317
+ return weakened.length
318
+ ? { code: 1, reason: `Fails: ${weakened.length} test${weakened.length === 1 ? " was" : "s were"} weakened (${named(weakened)}). Add --rerun in CI to fail only when the build needed the change.` }
319
+ : { code: 0, reason: "Passes: no test was weakened." };
320
+ }
321
+ /** Exit codes, as in docs/audit.md: 0 report printed; with --fail-on-weakening, 1 on a weakened test and 3 when anything was not read. */
322
+ export async function auditCommand(args) {
323
+ let parsed;
324
+ try {
325
+ parsed = parseArgs({ args, allowPositionals: true, options: {
326
+ base: { type: "string" }, head: { type: "string" }, json: { type: "boolean" }, "fail-on-weakening": { type: "boolean" },
327
+ rerun: { type: "boolean" }, config: { type: "string" }, project: { type: "string" }, "rerun-timeout": { type: "string" },
328
+ "fail-on-change-needed": { type: "boolean" }, summary: { type: "string" },
329
+ } });
330
+ }
331
+ catch (error) {
332
+ console.error(String(error.message));
333
+ return 2;
334
+ }
335
+ const { values, positionals } = parsed;
336
+ if (!values.base) {
337
+ console.error("audit needs --base <commit>, such as --base origin/main.");
338
+ return 2;
339
+ }
340
+ if (values["fail-on-change-needed"] && values["fail-on-weakening"]) {
341
+ console.error("Use --fail-on-weakening or --fail-on-change-needed, not both.");
342
+ return 2;
343
+ }
344
+ if (!values.rerun && (values["fail-on-change-needed"] || values.config || values.project || values["rerun-timeout"])) {
345
+ console.error("--fail-on-change-needed, --config, --project and --rerun-timeout need --rerun, which runs the project's own tests.");
346
+ return 2;
347
+ }
348
+ const timeoutSeconds = values["rerun-timeout"] === undefined ? 600 : Number(values["rerun-timeout"]);
349
+ if (!Number.isInteger(timeoutSeconds) || timeoutSeconds < 10 || timeoutSeconds > 7200) {
350
+ console.error("--rerun-timeout is a whole number of seconds from 10 to 7200.");
351
+ return 2;
352
+ }
353
+ let report;
354
+ try {
355
+ report = await auditRepository(process.cwd(), { base: values.base, ...(values.head ? { head: values.head } : {}), paths: positionals });
356
+ }
357
+ catch (error) {
358
+ if (error instanceof GitUsageError) {
359
+ console.error(error.message);
360
+ return 2;
361
+ }
362
+ throw error;
363
+ }
364
+ if (values.rerun) {
365
+ try {
366
+ report = await rerunAudit(process.cwd(), report, { timeoutMs: timeoutSeconds * 1000, ...(values.config ? { config: values.config } : {}), ...(values.project ? { project: values.project } : {}) });
367
+ }
368
+ catch (error) {
369
+ if (error instanceof RerunUsageError) {
370
+ console.error(error.message);
371
+ return 2;
372
+ }
373
+ throw error;
374
+ }
375
+ }
376
+ const verdict = values["fail-on-change-needed"] ? changeNeededVerdict(report) : values["fail-on-weakening"] ? weakeningVerdict(report) : undefined;
377
+ if (values.json)
378
+ console.log(JSON.stringify({ untrusted: report.rerun ? "repository-provided and page-provided text" : "repository-provided text", report }));
379
+ else
380
+ console.log([...formatAudit(report), ...(verdict ? ["", `Gate (exit ${verdict.code}): ${verdict.reason}`] : [])].join("\n"));
381
+ // With --json, stdout stays one report object; the gate's reason goes to stderr.
382
+ if (values.json && verdict)
383
+ console.error(`Gate (exit ${verdict.code}): ${verdict.reason}`);
384
+ if (values.summary)
385
+ await writeSummary(values.summary, auditSummary(report, verdict));
386
+ return verdict?.code ?? 0;
387
+ }
@@ -0,0 +1,87 @@
1
+ import { writeFile } from "node:fs/promises";
2
+ import { md } from "./ci-report.js";
3
+ /**
4
+ * Markdown summaries of `audit` and `ledger` for a CI job summary or a pull request comment. Every value from the
5
+ * repository or the page goes through `md`, and no value starts a line, so it cannot add markup, links or mentions.
6
+ */
7
+ const MAX_ROWS = 100;
8
+ const plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
9
+ const title = (parts) => parts.map((part) => md(part)).join(" › ");
10
+ const RERUN = { "change-needed": "**change needed**", "not-needed": "not needed", inconclusive: "inconclusive", "not-applicable": "not applicable" };
11
+ const DIRECTION = { site: "**the site**", task: "the old test", unclear: "neither (unclear)" };
12
+ export function auditSummary(report, verdict) {
13
+ const { totals } = report;
14
+ const tests = report.files.flatMap((file) => file.tests.map((test) => ({ file, test })))
15
+ .filter(({ test }) => test.findings.some((finding) => finding.effect !== "neutral"));
16
+ const weakened = (test) => test.findings.some((finding) => finding.effect === "weakens");
17
+ tests.sort((a, b) => Number(weakened(b.test)) - Number(weakened(a.test)));
18
+ const needed = tests.filter(({ test }) => test.rerun?.outcome === "change-needed").length;
19
+ const lines = [
20
+ `## AgentPath audit: ${plural(totals.testsChanged, "test")} changed, ${totals.weakened} weakened${report.rerun ? `, ${needed} change${needed === 1 ? "" : "s"} needed on this build` : ""}`,
21
+ ``,
22
+ ];
23
+ // The reason quotes test titles from the repository, so it is escaped like every other repository text here.
24
+ if (verdict)
25
+ lines.push(`**Gate ${verdict.code === 0 ? "passes" : verdict.code === 1 ? "fails" : "not decided"} (exit ${verdict.code}).** ${md(verdict.reason)}`, ``);
26
+ if (tests.length) {
27
+ lines.push(report.rerun ? `| Test | Change | Rerun | Evidence points to |` : `| Test | Change |`, report.rerun ? `|---|---|---|---|` : `|---|---|`);
28
+ for (const { file, test } of tests.slice(0, MAX_ROWS)) {
29
+ const line = test.headLine ?? test.baseLine;
30
+ const kinds = [...new Set(test.findings.filter((finding) => finding.effect !== "neutral").map((finding) => `${finding.effect === "weakens" ? "⚠️ " : ""}\`${finding.kind}\``))].join(", ");
31
+ const cell = `${md(file.path)}${line ? `:${line}` : ""} — ${title(test.title)}`;
32
+ lines.push(report.rerun
33
+ ? `| ${cell} | ${kinds} | ${test.rerun ? RERUN[test.rerun.outcome] : ""} | ${test.direction ? DIRECTION[test.direction] : ""} |`
34
+ : `| ${cell} | ${kinds} |`);
35
+ }
36
+ if (tests.length > MAX_ROWS)
37
+ lines.push(``, `${tests.length - MAX_ROWS} more changed tests are in the command's output.`);
38
+ }
39
+ else
40
+ lines.push(`No test changed in a way this command reports.`);
41
+ if (totals.unreadable)
42
+ lines.push(``, `Not read: ${totals.unreadable}. Unread files and tests are listed in the command's output.`);
43
+ if (totals.outsidePaths)
44
+ lines.push(``, `Not read, outside the paths given: ${plural(totals.outsidePaths, "changed test file")}. Add their suite's directory if they are Playwright tests.`);
45
+ if (totals.otherRunner)
46
+ lines.push(``, `Not read, another test runner's: ${plural(totals.otherRunner, "changed test file")}.`);
47
+ if (report.rerun?.timedOut)
48
+ lines.push(``, `The rerun ran out of time; tests it did not finish are inconclusive.`);
49
+ lines.push(``, report.rerun
50
+ ? `<sub>The rerun ran the project's own Playwright tests on this build. A change it calls needed is one this build needs for the test to pass; whether the product or the old test is wrong is the reviewer's call.</sub>`
51
+ : `<sub>Read from test source in git only: nothing ran, so this cannot say whether a change hid a bug.</sub>`, ``);
52
+ return lines.join("\n");
53
+ }
54
+ const commitCell = (commit) => `\`${commit.commit.slice(0, 12)}\` ${md(commit.subject)}${commit.saysFlaky ? " · says flaky" : ""}${commit.automated ? " · bot or agent" : ""}`;
55
+ export function ledgerSummary(report) {
56
+ const { totals } = report;
57
+ const lines = [
58
+ `## AgentPath ledger: ${totals.disabled} of ${plural(totals.tests, "test")} turned off`,
59
+ ``,
60
+ `Turning-off commit: ${totals.disabledSaysFlaky} say flaky, ${totals.disabledAutomated} from a bot or agent, ${totals.disabledSinceUnknown} not in the history read${totals.disabledAppearedOff ? `, ${totals.disabledAppearedOff} added already off (not counted as flaky or bot)` : ""}. ${plural(totals.conditional, "more test")} skipped only under a condition.`,
61
+ ``,
62
+ ];
63
+ if (report.disabled.length) {
64
+ lines.push(`| Test | How | Days off | Turned off by |`, `|---|---|---|---|`);
65
+ for (const test of report.disabled.slice(0, MAX_ROWS)) {
66
+ lines.push(`| ${md(test.path)}:${test.line} — ${title(test.title)} | ${test.how}${test.scope === "group" ? " (group)" : ""} | ${test.ageDays === undefined ? "unknown" : `${test.appearedOff ? "≥ " : ""}${test.ageDays}`} | ${test.since ? commitCell(test.since) : ""} |`);
67
+ }
68
+ if (report.disabled.length > MAX_ROWS)
69
+ lines.push(``, `${report.disabled.length - MAX_ROWS} more turned-off tests are in the command's output.`);
70
+ }
71
+ if (report.reenabled.length) {
72
+ lines.push(``, `### Turned off and back on since ${report.since.slice(0, 10)}`, ``, `| Test | Days off | Off | On | Product files changed by the re-enable |`, `|---|---|---|---|---|`);
73
+ for (const test of report.reenabled.slice(-MAX_ROWS)) {
74
+ lines.push(`| ${md(test.path)} — ${title(test.title)} | ${test.disabledAppeared ? "≥ " : ""}${test.days} | ${commitCell(test.disabled)} | ${commitCell(test.enabled)} | ${test.productFiles} |`);
75
+ }
76
+ if (report.reenabled.length > MAX_ROWS)
77
+ lines.push(``, `${report.reenabled.length - MAX_ROWS} earlier re-enables are in the command's output.`);
78
+ }
79
+ if (totals.unreadable)
80
+ lines.push(``, `Not read: ${totals.unreadable}. Details are in the command's output.`);
81
+ lines.push(``, `<sub>Read from test source and git history only: nothing ran. A re-enable that changed product files is a fact about that commit, not proof that the skip hid a fault.</sub>`, ``);
82
+ return lines.join("\n");
83
+ }
84
+ /** Writes a summary, appending when the file is the job summary GitHub Actions names. */
85
+ export async function writeSummary(file, text) {
86
+ await writeFile(file, text, { flag: file === process.env.GITHUB_STEP_SUMMARY ? "a" : "w" });
87
+ }
@@ -0,0 +1,88 @@
1
+ import { displayPath } from "./paths.js";
2
+ const direction = { task: "points to the task", site: "points to the site", unclear: "fact" };
3
+ // XML 1.0 forbids most C0 controls even when escaped; drop them along with lone surrogates.
4
+ function xml(value) {
5
+ return value
6
+ .replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F￾￿]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "")
7
+ .replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
8
+ }
9
+ function seconds(ms) {
10
+ return (ms / 1000).toFixed(3);
11
+ }
12
+ function where(result, guidance) {
13
+ const { location } = result.failure;
14
+ const step = location.phase === "startup" ? "startup" : `${location.phase} ${location.index + 1}`;
15
+ return guidance?.taskPath ? `${step} (task file ${guidance.taskPath})` : step;
16
+ }
17
+ /** One JUnit test case per task file, in the order given. Cancelled runs are reported as skipped. */
18
+ export function junitXml(entries) {
19
+ const failures = entries.filter((entry) => entry.result.status === "failed").length;
20
+ const skipped = entries.filter((entry) => entry.result.status === "cancelled").length;
21
+ const total = entries.reduce((sum, entry) => sum + entry.result.durationMs, 0);
22
+ const cases = entries.map(({ file, name, result, guidance }) => {
23
+ const open = ` <testcase classname="agentpath" name="${xml(`${result.taskId} — ${name}`)}" file="${xml(displayPath(file))}" time="${seconds(result.durationMs)}">`;
24
+ if (result.status === "passed")
25
+ return `${open}</testcase>`;
26
+ if (result.status === "cancelled")
27
+ return `${open}\n <skipped message="Run cancelled"/>\n </testcase>`;
28
+ const { category, observed, expected } = result.failure;
29
+ const body = [
30
+ `${category} at ${where(result, guidance)}`, observed, `Expected ${expected}`,
31
+ ...(guidance?.findings ?? []).map((finding) => `[${direction[finding.pointsTo]}] ${finding.statement}`),
32
+ ...(guidance?.suggestedChanges.length ? ["Possible task changes (JSON Patch; not applied):",
33
+ ...guidance.suggestedChanges.map(({ op, path, value }) => JSON.stringify({ op, path, value }))] : []),
34
+ `Run ${result.runId}`,
35
+ ].join("\n");
36
+ return `${open}\n <failure type="${xml(category)}" message="${xml(`${category} at ${where(result, guidance)}`)}">${xml(body)}</failure>\n </testcase>`;
37
+ });
38
+ return [
39
+ `<?xml version="1.0" encoding="UTF-8"?>`,
40
+ `<testsuites name="agentpath" tests="${entries.length}" failures="${failures}" skipped="${skipped}" time="${seconds(total)}">`,
41
+ ` <testsuite name="agentpath" tests="${entries.length}" failures="${failures}" errors="0" skipped="${skipped}" time="${seconds(total)}">`,
42
+ ...cases,
43
+ ` </testsuite>`,
44
+ `</testsuites>`,
45
+ ``,
46
+ ].join("\n");
47
+ }
48
+ // Markdown and HTML in a pull request: neutralise every character that could start markup, emphasis, a table
49
+ // cell, a link, an autolink or a mention. Values never start a line, so list and heading markers cannot apply.
50
+ export function md(value) {
51
+ return value.replace(/[\u0000-\u001F\u007F]/g, " ")
52
+ .replace(/[\\`*_{}[\]<>#|~@&]|:(?=\/\/)|(?<=www)\./gi, (char) => `&#${char.charCodeAt(0)};`);
53
+ }
54
+ /** A Markdown summary for a CI job summary or a pull request comment. */
55
+ export function markdownSummary(entries) {
56
+ const passed = entries.filter((entry) => entry.result.status === "passed").length;
57
+ const failed = entries.filter((entry) => entry.result.status === "failed");
58
+ const cancelled = entries.length - passed - failed.length;
59
+ const lines = [
60
+ `## AgentPath: ${passed} of ${entries.length} passed${failed.length ? `, ${failed.length} failed` : ""}${cancelled ? `, ${cancelled} cancelled` : ""}`,
61
+ ``,
62
+ `| Task | Verdict | Where | Evidence points to |`,
63
+ `|---|---|---|---|`,
64
+ ...entries.map(({ name, result, guidance }) => {
65
+ const verdict = result.status === "passed" ? "✅ passed" : result.status === "failed" ? `❌ \`${result.failure.category}\`` : "⏹ cancelled";
66
+ const at = result.status === "failed" ? md(where(result, guidance)) : "";
67
+ const points = [...new Set(guidance?.findings.map((finding) => finding.pointsTo) ?? [])];
68
+ const label = points.includes("site") ? "**the site**" : points.includes("task") ? "the task" : result.status === "failed" ? "neither (facts only)" : "";
69
+ return `| ${md(name)} | ${verdict} | ${at} | ${label} |`;
70
+ }),
71
+ ];
72
+ for (const { name, result, guidance } of failed) {
73
+ if (result.status !== "failed")
74
+ continue;
75
+ lines.push(``, `### ${md(name)}`, ``, `${md(result.failure.observed)} Expected ${md(result.failure.expected)}`);
76
+ for (const finding of guidance?.findings ?? [])
77
+ lines.push(`- *${direction[finding.pointsTo]}*: ${md(finding.statement)}`);
78
+ if (guidance?.suggestedChanges.length) {
79
+ lines.push(``, `Possible task changes (JSON Patch, not applied; each assumes the page is correct):`, ``, "```json", ...guidance.suggestedChanges.map(({ op, path, value }) => JSON.stringify({ op, path, value }).replace(/`/g, "\\u0060")), "```");
80
+ }
81
+ else if (guidance?.findings.some((finding) => finding.pointsTo === "site")) {
82
+ lines.push(``, `No task change is suggested: the evidence points to the site, so changing the test could hide a real defect.`);
83
+ }
84
+ lines.push(``, `Run \`${result.runId}\``);
85
+ }
86
+ lines.push(``, `<sub>Independent assertions decide every verdict. Suggestions are never applied automatically.</sub>`, ``);
87
+ return lines.join("\n");
88
+ }