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.
package/README.md CHANGED
@@ -1,19 +1,19 @@
1
- # Traceyard CLI
1
+ # TraceYard CLI
2
2
 
3
- Prove a failing test is fixed, on your own machine. No account, no server, no network unless you ask for it.
3
+ Prove a failing test is fixed on your own machine. No TraceYard account or server is required. Test execution is local; dependency installation, optional Git fetching, and the initial package bootstrap can use the network when requested.
4
4
 
5
5
  ```bash
6
6
  traceyard repro src/cart.test.ts --at 3f2c9e1 # fails at the commit CI tested
7
7
  traceyard check # run it against your edits, as often as you like
8
8
  git commit -am "Fix cart rounding"
9
9
  traceyard verify # failed before, passes now, test untouched
10
- traceyard guard # exit 0 only if HEAD is proven fixed
10
+ traceyard guard # rerun the test; exit 0 if still fixed at HEAD
11
11
  traceyard receipt # Markdown you can paste into the PR
12
12
  ```
13
13
 
14
14
  Coding agents get the same commands as MCP tools with `traceyard mcp`. See [Coding agents](#coding-agents-mcp).
15
15
 
16
- Until the npm package ships (#49), run it from a Traceyard checkout with `node packages/cli/bin/traceyard.mjs`. Node 22.12 or later.
16
+ Released use is `npx traceyard@0.1.0` (or `npx traceyard` when you intentionally want the current latest). From a checkout, after `npm ci` and with Node.js 22.12.0 or newer, use `node packages/cli/bin/traceyard.mjs` for development.
17
17
 
18
18
  ## Commands
19
19
 
@@ -25,6 +25,8 @@ Runs the test at an exact commit in a throwaway `git worktree`. Your working tre
25
25
 
26
26
  Traceyard remembers the test and commit, so `check` and `verify` can run without arguments afterwards.
27
27
 
28
+ With `--from`, test paths in a job log are relative to the folder the runner started in. Traceyard looks for the file at the tested commit, so `tests/test_cart.py` can resolve to `services/api/tests/test_cart.py`. If more than one file could be meant, or a failing file can't be found, it stops and asks you for the path.
29
+
28
30
  ### `traceyard check [test]`
29
31
 
30
32
  Runs the test in your working tree, including uncommitted edits. This is the fast loop for each attempt at a fix. It never writes a receipt, because uncommitted code can't be pinned to a commit.
@@ -35,13 +37,19 @@ Runs the test at the failing commit (`--before`, default: the last reproduced co
35
37
 
36
38
  1. The test failed at `--before`.
37
39
  2. The same test file passed at `--after`, with at least one passing test and no extra skips.
38
- 3. No tests, fixtures, snapshots, mocks or test runner config changed between the two commits.
40
+ 3. No tests, fixtures, snapshots, mocks, setup files or test runner config changed between the two commits. A change to the test script, the `jest` key in `package.json`, or a config file the script names counts as a runner config change. See [execution trust](https://github.com/fysaio/traceyard/blob/main/docs/EXECUTION_TRUST.md#test-inputs).
39
41
 
40
42
  Each verify writes a receipt to `.traceyard/receipts/` as JSON and Markdown.
41
43
 
42
- ### `traceyard guard [receipt]`
44
+ ### `traceyard guard [receipt] [--before <sha>]`
45
+
46
+ A check for scripts, hooks and agents. It takes the newest receipt (or the one you name), and if that receipt is intact, says `FIXED` and its fix commit is exactly `HEAD`, it runs the verification again: the receipt's test at its failing commit and at `HEAD`, ignoring cached results, followed by the same rules `verify` uses. It passes (`FIXED`, exit 0) only when that fresh run is `FIXED`. The receipt is never proof by itself, because anyone who can edit the file can also recompute its digest. A guard therefore takes about as long as a `verify`.
47
+
48
+ If there is no receipt, commits were added after it, or the rerun does not fix the test, the verdict is `UNVERIFIED` (exit 1). An edited receipt, a `NEEDS_REVIEW` receipt or changed test inputs give `NEEDS_REVIEW` (exit 2). A test that cannot run gives `BLOCKED` (exit 3). Uncommitted changes add a warning, because only `HEAD` is checked.
49
+
50
+ The receipt's failing commit must be on `HEAD`'s first-parent line (the branch's own commits), otherwise the answer is `NEEDS_REVIEW`. That happens after a rebase, when the failing commit arrived through a merge, or when the failure was reproduced on a pull request merge commit. Check which commit really failed and pass it as `--before <sha>`, which replaces the receipt's value. The MCP `guard` tool has no such override.
43
51
 
44
- A merge gate for scripts, hooks and agents. It passes (`FIXED`, exit 0) only when the newest receipt (or the one you name) is intact, says `FIXED`, and its fix commit is exactly `HEAD`. If there is no receipt, or commits were added after it, the verdict is `UNVERIFIED` (exit 1). An edited receipt or a `NEEDS_REVIEW` receipt gives `NEEDS_REVIEW` (exit 2). Uncommitted changes add a warning, because only `HEAD` is checked.
52
+ A pass covers one test. It says nothing about the rest of the suite or whether the change is safe to merge. The receipt still chooses the test and, without `--before`, which earlier commit counts as failing. Someone who can write commits can break the code in one and restore it in the next, or arrange the history so a made-up commit sits on that line, so test changes made before the failing commit are not seen. A reviewer should check both, and a hook that knows the failing commit should pass `--before`. The rerun happens on your machine, with your installed packages and tools, so it is not protection against someone who controls that environment. Use CI for that.
45
53
 
46
54
  ```bash
47
55
  # .git/hooks/pre-push
@@ -91,7 +99,11 @@ Receipts have trust level `local`: they record what ran on this machine. Signed
91
99
 
92
100
  ## JSON output
93
101
 
94
- Every command prints one object. The schema is `cliResultSchema` in [`shared/contracts/cli.ts`](https://github.com/fysaio/traceyard/blob/main/docs/../shared/contracts/cli.ts), and contract tests check every command against it. Fields are only added within `schemaVersion: 1`.
102
+ With `--json`, every supported command prints exactly one JSON object on stdout; without it, commands print human-readable output. Progress is sent to stderr or suppressed as appropriate in JSON mode. The schema is `cliResultSchema` in [`shared/contracts/cli.ts`](https://github.com/fysaio/traceyard/blob/main/docs/../shared/contracts/cli.ts), and contract tests check every command against it. Fields are only added within `schemaVersion: 1`.
103
+
104
+ ```bash
105
+ traceyard verify --json
106
+ ```
95
107
 
96
108
  ```json
97
109
  {
@@ -143,6 +155,11 @@ Every command prints one object. The schema is `cliResultSchema` in [`shared/con
143
155
  - `next` is one sentence telling a person or agent what to do next.
144
156
  - Output is bounded for agents: up to 5 failures, 600 characters each, with stack frames from `node_modules` removed. Raw output only appears with `--log`. A full result stays well under 1,500 tokens.
145
157
  - Every run that executed has an `evidenceId`. The full log stays on disk; read it with `inspect <evidenceId>` in bounded slices. Terminal colours, progress bars, repeated lines and absolute paths are removed first.
158
+ - `repro`, `check` and `verify` also return `evidenceEnvelope`, the versioned evidence contract in [`shared/contracts/evidence.ts`](https://github.com/fysaio/traceyard/blob/main/docs/../shared/contracts/evidence.ts). It keeps the execution `state` (`COMPLETED`, `FAILED`, `BLOCKED`, `STALE`, ...) separate from the `claim` made about it (`FOCUSED_PASS`, `FAILED`, `INCONCLUSIVE`, ...), and records the exact revision (`commit`, or a `worktreeFingerprint` for `check`), input, policy and environment fingerprints, one entry per rule in `checks`, the `limitations`, and `next`. The claim is always derived from the state and checks, never set by hand.
159
+ - CLI evidence is always `source: "LOCAL_PROVISIONAL"` and `scope: "FOCUSED"`: one selected test on this machine. `FOCUSED_PASS` is not proof that the whole suite passes or that a change is safe to merge.
160
+ - `verify` reaches `FOCUSED_PASS` only for a `FIXED` verdict. Its checks are `reproduces-before`, `passes-after`, `distinct-commits`, `no-new-skips` and `test-inputs-unchanged`, so an `INCONCLUSIVE` claim names the rule that failed.
161
+ - `check` fingerprints the working tree before and after the run. If a tracked file, or an untracked file that existed before, changes while the test runs, the state is `STALE`, the claim is `INCONCLUSIVE` and the verdict is `INCONCLUSIVE` (exit code 2). New untracked files, such as caches a test runner writes, don't count.
162
+ - Receipts store the envelope inside their digest, which catches accidental edits but is not a signature. `guard` reruns the test and also treats a `FIXED` receipt whose envelope doesn't claim `FOCUSED_PASS` for the same fix commit as `NEEDS_REVIEW`. Receipts written before the envelope existed are still accepted.
146
163
  - `dependencies` says how packages were made available:
147
164
  - `existing`: already installed.
148
165
  - `linked`: the commit has the same lockfile as your clone, so your `node_modules` was linked in.
@@ -168,14 +185,14 @@ Installed dependencies are cached per user, outside the repository: `~/.cache/tr
168
185
 
169
186
  ## Coding agents (MCP)
170
187
 
171
- `traceyard mcp` serves six tools over stdio to any MCP client. They run on your machine with no account. They return the same envelope as the hosted server: `status` holds the verdict, and the `outputChars` budget (default 4,000) bounds every response.
188
+ `traceyard mcp` serves six local tools over stdio to any MCP client. They run on your machine with no account. Hosted MCP is a different server with three tools (`investigate`, `inspect`, and `verify`) and requires OAuth plus project authorization; see [Connect a coding agent](https://github.com/fysaio/traceyard/blob/main/docs/MCP.md). The local tools return a bounded result envelope; they are not interchangeable with the hosted tool schemas.
172
189
 
173
190
  | Tool | Same as | Use |
174
191
  | ----------- | ------------------- | --------------------------------------------------------------------------------------- |
175
192
  | `reproduce` | `traceyard repro` | Rerun the failing test at the exact commit, or at the commit a GitHub Actions job used. |
176
193
  | `check` | `traceyard check` | Run it against the working tree after each fix attempt. |
177
194
  | `verify` | `traceyard verify` | Prove the committed fix and write a receipt. |
178
- | `guard` | `traceyard guard` | Before claiming "fixed": `FIXED` only if HEAD has an intact FIXED receipt. |
195
+ | `guard` | `traceyard guard` | Before claiming "fixed": reruns the receipt's test; `FIXED` covers that test only. |
179
196
  | `explain` | `traceyard explain` | The first failure, the line it points to, and the source around it. |
180
197
  | `inspect` | `traceyard inspect` | Recent runs and receipts, a run's full log in slices, or a receipt's Markdown. |
181
198
 
@@ -211,8 +228,8 @@ command = "npx"
211
228
  args = ["-y", "traceyard", "mcp"]
212
229
  ```
213
230
 
214
- Before the npm release, replace `npx -y traceyard` with `node /path/to/traceyard/packages/cli/bin/traceyard.mjs`.
231
+ For checkout development, replace `npx -y traceyard` with `node /path/to/traceyard/packages/cli/bin/traceyard.mjs` after running `npm ci` with Node.js 22.12.0 or newer.
215
232
 
216
233
  ### Token budget
217
234
 
218
- Every tool response is under 1,500 tokens. The tests check this on each call, and `node scripts/bench-cli.mjs` records it in [`docs/benchmarks/cli-agent.json`](https://github.com/fysaio/traceyard/blob/main/docs/benchmarks/cli-agent.json). On the benchmark repository (10 Vitest cases, 7 failing), the full loop costs about 1,900 tokens across eight calls: reproduce, reproduce again, explain, two inspects, check, verify and guard. The largest single call is `verify` at about 470 tokens. A repeated `reproduce` at the same commit returns in about 70 ms from the cache.
235
+ Every tool response is under 1,500 tokens. The tests check this on each call, and `node scripts/bench-cli.mjs` records it in [`docs/benchmarks/cli-agent.json`](https://github.com/fysaio/traceyard/blob/main/docs/benchmarks/cli-agent.json). On the benchmark repository (10 Vitest cases, 7 failing), the full loop costs about 2,400 tokens across eight calls: reproduce, reproduce again, explain, two inspects, check, verify and guard. The largest are `verify` and `guard`, at about 450 tokens each, because `guard` reruns both commits. A repeated `reproduce` at the same commit returns in about 70 ms from the cache.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.1.0",
2
+ "version": "0.1.1",
3
3
  "type": "module",
4
4
  "private": true
5
5
  }
@@ -0,0 +1,235 @@
1
+ // Map local CLI runs onto the versioned evidence envelope
2
+ // (shared/contracts/evidence.ts). Everything the CLI produces is
3
+ // LOCAL_PROVISIONAL and FOCUSED: one selected test on this machine, never a
4
+ // required-check, full-suite or merge-safety claim.
5
+
6
+ import { createHash, randomBytes } from "node:crypto";
7
+ import { buildEvidenceEnvelope, fingerprint } from "../../core/src/evidence.mjs";
8
+ import { VERSION } from "./version.mjs";
9
+
10
+ const SOURCE = "LOCAL_PROVISIONAL";
11
+ const SCOPE = "FOCUSED";
12
+
13
+ export const LOCAL_LIMITATION =
14
+ "Local provisional evidence from this machine, not a hosted attestation.";
15
+ const focusedLimitation = (test) =>
16
+ `Covers only ${label(test)}; it says nothing about other tests or whether the change is safe to merge.`;
17
+
18
+ /**
19
+ * True for the two limitations every CLI envelope carries. They restate
20
+ * `source: LOCAL_PROVISIONAL` and `scope: FOCUSED`, so compact agent
21
+ * responses may leave them out and keep only the run-specific ones.
22
+ */
23
+ export const isStandardLimitation = (text) =>
24
+ text === LOCAL_LIMITATION || /^Covers only .+; it says nothing about other tests/.test(text);
25
+
26
+ const label = (test) => (test.case ? `${test.path}::${test.case}` : test.path);
27
+
28
+ /** The built-in verdict rules. Changes when the rules (or the CLI) change. */
29
+ export const policyFingerprint = () =>
30
+ fingerprint({ policy: "traceyard-builtin-focused", version: 1, tool: VERSION });
31
+
32
+ function environmentFingerprint(runs) {
33
+ return fingerprint({
34
+ node: process.version,
35
+ platform: process.platform,
36
+ arch: process.arch,
37
+ tool: VERSION,
38
+ runners: runs.map((run) => run?.runner?.script ?? null),
39
+ dependencies: runs.map((run) => run?.dependencies ?? null),
40
+ });
41
+ }
42
+
43
+ export const newRequestId = () => "req_" + randomBytes(8).toString("hex");
44
+
45
+ /** Stable, non-reversible ID for a repository without a GitHub remote. */
46
+ export const repositoryId = (github, root) =>
47
+ github
48
+ ? "github:" + github
49
+ : "local:" + createHash("sha256").update(root).digest("hex").slice(0, 16);
50
+
51
+ /** A selected test's outcome as one check. A run with no passing test checked nothing. */
52
+ function testStatus(run) {
53
+ if (!run) return "NOT_RUN";
54
+ if (run.status === "BLOCKED") return "BLOCKED";
55
+ if (run.status === "FAILED") return "FAILED";
56
+ return run.counts.passed > 0 ? "PASSED" : "SKIPPED";
57
+ }
58
+
59
+ function runState(run) {
60
+ if (run.status === "BLOCKED") return "BLOCKED";
61
+ if (run.status === "FAILED") return "FAILED";
62
+ return "COMPLETED";
63
+ }
64
+
65
+ function runLimitations(run, role) {
66
+ const notes = [];
67
+ if (run.status === "BLOCKED") notes.push(`The ${role} run was blocked: ${run.message}`);
68
+ else if (!run.counts.passed && run.status !== "FAILED")
69
+ notes.push(`The ${role} run had no passing test, so nothing was checked.`);
70
+ if (run.cached)
71
+ notes.push(
72
+ `The ${role} result was reused from an earlier run of the same commit and test${run.recordedAt ? ` (${run.recordedAt})` : ""}.`,
73
+ );
74
+ if (run.truncated) notes.push(`The ${role} failure list was truncated.`);
75
+ return notes;
76
+ }
77
+
78
+ const evidenceIdFor = (...runs) =>
79
+ runs.find((run) => run?.evidenceId)?.evidenceId ?? "ev_blocked_" + randomBytes(6).toString("hex");
80
+
81
+ /**
82
+ * Envelope for `repro` (a commit) or `check` (the working tree).
83
+ * `worktree` is `{ fingerprint, stale, complete }` for check: if the tree
84
+ * changed while the test ran, the result is STALE rather than a pass or a failure.
85
+ */
86
+ export function singleRunEnvelope({
87
+ command,
88
+ run,
89
+ test,
90
+ repository,
91
+ requestId,
92
+ worktree = null,
93
+ next,
94
+ startedAt,
95
+ completedAt,
96
+ }) {
97
+ const checks = [{ id: `test:${label(test)}`, status: testStatus(run), required: false }];
98
+ const limitations = [LOCAL_LIMITATION, focusedLimitation(test), ...runLimitations(run, command)];
99
+ let state = runState(run);
100
+ if (worktree) {
101
+ if (worktree.stale) {
102
+ state = "STALE";
103
+ limitations.push("The working tree changed while the test ran, so this result is stale.");
104
+ }
105
+ if (!worktree.complete)
106
+ limitations.push(
107
+ "The working-tree fingerprint does not cover every untracked file, so some edits may go undetected.",
108
+ );
109
+ }
110
+ const evidenceId = evidenceIdFor(run);
111
+ return buildEvidenceEnvelope({
112
+ evidenceId,
113
+ runId: run.evidenceId ?? evidenceId,
114
+ requestId,
115
+ repositoryId: repository,
116
+ source: SOURCE,
117
+ scope: SCOPE,
118
+ state,
119
+ revision: {
120
+ commit: run.commit ?? null,
121
+ worktreeFingerprint: worktree ? worktree.fingerprint : null,
122
+ inputFingerprint: fingerprint({
123
+ command,
124
+ test: { path: test.path, case: test.case ?? null },
125
+ commit: run.commit ?? null,
126
+ worktree: worktree ? worktree.fingerprint : null,
127
+ }),
128
+ policyFingerprint: policyFingerprint(),
129
+ environmentFingerprint: environmentFingerprint([run]),
130
+ },
131
+ checks,
132
+ limitations,
133
+ next,
134
+ startedAt,
135
+ completedAt,
136
+ });
137
+ }
138
+
139
+ /**
140
+ * Envelope for `verify`. Each rule the verdict depends on is its own check,
141
+ * so a FIXED verdict is the only way to reach FOCUSED_PASS: the failure
142
+ * reproduced before, the same test passes after, the commits differ, no new
143
+ * skips, and no test inputs changed.
144
+ */
145
+ export function verifyEnvelope({
146
+ baseline,
147
+ candidate,
148
+ test,
149
+ changedTests,
150
+ repository,
151
+ requestId,
152
+ next,
153
+ startedAt,
154
+ completedAt,
155
+ }) {
156
+ const reproduced =
157
+ baseline.status === "BLOCKED"
158
+ ? "BLOCKED"
159
+ : baseline.status === "FAILED" && baseline.counts.failed > 0
160
+ ? "PASSED"
161
+ : "FAILED";
162
+ const ran = Boolean(candidate) && reproduced === "PASSED";
163
+ const checks = [
164
+ { id: `reproduces-before:${label(test)}`, status: reproduced, required: false },
165
+ {
166
+ id: `passes-after:${label(test)}`,
167
+ status: ran ? testStatus(candidate) : "NOT_RUN",
168
+ required: false,
169
+ },
170
+ {
171
+ id: "distinct-commits",
172
+ status: !ran ? "NOT_RUN" : baseline.commit !== candidate.commit ? "PASSED" : "FAILED",
173
+ required: false,
174
+ },
175
+ {
176
+ id: "no-new-skips",
177
+ status: !ran
178
+ ? "NOT_RUN"
179
+ : candidate.counts.skipped > baseline.counts.skipped
180
+ ? "FAILED"
181
+ : "PASSED",
182
+ required: false,
183
+ },
184
+ {
185
+ id: "test-inputs-unchanged",
186
+ status: !ran ? "NOT_RUN" : changedTests.length ? "FAILED" : "PASSED",
187
+ required: false,
188
+ },
189
+ ];
190
+ const limitations = [
191
+ LOCAL_LIMITATION,
192
+ focusedLimitation(test),
193
+ ...runLimitations(baseline, "baseline"),
194
+ ...(candidate ? runLimitations(candidate, "candidate") : []),
195
+ ];
196
+ if (reproduced === "FAILED")
197
+ limitations.push("The test did not fail at the baseline commit, so no fix can be shown.");
198
+ if (ran && changedTests.length)
199
+ limitations.push(
200
+ `Test inputs changed between the commits: ${changedTests.slice(0, 5).join(", ")}${changedTests.length > 5 ? ", ..." : ""}.`,
201
+ );
202
+ let state = "COMPLETED";
203
+ if (baseline.status === "BLOCKED" || candidate?.status === "BLOCKED") state = "BLOCKED";
204
+ // Same commit on both sides proves nothing either way, even if the test fails.
205
+ else if (ran && candidate.status === "FAILED" && baseline.commit !== candidate.commit)
206
+ state = "FAILED";
207
+ const evidenceId = evidenceIdFor(candidate, baseline);
208
+ return buildEvidenceEnvelope({
209
+ evidenceId,
210
+ runId: (candidate ?? baseline).evidenceId ?? evidenceId,
211
+ requestId,
212
+ repositoryId: repository,
213
+ source: SOURCE,
214
+ scope: SCOPE,
215
+ state,
216
+ revision: {
217
+ commit: (candidate ?? baseline).commit ?? null,
218
+ worktreeFingerprint: null,
219
+ inputFingerprint: fingerprint({
220
+ command: "verify",
221
+ test: { path: test.path, case: test.case ?? null },
222
+ baseline: baseline.commit ?? null,
223
+ candidate: candidate?.commit ?? null,
224
+ changedTests: [...changedTests].sort(),
225
+ }),
226
+ policyFingerprint: policyFingerprint(),
227
+ environmentFingerprint: environmentFingerprint([baseline, candidate]),
228
+ },
229
+ checks,
230
+ limitations,
231
+ next,
232
+ startedAt,
233
+ completedAt,
234
+ });
235
+ }
@@ -1,5 +1,6 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { realpath } from "node:fs/promises";
3
+ import { posix } from "node:path";
3
4
  import { promisify } from "node:util";
4
5
 
5
6
  const run = promisify(execFile);
@@ -35,10 +36,12 @@ export async function resolveCommit(repo, ref) {
35
36
 
36
37
  /** Files that differ between two commits, as repository-relative paths. */
37
38
  export async function changedFiles(repo, from, to) {
38
- const out = await git(repo, ["diff", "--name-only", "--no-renames", from, to], {
39
+ // -z keeps names as they are. Without it Git quotes and escapes non-ASCII
40
+ // names, and a quoted path matches none of the test-input rules.
41
+ const out = await git(repo, ["diff", "--name-only", "--no-renames", "-z", from, to], {
39
42
  timeoutMs: 60000,
40
43
  });
41
- return out ? out.split("\n").filter(Boolean) : [];
44
+ return out.split("\0").filter(Boolean);
42
45
  }
43
46
 
44
47
  /** True when tracked files have uncommitted changes. Untracked files are ignored. */
@@ -79,3 +82,168 @@ export async function showFile(repo, commit, path) {
79
82
  return null;
80
83
  }
81
84
  }
85
+
86
+ const MAX_UNTRACKED = 2000;
87
+
88
+ const gitBuffer = (repo, args) =>
89
+ run("git", args, {
90
+ cwd: repo,
91
+ timeout: 60000,
92
+ maxBuffer: 256 * 1024 * 1024,
93
+ encoding: "buffer",
94
+ }).then(({ stdout }) => stdout);
95
+
96
+ /**
97
+ * Snapshot of the working tree a `check` runs against: HEAD, the diff of
98
+ * tracked files against HEAD (staged and unstaged), and the blob IDs of
99
+ * untracked files that aren't ignored. The same tree always gives the same
100
+ * fingerprint, and any edit to a tracked or untracked file changes it.
101
+ * `complete` is false when some untracked files could not be hashed.
102
+ */
103
+ export async function worktreeSnapshot(repo) {
104
+ const { createHash } = await import("node:crypto");
105
+ const head = (await resolveCommit(repo, "HEAD")) ?? "unborn";
106
+ const diff = await gitBuffer(repo, [
107
+ "diff",
108
+ "HEAD",
109
+ "--binary",
110
+ "--no-ext-diff",
111
+ "--no-color",
112
+ ]).catch(
113
+ // No HEAD yet: every tracked file is staged, so diff the index instead.
114
+ () => gitBuffer(repo, ["diff", "--cached", "--binary", "--no-ext-diff", "--no-color"]),
115
+ );
116
+ const tracked = createHash("sha256")
117
+ .update("head\0" + head + "\0diff\0")
118
+ .update(diff)
119
+ .digest("hex");
120
+ const listed = (
121
+ await gitBuffer(repo, ["ls-files", "--others", "--exclude-standard", "-z"])
122
+ ).toString("utf8");
123
+ const names = listed.split("\0").filter(Boolean).sort();
124
+ // hash-object reads one path per line, so a name with a newline can't be hashed.
125
+ const hashed = names.filter((path) => !path.includes("\n")).slice(0, MAX_UNTRACKED);
126
+ const untracked = new Map();
127
+ if (hashed.length) {
128
+ const ids = await new Promise((done, fail) => {
129
+ const child = execFile(
130
+ "git",
131
+ ["hash-object", "--no-filters", "--stdin-paths"],
132
+ { cwd: repo, timeout: 60000, maxBuffer: 8 * 1024 * 1024 },
133
+ (error, stdout) => (error ? fail(error) : done(stdout.trim().split("\n"))),
134
+ );
135
+ child.stdin.end(hashed.join("\n") + "\n");
136
+ });
137
+ hashed.forEach((path, index) => untracked.set(path, ids[index] ?? ""));
138
+ }
139
+ const hash = createHash("sha256").update("tracked\0" + tracked + "\0untracked\0" + names.length);
140
+ for (const [path, id] of untracked) hash.update("\0" + path + "\0" + id);
141
+ return {
142
+ fingerprint: hash.digest("hex"),
143
+ tracked,
144
+ untracked,
145
+ complete: hashed.length === names.length,
146
+ };
147
+ }
148
+
149
+ /**
150
+ * True when `after` no longer matches the tree `before` described: a tracked
151
+ * file changed, or an untracked file that existed before was edited or
152
+ * removed. New untracked files are ignored, because test runners create
153
+ * caches (__pycache__, coverage) in repositories that don't ignore them.
154
+ */
155
+ export const worktreeChanged = (before, after) =>
156
+ before.tracked !== after.tracked ||
157
+ [...before.untracked].some(([path, id]) => after.untracked.get(path) !== id);
158
+
159
+ /** Every file tracked at a commit, as repository-relative paths. */
160
+ export async function filesAtCommit(repo, commit) {
161
+ const out = await gitBuffer(repo, ["ls-tree", "-r", "-z", "--name-only", "--full-tree", commit]);
162
+ return out.toString("utf8").split("\0").filter(Boolean);
163
+ }
164
+
165
+ /**
166
+ * True when `ancestor` is on `commit`'s own line of history (first parents
167
+ * only). A commit that arrived through a merge doesn't count: a merge can
168
+ * bring in a side commit without taking any of its files.
169
+ */
170
+ export async function onFirstParentLine(repo, ancestor, commit) {
171
+ try {
172
+ const line = await gitBuffer(repo, ["rev-list", "--first-parent", commit, "--"]);
173
+ return line.toString("utf8").split("\n").includes(ancestor);
174
+ } catch {
175
+ return false;
176
+ }
177
+ }
178
+
179
+ /** Symlinks tracked at a commit, as `path -> target text`. */
180
+ async function symlinksAtCommit(repo, commit) {
181
+ const out = await gitBuffer(repo, ["ls-tree", "-r", "-z", "--full-tree", commit]);
182
+ const links = new Map();
183
+ for (const entry of out.toString("utf8").split("\0")) {
184
+ const match = entry.match(/^120000 blob ([0-9a-f]+)\t([\s\S]+)$/);
185
+ if (match)
186
+ links.set(match[2], (await gitBuffer(repo, ["cat-file", "blob", match[1]])).toString("utf8"));
187
+ }
188
+ return links;
189
+ }
190
+
191
+ /**
192
+ * Every repository path read when opening `link`: each link passed through,
193
+ * including linked folders partway along a target, and the final path. Targets
194
+ * outside the repository end the walk.
195
+ */
196
+ function pathsBehind(link, links) {
197
+ const seen = [];
198
+ let done = link.split("/").slice(0, -1);
199
+ let rest = [link.split("/").at(-1)];
200
+ // The limit stops link cycles.
201
+ for (let hops = 0; rest.length;) {
202
+ const part = rest.shift();
203
+ if (part === "" || part === ".") continue;
204
+ if (part === "..") {
205
+ if (!done.length) return seen;
206
+ done.pop();
207
+ continue;
208
+ }
209
+ const path = [...done, part].join("/");
210
+ const target = links.get(path);
211
+ if (target === undefined) {
212
+ done.push(part);
213
+ continue;
214
+ }
215
+ seen.push(path);
216
+ if (posix.isAbsolute(target) || ++hops > 40) return seen;
217
+ rest = [...target.split("/"), ...rest];
218
+ }
219
+ seen.push(done.join("/"));
220
+ return seen;
221
+ }
222
+
223
+ /**
224
+ * Symlinks that lead to something changed between two commits although the link
225
+ * itself did not. A config or test file that is a link can be rewritten this
226
+ * way without its own name appearing in the diff.
227
+ */
228
+ export async function changedThroughLinks(repo, from, to, changed) {
229
+ const maps = [await symlinksAtCommit(repo, from), await symlinksAtCommit(repo, to)];
230
+ const touched = new Set(changed);
231
+ const reached = (link, path) =>
232
+ path !== link &&
233
+ (path === ""
234
+ ? touched.size > 0
235
+ : [...touched].some((f) => f === path || f.startsWith(path + "/")));
236
+ const found = [];
237
+ // Repeat so a linked file inside a linked folder is followed to its end.
238
+ for (let added = true; added;) {
239
+ added = false;
240
+ for (const links of maps)
241
+ for (const link of links.keys())
242
+ if (!touched.has(link) && pathsBehind(link, links).some((path) => reached(link, path))) {
243
+ touched.add(link);
244
+ found.push(link);
245
+ added = true;
246
+ }
247
+ }
248
+ return found;
249
+ }
@@ -4,6 +4,7 @@ import {
4
4
  failingTestsFromLog,
5
5
  parseActionsUrl,
6
6
  readCheckoutRevision,
7
+ unreadableFailuresInLog,
7
8
  } from "../../core/src/ci-link.mjs";
8
9
  import { UsageError, BlockedError } from "./errors.mjs";
9
10
 
@@ -132,6 +133,7 @@ export async function resolveActionsLink(
132
133
  commit: checkout.commit,
133
134
  mergeCommit: checkout.merge,
134
135
  failingTests: failingTestsFromLog(log),
136
+ unreadableFailures: unreadableFailuresInLog(log),
135
137
  jobUrl: `https://github.com/${link.repository}/actions/runs/${link.runId}/job/${jobId}`,
136
138
  };
137
139
  }