traceyard 0.1.0 → 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.
@@ -1,5 +1,7 @@
1
1
  // Verdicts and exit codes for every command. Pure functions, so the rules are
2
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";
3
5
 
4
6
  export const EXIT = {
5
7
  OK: 0, // REPRODUCED, PASSED, FIXED
@@ -28,15 +30,8 @@ export const exitCodeFor = (verdict) =>
28
30
 
29
31
  const short = (sha) => (sha ? sha.slice(0, 12) : "your working tree");
30
32
 
31
- /** Tests, fixtures, snapshots and Pytest configuration: edits here can make a test pass without a fix. */
32
- export const isTestInput = (path) =>
33
- /\.(?:test|spec|fixture)\.[cm]?[jt]sx?$|(?:^|\/)(?:__(?:tests|fixtures|snapshots|mocks)__|tests?|fixtures?)\/|\.snap$/i.test(
34
- path,
35
- ) ||
36
- /(?:^|\/)(?:test_[^/]+\.py|[^/]+_test\.py|conftest\.py|pytest\.ini|pyproject\.toml|setup\.cfg|tox\.ini|requirements[^/]*\.txt)$/.test(
37
- path,
38
- ) ||
39
- /(?:^|\/)(?:vitest|vite|jest)\.config\.[cm]?[jt]s$/.test(path);
33
+ /** Tests, fixtures, snapshots, setup files and runner config: edits here can make a test pass without a fix. */
34
+ export { isTestInput };
40
35
 
41
36
  export function reproVerdict(run, testPath, { fromCi = false } = {}) {
42
37
  if (run.status === "BLOCKED")
@@ -91,8 +86,17 @@ export function checkVerdict(run, testPath) {
91
86
  * hosted verification: a pass only counts as FIXED when the failure reproduced,
92
87
  * the same test passed, nothing was skipped away and no test inputs changed.
93
88
  */
94
- export function verifyVerdict({ baseline, candidate, testPath, changedFiles }) {
95
- const changedTests = changedFiles.filter(isTestInput);
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
+ ];
96
100
  const result = (verdict, summary, next) => ({ verdict, summary, next, changedTests });
97
101
  if (baseline.status === "BLOCKED")
98
102
  return result(
@@ -148,42 +152,103 @@ export function verifyVerdict({ baseline, candidate, testPath, changedFiles }) {
148
152
  );
149
153
  }
150
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
+
151
180
  /**
152
- * The merge gate. FIXED only for an intact receipt whose verdict is FIXED and
153
- * whose fix commit is exactly HEAD; anything else keeps the claim unproven.
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.
154
185
  */
155
- export function guardVerdict({ receipt, intact, head }) {
186
+ export function guardVerdict({ receipt, intact, head, id = "this receipt" }) {
156
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 });
157
189
  if (!receipt)
158
- return {
159
- verdict: "UNVERIFIED",
160
- summary: "No receipt yet, so nothing proves this commit fixes a failing test.",
161
- next: "Run `traceyard repro <test>` on the failing commit, fix the code, commit, then `traceyard verify`.",
162
- };
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
+ );
163
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")
164
238
  return {
165
- verdict: "NEEDS_REVIEW",
166
- summary: `Receipt ${receipt.id} was edited after it was written; its digest doesn't match.`,
167
- next: verify,
168
- };
169
- if (receipt.verdict !== "FIXED")
170
- return {
171
- verdict: receipt.verdict === "NEEDS_REVIEW" ? "NEEDS_REVIEW" : "UNVERIFIED",
172
- summary: `The latest receipt (${receipt.id}) says ${receipt.verdict}, not FIXED: ${receipt.summary}`,
173
- next:
174
- receipt.verdict === "NEEDS_REVIEW"
175
- ? "A person should review the changed test files before this merges."
176
- : verify,
177
- };
178
- if (!head || receipt.candidate?.commit !== head)
179
- return {
180
- verdict: "UNVERIFIED",
181
- summary: `Receipt ${receipt.id} proves ${short(receipt.candidate?.commit)}, but HEAD is ${short(head)}. Commits after the receipt aren't verified.`,
182
- next: verify,
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.",
183
242
  };
243
+ const verdict = ["NEEDS_REVIEW", "BLOCKED"].includes(recheck.verdict)
244
+ ? recheck.verdict
245
+ : "UNVERIFIED";
184
246
  return {
185
- verdict: "FIXED",
186
- summary: `HEAD ${short(head)} is proven: ${receipt.test.path} failed at ${short(receipt.baseline.commit)} and passes here, with no test files changed.`,
187
- next: "Safe to open or merge the pull request. Attach the receipt.",
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`.",
188
253
  };
189
254
  }
@@ -41,6 +41,22 @@ function compactVerification(packet, size, limit) {
41
41
  changedTestsCount: Array.isArray(v.changedTests) ? v.changedTests.length : 0,
42
42
  changedTests: Array.isArray(v.changedTests) ? v.changedTests.slice(0, 5) : [],
43
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
+ : {}),
44
60
  };
45
61
  if (Array.isArray(v.changedTests) && v.changedTests.length > 5) packet.omitted = true;
46
62
  const compact = packet.verification;
@@ -56,6 +72,10 @@ function compactVerification(packet, size, limit) {
56
72
  compact.evidence = compact.evidence.map((item) => item?.evidenceId ?? null);
57
73
  packet.omitted = true;
58
74
  }
75
+ while (size() > limit && compact.claim?.limitations.length > 1) {
76
+ compact.claim.limitations.pop();
77
+ packet.omitted = true;
78
+ }
59
79
  }
60
80
 
61
81
  /**
@@ -97,6 +117,17 @@ export function agentResult(value, limit = 4000) {
97
117
  packet.explanation.source = null;
98
118
  packet.omitted = true;
99
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
+ }
100
131
  for (const key of OPTIONAL_ARRAYS) {
101
132
  const array = packet[key];
102
133
  if (Array.isArray(array))
@@ -112,6 +143,32 @@ export function agentResult(value, limit = 4000) {
112
143
  packet.omitted = true;
113
144
  }
114
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
+ }
115
172
  while (size() > limit && typeof packet.summary === "string" && packet.summary.length > 20) {
116
173
  packet.summary = packet.summary.slice(
117
174
  0,
@@ -67,21 +67,64 @@ const testPathPattern = /^[A-Za-z0-9_./@-]+$/;
67
67
  * repository-relative paths in first-seen order, without duplicates.
68
68
  */
69
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) {
70
85
  const found = [];
86
+ const unreadable = [];
71
87
  const add = (path) => {
72
88
  const clean = path.replace(/^\.\//, "");
73
- if (testPathPattern.test(clean) && !clean.startsWith("..") && !found.includes(clean))
74
- found.push(clean);
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;
75
94
  };
76
95
  for (const line of cleanLines(log)) {
77
96
  // Vitest: " FAIL src/a.test.ts > suite > case", Jest: "FAIL src/a.test.ts (1.2 s)"
78
97
  const js = line.match(
79
98
  /^(?:[×✗❯]\s*)?FAIL\s+(?:\|[^|]+\|\s+)?(\S+\.(?:test|spec)\.[cm]?[jt]sx?)\b/,
80
99
  );
81
- if (js?.[1]) add(js[1]);
82
100
  // Pytest short summary: "FAILED tests/test_a.py::test_case - AssertionError"
83
101
  const py = line.match(/^FAILED\s+(\S+?\.py)::/);
84
- if (py?.[1]) add(py[1]);
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
+ }
85
118
  }
86
- return found;
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));
87
130
  }
@@ -0,0 +1,118 @@
1
+ // Versioned evidence envelope (schema version 1), the JavaScript side of
2
+ // shared/contracts/evidence.ts. Pure functions only: no I/O, no clock.
3
+ //
4
+ // The TypeScript schema is the authority. Tests check that every envelope
5
+ // built here parses against it and that `deriveEvidenceOutcome` here returns
6
+ // the same outcome as the TypeScript version for every state and scope.
7
+
8
+ import { createHash } from "node:crypto";
9
+
10
+ export const EVIDENCE_SCHEMA_VERSION = 1;
11
+
12
+ const PENDING = ["PLANNED", "QUEUED", "RUNNING"];
13
+ const INTERRUPTED = ["BLOCKED", "CANCELLED", "STALE", "REJECTED"];
14
+ const TERMINAL = ["COMPLETED", "FAILED"];
15
+
16
+ const sorted = (value) =>
17
+ Array.isArray(value)
18
+ ? value.map(sorted)
19
+ : value && typeof value === "object"
20
+ ? Object.fromEntries(
21
+ Object.keys(value)
22
+ .sort()
23
+ .map((key) => [key, sorted(value[key])]),
24
+ )
25
+ : value;
26
+
27
+ /** Stable JSON with sorted keys at every level. */
28
+ export const canonicalJson = (value) => JSON.stringify(sorted(value));
29
+
30
+ /** 64-character lowercase SHA-256 of a value's canonical JSON. */
31
+ export const fingerprint = (value) =>
32
+ createHash("sha256").update(canonicalJson(value)).digest("hex");
33
+
34
+ /** Derive only claims that are safe for the supplied execution state and check set. */
35
+ export function deriveEvidenceOutcome({ state, scope, checks }) {
36
+ if (PENDING.includes(state)) return { state, claim: "NOT_RUN" };
37
+ if (INTERRUPTED.includes(state)) return { state, claim: "INCONCLUSIVE" };
38
+ if (state === "FAILED") return { state: "FAILED", claim: "FAILED" };
39
+ if (checks.length === 0 || checks.some((check) => check.status !== "PASSED"))
40
+ return { state: "COMPLETED", claim: "INCONCLUSIVE" };
41
+ if (scope === "AFFECTED") return { state: "COMPLETED", claim: "INCONCLUSIVE" };
42
+ return { state: "COMPLETED", claim: scope === "FOCUSED" ? "FOCUSED_PASS" : "REQUIRED_PASS" };
43
+ }
44
+
45
+ /**
46
+ * Assemble an envelope. The claim is always derived, never supplied, so a
47
+ * caller cannot turn blocked, stale or incomplete evidence into a pass.
48
+ * A completed run that is inconclusive must say why, so a generic limitation
49
+ * is added when the caller gave none.
50
+ */
51
+ export function buildEvidenceEnvelope({
52
+ evidenceId,
53
+ runId,
54
+ requestId,
55
+ repositoryId,
56
+ source,
57
+ scope,
58
+ state,
59
+ revision,
60
+ checks,
61
+ limitations = [],
62
+ next,
63
+ startedAt,
64
+ completedAt,
65
+ }) {
66
+ const outcome = deriveEvidenceOutcome({ state, scope, checks });
67
+ const notes = [...new Set(limitations.filter(Boolean).map((item) => item.slice(0, 500)))];
68
+ if (
69
+ outcome.state === "COMPLETED" &&
70
+ outcome.claim === "INCONCLUSIVE" &&
71
+ checks.every((check) => check.status === "PASSED") &&
72
+ notes.length === 0
73
+ )
74
+ notes.push("The run completed without enough evidence for a pass.");
75
+ return {
76
+ schemaVersion: EVIDENCE_SCHEMA_VERSION,
77
+ evidenceId,
78
+ runId,
79
+ requestId,
80
+ repositoryId,
81
+ source,
82
+ scope,
83
+ state: outcome.state,
84
+ claim: outcome.claim,
85
+ revision: {
86
+ commit: revision.commit ?? null,
87
+ worktreeFingerprint: revision.worktreeFingerprint ?? null,
88
+ inputFingerprint: revision.inputFingerprint,
89
+ policyFingerprint: revision.policyFingerprint,
90
+ environmentFingerprint: revision.environmentFingerprint,
91
+ },
92
+ checks: checks.slice(0, 1000),
93
+ limitations: notes.slice(0, 100),
94
+ ...(next ? { next: next.slice(0, 500) } : {}),
95
+ startedAt,
96
+ completedAt: TERMINAL.includes(outcome.state) ? completedAt : null,
97
+ };
98
+ }
99
+
100
+ /**
101
+ * The part of an envelope an agent must never lose: what state the run is in,
102
+ * what it claims, how wide the claim is, where it came from and which revision
103
+ * it is about. Compact responses keep this and may shorten only limitations.
104
+ */
105
+ export function evidenceClaimSummary(envelope) {
106
+ return {
107
+ evidenceId: envelope.evidenceId,
108
+ state: envelope.state,
109
+ claim: envelope.claim,
110
+ scope: envelope.scope,
111
+ source: envelope.source,
112
+ commit: envelope.revision.commit,
113
+ worktree: envelope.revision.worktreeFingerprint
114
+ ? envelope.revision.worktreeFingerprint.slice(0, 12)
115
+ : null,
116
+ limitations: envelope.limitations,
117
+ };
118
+ }
@@ -1,4 +1,5 @@
1
- import { readFile, realpath, mkdtemp, rm } from "node:fs/promises";
1
+ import { chown, readFile, realpath, mkdtemp, rm } from "node:fs/promises";
2
+ import { constants as fsConstants } from "node:fs";
2
3
  import { join, resolve, relative, isAbsolute } from "node:path";
3
4
  import { tmpdir } from "node:os";
4
5
  import { spawn } from "node:child_process";
@@ -7,6 +8,7 @@ import { relatedTests } from "./repository-index.mjs";
7
8
  import { isPytestFile } from "./pytest.mjs";
8
9
  import { adapterForFile, adapterForScript, runnerAdapters } from "./runners.mjs";
9
10
  import { detectPackageManager, scriptCommand } from "./package-manager.mjs";
11
+ import { runnerConfigDigest } from "./test-inputs.mjs";
10
12
 
11
13
  import { sanitizeDiagnostic, normalizeVitestReport } from "./test-report.mjs";
12
14
  export { sanitizeDiagnostic, normalizeVitestReport };
@@ -117,6 +119,7 @@ export async function prepareTargetedTest(workspace, index, plan) {
117
119
  directory,
118
120
  file,
119
121
  runner: selected.runner,
122
+ runnerConfig: await runnerConfigDigest({ root, directory, pkg, script: selected.name }),
120
123
  command: { directory: test.packageDirectory, script: selected.name, testPath: test.path },
121
124
  };
122
125
  }
@@ -142,7 +145,7 @@ export async function runTargetedTest(workspace, index, plan, env, options = {})
142
145
  });
143
146
  const prepared = await prepareTargetedTest(workspace, index, plan);
144
147
  if (prepared.reason) return blocked(prepared.reason);
145
- const { root, directory, file, runner, command } = prepared;
148
+ const { root, directory, file, runner, command, runnerConfig } = prepared;
146
149
  if (plan.replayRecording)
147
150
  return options.replay
148
151
  ? options.replay(root, command, plan)
@@ -152,6 +155,10 @@ export async function runTargetedTest(workspace, index, plan, env, options = {})
152
155
  const testArgument = path.startsWith("-") ? "./" + path : path;
153
156
  const temporary = await mkdtemp(join(tmpdir(), "traceyard-evidence-")),
154
157
  output = join(temporary, "report.json");
158
+ // A hosted sandbox runs the test as a separate user, which must own the
159
+ // directory its structured reporter writes to.
160
+ const sandbox = options.sandbox ?? null;
161
+ if (sandbox) await chown(temporary, sandbox.uid, sandbox.gid);
155
162
  let tail = "",
156
163
  timedOut = false;
157
164
  try {
@@ -168,9 +175,11 @@ export async function runTargetedTest(workspace, index, plan, env, options = {})
168
175
  );
169
176
  let evidenceError;
170
177
  const exitCode = await new Promise((done, reject) => {
178
+ const childEnv = adapter.environment ? adapter.environment(env) : env;
171
179
  const child = spawn(invocation.program, invocation.args, {
172
180
  cwd: directory,
173
- env: adapter.environment ? adapter.environment(env) : env,
181
+ env: sandbox ? { ...childEnv, HOME: sandbox.home } : childEnv,
182
+ ...(sandbox ? { uid: sandbox.uid, gid: sandbox.gid } : {}),
174
183
  shell: !isPytest && process.platform === "win32",
175
184
  detached: process.platform !== "win32",
176
185
  stdio: ["ignore", "pipe", "pipe"],
@@ -207,7 +216,12 @@ export async function runTargetedTest(workspace, index, plan, env, options = {})
207
216
  let result;
208
217
  const retainedOutput = sanitizeDiagnostic(tail.slice(-4000), 4000);
209
218
  try {
210
- const text = await readFile(output, "utf8");
219
+ // The reporter output is written by the test process; never follow a link
220
+ // it planted in place of the file.
221
+ const text = await readFile(output, {
222
+ encoding: "utf8",
223
+ flag: process.platform === "win32" ? "r" : fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW,
224
+ });
211
225
  if (Buffer.byteLength(text) > 8_000_000)
212
226
  return blocked("The structured reporter exceeded the supported artifact size.");
213
227
  if (timedOut)
@@ -242,6 +256,7 @@ export async function runTargetedTest(workspace, index, plan, env, options = {})
242
256
  exitCode,
243
257
  nodeVersion: process.version,
244
258
  command,
259
+ ...(runnerConfig ? { runnerConfig } : {}),
245
260
  };
246
261
  } finally {
247
262
  await rm(temporary, { recursive: true, force: true });
@@ -0,0 +1,97 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFile, realpath } from "node:fs/promises";
3
+ import { isAbsolute, relative, resolve } from "node:path";
4
+
5
+ // Files whose edits can make a test pass without fixing the code: the tests
6
+ // themselves, fixtures, snapshots, mocks, setup files and runner configuration.
7
+ // The CLI and the hosted verification both use these rules, so a fix commit is
8
+ // judged the same way wherever it is verified.
9
+
10
+ const javascriptTestInput = [
11
+ /\.(?:test|spec|fixture)\.[cm]?[jt]sx?$/i,
12
+ /(?:^|\/)(?:__(?:tests|fixtures|snapshots|mocks)__|tests?|fixtures?)\//i,
13
+ /\.snap$/i,
14
+ // Runner configuration and workspaces.
15
+ /(?:^|\/)(?:vitest|vite|jest)\.(?:config|workspace)(?:\.[^/]+)?\.(?:[cm]?[jt]s|json)$/i,
16
+ /(?:^|\/)vitest\.(?:projects?)\.[cm]?[jt]s$/i,
17
+ // Setup files that run before every test.
18
+ /(?:^|\/)(?:setup-?tests?|tests?-?setup|(?:vitest|jest)[.-]setup(?:[.-][^/]+)?)\.[cm]?[jt]sx?$/i,
19
+ /\.setup\.[cm]?[jt]sx?$/i,
20
+ ];
21
+
22
+ // The config names are every file Pytest reads settings from, including the
23
+ // hidden and TOML forms. Any of them can redirect imports with `pythonpath`.
24
+ const pytestTestInput =
25
+ /(?:^|\/)(?:test_[^/]+\.py|[^/]+_test\.py|conftest\.py|\.?pytest\.(?:ini|toml)|pyproject\.toml|setup\.cfg|tox\.ini|requirements[^/]*\.txt)$/;
26
+
27
+ /** True for JavaScript test inputs: tests, fixtures, snapshots, mocks, setup and runner config. */
28
+ export const isJavaScriptTestInput = (path) => javascriptTestInput.some((rule) => rule.test(path));
29
+
30
+ /** True for Pytest test inputs: test modules, conftest and Pytest or dependency configuration. */
31
+ export const isPytestInput = (path) => pytestTestInput.test(path);
32
+
33
+ /** True when a path is a test input for any supported runner. */
34
+ export const isTestInput = (path) => isJavaScriptTestInput(path) || isPytestInput(path);
35
+
36
+ /** The `--config`/`-c` file a runner script names, when it names one. */
37
+ export function scriptConfigPath(command) {
38
+ const words = String(command).trim().split(/\s+/);
39
+ for (let i = 0; i < words.length; i++) {
40
+ const word = words[i].replace(/^["']|["']$/g, "");
41
+ const inline = word.match(/^(?:--config|-c)=(.+)$/);
42
+ if (inline) return inline[1].replace(/^["']|["']$/g, "");
43
+ if ((word === "--config" || word === "-c") && words[i + 1])
44
+ return words[i + 1].replace(/^["']|["']$/g, "");
45
+ }
46
+ return null;
47
+ }
48
+
49
+ /**
50
+ * A digest of the runner configuration a JavaScript run used: the package
51
+ * script that ran, the package.json `jest` key, and the contents of a config
52
+ * file the script names. Two runs with different digests did not run the test
53
+ * the same way, even when no file matched the test-input rules.
54
+ */
55
+ export async function runnerConfigDigest({ root, directory, pkg, script }) {
56
+ const command = String(pkg.scripts?.[script] ?? "");
57
+ const configPath = scriptConfigPath(command);
58
+ let config = null;
59
+ if (configPath) {
60
+ try {
61
+ // Compare resolved paths: on Windows a temporary root may be a short 8.3
62
+ // name while realpath returns the long one.
63
+ const file = await realpath(resolve(directory, configPath));
64
+ const inside = relative(await realpath(root), file);
65
+ config =
66
+ inside.startsWith("..") || isAbsolute(inside)
67
+ ? "outside-repository"
68
+ : createHash("sha256")
69
+ .update(await readFile(file))
70
+ .digest("hex");
71
+ } catch {
72
+ config = "missing";
73
+ }
74
+ }
75
+ return createHash("sha256")
76
+ .update(JSON.stringify({ script, command, jest: pkg.jest ?? null, configPath, config }))
77
+ .digest("hex");
78
+ }
79
+
80
+ /**
81
+ * The package.json a pair of runs disagrees about. Returns `changed` with the
82
+ * package.json path when both runs recorded different runner configurations.
83
+ * When only one run recorded one, `unknown` is true and a package.json listed
84
+ * in `changedFiles` counts as changed, since it can't be ruled out.
85
+ */
86
+ export function runnerConfigChange(baseline, candidate, directory = ".", changedFiles = []) {
87
+ if (!baseline || !candidate) return { changed: [], unknown: false };
88
+ const dir = String(directory || ".").replace(/\/+$/, "");
89
+ const manifest = dir === "." || !dir ? "package.json" : dir + "/package.json";
90
+ if (!baseline.runnerConfig || !candidate.runnerConfig) {
91
+ const unknown = !!(baseline.runnerConfig || candidate.runnerConfig);
92
+ // Without both digests, a changed package.json can't be ruled out.
93
+ return { changed: unknown && changedFiles.includes(manifest) ? [manifest] : [], unknown };
94
+ }
95
+ if (baseline.runnerConfig === candidate.runnerConfig) return { changed: [], unknown: false };
96
+ return { changed: [manifest], unknown: false };
97
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "traceyard",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Reproduce a failing test at the exact commit, check a fix, and record a receipt that it passed. No account, no server.",
5
5
  "license": "MIT",
6
6
  "type": "module",