traceyard 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +217 -2
- package/lib/cli/bin/traceyard.mjs +4 -0
- package/lib/cli/package.json +5 -0
- package/lib/cli/src/compact.mjs +73 -0
- package/lib/cli/src/errors.mjs +9 -0
- package/lib/cli/src/git.mjs +81 -0
- package/lib/cli/src/github.mjs +137 -0
- package/lib/cli/src/main.mjs +780 -0
- package/lib/cli/src/mcp.mjs +304 -0
- package/lib/cli/src/receipt.mjs +143 -0
- package/lib/cli/src/run.mjs +457 -0
- package/lib/cli/src/verdicts.mjs +189 -0
- package/lib/cli/src/version.mjs +5 -0
- package/lib/core/src/agent-result.mjs +128 -0
- package/lib/core/src/ci-link.mjs +87 -0
- package/lib/core/src/discovery.mjs +105 -0
- package/lib/core/src/failure-summary.mjs +39 -0
- package/lib/core/src/index.mjs +70 -0
- package/lib/core/src/package-manager.mjs +97 -0
- package/lib/core/src/pytest-runner.py +68 -0
- package/lib/core/src/pytest.mjs +118 -0
- package/lib/core/src/repository-index.mjs +310 -0
- package/lib/core/src/runners.mjs +103 -0
- package/lib/core/src/source-flow.mjs +135 -0
- package/lib/core/src/test-evidence.mjs +311 -0
- package/lib/core/src/test-report.mjs +64 -0
- package/lib/core/src/worktree.mjs +95 -0
- package/package.json +45 -4
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// The response envelope every Traceyard MCP tool returns, hosted or local.
|
|
2
|
+
// One implementation, so both servers bound output the same way.
|
|
3
|
+
//
|
|
4
|
+
// `limit` is a budget in bytes of UTF-16 (two per character) plus a fixed
|
|
5
|
+
// overhead, matching the hosted `outputChars` argument. Fields are dropped in a
|
|
6
|
+
// fixed order until the packet fits, and `omitted` says whether anything was.
|
|
7
|
+
|
|
8
|
+
const OPTIONAL_ARRAYS = [
|
|
9
|
+
"items",
|
|
10
|
+
"evidence",
|
|
11
|
+
"attempts",
|
|
12
|
+
"recordings",
|
|
13
|
+
"verifications",
|
|
14
|
+
"limitations",
|
|
15
|
+
];
|
|
16
|
+
const DROPPABLE = [
|
|
17
|
+
"recordings",
|
|
18
|
+
"verifications",
|
|
19
|
+
"snapshot",
|
|
20
|
+
"limitations",
|
|
21
|
+
"attempts",
|
|
22
|
+
"evidence",
|
|
23
|
+
"items",
|
|
24
|
+
"nextAction",
|
|
25
|
+
"browserUrl",
|
|
26
|
+
];
|
|
27
|
+
|
|
28
|
+
function compactVerification(packet, size, limit) {
|
|
29
|
+
const v = packet.verification;
|
|
30
|
+
packet.verification = {
|
|
31
|
+
id: v.id,
|
|
32
|
+
baselineId: v.baselineId,
|
|
33
|
+
candidateId: v.candidateId,
|
|
34
|
+
verdict: v.verdict,
|
|
35
|
+
label: v.label,
|
|
36
|
+
evidence: [v.baselineRun, v.candidateRun].map((run) => {
|
|
37
|
+
if (!run || typeof run !== "object") return null;
|
|
38
|
+
const { commit, evidenceId, status } = run;
|
|
39
|
+
return { commit, evidenceId, status };
|
|
40
|
+
}),
|
|
41
|
+
changedTestsCount: Array.isArray(v.changedTests) ? v.changedTests.length : 0,
|
|
42
|
+
changedTests: Array.isArray(v.changedTests) ? v.changedTests.slice(0, 5) : [],
|
|
43
|
+
metrics: v.metrics,
|
|
44
|
+
};
|
|
45
|
+
if (Array.isArray(v.changedTests) && v.changedTests.length > 5) packet.omitted = true;
|
|
46
|
+
const compact = packet.verification;
|
|
47
|
+
while (size() > limit && compact.changedTests.length) {
|
|
48
|
+
compact.changedTests.pop();
|
|
49
|
+
packet.omitted = true;
|
|
50
|
+
}
|
|
51
|
+
if (size() > limit) {
|
|
52
|
+
delete compact.metrics;
|
|
53
|
+
packet.omitted = true;
|
|
54
|
+
}
|
|
55
|
+
if (size() > limit) {
|
|
56
|
+
compact.evidence = compact.evidence.map((item) => item?.evidenceId ?? null);
|
|
57
|
+
packet.omitted = true;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Local runs: shorten failure messages, then drop logs, then keep only the
|
|
63
|
+
* first failure. The evidence ID stays, so nothing is lost for good.
|
|
64
|
+
*/
|
|
65
|
+
function compactRuns(packet, size, limit) {
|
|
66
|
+
const runs = packet.runs;
|
|
67
|
+
for (const length of [300, 120]) {
|
|
68
|
+
if (size() <= limit) return;
|
|
69
|
+
for (const run of runs)
|
|
70
|
+
for (const failure of run.failures ?? [])
|
|
71
|
+
if (failure.message?.length > length) {
|
|
72
|
+
failure.message = failure.message.slice(0, length);
|
|
73
|
+
run.truncated = true;
|
|
74
|
+
packet.omitted = true;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
for (const run of runs)
|
|
78
|
+
if (size() > limit && "output" in run) {
|
|
79
|
+
delete run.output;
|
|
80
|
+
packet.omitted = true;
|
|
81
|
+
}
|
|
82
|
+
for (const run of runs)
|
|
83
|
+
while (size() > limit && run.failures?.length > 1) {
|
|
84
|
+
run.failures.pop();
|
|
85
|
+
run.truncated = true;
|
|
86
|
+
packet.omitted = true;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function agentResult(value, limit = 4000) {
|
|
91
|
+
const packet = { schemaVersion: 1, ...JSON.parse(JSON.stringify(value)), omitted: false };
|
|
92
|
+
const size = () => JSON.stringify(packet).length * 2 + 200;
|
|
93
|
+
if (packet.verification && typeof packet.verification === "object")
|
|
94
|
+
compactVerification(packet, size, limit);
|
|
95
|
+
if (Array.isArray(packet.runs)) compactRuns(packet, size, limit);
|
|
96
|
+
if (packet.explanation?.source && size() > limit) {
|
|
97
|
+
packet.explanation.source = null;
|
|
98
|
+
packet.omitted = true;
|
|
99
|
+
}
|
|
100
|
+
for (const key of OPTIONAL_ARRAYS) {
|
|
101
|
+
const array = packet[key];
|
|
102
|
+
if (Array.isArray(array))
|
|
103
|
+
while (array.length > 1 && size() > limit) {
|
|
104
|
+
array.pop();
|
|
105
|
+
packet.omitted = true;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
for (const key of DROPPABLE) {
|
|
109
|
+
if (size() <= limit) break;
|
|
110
|
+
if (key in packet) {
|
|
111
|
+
delete packet[key];
|
|
112
|
+
packet.omitted = true;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
while (size() > limit && typeof packet.summary === "string" && packet.summary.length > 20) {
|
|
116
|
+
packet.summary = packet.summary.slice(
|
|
117
|
+
0,
|
|
118
|
+
Math.max(20, Math.floor(packet.summary.length * 0.75)),
|
|
119
|
+
);
|
|
120
|
+
packet.omitted = true;
|
|
121
|
+
}
|
|
122
|
+
if (packet.omitted && typeof packet.offset === "number" && typeof packet.summary === "string")
|
|
123
|
+
packet.nextOffset = packet.offset + packet.summary.length;
|
|
124
|
+
return {
|
|
125
|
+
content: [{ type: "text", text: JSON.stringify(packet) }],
|
|
126
|
+
structuredContent: packet,
|
|
127
|
+
};
|
|
128
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// Pure helpers for GitHub Actions links and job logs. Shared by the hosted
|
|
2
|
+
// service (worker/services/ci-revision.ts) and the local `traceyard` CLI.
|
|
3
|
+
|
|
4
|
+
const shaPattern = /^[a-f0-9]{40}$/i;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Parse a GitHub Actions run, attempt or job link. Returns null for anything
|
|
8
|
+
* else, including links with credentials or a non-GitHub origin.
|
|
9
|
+
*/
|
|
10
|
+
export function parseActionsUrl(value) {
|
|
11
|
+
let url;
|
|
12
|
+
try {
|
|
13
|
+
url = new URL(value);
|
|
14
|
+
} catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
const match = url.pathname.match(
|
|
18
|
+
/^\/([\w.-]+\/[\w.-]+)\/actions\/runs\/([1-9]\d{0,17})(?:\/attempts\/([1-9]\d{0,17}))?(?:\/job\/([1-9]\d{0,17}))?\/?$/,
|
|
19
|
+
);
|
|
20
|
+
if (url.origin !== "https://github.com" || url.username || url.password || !match?.[1])
|
|
21
|
+
return null;
|
|
22
|
+
return { repository: match[1], runId: match[2], attempt: match[3], jobId: match[4] };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const cleanLines = (log) =>
|
|
26
|
+
log.split(/\r?\n/).map((line) =>
|
|
27
|
+
line
|
|
28
|
+
.replace(/^\d{4}-\d\d-\d\dT[\d:.]+Z\s+/, "")
|
|
29
|
+
// eslint-disable-next-line no-control-regex -- GitHub can colorize job logs.
|
|
30
|
+
.replace(/\x1b\[[\d;]*m/g, "")
|
|
31
|
+
.trim(),
|
|
32
|
+
);
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Find the single commit that actions/checkout checked out for `repository`.
|
|
36
|
+
* Returns null when there is no checkout or more than one, so callers never
|
|
37
|
+
* guess between revisions.
|
|
38
|
+
*/
|
|
39
|
+
export function readCheckoutRevision(log, repository) {
|
|
40
|
+
const lines = cleanLines(log);
|
|
41
|
+
const checkouts = [];
|
|
42
|
+
let observing = false,
|
|
43
|
+
merge = false;
|
|
44
|
+
for (const [index, line] of lines.entries()) {
|
|
45
|
+
const checkout = line.match(/^(?:##\[group\])?Syncing repository: (\S+)$/i);
|
|
46
|
+
if (checkout?.[1]) {
|
|
47
|
+
observing = checkout[1].toLowerCase() === repository.toLowerCase();
|
|
48
|
+
merge = false;
|
|
49
|
+
}
|
|
50
|
+
if (!observing) continue;
|
|
51
|
+
if (/^\[command\].*\s(?:checkout|fetch)\s.*refs\/(?:remotes\/)?pull\/\d+\/merge\b/.test(line))
|
|
52
|
+
merge = true;
|
|
53
|
+
if (/^\[command\].*\bgit\s+log\s+-1\s+--format=%H$/.test(line)) {
|
|
54
|
+
const commit = lines[index + 1];
|
|
55
|
+
if (commit && shaPattern.test(commit))
|
|
56
|
+
checkouts.push({ commit: commit.toLowerCase(), merge });
|
|
57
|
+
observing = false;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return checkouts.length === 1 ? checkouts[0] : null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const testPathPattern = /^[A-Za-z0-9_./@-]+$/;
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Read failing test files from a Vitest, Jest or Pytest job log. Returns
|
|
67
|
+
* repository-relative paths in first-seen order, without duplicates.
|
|
68
|
+
*/
|
|
69
|
+
export function failingTestsFromLog(log) {
|
|
70
|
+
const found = [];
|
|
71
|
+
const add = (path) => {
|
|
72
|
+
const clean = path.replace(/^\.\//, "");
|
|
73
|
+
if (testPathPattern.test(clean) && !clean.startsWith("..") && !found.includes(clean))
|
|
74
|
+
found.push(clean);
|
|
75
|
+
};
|
|
76
|
+
for (const line of cleanLines(log)) {
|
|
77
|
+
// Vitest: " FAIL src/a.test.ts > suite > case", Jest: "FAIL src/a.test.ts (1.2 s)"
|
|
78
|
+
const js = line.match(
|
|
79
|
+
/^(?:[×✗❯]\s*)?FAIL\s+(?:\|[^|]+\|\s+)?(\S+\.(?:test|spec)\.[cm]?[jt]sx?)\b/,
|
|
80
|
+
);
|
|
81
|
+
if (js?.[1]) add(js[1]);
|
|
82
|
+
// Pytest short summary: "FAILED tests/test_a.py::test_case - AssertionError"
|
|
83
|
+
const py = line.match(/^FAILED\s+(\S+?\.py)::/);
|
|
84
|
+
if (py?.[1]) add(py[1]);
|
|
85
|
+
}
|
|
86
|
+
return found;
|
|
87
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { parse } from "@babel/parser";
|
|
2
|
+
import { sourceDefinitions, sourceFlow } from "./source-flow.mjs";
|
|
3
|
+
|
|
4
|
+
// A conservative source index. A discovered entry point is not proof of execution.
|
|
5
|
+
export function discoverFile(file, source, { includeFlow = true } = {}) {
|
|
6
|
+
const operations = [];
|
|
7
|
+
let ast;
|
|
8
|
+
try {
|
|
9
|
+
ast = parse(source, {
|
|
10
|
+
sourceType: "unambiguous",
|
|
11
|
+
plugins: ["typescript", "jsx"],
|
|
12
|
+
errorRecovery: false,
|
|
13
|
+
});
|
|
14
|
+
} catch {
|
|
15
|
+
return { operations, warning: `Could not parse ${file}.` };
|
|
16
|
+
}
|
|
17
|
+
const visit = (node, fn) => {
|
|
18
|
+
if (!node || typeof node !== "object") return;
|
|
19
|
+
if (typeof node.type === "string") fn(node);
|
|
20
|
+
for (const [key, value] of Object.entries(node)) {
|
|
21
|
+
if (["loc", "start", "end", "tokens", "comments"].includes(key)) continue;
|
|
22
|
+
if (Array.isArray(value)) value.forEach((v) => visit(v, fn));
|
|
23
|
+
else if (value && typeof value === "object") visit(value, fn);
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
const name = (n) =>
|
|
27
|
+
n?.type === "Identifier"
|
|
28
|
+
? n.name
|
|
29
|
+
: n?.type === "MemberExpression"
|
|
30
|
+
? `${name(n.object)}.${name(n.property)}`
|
|
31
|
+
: "";
|
|
32
|
+
const functions = new Map();
|
|
33
|
+
const definitions = includeFlow ? sourceDefinitions(ast.program) : null;
|
|
34
|
+
visit(ast, (n) => {
|
|
35
|
+
if (["AssignmentExpression", "UpdateExpression"].includes(n.type)) {
|
|
36
|
+
const target = n.left ?? n.argument;
|
|
37
|
+
if (target.type === "Identifier" && definitions?.has(target.name))
|
|
38
|
+
definitions.set(target.name, null);
|
|
39
|
+
}
|
|
40
|
+
if (n.type === "FunctionDeclaration" && n.id) functions.set(n.id.name, n);
|
|
41
|
+
if (
|
|
42
|
+
n.type === "VariableDeclarator" &&
|
|
43
|
+
n.id?.type === "Identifier" &&
|
|
44
|
+
["ArrowFunctionExpression", "FunctionExpression"].includes(n.init?.type)
|
|
45
|
+
)
|
|
46
|
+
functions.set(n.id.name, n.init);
|
|
47
|
+
});
|
|
48
|
+
function add(n, operationName, kind, handler) {
|
|
49
|
+
const target = handler?.type === "Identifier" ? functions.get(handler.name) : handler;
|
|
50
|
+
const analysis = includeFlow ? sourceFlow(target, definitions) : null;
|
|
51
|
+
const calls = new Set();
|
|
52
|
+
if (!analysis && target)
|
|
53
|
+
visit(target.body, (child) => {
|
|
54
|
+
if (child.type === "CallExpression") {
|
|
55
|
+
const value = name(child.callee);
|
|
56
|
+
if (value && !value.startsWith("console.")) calls.add(value.slice(0, 150));
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
const line = n.loc?.start.line ?? 1;
|
|
60
|
+
operations.push({
|
|
61
|
+
id: `${file}:${line}:${n.start ?? 0}`,
|
|
62
|
+
name: operationName.slice(0, 200),
|
|
63
|
+
kind,
|
|
64
|
+
file,
|
|
65
|
+
line,
|
|
66
|
+
calls: analysis?.calls ?? [...calls].slice(0, 12),
|
|
67
|
+
...(analysis ? { sourceFlow: analysis.flow } : {}),
|
|
68
|
+
evidence: "source",
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
const verbs = new Set(["get", "post", "put", "patch", "delete", "head", "options"]);
|
|
72
|
+
visit(ast, (n) => {
|
|
73
|
+
if (n.type === "CallExpression") {
|
|
74
|
+
const callee = name(n.callee);
|
|
75
|
+
const method = callee.split(".").at(-1);
|
|
76
|
+
const first = n.arguments?.[0];
|
|
77
|
+
if (verbs.has(method) && first?.type === "StringLiteral" && n.arguments.length >= 2) {
|
|
78
|
+
// Only conventional HTTP routers; foo.get('key') is not an HTTP workflow.
|
|
79
|
+
const receiver = callee.split(".").slice(0, -1).join(".");
|
|
80
|
+
if (/^(?:app|router|server|routes|fastify|api)(?:\.|$)/.test(receiver))
|
|
81
|
+
add(n, `${method.toUpperCase()} ${first.value}`, "http", n.arguments.at(-1));
|
|
82
|
+
}
|
|
83
|
+
if (callee === "Deno.serve") add(n, "HTTP handler", "http", n.arguments.at(-1));
|
|
84
|
+
if (
|
|
85
|
+
["queue.process", "worker.process", "cron.schedule", "schedule.scheduleJob"].includes(
|
|
86
|
+
callee,
|
|
87
|
+
)
|
|
88
|
+
)
|
|
89
|
+
add(n, first?.value ? `${callee}: ${first.value}` : callee, "job", n.arguments.at(-1));
|
|
90
|
+
}
|
|
91
|
+
if (
|
|
92
|
+
n.type === "ExportNamedDeclaration" &&
|
|
93
|
+
/(?:^|\/)app\/(?:.*\/)?route\.[cm]?[jt]sx?$/.test(file)
|
|
94
|
+
) {
|
|
95
|
+
const d = n.declaration;
|
|
96
|
+
if (d?.type === "FunctionDeclaration" && verbs.has(d.id?.name?.toLowerCase()))
|
|
97
|
+
add(d, d.id.name + " " + file, "http", d);
|
|
98
|
+
for (const v of d?.declarations ?? [])
|
|
99
|
+
if (verbs.has(v.id?.name?.toLowerCase())) add(v, v.id.name + " " + file, "http", v.init);
|
|
100
|
+
}
|
|
101
|
+
if (n.type === "ExportDefaultDeclaration" && /(?:^|\/)pages\/api\//.test(file))
|
|
102
|
+
add(n, "API " + file, "http", n.declaration);
|
|
103
|
+
});
|
|
104
|
+
return { operations: operations.slice(0, 100) };
|
|
105
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { stripVTControlCharacters } from "node:util";
|
|
2
|
+
|
|
3
|
+
// Upload only recognized diagnostic categories and counts, never raw application
|
|
4
|
+
// output: logs can contain credentials, customer data, and assertion snapshots.
|
|
5
|
+
export function summarizeCommandFailure(output, phase, result) {
|
|
6
|
+
const text = stripVTControlCharacters(output);
|
|
7
|
+
const label =
|
|
8
|
+
{ install: "Dependency installation", build: "Build", test: "Tests" }[phase] ?? "Command";
|
|
9
|
+
const details = [];
|
|
10
|
+
const counts = [...text.matchAll(/Test Files\s+(\d+) failed/g)];
|
|
11
|
+
if (counts.length) {
|
|
12
|
+
const count = counts.reduce((total, match) => total + Number(match[1]), 0);
|
|
13
|
+
details.push(`${count} test file${count === 1 ? "" : "s"} failed.`);
|
|
14
|
+
}
|
|
15
|
+
if (/supabaseUrl is required|supabaseKey is required/i.test(text))
|
|
16
|
+
details.push(
|
|
17
|
+
"Supabase test configuration is missing. Configure the test environment or fully mock the Supabase client.",
|
|
18
|
+
);
|
|
19
|
+
if (/No Groq API keys configured|GROQ_API_KEY_PRIMARY is missing/.test(text))
|
|
20
|
+
details.push(
|
|
21
|
+
"Groq configuration is missing. Mocked tests need test-only configuration; live tests need a configured provider.",
|
|
22
|
+
);
|
|
23
|
+
if (/ERR_MODULE_NOT_FOUND|MODULE_NOT_FOUND|Cannot find (?:module|package)/.test(text))
|
|
24
|
+
details.push(
|
|
25
|
+
"A required module could not be loaded. Check installed dependencies and import paths.",
|
|
26
|
+
);
|
|
27
|
+
if (/ERESOLVE/.test(text))
|
|
28
|
+
details.push(
|
|
29
|
+
"npm could not resolve the dependency versions. Check package.json and the lockfile.",
|
|
30
|
+
);
|
|
31
|
+
if (/EUSAGE/.test(text) && /npm ci/.test(text))
|
|
32
|
+
details.push("npm ci rejected the lockfile. Synchronize package.json and package-lock.json.");
|
|
33
|
+
if (!details.length && /AssertionError|⎯+ Failed Tests|ERR_ASSERTION/.test(text))
|
|
34
|
+
details.push("A test assertion failed.");
|
|
35
|
+
return `${label} failed (${result}). ${details.join(" ")}${details.length ? " " : ""}Open the command logs for details.`.slice(
|
|
36
|
+
0,
|
|
37
|
+
500,
|
|
38
|
+
);
|
|
39
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// @traceyard/core: run one test at an exact commit, locally, with no server and
|
|
2
|
+
// no network. The hosted runner and the CLI are both thin layers over this.
|
|
3
|
+
import { indexRepository } from "./repository-index.mjs";
|
|
4
|
+
import { runInvestigationPlan, runTargetedTest } from "./test-evidence.mjs";
|
|
5
|
+
import { withCommit } from "./worktree.mjs";
|
|
6
|
+
|
|
7
|
+
export { analyzeRepositoryFiles, indexRepository, relatedTests } from "./repository-index.mjs";
|
|
8
|
+
export {
|
|
9
|
+
normalizeVitestReport,
|
|
10
|
+
prepareTargetedTest,
|
|
11
|
+
runInvestigationPlan,
|
|
12
|
+
runTargetedTest,
|
|
13
|
+
sanitizeDiagnostic,
|
|
14
|
+
selectTest,
|
|
15
|
+
} from "./test-evidence.mjs";
|
|
16
|
+
export { discoverFile } from "./discovery.mjs";
|
|
17
|
+
export { summarizeCommandFailure } from "./failure-summary.mjs";
|
|
18
|
+
export { isPytestFile, validPytestCase } from "./pytest.mjs";
|
|
19
|
+
export { adapterForFile, adapterForScript, runnerAdapters } from "./runners.mjs";
|
|
20
|
+
export {
|
|
21
|
+
detectPackageManager,
|
|
22
|
+
installCommand,
|
|
23
|
+
parsePackageManagerField,
|
|
24
|
+
scriptCommand,
|
|
25
|
+
} from "./package-manager.mjs";
|
|
26
|
+
export { failingTestsFromLog, parseActionsUrl, readCheckoutRevision } from "./ci-link.mjs";
|
|
27
|
+
export { checkoutCommit, ensureCommit, githubFetchEnv, withCommit } from "./worktree.mjs";
|
|
28
|
+
|
|
29
|
+
const DEFAULT_TIMEOUT_MS = 120000;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Run one test file (optionally one Pytest case) and return a structured result.
|
|
33
|
+
* With `commit`, the test runs in a throwaway worktree at that exact SHA and the
|
|
34
|
+
* developer's working tree is left alone. Dependencies must already be
|
|
35
|
+
* installable or installed; installing is the caller's decision.
|
|
36
|
+
*/
|
|
37
|
+
export async function runLocalTest({
|
|
38
|
+
repo,
|
|
39
|
+
testPath,
|
|
40
|
+
testCase,
|
|
41
|
+
question = "",
|
|
42
|
+
commit,
|
|
43
|
+
changedFiles,
|
|
44
|
+
maxTestFiles = 1,
|
|
45
|
+
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
46
|
+
env = process.env,
|
|
47
|
+
packageManager,
|
|
48
|
+
fetch = false,
|
|
49
|
+
token,
|
|
50
|
+
beforeRun,
|
|
51
|
+
}) {
|
|
52
|
+
if (!repo) throw Error("Pass the repository directory as `repo`.");
|
|
53
|
+
const plan = { question, testPath, testCase, timeoutMs, changedFiles, maxTestFiles };
|
|
54
|
+
const run = async (directory, sha) => {
|
|
55
|
+
if (beforeRun) await beforeRun(directory);
|
|
56
|
+
const index = await indexRepository(directory);
|
|
57
|
+
const options = packageManager ? { packageManager } : {};
|
|
58
|
+
const report =
|
|
59
|
+
changedFiles?.length || maxTestFiles > 1
|
|
60
|
+
? await runInvestigationPlan(directory, index, plan, env, options)
|
|
61
|
+
: await runTargetedTest(directory, index, plan, env, options);
|
|
62
|
+
return { ...report, commit: sha ?? null, snapshotId: index.snapshotId };
|
|
63
|
+
};
|
|
64
|
+
if (!commit) return run(repo);
|
|
65
|
+
return withCommit(repo, commit, (checkout) => run(checkout.path, checkout.sha), {
|
|
66
|
+
fetch,
|
|
67
|
+
token,
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
export * from "./agent-result.mjs";
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { readFile, stat } from "node:fs/promises";
|
|
2
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
3
|
+
|
|
4
|
+
// Lockfiles in order of preference when a directory has more than one.
|
|
5
|
+
const lockfiles = [
|
|
6
|
+
["package-lock.json", "npm"],
|
|
7
|
+
["npm-shrinkwrap.json", "npm"],
|
|
8
|
+
["pnpm-lock.yaml", "pnpm"],
|
|
9
|
+
["yarn.lock", "yarn"],
|
|
10
|
+
["bun.lock", "bun"],
|
|
11
|
+
["bun.lockb", "bun"],
|
|
12
|
+
];
|
|
13
|
+
const names = new Set(["npm", "pnpm", "yarn", "bun"]);
|
|
14
|
+
|
|
15
|
+
const exists = (path) =>
|
|
16
|
+
stat(path).then(
|
|
17
|
+
(s) => s.isFile(),
|
|
18
|
+
() => false,
|
|
19
|
+
);
|
|
20
|
+
|
|
21
|
+
async function readPackageJson(directory) {
|
|
22
|
+
try {
|
|
23
|
+
return JSON.parse(await readFile(join(directory, "package.json"), "utf8"));
|
|
24
|
+
} catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Parse the Corepack `packageManager` field, for example "pnpm@9.15.0+sha512...". */
|
|
30
|
+
export function parsePackageManagerField(value) {
|
|
31
|
+
if (typeof value !== "string") return null;
|
|
32
|
+
const match = value.trim().match(/^(npm|pnpm|yarn|bun)@(\d+)(?:\.\d+){0,2}/);
|
|
33
|
+
return match ? { name: match[1], major: Number(match[2]) } : null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Find the package manager that owns `packageDirectory`, walking up to `root`.
|
|
38
|
+
* The Corepack `packageManager` field wins over lockfiles because it is explicit.
|
|
39
|
+
* Returns the directory where installs must run, which is the workspace root for
|
|
40
|
+
* monorepos.
|
|
41
|
+
*/
|
|
42
|
+
export async function detectPackageManager(root, packageDirectory = root) {
|
|
43
|
+
const top = resolve(root);
|
|
44
|
+
let directory = resolve(packageDirectory);
|
|
45
|
+
if (relative(top, directory).startsWith("..")) directory = top;
|
|
46
|
+
for (;;) {
|
|
47
|
+
const pkg = await readPackageJson(directory);
|
|
48
|
+
const declared = parsePackageManagerField(pkg?.packageManager);
|
|
49
|
+
if (declared)
|
|
50
|
+
return { ...declared, installRoot: directory, source: "packageManager", lockfile: null };
|
|
51
|
+
for (const [file, name] of lockfiles)
|
|
52
|
+
if (await exists(join(directory, file)))
|
|
53
|
+
return { name, major: null, installRoot: directory, source: "lockfile", lockfile: file };
|
|
54
|
+
if (directory === top) break;
|
|
55
|
+
const parent = dirname(directory);
|
|
56
|
+
if (parent === directory) break;
|
|
57
|
+
directory = parent;
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
name: "npm",
|
|
61
|
+
major: null,
|
|
62
|
+
installRoot: resolve(packageDirectory),
|
|
63
|
+
source: "default",
|
|
64
|
+
lockfile: null,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const binary = (name) => (process.platform === "win32" ? name + ".cmd" : name);
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Command that runs a package.json script with extra arguments. npm needs `--`
|
|
72
|
+
* before forwarded arguments; pnpm, Yarn and Bun forward everything after the
|
|
73
|
+
* script name, and pnpm would pass a literal `--` through to the test runner.
|
|
74
|
+
*/
|
|
75
|
+
export function scriptCommand(manager, script, args = []) {
|
|
76
|
+
const name = names.has(manager?.name ?? manager) ? (manager?.name ?? manager) : "npm";
|
|
77
|
+
if (name === "npm") return { program: binary("npm"), args: ["run", script, "--", ...args] };
|
|
78
|
+
return { program: binary(name), args: ["run", script, ...args] };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Reproducible install command for a clean checkout. Lifecycle scripts stay off. */
|
|
82
|
+
export function installCommand(manager) {
|
|
83
|
+
const name = manager?.name ?? manager;
|
|
84
|
+
const major = manager?.major ?? null;
|
|
85
|
+
if (name === "pnpm")
|
|
86
|
+
return { program: binary("pnpm"), args: ["install", "--frozen-lockfile", "--ignore-scripts"] };
|
|
87
|
+
if (name === "yarn")
|
|
88
|
+
return major !== null && major < 2
|
|
89
|
+
? { program: binary("yarn"), args: ["install", "--frozen-lockfile", "--ignore-scripts"] }
|
|
90
|
+
: { program: binary("yarn"), args: ["install", "--immutable", "--mode=skip-build"] };
|
|
91
|
+
if (name === "bun")
|
|
92
|
+
return { program: binary("bun"), args: ["install", "--frozen-lockfile", "--ignore-scripts"] };
|
|
93
|
+
return {
|
|
94
|
+
program: binary("npm"),
|
|
95
|
+
args: ["ci", "--ignore-scripts", "--no-audit", "--no-fund"],
|
|
96
|
+
};
|
|
97
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Execute an existing Pytest selection and retain its observed outcomes."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
import pytest
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Evidence:
|
|
12
|
+
def __init__(self, file, case):
|
|
13
|
+
self.file = Path(file).resolve()
|
|
14
|
+
self.case = case
|
|
15
|
+
self.selected = set()
|
|
16
|
+
self.results = {}
|
|
17
|
+
self.reason = None
|
|
18
|
+
|
|
19
|
+
@pytest.hookimpl(trylast=True)
|
|
20
|
+
def pytest_collection_finish(self, session):
|
|
21
|
+
items = session.items
|
|
22
|
+
if len(items) > 1000:
|
|
23
|
+
self.reason = "The selected Pytest file contains more than 1,000 cases."
|
|
24
|
+
elif any(item.path.resolve() != self.file for item in items):
|
|
25
|
+
self.reason = "Pytest collected cases outside the selected file."
|
|
26
|
+
elif self.case and (
|
|
27
|
+
len(items) != 1 or items[0].nodeid.partition("::")[2] != self.case
|
|
28
|
+
):
|
|
29
|
+
self.reason = "Pytest did not collect the exact selected case."
|
|
30
|
+
if self.reason:
|
|
31
|
+
pytest.exit(self.reason, returncode=4)
|
|
32
|
+
self.selected = {item.nodeid for item in items}
|
|
33
|
+
|
|
34
|
+
def pytest_runtest_logreport(self, report):
|
|
35
|
+
if report.nodeid not in self.selected:
|
|
36
|
+
self.reason = "Pytest reported a case outside the selection."
|
|
37
|
+
return
|
|
38
|
+
result = self.results.setdefault(
|
|
39
|
+
report.nodeid, {"name": report.nodeid.partition("::")[2], "status": "incomplete"}
|
|
40
|
+
)
|
|
41
|
+
if report.failed:
|
|
42
|
+
result.update(status="failed", message=report.longreprtext[-4500:])
|
|
43
|
+
elif result["status"] != "failed":
|
|
44
|
+
if report.skipped:
|
|
45
|
+
result["status"] = "skipped"
|
|
46
|
+
elif report.when == "call" and report.passed:
|
|
47
|
+
result["status"] = "passed"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def main():
|
|
51
|
+
file, case, output = sys.argv[1:]
|
|
52
|
+
evidence = Evidence(file, case)
|
|
53
|
+
selector = file + "::" + case if case else file
|
|
54
|
+
sys.path.insert(0, os.getcwd())
|
|
55
|
+
code = pytest.main(
|
|
56
|
+
["-o", "addopts=", "--color=no", "--tb=short", "-q", selector], plugins=[evidence]
|
|
57
|
+
)
|
|
58
|
+
if not evidence.reason and (not evidence.selected or evidence.selected != evidence.results.keys()):
|
|
59
|
+
evidence.reason = "Pytest did not complete the selected cases."
|
|
60
|
+
Path(output).write_text(
|
|
61
|
+
json.dumps({"reason": evidence.reason, "results": list(evidence.results.values())}),
|
|
62
|
+
encoding="utf-8",
|
|
63
|
+
)
|
|
64
|
+
return code
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
if __name__ == "__main__":
|
|
68
|
+
sys.exit(main())
|