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,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
+ }
@@ -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())
@@ -0,0 +1,118 @@
1
+ import { lstat, realpath } from "node:fs/promises";
2
+ import { isAbsolute, join, relative } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { sanitizeDiagnostic } from "./test-report.mjs";
5
+
6
+ export const isPytestFile = (path) => /(?:^|\/)(?:test_[^/]+|[^/]+_test)\.py$/.test(path);
7
+ const casePattern = /^[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*(?:\[[^\p{Cc}]{0,150}\])?$/u;
8
+
9
+ export function validPytestCase(value) {
10
+ return typeof value === "string" && value.length <= 240 && casePattern.test(value);
11
+ }
12
+
13
+ export async function preparePytest(directory, file, test, plan) {
14
+ if (plan.replayRecording || plan.flakeCandidate)
15
+ return {
16
+ reason:
17
+ "This Pytest runner supports focused test execution. Replay and flakiness runs require Vitest.",
18
+ };
19
+ if (plan.testCase !== undefined && !validPytestCase(plan.testCase))
20
+ return { reason: "Provide a valid Pytest case selector, without the file path." };
21
+ for (const name of ["requirements-test.txt", "requirements.txt"]) {
22
+ const path = join(directory, name);
23
+ const stat = await lstat(path).catch(() => null);
24
+ if (!stat) continue;
25
+ const inside = relative(directory, await realpath(path));
26
+ if (!stat.isFile() || stat.size > 128000 || inside.startsWith("..") || isAbsolute(inside))
27
+ return { reason: "Pytest requires a regular requirements file in its package." };
28
+ return {
29
+ directory,
30
+ file,
31
+ requirements: path,
32
+ runner: "pytest",
33
+ command: {
34
+ directory: test.packageDirectory,
35
+ script: "pytest",
36
+ testPath: test.path,
37
+ ...(plan.testCase ? { testCase: plan.testCase } : {}),
38
+ },
39
+ };
40
+ }
41
+ return {
42
+ reason:
43
+ "Add requirements-test.txt or requirements.txt containing Pytest to this Python package.",
44
+ };
45
+ }
46
+
47
+ export function pytestEnvironment(env, install = false) {
48
+ return Object.fromEntries(
49
+ Object.entries(env).filter(
50
+ ([key]) =>
51
+ (install && /^(?:HTTPS?|NO|ALL)_PROXY$/i.test(key)) ||
52
+ /^(?:PATH|SYSTEMROOT|HOME|USERPROFILE|TMPDIR|TMP|TEMP|CI|LANG|LC_ALL|SSL_CERT_FILE|SSL_CERT_DIR)$/i.test(
53
+ key,
54
+ ),
55
+ ),
56
+ );
57
+ }
58
+
59
+ export const pytestArgs = (file, testCase, output) => [
60
+ "-I",
61
+ fileURLToPath(new URL("./pytest-runner.py", import.meta.url)),
62
+ file,
63
+ testCase ?? "",
64
+ output,
65
+ ];
66
+
67
+ export function normalizePytestEvidence(data, exitCode, command) {
68
+ if (data.reason) throw Error(sanitizeDiagnostic(data.reason, 500));
69
+ const results = data.results;
70
+ if (
71
+ ![0, 1].includes(exitCode) ||
72
+ !Array.isArray(results) ||
73
+ !results.length ||
74
+ (command.testCase && (results.length !== 1 || results[0]?.name !== command.testCase)) ||
75
+ results.some(
76
+ (item) =>
77
+ typeof item?.name !== "string" || !["passed", "failed", "skipped"].includes(item.status),
78
+ )
79
+ )
80
+ throw Error("Pytest did not report a complete outcome for the selected test.");
81
+ const counts = { passed: 0, failed: 0, skipped: 0 };
82
+ const failures = [];
83
+ let truncated = false;
84
+ for (const item of results) {
85
+ counts[item.status]++;
86
+ if (item.status !== "failed") continue;
87
+ if (failures.length >= 8) {
88
+ truncated = true;
89
+ continue;
90
+ }
91
+ const diagnostic =
92
+ typeof item.message === "string" ? item.message : "Pytest reported a failure.";
93
+ if (diagnostic.length > 1500) truncated = true;
94
+ failures.push({
95
+ file: command.testPath,
96
+ name: sanitizeDiagnostic(item.name, 250),
97
+ message: sanitizeDiagnostic(diagnostic),
98
+ });
99
+ }
100
+ if (counts.failed > 0 !== (exitCode === 1))
101
+ throw Error("The Pytest process and retained outcomes disagree.");
102
+ const status = counts.failed ? "FAILED" : counts.passed ? "SUCCEEDED" : "BLOCKED";
103
+ return {
104
+ status,
105
+ counts,
106
+ failures,
107
+ truncated,
108
+ message:
109
+ "Pytest: " +
110
+ counts.passed +
111
+ " passed, " +
112
+ counts.failed +
113
+ " failed, " +
114
+ counts.skipped +
115
+ " skipped." +
116
+ (status === "BLOCKED" ? " No passing executed case establishes success." : ""),
117
+ };
118
+ }