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,509 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { posix } from "node:path";
|
|
3
|
+
import { parseArgs } from "node:util";
|
|
4
|
+
import { ledgerReportSchema } from "#agentpath/contracts";
|
|
5
|
+
import { conditionallySkipped, disabledState, plainText } from "#agentpath/core";
|
|
6
|
+
import { ledgerSummary, writeSummary } from "./change-summaries.js";
|
|
7
|
+
import { git } from "./git.js";
|
|
8
|
+
import { CONFIG_FILE, GitUsageError, isSelectedTestFile, isTestFile, JSX_TEST_FILE, MISSING_FILE, PLAYWRIGHT_IMPORT, readSide, resolveCommit, stripComments, TEST_FILE, testMatchPathspecs, testMatchScopes, usesOtherRunnerSource } from "./test-source.js";
|
|
9
|
+
const MAX_TEST_FILES = 2000;
|
|
10
|
+
const MAX_HISTORY_COMMITS = 2000;
|
|
11
|
+
const MAX_HISTORY_READS = 6000;
|
|
12
|
+
const MAX_LISTED = 5000;
|
|
13
|
+
const MAX_TITLE_PARTS = 64;
|
|
14
|
+
const DAY = 24 * 60 * 60 * 1000;
|
|
15
|
+
const TEST_PATHSPECS = ["spec", "test"].flatMap((kind) => ["ts", "mts", "cts", "js", "mjs", "cjs"].map((ext) => `:(glob)**/*.${kind}.${ext}`));
|
|
16
|
+
class LedgerUsageError extends GitUsageError {
|
|
17
|
+
}
|
|
18
|
+
const SHA = /^[0-9a-f]{40,64}$/;
|
|
19
|
+
const TEXT_LIMIT = 2000;
|
|
20
|
+
const clip = (text) => { const plain = plainText(text); return plain.length > TEXT_LIMIT ? `${plain.slice(0, TEXT_LIMIT - 1)}…` : plain; };
|
|
21
|
+
/**
|
|
22
|
+
* `git log --format=%x1e%H --name-only -z`: each record is "\x1e<sha>\0" and then NUL-separated paths. The log carries
|
|
23
|
+
* no commit text, so a message cannot forge a record; a record whose commit is not a full hexadecimal id is counted as bad.
|
|
24
|
+
*/
|
|
25
|
+
function parseLog(output) {
|
|
26
|
+
const entries = [];
|
|
27
|
+
let bad = 0;
|
|
28
|
+
for (const record of output.split("\x1e")) {
|
|
29
|
+
if (!record.trim())
|
|
30
|
+
continue;
|
|
31
|
+
const [commit, ...files] = record.split("\0");
|
|
32
|
+
if (!SHA.test(commit ?? "")) {
|
|
33
|
+
bad++;
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
entries.push({ commit: commit, files: files.map((file) => file.replace(/^\n/, "")).filter(Boolean) });
|
|
37
|
+
}
|
|
38
|
+
return { entries, bad };
|
|
39
|
+
}
|
|
40
|
+
/** A bot author, or a co-author trailer with a bot or noreply address. */
|
|
41
|
+
const AUTOMATED = (author, body) => /\[bot\]/.test(author) || /^co-authored-by:.*(\[bot\]@|<noreply@)/im.test(body);
|
|
42
|
+
const FLAKY = /flak(y|e|ey|iness)\b/i;
|
|
43
|
+
const MAX_MERGED_MESSAGES = 50;
|
|
44
|
+
/**
|
|
45
|
+
* Reads one validated commit's facts. For a merge on the first-parent history, flakiness and automation are read from
|
|
46
|
+
* the merge's own message and those of the commits it merged (at most 50), whose messages say what the change did.
|
|
47
|
+
*/
|
|
48
|
+
async function readCommit(root, commit) {
|
|
49
|
+
const [date = "", parents = "", author = "", ...body] = (await git(root, ["show", "-s", "-z", "--format=%cI%x00%P%x00%an <%ae>%x00%B", commit])).split("\0");
|
|
50
|
+
const message = body.join("\n");
|
|
51
|
+
const [parent, ...others] = parents.split(" ").filter((id) => SHA.test(id));
|
|
52
|
+
let automated = AUTOMATED(author, message);
|
|
53
|
+
let saysFlaky = FLAKY.test(message);
|
|
54
|
+
if (others.length && parent) {
|
|
55
|
+
const merged = await git(root, ["log", `--max-count=${MAX_MERGED_MESSAGES}`, "--format=%x01%an <%ae>%n%B", commit, `^${parent}`, "--"]).catch(() => "");
|
|
56
|
+
for (const part of merged.split("\x01")) {
|
|
57
|
+
const [mergedAuthor = "", ...mergedBody] = part.split("\n");
|
|
58
|
+
automated ||= AUTOMATED(mergedAuthor, mergedBody.join("\n"));
|
|
59
|
+
saysFlaky ||= FLAKY.test(mergedBody.join("\n"));
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return {
|
|
63
|
+
commit, date: date.trim(), subject: plainText(message.split("\n", 1)[0] ?? "").trim().slice(0, 300), automated, saysFlaky,
|
|
64
|
+
...(parent ? { parent } : {}),
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
const titleKey = (title) => title.join("\u0000");
|
|
68
|
+
const EMPTY = { disabled: new Map(), present: new Map() };
|
|
69
|
+
function disabledMap(read) {
|
|
70
|
+
const disabled = new Map();
|
|
71
|
+
const present = new Map();
|
|
72
|
+
for (const test of read.tests) {
|
|
73
|
+
if (!test.ownModifiers)
|
|
74
|
+
continue; // a hook
|
|
75
|
+
const key = titleKey(test.title);
|
|
76
|
+
present.set(key, test.bodyHash);
|
|
77
|
+
const state = disabledState(test);
|
|
78
|
+
if (state)
|
|
79
|
+
disabled.set(key, state);
|
|
80
|
+
}
|
|
81
|
+
return { disabled, present };
|
|
82
|
+
}
|
|
83
|
+
/** Pairs tests that left and arrived in one commit with the same body, when each body hash is unique on both sides. */
|
|
84
|
+
function renamedTests(was, now) {
|
|
85
|
+
const gone = new Map();
|
|
86
|
+
const arrived = new Map();
|
|
87
|
+
for (const [key, hash] of was.present)
|
|
88
|
+
if (!now.present.has(key))
|
|
89
|
+
gone.set(hash, [...(gone.get(hash) ?? []), key]);
|
|
90
|
+
for (const [key, hash] of now.present)
|
|
91
|
+
if (!was.present.has(key))
|
|
92
|
+
arrived.set(hash, [...(arrived.get(hash) ?? []), key]);
|
|
93
|
+
const pairs = new Map();
|
|
94
|
+
for (const [hash, keys] of gone) {
|
|
95
|
+
const targets = arrived.get(hash);
|
|
96
|
+
if (keys.length === 1 && targets?.length === 1)
|
|
97
|
+
pairs.set(keys[0], targets[0]);
|
|
98
|
+
}
|
|
99
|
+
return pairs;
|
|
100
|
+
}
|
|
101
|
+
/** `git diff-tree -z --name-status --diff-filter=R` records: "R100\0old\0new\0", as new path to old path. */
|
|
102
|
+
function renamesIn(output) {
|
|
103
|
+
const fields = output.split("\0");
|
|
104
|
+
const renames = new Map();
|
|
105
|
+
for (let index = 0; index + 2 < fields.length; index += 3)
|
|
106
|
+
if (fields[index]?.startsWith("R"))
|
|
107
|
+
renames.set(fields[index + 2], fields[index + 1]);
|
|
108
|
+
return renames;
|
|
109
|
+
}
|
|
110
|
+
const E2E_DIR = /playwright|e2e/i;
|
|
111
|
+
/** A directory named for end-to-end tests: its name starts or ends with "e2e" or "playwright". */
|
|
112
|
+
const E2E_NAME = /^(e2e|playwright)|(e2e|playwright)$/i;
|
|
113
|
+
/** The shallowest directories below `base` whose name is E2E_NAME and that hold a test file. */
|
|
114
|
+
function e2eDirs(tree, base) {
|
|
115
|
+
const found = new Set();
|
|
116
|
+
for (const path of tree) {
|
|
117
|
+
if (!TEST_FILE.test(path) || !under(path, base) || path.split("/").includes("node_modules"))
|
|
118
|
+
continue;
|
|
119
|
+
const parts = path.split("/").slice(0, -1);
|
|
120
|
+
const start = base ? base.split("/").length : 0;
|
|
121
|
+
const index = parts.findIndex((part, position) => position >= start && E2E_NAME.test(part));
|
|
122
|
+
if (index >= 0)
|
|
123
|
+
found.add(parts.slice(0, index + 1).join("/"));
|
|
124
|
+
}
|
|
125
|
+
return [...found].filter((dir) => ![...found].some((other) => other !== dir && under(dir, other)));
|
|
126
|
+
}
|
|
127
|
+
const under = (path, dir) => dir === "" || path.startsWith(`${dir}/`);
|
|
128
|
+
/**
|
|
129
|
+
* The Playwright suites at head: for each playwright.config.*, its testDir when the configuration writes it as a
|
|
130
|
+
* plain string literal, else the configuration's own directory (Playwright's default). The configuration is read
|
|
131
|
+
* as text, never run.
|
|
132
|
+
*/
|
|
133
|
+
async function suiteDirs(root, head, tree, unreadable) {
|
|
134
|
+
const dirs = new Set();
|
|
135
|
+
for (const config of tree.filter((path) => CONFIG_FILE.test(path) && !path.split("/").includes("node_modules"))) {
|
|
136
|
+
const configDir = posix.dirname(config) === "." ? "" : posix.dirname(config);
|
|
137
|
+
// Comments are dropped so a commented-out testDir does not count. Strings holding "//" are rare in a configuration.
|
|
138
|
+
const source = stripComments(await git(root, ["cat-file", "blob", `${head}:${config}`]).catch(() => ""));
|
|
139
|
+
const all = [...source.matchAll(/\btestDir\s*:/g)].length;
|
|
140
|
+
const literals = [...source.matchAll(/\btestDir\s*:\s*(['"])([^'"`${}\\\n]*)\1/g)].map((match) => match[2]);
|
|
141
|
+
for (const literal of literals) {
|
|
142
|
+
const dir = posix.normalize(posix.join(configDir || ".", literal)).replace(/\/$/, "");
|
|
143
|
+
if (!dir.startsWith(".."))
|
|
144
|
+
dirs.add(dir === "." ? "" : dir);
|
|
145
|
+
}
|
|
146
|
+
if (all > literals.length || !all) {
|
|
147
|
+
// No testDir, or one that is not a literal: Playwright's default is the configuration's directory. When a
|
|
148
|
+
// testDir is computed, read only the directories below it named for end-to-end tests, if there are any, so a
|
|
149
|
+
// repository's unit tests are not read as Playwright tests.
|
|
150
|
+
const named = all > literals.length ? e2eDirs(tree, configDir) : [];
|
|
151
|
+
for (const dir of named.length ? named : [configDir])
|
|
152
|
+
dirs.add(dir);
|
|
153
|
+
if (all > literals.length)
|
|
154
|
+
unreadable.push({ path: clip(config), reason: `A testDir that is not a plain string literal; read ${named.length ? `the directories named for end-to-end tests below ${configDir || "the root"}` : `${configDir || "the root"}`} instead.` });
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return [...dirs].sort();
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* The directory of a test file's suite: the deepest suite directory that holds it, or else the file's first
|
|
161
|
+
* directory. Changes outside it, other than test files, configuration, Markdown and .github/, count as product changes.
|
|
162
|
+
*/
|
|
163
|
+
function suiteRoot(path, suites) {
|
|
164
|
+
const suite = suites.filter((dir) => dir && under(path, dir)).sort((a, b) => b.length - a.length)[0];
|
|
165
|
+
if (suite)
|
|
166
|
+
return suite;
|
|
167
|
+
// A path the suite has since moved from: up to its first directory named for end-to-end tests.
|
|
168
|
+
const parts = path.split("/").slice(0, -1);
|
|
169
|
+
const named = parts.findIndex((part) => E2E_DIR.test(part));
|
|
170
|
+
if (named >= 0)
|
|
171
|
+
return parts.slice(0, named + 1).join("/");
|
|
172
|
+
return parts[0] ?? "";
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Whether a test file outside today's suites is a Playwright test: it sits in a directory named for Playwright, a
|
|
176
|
+
* module specifier names Playwright ("@playwright/test", "./helpers/playwright"), or a callback takes Playwright's
|
|
177
|
+
* fixtures (`async ({ page }) =>`), as a test importing the project's own "./fixtures" does.
|
|
178
|
+
*/
|
|
179
|
+
/** Whether a file imports another test runner and no Playwright module. */
|
|
180
|
+
async function usesOtherRunner(root, commit, path) {
|
|
181
|
+
const source = await git(root, ["cat-file", "blob", `${commit}:${path}`]).catch(() => "");
|
|
182
|
+
return usesOtherRunnerSource(source);
|
|
183
|
+
}
|
|
184
|
+
async function looksLikePlaywright(root, commit, path) {
|
|
185
|
+
if (path.split("/").slice(0, -1).some((part) => /playwright/i.test(part)))
|
|
186
|
+
return true;
|
|
187
|
+
const source = await git(root, ["cat-file", "blob", `${commit}:${path}`]).catch(() => "");
|
|
188
|
+
return PLAYWRIGHT_IMPORT.test(source)
|
|
189
|
+
|| /\(\s*\{[^}()]*\b(?:page|context|browser)\b[^}()]*\}[^)]*\)\s*=>/.test(source);
|
|
190
|
+
}
|
|
191
|
+
const isProductFile = (file, root, isTest) => !(root && file.startsWith(`${root}/`)) && !isTest(file) && !JSX_TEST_FILE.test(file)
|
|
192
|
+
&& !CONFIG_FILE.test(file) && !/\.md$/i.test(file) && !file.startsWith(".github/");
|
|
193
|
+
export async function ledgerRepository(cwd, options = {}) {
|
|
194
|
+
let root;
|
|
195
|
+
try {
|
|
196
|
+
root = (await git(cwd, ["rev-parse", "--show-toplevel"])).trim();
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
throw new LedgerUsageError("ledger must run inside a git repository.");
|
|
200
|
+
}
|
|
201
|
+
const head = await resolveCommit(root, options.head ?? "HEAD", "--head");
|
|
202
|
+
const headDate = (await git(root, ["show", "-s", "--format=%cI", head])).trim();
|
|
203
|
+
const since = new Date(Date.parse(headDate) - (options.days ?? 365) * DAY).toISOString();
|
|
204
|
+
const scoped = (options.paths ?? []).map((path) => `:(top,literal)${posix.normalize(posix.join(posix.relative(root, cwd) || ".", path))}`);
|
|
205
|
+
const unreadable = [];
|
|
206
|
+
// The commits at a shallow clone's boundary: git shows them without their parents, as if they added every file.
|
|
207
|
+
let boundary = new Set();
|
|
208
|
+
if ((await git(root, ["rev-parse", "--is-shallow-repository"])).trim() === "true") {
|
|
209
|
+
const shallowFile = (await git(root, ["rev-parse", "--path-format=absolute", "--git-path", "shallow"])).trim();
|
|
210
|
+
boundary = new Set((await readFile(shallowFile, "utf8").catch(() => "")).split("\n").map((line) => line.trim()).filter(Boolean));
|
|
211
|
+
unreadable.push({ path: ".", reason: "History: this is a shallow clone, so commits before its oldest one are not known. Fetch the full history (git fetch --unshallow, or fetch-depth: 0 in CI)." });
|
|
212
|
+
}
|
|
213
|
+
const fullTree = (await git(root, ["ls-tree", "-r", "-z", "--name-only", head])).split("\0").filter(Boolean);
|
|
214
|
+
const suites = await suiteDirs(root, head, fullTree, unreadable);
|
|
215
|
+
// A testMatch that can be applied selects other names, or fewer files; one that cannot, and may select other names, is listed as unreadable.
|
|
216
|
+
const scopes = await testMatchScopes(root, head, fullTree);
|
|
217
|
+
for (const scope of scopes.filter((entry) => entry.kind === "unapplied" && !entry.defaultNames)) {
|
|
218
|
+
unreadable.push({ path: clip(scope.config), reason: "A testMatch the ledger does not apply: it reads only test files named with .spec. or .test., so tests named otherwise are not read." });
|
|
219
|
+
}
|
|
220
|
+
const isTest = (path) => isSelectedTestFile(path, scopes);
|
|
221
|
+
const pathspecs = [...TEST_PATHSPECS, ...testMatchPathspecs(scopes)];
|
|
222
|
+
const tree = scoped.length ? (await git(root, ["ls-tree", "-r", "-z", "--name-only", head, "--", ...scoped])).split("\0").filter(Boolean) : fullTree;
|
|
223
|
+
// Without paths, only test files inside a Playwright suite are read, when the repository has a playwright.config.*.
|
|
224
|
+
const inScope = (path) => isTest(path) && !path.split("/").includes("node_modules") && (scoped.length > 0 || !suites.length || suites.some((dir) => under(path, dir)));
|
|
225
|
+
// Without paths, a file that imports another test runner and no Playwright module is left out, as audit lists it apart:
|
|
226
|
+
// unit tests inside a suite's directory, or under a testDir every project overrides (API specs run by another
|
|
227
|
+
// runner). Paths given are read whatever they hold.
|
|
228
|
+
const testFiles = [];
|
|
229
|
+
for (const path of tree.filter(inScope)) {
|
|
230
|
+
if (scoped.length || testFiles.length > MAX_TEST_FILES || !(await usesOtherRunner(root, head, path)))
|
|
231
|
+
testFiles.push(path);
|
|
232
|
+
}
|
|
233
|
+
// History also reads paths a suite has moved from: a test file under a directory named for end-to-end tests.
|
|
234
|
+
// A testMatch narrows only today's files: history keeps every test name, as files are renamed (a .test.js that became
|
|
235
|
+
// .test.ts), and a re-enable outside today's suites must still look like Playwright.
|
|
236
|
+
const isNamedTest = (path) => isTestFile(path, scopes);
|
|
237
|
+
const inHistoryScope = (path) => inScope(path) || (!path.split("/").includes("node_modules") && isNamedTest(path)
|
|
238
|
+
&& (scoped.length > 0 || !suites.length || suites.some((dir) => under(path, dir)) || path.split("/").slice(0, -1).some((part) => E2E_DIR.test(part))));
|
|
239
|
+
// Turned off at head.
|
|
240
|
+
const atHead = [];
|
|
241
|
+
let tests = 0;
|
|
242
|
+
let conditional = 0;
|
|
243
|
+
for (const path of testFiles.slice(0, MAX_TEST_FILES)) {
|
|
244
|
+
const read = await readSide(root, head, path);
|
|
245
|
+
if (typeof read === "string") {
|
|
246
|
+
unreadable.push({ path: clip(path), reason: read });
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
for (const line of read.unreadableTests)
|
|
250
|
+
unreadable.push({ path: clip(path), reason: `line ${line}: a test or describe title that is not a literal string` });
|
|
251
|
+
for (const test of read.tests) {
|
|
252
|
+
if (!test.ownModifiers)
|
|
253
|
+
continue;
|
|
254
|
+
tests++;
|
|
255
|
+
if (conditionallySkipped(test))
|
|
256
|
+
conditional++;
|
|
257
|
+
const state = disabledState(test);
|
|
258
|
+
if (!state)
|
|
259
|
+
continue;
|
|
260
|
+
if (test.title.length > MAX_TITLE_PARTS) {
|
|
261
|
+
unreadable.push({ path: clip(path), reason: `line ${test.line}: nested more than ${MAX_TITLE_PARTS} levels deep` });
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
atHead.push({ path, line: test.line, title: test.title, state });
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
if (testFiles.length > MAX_TEST_FILES)
|
|
268
|
+
unreadable.push({ path: ".", reason: `Not read: ${testFiles.length - MAX_TEST_FILES} test files past the first ${MAX_TEST_FILES}.` });
|
|
269
|
+
// History: first-parent commits that change a skip, fixme or fail line in a test file.
|
|
270
|
+
const log = await git(root, [
|
|
271
|
+
"log", "--first-parent", "--diff-merges=first-parent", "--no-renames", "--no-ext-diff", "--no-textconv",
|
|
272
|
+
`--max-count=${MAX_HISTORY_COMMITS + 1}`, "-G", String.raw `\.(skip|fixme|fail)([^A-Za-z0-9_$]|$)`, // ERE without \b, which macOS's regex library lacks
|
|
273
|
+
"--format=%x1e%H", "--name-only", "-z", head, "--", ...(scoped.length ? scoped : pathspecs),
|
|
274
|
+
]).catch(() => { throw new LedgerUsageError("git could not read the history. In a shallow clone, fetch the full history first (git fetch --unshallow, or fetch-depth: 0 in CI)."); });
|
|
275
|
+
const parsed = parseLog(log);
|
|
276
|
+
if (parsed.bad)
|
|
277
|
+
unreadable.push({ path: ".", reason: `History: ${parsed.bad} log record${parsed.bad === 1 ? "" : "s"} could not be read.` });
|
|
278
|
+
// Newest first: past a limit, the oldest commits are the ones dropped, so recent turn-offs stay known.
|
|
279
|
+
const history = [];
|
|
280
|
+
let reads = 0;
|
|
281
|
+
for (const entry of parsed.entries) {
|
|
282
|
+
const files = entry.files.filter(inHistoryScope);
|
|
283
|
+
if (!files.length)
|
|
284
|
+
continue;
|
|
285
|
+
if (history.length >= MAX_HISTORY_COMMITS || reads + files.length * 2 > MAX_HISTORY_READS) {
|
|
286
|
+
unreadable.push({ path: ".", reason: `History: read back to ${history.at(-1)?.commit.slice(0, 12) ?? "the head"} only (at most ${MAX_HISTORY_COMMITS} commits and ${MAX_HISTORY_READS} file reads); older turning-off commits are not known.` });
|
|
287
|
+
break;
|
|
288
|
+
}
|
|
289
|
+
reads += files.length * 2;
|
|
290
|
+
history.push({ commit: entry.commit, files });
|
|
291
|
+
}
|
|
292
|
+
history.reverse();
|
|
293
|
+
const lastOff = new Map();
|
|
294
|
+
const reenabled = [];
|
|
295
|
+
for (const { commit: id, files } of history) {
|
|
296
|
+
// A boundary commit's diff is unknown: the tests it seems to add were there before it, so they get no turning-off commit.
|
|
297
|
+
if (boundary.has(id))
|
|
298
|
+
continue;
|
|
299
|
+
const { parent, ...info } = await readCommit(root, id);
|
|
300
|
+
const raw = { ...info, commit: id };
|
|
301
|
+
let productFiles;
|
|
302
|
+
let renames;
|
|
303
|
+
for (const path of files) {
|
|
304
|
+
reads += 2;
|
|
305
|
+
let before = parent ? await readSide(root, parent, path) : MISSING_FILE;
|
|
306
|
+
const after = await readSide(root, raw.commit, path);
|
|
307
|
+
// A deleted file, or a side that cannot be read, gives no transitions: nothing is guessed.
|
|
308
|
+
if (typeof after === "string" || (typeof before === "string" && before !== MISSING_FILE))
|
|
309
|
+
continue;
|
|
310
|
+
if (before === MISSING_FILE && parent) {
|
|
311
|
+
// A moved file keeps its tests' history: compare with the old path and carry its open turn-offs over.
|
|
312
|
+
renames ??= renamesIn(await git(root, ["diff-tree", "-r", "-z", "-M", "--name-status", "--diff-filter=R", "--no-commit-id", parent, raw.commit]));
|
|
313
|
+
const from = renames.get(path);
|
|
314
|
+
if (from) {
|
|
315
|
+
before = await readSide(root, parent, from);
|
|
316
|
+
if (typeof before === "string")
|
|
317
|
+
continue;
|
|
318
|
+
for (const [key, value] of [...lastOff]) {
|
|
319
|
+
if (!key.startsWith(`${from}\u0001`))
|
|
320
|
+
continue;
|
|
321
|
+
lastOff.delete(key);
|
|
322
|
+
lastOff.set(`${path}${key.slice(from.length)}`, value);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
const was = typeof before === "string" ? EMPTY : disabledMap(before);
|
|
327
|
+
const now = disabledMap(after);
|
|
328
|
+
// A renamed test (its title or a describe title changed) keeps its history when its body is token-for-token identical.
|
|
329
|
+
const renamedTo = renamedTests(was, now);
|
|
330
|
+
for (const [from, to] of renamedTo) {
|
|
331
|
+
const off = lastOff.get(`${path}\u0001${from}`);
|
|
332
|
+
if (!off)
|
|
333
|
+
continue;
|
|
334
|
+
lastOff.delete(`${path}\u0001${from}`);
|
|
335
|
+
lastOff.set(`${path}\u0001${to}`, off);
|
|
336
|
+
}
|
|
337
|
+
const renamedFrom = new Map([...renamedTo].map(([from, to]) => [to, from]));
|
|
338
|
+
for (const [key, state] of now.disabled) {
|
|
339
|
+
const previous = was.present.has(key) ? key : renamedFrom.get(key);
|
|
340
|
+
if (previous !== undefined && was.disabled.has(previous))
|
|
341
|
+
continue;
|
|
342
|
+
// A test that first appears here already off (a new file or test, or a rename with a changed body) was added
|
|
343
|
+
// by this commit, which need not be the one that turned it off.
|
|
344
|
+
lastOff.set(`${path}\u0001${key}`, { commit: raw, how: state.how, appeared: previous === undefined });
|
|
345
|
+
}
|
|
346
|
+
for (const old of was.disabled.keys()) {
|
|
347
|
+
const key = now.present.has(old) ? old : renamedTo.get(old);
|
|
348
|
+
if (key === undefined || now.disabled.has(key))
|
|
349
|
+
continue;
|
|
350
|
+
const off = lastOff.get(`${path}\u0001${key}`);
|
|
351
|
+
lastOff.delete(`${path}\u0001${key}`);
|
|
352
|
+
if (!off || Date.parse(raw.date) < Date.parse(since))
|
|
353
|
+
continue;
|
|
354
|
+
const title = key.split("\u0000");
|
|
355
|
+
if (title.length > MAX_TITLE_PARTS)
|
|
356
|
+
continue;
|
|
357
|
+
// A path outside today's suites entered history only by its directory name: list it only when it looks like a
|
|
358
|
+
// Playwright test, so other end-to-end tests (an API suite in an "e2e-api" folder) are left out.
|
|
359
|
+
if (!inScope(path) && !(await looksLikePlaywright(root, raw.commit, path)))
|
|
360
|
+
continue;
|
|
361
|
+
if (!scoped.length && await usesOtherRunner(root, raw.commit, path))
|
|
362
|
+
continue;
|
|
363
|
+
if (productFiles === undefined) {
|
|
364
|
+
const changed = (await git(root, ["diff-tree", "--no-commit-id", "-r", "-z", "--name-only", "--no-renames", ...(parent ? [parent] : ["--root"]), raw.commit])).split("\0").filter(Boolean);
|
|
365
|
+
productFiles = changed.filter((file) => isProductFile(file, suiteRoot(path, suites), isNamedTest)).length;
|
|
366
|
+
}
|
|
367
|
+
reenabled.push({
|
|
368
|
+
path: clip(path), title: title.map(clip), how: off.how, disabled: off.commit, ...(off.appeared ? { disabledAppeared: true } : {}), enabled: raw,
|
|
369
|
+
days: Math.max(0, Math.floor((Date.parse(raw.date) - Date.parse(off.commit.date)) / DAY)), productFiles,
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
const disabled = atHead.map(({ path, line, title, state }) => {
|
|
375
|
+
const off = lastOff.get(`${path}\u0001${titleKey(title)}`);
|
|
376
|
+
return {
|
|
377
|
+
path: clip(path), line, title: title.map(clip), how: state.how, scope: state.scope,
|
|
378
|
+
...(off ? { since: off.commit, ageDays: Math.max(0, Math.floor((Date.parse(headDate) - Date.parse(off.commit.date)) / DAY)), ...(off.appeared ? { appearedOff: true } : {}) } : {}),
|
|
379
|
+
};
|
|
380
|
+
}).sort((a, b) => (b.ageDays ?? Infinity) - (a.ageDays ?? Infinity) || a.path.localeCompare(b.path) || a.line - b.line);
|
|
381
|
+
reenabled.sort((a, b) => a.enabled.date.localeCompare(b.enabled.date));
|
|
382
|
+
const report = {
|
|
383
|
+
schemaVersion: 1,
|
|
384
|
+
head,
|
|
385
|
+
since,
|
|
386
|
+
suites: scoped.length ? [] : suites.map(plainText).slice(0, 200),
|
|
387
|
+
disabled: disabled.slice(0, MAX_LISTED),
|
|
388
|
+
reenabled: reenabled.slice(0, MAX_LISTED),
|
|
389
|
+
unreadable: unreadable.slice(0, MAX_LISTED),
|
|
390
|
+
totals: {
|
|
391
|
+
testFiles: testFiles.length,
|
|
392
|
+
tests,
|
|
393
|
+
disabled: disabled.length,
|
|
394
|
+
conditional,
|
|
395
|
+
// A commit that only added a test already off may not be the one that turned it off, so it says nothing about why.
|
|
396
|
+
disabledSaysFlaky: disabled.filter((test) => test.since?.saysFlaky && !test.appearedOff).length,
|
|
397
|
+
disabledAutomated: disabled.filter((test) => test.since?.automated && !test.appearedOff).length,
|
|
398
|
+
disabledSinceUnknown: disabled.filter((test) => !test.since).length,
|
|
399
|
+
disabledAppearedOff: disabled.filter((test) => test.appearedOff).length,
|
|
400
|
+
reenabled: reenabled.length,
|
|
401
|
+
reenabledWithProduct: reenabled.filter((test) => test.productFiles > 0).length,
|
|
402
|
+
unreadable: unreadable.length,
|
|
403
|
+
},
|
|
404
|
+
};
|
|
405
|
+
return ledgerReportSchema.parse(report);
|
|
406
|
+
}
|
|
407
|
+
const quoteTitle = (title) => title.map((part) => JSON.stringify(part)).join(" > ");
|
|
408
|
+
const commitText = (commit) => `${commit.commit.slice(0, 12)} ${commit.date.slice(0, 10)} ${JSON.stringify(commit.subject)}${commit.saysFlaky ? " [says flaky]" : ""}${commit.automated ? " [bot or agent]" : ""}`;
|
|
409
|
+
const HOW = { skip: "skipped", fixme: "fixme", fail: "expected to fail" };
|
|
410
|
+
function commonPrefix(titles) {
|
|
411
|
+
const first = titles[0];
|
|
412
|
+
let length = first.length;
|
|
413
|
+
for (const title of titles) {
|
|
414
|
+
let index = 0;
|
|
415
|
+
while (index < length && index < title.length && title[index] === first[index])
|
|
416
|
+
index++;
|
|
417
|
+
length = index;
|
|
418
|
+
}
|
|
419
|
+
return first.slice(0, length);
|
|
420
|
+
}
|
|
421
|
+
/** Entries that one commit turned off (or on) together in one file, such as every test of a skipped group, print as one. */
|
|
422
|
+
function grouped(entries, key) {
|
|
423
|
+
const groups = new Map();
|
|
424
|
+
for (const entry of entries) {
|
|
425
|
+
const id = key(entry);
|
|
426
|
+
groups.set(id, [...(groups.get(id) ?? []), entry]);
|
|
427
|
+
}
|
|
428
|
+
return [...groups.values()];
|
|
429
|
+
}
|
|
430
|
+
const testsLabel = (titles) => {
|
|
431
|
+
if (titles.length === 1)
|
|
432
|
+
return quoteTitle(titles[0]);
|
|
433
|
+
const prefix = commonPrefix(titles);
|
|
434
|
+
return `${titles.length} tests${prefix.length ? ` in ${quoteTitle(prefix)}` : ""}`;
|
|
435
|
+
};
|
|
436
|
+
const plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
|
|
437
|
+
/** The text report: turned-off tests oldest first, then tests turned back on inside the window. */
|
|
438
|
+
export function formatLedger(report) {
|
|
439
|
+
const { totals } = report;
|
|
440
|
+
const lines = [`Turned-off Playwright tests at ${report.head.slice(0, 12)}: ${totals.disabled} of ${totals.tests} tests in ${plural(totals.testFiles, "test file")}${report.suites.length ? ` under ${report.suites.map((dir) => `${dir || "."}/`).join(", ")}` : ""}.`];
|
|
441
|
+
lines.push(` 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)` : ""}. ${totals.conditional} more ${totals.conditional === 1 ? "test is" : "tests are"} skipped only under a condition.`, "");
|
|
442
|
+
if (report.disabled.length) {
|
|
443
|
+
lines.push(`Turned off (${totals.disabled}), oldest first`);
|
|
444
|
+
for (const group of grouped(report.disabled, (test) => [test.path, test.how, test.scope, test.since?.commit ?? "", test.scope === "test" ? test.line : ""].join("\u0001"))) {
|
|
445
|
+
const test = group[0];
|
|
446
|
+
lines.push(` ${test.path}:${test.line} ${testsLabel(group.map((entry) => entry.title))}`);
|
|
447
|
+
const age = test.ageDays === undefined ? "since an unknown commit" : plural(test.ageDays, "day");
|
|
448
|
+
lines.push(` ${HOW[test.how]}${test.scope === "group" ? " (by its group)" : ""} · ${age}${test.since ? ` · ${commitText(test.since)}${test.appearedOff ? " (added already off; an earlier commit may have turned it off)" : ""}` : ""}`);
|
|
449
|
+
}
|
|
450
|
+
lines.push("");
|
|
451
|
+
}
|
|
452
|
+
if (report.reenabled.length) {
|
|
453
|
+
const events = grouped(report.reenabled, (test) => [test.path, test.how, test.disabled.commit, test.enabled.commit].join("\u0001"));
|
|
454
|
+
const withProduct = events.filter((group) => group[0].productFiles > 0).length;
|
|
455
|
+
lines.push(`Turned off and back on since ${report.since.slice(0, 10)}: ${plural(totals.reenabled, "test")} in ${plural(events.length, "event")}; in ${withProduct} the commit that turned them back on also changed product files`);
|
|
456
|
+
for (const group of events) {
|
|
457
|
+
const test = group[0];
|
|
458
|
+
lines.push(` ${test.path} ${testsLabel(group.map((entry) => entry.title))}: ${HOW[test.how]} for ${test.disabledAppeared ? "at least " : ""}${plural(test.days, "day")}`);
|
|
459
|
+
lines.push(` off · ${commitText(test.disabled)}${test.disabledAppeared ? " (added already off; an earlier commit may have turned it off)" : ""}`);
|
|
460
|
+
lines.push(` on · ${commitText(test.enabled)}${test.productFiles ? ` · changed ${plural(test.productFiles, "product file")}` : ""}`);
|
|
461
|
+
}
|
|
462
|
+
lines.push("");
|
|
463
|
+
}
|
|
464
|
+
if (report.unreadable.length) {
|
|
465
|
+
lines.push(`Not read (${totals.unreadable})`);
|
|
466
|
+
for (const entry of report.unreadable.slice(0, 50))
|
|
467
|
+
lines.push(` ${entry.path}: ${entry.reason}`);
|
|
468
|
+
if (report.unreadable.length > 50)
|
|
469
|
+
lines.push(` … ${report.unreadable.length - 50} more in --json.`);
|
|
470
|
+
lines.push("");
|
|
471
|
+
}
|
|
472
|
+
lines.push("This reads test source and first-parent history from git only: it ran nothing and cannot say whether a turned-off test hides a bug. A re-enable that changed product files is a fact about that commit, not proof that the skip hid a fault. Titles and commit messages are quoted from the repository and are untrusted.");
|
|
473
|
+
return lines;
|
|
474
|
+
}
|
|
475
|
+
/** Exit codes: 0 report printed; 2 usage error. */
|
|
476
|
+
export async function ledgerCommand(args) {
|
|
477
|
+
let parsed;
|
|
478
|
+
try {
|
|
479
|
+
parsed = parseArgs({ args, allowPositionals: true, options: { head: { type: "string" }, days: { type: "string" }, json: { type: "boolean" }, summary: { type: "string" } } });
|
|
480
|
+
}
|
|
481
|
+
catch (error) {
|
|
482
|
+
console.error(String(error.message));
|
|
483
|
+
return 2;
|
|
484
|
+
}
|
|
485
|
+
const { values, positionals } = parsed;
|
|
486
|
+
const days = values.days === undefined ? 365 : Number(values.days);
|
|
487
|
+
if (!Number.isInteger(days) || days < 1 || days > 3650) {
|
|
488
|
+
console.error("--days is a whole number of days from 1 to 3650.");
|
|
489
|
+
return 2;
|
|
490
|
+
}
|
|
491
|
+
let report;
|
|
492
|
+
try {
|
|
493
|
+
report = await ledgerRepository(process.cwd(), { ...(values.head ? { head: values.head } : {}), days, paths: positionals });
|
|
494
|
+
}
|
|
495
|
+
catch (error) {
|
|
496
|
+
if (error instanceof GitUsageError) {
|
|
497
|
+
console.error(error.message);
|
|
498
|
+
return 2;
|
|
499
|
+
}
|
|
500
|
+
throw error;
|
|
501
|
+
}
|
|
502
|
+
if (values.json)
|
|
503
|
+
console.log(JSON.stringify({ untrusted: "repository-provided text", report }));
|
|
504
|
+
else
|
|
505
|
+
console.log(formatLedger(report).join("\n"));
|
|
506
|
+
if (values.summary)
|
|
507
|
+
await writeSummary(values.summary, ledgerSummary(report));
|
|
508
|
+
return 0;
|
|
509
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { createServer } from "node:http";
|
|
2
|
+
import { access, readFile } from "node:fs/promises";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { listenLocalApi, studioPort } from "#agentpath/server";
|
|
5
|
+
import { taskSchema } from "#agentpath/contracts";
|
|
6
|
+
const root = new URL("../../../", import.meta.url);
|
|
7
|
+
const studio = new URL("apps/studio/dist/", root);
|
|
8
|
+
export const demoPort = 4173;
|
|
9
|
+
export async function sample(name, baseUrl) {
|
|
10
|
+
const task = JSON.parse(await readFile(new URL(`examples/tasks/${name}.json`, root), "utf8"));
|
|
11
|
+
return taskSchema.parse({ ...task, baseUrl, allowedHosts: [new URL(baseUrl).host] });
|
|
12
|
+
}
|
|
13
|
+
export function portOption(value, fallback) {
|
|
14
|
+
if (value === undefined)
|
|
15
|
+
return fallback;
|
|
16
|
+
const port = Number(value);
|
|
17
|
+
if (!/^\d+$/.test(value) || !Number.isInteger(port) || port < 0 || port > 65535) {
|
|
18
|
+
throw new Error("Use a port from 1 to 65535, or 0 to choose a free port automatically.");
|
|
19
|
+
}
|
|
20
|
+
return port;
|
|
21
|
+
}
|
|
22
|
+
export function errorCode(error) {
|
|
23
|
+
return error?.code;
|
|
24
|
+
}
|
|
25
|
+
export async function listenLoopback(server, port) {
|
|
26
|
+
await new Promise((resolve, reject) => {
|
|
27
|
+
function unavailable(error) {
|
|
28
|
+
server.off("listening", ready);
|
|
29
|
+
reject(error);
|
|
30
|
+
}
|
|
31
|
+
function ready() {
|
|
32
|
+
server.off("error", unavailable);
|
|
33
|
+
resolve();
|
|
34
|
+
}
|
|
35
|
+
server.once("error", unavailable);
|
|
36
|
+
server.listen(port, "127.0.0.1", ready);
|
|
37
|
+
});
|
|
38
|
+
const address = server.address();
|
|
39
|
+
if (!address || typeof address === "string")
|
|
40
|
+
throw new Error("Loopback listener did not report a TCP address.");
|
|
41
|
+
return `http://127.0.0.1:${address.port}`;
|
|
42
|
+
}
|
|
43
|
+
export function closeLoopback(server) {
|
|
44
|
+
return new Promise((resolve) => {
|
|
45
|
+
server.close(() => resolve());
|
|
46
|
+
server.closeAllConnections();
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
export async function startStudio(workspace, port = studioPort) {
|
|
50
|
+
await access(new URL("index.html", studio)).catch(() => {
|
|
51
|
+
throw Object.assign(new Error("Studio assets are missing. Reinstall the tarball, or run pnpm build in a source checkout."), { code: "STUDIO_ASSETS_MISSING" });
|
|
52
|
+
});
|
|
53
|
+
return listenLocalApi({ workspace, port, studioDirectory: fileURLToPath(studio) });
|
|
54
|
+
}
|
|
55
|
+
export async function withShutdown(work, closeOnInputEnd = false) {
|
|
56
|
+
const controller = new AbortController();
|
|
57
|
+
const stop = () => controller.abort();
|
|
58
|
+
process.on("SIGINT", stop);
|
|
59
|
+
process.on("SIGTERM", stop);
|
|
60
|
+
if (closeOnInputEnd) {
|
|
61
|
+
process.stdin.once("end", stop);
|
|
62
|
+
process.stdin.resume();
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
await work(controller.signal);
|
|
66
|
+
}
|
|
67
|
+
finally {
|
|
68
|
+
process.off("SIGINT", stop);
|
|
69
|
+
process.off("SIGTERM", stop);
|
|
70
|
+
if (closeOnInputEnd) {
|
|
71
|
+
process.stdin.off("end", stop);
|
|
72
|
+
process.stdin.pause();
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return 0;
|
|
76
|
+
}
|
|
77
|
+
export async function waitForShutdown(signal) {
|
|
78
|
+
if (!signal.aborted) {
|
|
79
|
+
await new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true }));
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
export async function checkPort(port) {
|
|
83
|
+
const probe = createServer();
|
|
84
|
+
await listenLoopback(probe, port);
|
|
85
|
+
await closeLoopback(probe);
|
|
86
|
+
}
|
|
87
|
+
export function startupError(error, portFlag = "--port") {
|
|
88
|
+
switch (errorCode(error)) {
|
|
89
|
+
case "STUDIO_ASSETS_MISSING": return error;
|
|
90
|
+
case "EADDRINUSE": return new Error(`The loopback port is already in use. Choose another port with ${portFlag} or use 0 to select a free port.`);
|
|
91
|
+
case "EACCES":
|
|
92
|
+
case "EPERM":
|
|
93
|
+
case "EROFS": return new Error("Permission denied while opening the workspace or listener. Choose a writable workspace and an unprivileged port.");
|
|
94
|
+
case "ENOTDIR":
|
|
95
|
+
case "EEXIST": return new Error("A workspace directory is blocked by an existing file. Choose a different --workspace directory.");
|
|
96
|
+
default: {
|
|
97
|
+
// Name the error code, never the raw message, which can carry local paths.
|
|
98
|
+
const code = errorCode(error);
|
|
99
|
+
return new Error(`Studio could not start${code && /^[A-Z_]{2,32}$/.test(code) ? ` (${code})` : ""}. Run agentpath doctor to check the installation and workspace.`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|