traceyard 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,254 @@
1
+ // Verdicts and exit codes for every command. Pure functions, so the rules are
2
+ // easy to read and test. Exit codes are part of the public contract (docs/CLI.md).
3
+ import { validPytestCase } from "../../core/src/pytest.mjs";
4
+ import { isTestInput, runnerConfigChange } from "../../core/src/test-inputs.mjs";
5
+
6
+ export const EXIT = {
7
+ OK: 0, // REPRODUCED, PASSED, FIXED
8
+ FAILING: 1, // FAILING, STILL_FAILING, UNVERIFIED
9
+ REVIEW: 2, // NOT_REPRODUCED, NEEDS_REVIEW, INCONCLUSIVE
10
+ BLOCKED: 3, // BLOCKED: the test could not run here
11
+ USAGE: 64, // bad arguments
12
+ INTERNAL: 70, // a bug in Traceyard
13
+ };
14
+
15
+ export const exitCodeFor = (verdict) =>
16
+ ({
17
+ REPRODUCED: EXIT.OK,
18
+ PASSED: EXIT.OK,
19
+ FIXED: EXIT.OK,
20
+ AVAILABLE: EXIT.OK,
21
+ FAILING: EXIT.FAILING,
22
+ STILL_FAILING: EXIT.FAILING,
23
+ UNVERIFIED: EXIT.FAILING,
24
+ NOT_REPRODUCED: EXIT.REVIEW,
25
+ NEEDS_REVIEW: EXIT.REVIEW,
26
+ INCONCLUSIVE: EXIT.REVIEW,
27
+ BLOCKED: EXIT.BLOCKED,
28
+ ERROR: EXIT.USAGE,
29
+ })[verdict] ?? EXIT.INTERNAL;
30
+
31
+ const short = (sha) => (sha ? sha.slice(0, 12) : "your working tree");
32
+
33
+ /** Tests, fixtures, snapshots, setup files and runner config: edits here can make a test pass without a fix. */
34
+ export { isTestInput };
35
+
36
+ export function reproVerdict(run, testPath, { fromCi = false } = {}) {
37
+ if (run.status === "BLOCKED")
38
+ return {
39
+ verdict: "BLOCKED",
40
+ summary: run.message,
41
+ next: "Fix what blocked the run, then rerun the same command.",
42
+ };
43
+ if (run.status === "FAILED")
44
+ return {
45
+ verdict: "REPRODUCED",
46
+ summary: `${testPath} fails at ${short(run.commit)}: ${run.counts.failed} failed, ${run.counts.passed} passed.`,
47
+ next: "Fix the code, not the test. Run `traceyard check` after each attempt, then commit and run `traceyard verify`.",
48
+ };
49
+ return {
50
+ verdict: "NOT_REPRODUCED",
51
+ summary: `${testPath} passed at ${short(run.commit)}, so the failure did not reproduce.`,
52
+ next: fromCi
53
+ ? "This is the commit CI tested, so the failure may depend on CI's environment or on another test. Check the job log, then try the failing test CI named."
54
+ : "Check the commit and test file. If CI failed, pass the job link with --from so Traceyard uses the commit CI tested.",
55
+ };
56
+ }
57
+
58
+ export function checkVerdict(run, testPath) {
59
+ if (run.status === "BLOCKED")
60
+ return {
61
+ verdict: "BLOCKED",
62
+ summary: run.message,
63
+ next: "Fix what blocked the run, then rerun `traceyard check`.",
64
+ };
65
+ if (run.status === "FAILED")
66
+ return {
67
+ verdict: "FAILING",
68
+ summary: `${testPath} still fails in ${short(run.commit)}: ${run.counts.failed} failed, ${run.counts.passed} passed.`,
69
+ next: "Read the first failure, change the code, and run `traceyard check` again.",
70
+ };
71
+ if (!run.counts.passed)
72
+ return {
73
+ verdict: "BLOCKED",
74
+ summary: `${testPath} ran no passing tests, so nothing was checked.`,
75
+ next: "Make sure the test is not skipped, then rerun `traceyard check`.",
76
+ };
77
+ return {
78
+ verdict: "PASSED",
79
+ summary: `${testPath} passes in ${short(run.commit)}: ${run.counts.passed} passed.`,
80
+ next: "Commit the fix and run `traceyard verify` to record a receipt.",
81
+ };
82
+ }
83
+
84
+ /**
85
+ * Compare a baseline (failing commit) and a candidate (fix commit). Mirrors the
86
+ * hosted verification: a pass only counts as FIXED when the failure reproduced,
87
+ * the same test passed, nothing was skipped away and no test inputs changed.
88
+ */
89
+ export function verifyVerdict({ baseline, candidate, testPath, changedFiles, linked = [] }) {
90
+ // A changed test script or runner config changes how the test runs even when
91
+ // no file matched the path rules, so it counts as a changed test input.
92
+ const changedTests = [
93
+ ...new Set([
94
+ ...changedFiles.filter(isTestInput),
95
+ // A link can stand for a folder, such as `tests` pointing somewhere else.
96
+ ...linked.filter((link) => isTestInput(link) || isTestInput(link + "/x")),
97
+ ...runnerConfigChange(baseline, candidate, baseline.runner?.directory, changedFiles).changed,
98
+ ]),
99
+ ];
100
+ const result = (verdict, summary, next) => ({ verdict, summary, next, changedTests });
101
+ if (baseline.status === "BLOCKED")
102
+ return result(
103
+ "BLOCKED",
104
+ "The failing commit could not run: " + baseline.message,
105
+ "Fix what blocked the run, then rerun `traceyard verify`.",
106
+ );
107
+ if (baseline.status !== "FAILED" || !baseline.counts.failed)
108
+ return result(
109
+ "NOT_REPRODUCED",
110
+ `${testPath} passed at the failing commit ${short(baseline.commit)}, so there is no failure to verify a fix against.`,
111
+ "Check the --before commit. Use the commit CI tested, or pass the job link to `traceyard repro --from`.",
112
+ );
113
+ if (candidate.status === "BLOCKED")
114
+ return result(
115
+ "BLOCKED",
116
+ "The fix commit could not run: " + candidate.message,
117
+ "Fix what blocked the run, then rerun `traceyard verify`.",
118
+ );
119
+ if (baseline.commit === candidate.commit)
120
+ return result(
121
+ "INCONCLUSIVE",
122
+ "The failing commit and the fix commit are the same.",
123
+ "Commit the fix, then run `traceyard verify` again.",
124
+ );
125
+ if (candidate.status === "FAILED") {
126
+ const same =
127
+ candidate.failures[0]?.name && candidate.failures[0].name === baseline.failures[0]?.name;
128
+ return result(
129
+ "STILL_FAILING",
130
+ same
131
+ ? `${testPath} still fails at ${short(candidate.commit)} with the same test case.`
132
+ : `${testPath} fails at ${short(candidate.commit)} with a different test case.`,
133
+ "Read the first failure, change the code, and run `traceyard check` before verifying again.",
134
+ );
135
+ }
136
+ if (!candidate.counts.passed || candidate.counts.skipped > baseline.counts.skipped)
137
+ return result(
138
+ "INCONCLUSIVE",
139
+ `${testPath} did not fail at ${short(candidate.commit)}, but ${candidate.counts.skipped - baseline.counts.skipped} more test(s) were skipped, so the pass doesn't prove a fix.`,
140
+ "Remove the skips and verify again.",
141
+ );
142
+ if (changedTests.length)
143
+ return result(
144
+ "NEEDS_REVIEW",
145
+ `${testPath} passes at ${short(candidate.commit)}, but test files or fixtures changed between the commits.`,
146
+ "Review the changed test files before accepting the fix. A fix should change code, not the test.",
147
+ );
148
+ return result(
149
+ "FIXED",
150
+ `${testPath} failed at ${short(baseline.commit)} and passes at ${short(candidate.commit)}, with no test files changed.`,
151
+ "Open a pull request and attach the receipt.",
152
+ );
153
+ }
154
+
155
+ const sha = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
156
+ const isSha = (value) => typeof value === "string" && sha.test(value);
157
+
158
+ /**
159
+ * The test a receipt names, or null when it isn't a plain repository path and
160
+ * case. Receipts are untrusted files: these values reach the test runner and
161
+ * the output, so control characters are refused too.
162
+ */
163
+ export function receiptTest(receipt) {
164
+ const { path, case: testCase = null } = receipt?.test ?? {};
165
+ if (
166
+ typeof path !== "string" ||
167
+ !path ||
168
+ path.length > 240 ||
169
+ /\p{Cc}/u.test(path) ||
170
+ path.startsWith("/") ||
171
+ path.startsWith("-") ||
172
+ path.includes("\\") ||
173
+ path.split("/").includes("..") ||
174
+ (testCase !== null && !validPytestCase(testCase))
175
+ )
176
+ return null;
177
+ return { path, case: testCase };
178
+ }
179
+
180
+ /**
181
+ * Whether a receipt is worth rechecking: intact, FIXED, well formed and for
182
+ * exactly HEAD. This reads only the receipt, which proves nothing by itself, so
183
+ * a FIXED answer here must still pass `guardRecheckVerdict`. `id` is the
184
+ * receipt's file name; no text from inside the receipt is repeated.
185
+ */
186
+ export function guardVerdict({ receipt, intact, head, id = "this receipt" }) {
187
+ const verify = "Run `traceyard verify` on the fix commit, then run `traceyard guard` again.";
188
+ const answer = (verdict, summary, next = verify) => ({ verdict, summary, next });
189
+ if (!receipt)
190
+ return answer(
191
+ "UNVERIFIED",
192
+ "No receipt yet, so nothing proves this commit fixes a failing test.",
193
+ "Run `traceyard repro <test>` on the failing commit, fix the code, commit, then `traceyard verify`.",
194
+ );
195
+ if (!intact)
196
+ return answer(
197
+ "NEEDS_REVIEW",
198
+ `Receipt ${id} was edited after it was written; its digest doesn't match.`,
199
+ );
200
+ if (receipt.verdict === "NEEDS_REVIEW")
201
+ return answer(
202
+ "NEEDS_REVIEW",
203
+ `Receipt ${id} says NEEDS_REVIEW, not FIXED: test inputs changed.`,
204
+ "A person should review the changed test files before this merges.",
205
+ );
206
+ if (receipt.verdict !== "FIXED") return answer("UNVERIFIED", `Receipt ${id} does not say FIXED.`);
207
+ const commit = receipt.candidate?.commit;
208
+ if (!receiptTest(receipt) || !isSha(receipt.baseline?.commit) || !isSha(commit))
209
+ return answer("NEEDS_REVIEW", `Receipt ${id} doesn't name a usable test and commits.`);
210
+ // Receipts written since the evidence envelope must agree with it. Older
211
+ // receipts have none. Either way the tests are run again.
212
+ const envelope = receipt.evidenceEnvelope;
213
+ if (
214
+ envelope &&
215
+ (envelope.claim !== "FOCUSED_PASS" ||
216
+ envelope.state !== "COMPLETED" ||
217
+ envelope.revision?.commit !== commit)
218
+ )
219
+ return answer(
220
+ "NEEDS_REVIEW",
221
+ `Receipt ${id} says FIXED, but its evidence does not claim a focused pass for its fix commit.`,
222
+ );
223
+ if (!head || commit !== head)
224
+ return answer(
225
+ "UNVERIFIED",
226
+ `Receipt ${id} is for ${short(commit)}, but HEAD is ${short(head)}. Commits after the receipt aren't verified.`,
227
+ );
228
+ return answer("FIXED", `Receipt ${id} is for HEAD ${short(head)}.`);
229
+ }
230
+
231
+ /**
232
+ * The guard's answer: the verdict from running both commits again. Only a fresh
233
+ * FIXED passes. The claim is about one test, never about merge safety.
234
+ */
235
+ export function guardRecheckVerdict({ recheck, test, baseline, head }) {
236
+ const name = test.path + (test.case ? "::" + test.case : "");
237
+ if (recheck.verdict === "FIXED")
238
+ return {
239
+ verdict: "FIXED",
240
+ summary: `Rechecked: ${name} fails at ${short(baseline)} and passes at HEAD ${short(head)}, with no test files changed.`,
241
+ next: "This covers that one test only. Run the full suite and review the change before merging.",
242
+ };
243
+ const verdict = ["NEEDS_REVIEW", "BLOCKED"].includes(recheck.verdict)
244
+ ? recheck.verdict
245
+ : "UNVERIFIED";
246
+ return {
247
+ verdict,
248
+ summary: `The receipt says FIXED, but running it again gave ${recheck.verdict}: ${recheck.summary}`,
249
+ next:
250
+ verdict === "NEEDS_REVIEW"
251
+ ? "A person should review the changed test files before this merges."
252
+ : "Fix what the rerun found, commit, run `traceyard verify`, then `traceyard guard`.",
253
+ };
254
+ }
@@ -0,0 +1,5 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ export const VERSION = JSON.parse(
4
+ readFileSync(new URL("../package.json", import.meta.url), "utf8"),
5
+ ).version;
@@ -0,0 +1,185 @@
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
+ // Evidence state, claim, scope, source and revision are never dropped.
45
+ ...(v.evidence && typeof v.evidence === "object"
46
+ ? {
47
+ claim: {
48
+ evidenceId: v.evidence.evidenceId,
49
+ state: v.evidence.state,
50
+ claim: v.evidence.claim,
51
+ scope: v.evidence.scope,
52
+ source: v.evidence.source,
53
+ commit: v.evidence.revision?.commit ?? null,
54
+ limitations: Array.isArray(v.evidence.limitations)
55
+ ? v.evidence.limitations.slice(0, 3)
56
+ : [],
57
+ },
58
+ }
59
+ : {}),
60
+ };
61
+ if (Array.isArray(v.changedTests) && v.changedTests.length > 5) packet.omitted = true;
62
+ const compact = packet.verification;
63
+ while (size() > limit && compact.changedTests.length) {
64
+ compact.changedTests.pop();
65
+ packet.omitted = true;
66
+ }
67
+ if (size() > limit) {
68
+ delete compact.metrics;
69
+ packet.omitted = true;
70
+ }
71
+ if (size() > limit) {
72
+ compact.evidence = compact.evidence.map((item) => item?.evidenceId ?? null);
73
+ packet.omitted = true;
74
+ }
75
+ while (size() > limit && compact.claim?.limitations.length > 1) {
76
+ compact.claim.limitations.pop();
77
+ packet.omitted = true;
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Local runs: shorten failure messages, then drop logs, then keep only the
83
+ * first failure. The evidence ID stays, so nothing is lost for good.
84
+ */
85
+ function compactRuns(packet, size, limit) {
86
+ const runs = packet.runs;
87
+ for (const length of [300, 120]) {
88
+ if (size() <= limit) return;
89
+ for (const run of runs)
90
+ for (const failure of run.failures ?? [])
91
+ if (failure.message?.length > length) {
92
+ failure.message = failure.message.slice(0, length);
93
+ run.truncated = true;
94
+ packet.omitted = true;
95
+ }
96
+ }
97
+ for (const run of runs)
98
+ if (size() > limit && "output" in run) {
99
+ delete run.output;
100
+ packet.omitted = true;
101
+ }
102
+ for (const run of runs)
103
+ while (size() > limit && run.failures?.length > 1) {
104
+ run.failures.pop();
105
+ run.truncated = true;
106
+ packet.omitted = true;
107
+ }
108
+ }
109
+
110
+ export function agentResult(value, limit = 4000) {
111
+ const packet = { schemaVersion: 1, ...JSON.parse(JSON.stringify(value)), omitted: false };
112
+ const size = () => JSON.stringify(packet).length * 2 + 200;
113
+ if (packet.verification && typeof packet.verification === "object")
114
+ compactVerification(packet, size, limit);
115
+ if (Array.isArray(packet.runs)) compactRuns(packet, size, limit);
116
+ if (packet.explanation?.source && size() > limit) {
117
+ packet.explanation.source = null;
118
+ packet.omitted = true;
119
+ }
120
+ // The claim summary is never dropped; only its limitations shorten, to one.
121
+ const claimNotes = packet.claim?.limitations;
122
+ if (Array.isArray(claimNotes))
123
+ while (claimNotes.length > 1 && size() > limit) {
124
+ claimNotes.pop();
125
+ packet.omitted = true;
126
+ }
127
+ if (Array.isArray(claimNotes) && claimNotes[0]?.length > 160 && size() > limit) {
128
+ claimNotes[0] = claimNotes[0].slice(0, 160);
129
+ packet.omitted = true;
130
+ }
131
+ for (const key of OPTIONAL_ARRAYS) {
132
+ const array = packet[key];
133
+ if (Array.isArray(array))
134
+ while (array.length > 1 && size() > limit) {
135
+ array.pop();
136
+ packet.omitted = true;
137
+ }
138
+ }
139
+ for (const key of DROPPABLE) {
140
+ if (size() <= limit) break;
141
+ if (key in packet) {
142
+ delete packet[key];
143
+ packet.omitted = true;
144
+ }
145
+ }
146
+ // Last resort before cutting the summary: diagnostic run fields, then the
147
+ // claim's copy of an evidence ID that a run already carries. The claim's
148
+ // state, scope, source and revision are never removed.
149
+ if (Array.isArray(packet.runs))
150
+ for (const field of ["durationMs", "dependencies", "cached", "workingTree", "message"])
151
+ for (const run of packet.runs)
152
+ if (size() > limit && run && typeof run === "object" && field in run) {
153
+ delete run[field];
154
+ packet.omitted = true;
155
+ }
156
+ if (Array.isArray(packet.runs) && typeof packet.test?.path === "string")
157
+ for (const run of packet.runs)
158
+ for (const failure of run?.failures ?? [])
159
+ if (size() > limit && failure?.file === packet.test.path) {
160
+ delete failure.file;
161
+ packet.omitted = true;
162
+ }
163
+ if (
164
+ size() > limit &&
165
+ packet.claim?.evidenceId &&
166
+ Array.isArray(packet.runs) &&
167
+ packet.runs.some((run) => run?.evidenceId === packet.claim.evidenceId)
168
+ ) {
169
+ delete packet.claim.evidenceId;
170
+ packet.omitted = true;
171
+ }
172
+ while (size() > limit && typeof packet.summary === "string" && packet.summary.length > 20) {
173
+ packet.summary = packet.summary.slice(
174
+ 0,
175
+ Math.max(20, Math.floor(packet.summary.length * 0.75)),
176
+ );
177
+ packet.omitted = true;
178
+ }
179
+ if (packet.omitted && typeof packet.offset === "number" && typeof packet.summary === "string")
180
+ packet.nextOffset = packet.offset + packet.summary.length;
181
+ return {
182
+ content: [{ type: "text", text: JSON.stringify(packet) }],
183
+ structuredContent: packet,
184
+ };
185
+ }
@@ -0,0 +1,130 @@
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
+ return readFailures(log).found;
71
+ }
72
+
73
+ /**
74
+ * Failure lines that name a test file Traceyard can't read as a plain path,
75
+ * such as one with spaces, brackets or `../`. A caller that ignored these
76
+ * could pick another failure as if it were the only one.
77
+ */
78
+ export function unreadableFailuresInLog(log) {
79
+ return readFailures(log).unreadable;
80
+ }
81
+
82
+ const pytestFile = /(?:^|\/)(?:test_[^/]*\.py|[^/]*_test\.py|conftest\.py)$/;
83
+
84
+ function readFailures(log) {
85
+ const found = [];
86
+ const unreadable = [];
87
+ const add = (path) => {
88
+ const clean = path.replace(/^\.\//, "");
89
+ if (!testPathPattern.test(clean) || clean.startsWith("..")) return false;
90
+ // conftest.py holds fixtures, not a test that can be run on its own.
91
+ if (/(?:^|\/)conftest\.py$/.test(clean)) return false;
92
+ if (!found.includes(clean)) found.push(clean);
93
+ return true;
94
+ };
95
+ for (const line of cleanLines(log)) {
96
+ // Vitest: " FAIL src/a.test.ts > suite > case", Jest: "FAIL src/a.test.ts (1.2 s)"
97
+ const js = line.match(
98
+ /^(?:[×✗❯]\s*)?FAIL\s+(?:\|[^|]+\|\s+)?(\S+\.(?:test|spec)\.[cm]?[jt]sx?)\b/,
99
+ );
100
+ // Pytest short summary: "FAILED tests/test_a.py::test_case - AssertionError"
101
+ const py = line.match(/^FAILED\s+(\S+?\.py)::/);
102
+ // Setup, fixture and import failures: "ERROR tests/test_a.py::case - ...".
103
+ // Applications log "ERROR ..." too, so only a test case or a test file
104
+ // name counts. The subject may hold spaces; `add` then refuses it.
105
+ const error = line.match(/^ERROR\s+(.*?\.py)(::|\s+-\s|\s*$)/);
106
+ const pyError =
107
+ error && (error[2] === "::" || pytestFile.test(error[1])) ? error[1] : undefined;
108
+ const path = js?.[1] ?? py?.[1] ?? pyError;
109
+ if (path && add(path)) continue;
110
+ const looksFailed =
111
+ /^(?:[×✗❯]\s*)?FAIL\s.*\.(?:test|spec)\.[cm]?[jt]sx?\b/.test(line) ||
112
+ /^FAILED\s.*\.py::/.test(line) ||
113
+ pyError !== undefined;
114
+ if (looksFailed) {
115
+ const text = line.slice(0, 160);
116
+ if (!unreadable.includes(text)) unreadable.push(text);
117
+ }
118
+ }
119
+ return { found, unreadable };
120
+ }
121
+
122
+ /**
123
+ * Match a path from a job log to the files at the tested commit. Test runners
124
+ * print paths relative to the directory they ran in, so in a monorepo
125
+ * `tests/a.py` may mean `services/api/tests/a.py`. Returns every file that
126
+ * could be meant; callers must not choose between them.
127
+ */
128
+ export function matchTestPath(logPath, files) {
129
+ return files.filter((file) => file === logPath || file.endsWith("/" + logPath));
130
+ }
@@ -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
+ }