Skip to content

Commit bb1f260

Browse files
tido64Copilot
andcommitted
fix(agent-evals): audit the branch a local session switched to
Local sessions that start on one branch (e.g. `main`) and switch to another were audited on the start branch, which has none of their changes. The provider now takes the branch the session last switched to from the reflog of `HEAD`, and checks that it contains the session's start commit. Reports that audited no changes now warn about it, and are replaced by the workflow's audit of the diff. Also adds a PR description guideline to AGENTS.md. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 64b1994 commit bb1f260

12 files changed

Lines changed: 259 additions & 18 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"@rnx-kit/agent-evals": patch
3+
---
4+
5+
Audit the branch a local session last switched to, under its current name,
6+
instead of the branch it started on

‎AGENTS.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,25 @@ action creates a release PR or publishes to npm.
145145
Don't add change files for private packages (`"private": true`), e.g.
146146
`@rnx-kit/template` and test apps.
147147

148+
### Pull Request Descriptions
149+
150+
Follow `.github/pull_request_template.md`. Write the description for reviewers
151+
and users: give an overview of the change and explain the reasoning behind it,
152+
such as the motivation, alternatives considered and why they were rejected,
153+
breaking changes, and user-facing impact. Skip implementation details that can
154+
be inferred from the diff, such as file-by-file summaries or how the code was
155+
changed.
156+
157+
### Reviewing Pull Requests
158+
159+
Verify each finding before reporting it. Reproduce it with a test, a command or
160+
the relevant source (including dependencies in `node_modules`), and cite the
161+
evidence. Don't report a finding based only on how the code might behave, for
162+
example assuming what a token can access, what shape a dependency's output has,
163+
or that a third-party service or API is still available. If a finding can't be
164+
verified, say so and explain what would confirm it, or leave it out. Order
165+
findings by impact, and separate confirmed bugs from suggestions.
166+
148167
## Key Packages
149168

150169
- **`@rnx-kit/cli`** - Main CLI (`rnx-cli`) integrating all tools

‎evals/README.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,9 @@ requests that Copilot, Claude or Cursor created or co-authored. It runs
3535
`yarn eval:report <number>` with `GITHUB_TOKEN`, which cannot read the session
3636
logs, so it can only audit the changes. If the comment already has a report with
3737
the session log for the latest commit, the workflow skips the audit. Only
38-
reports by the author of the pull request and the workflow count. The workflow
39-
only reports; failed rules do not fail the check.
38+
reports by the workflow and by the account running `yarn eval:report` (in the
39+
workflow, the author of the pull request) count. The workflow only reports;
40+
failed rules do not fail the check.
4041

4142
## Adding rules
4243

‎evals/promptfooconfig.yaml‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,14 @@ prompts:
44
- "{{copilotSession}}"
55
providers:
66
# Replays a Copilot session from its event log in `$COPILOT_HOME` (default:
7-
# `~/.copilot`) and compares the session's branch with the commit the
8-
# session started from: the working tree if the branch is checked out, or
9-
# else the tip of the branch, local or on `config.remote` (default: `origin`),
10-
# in a temporary worktree. Looks up modified issues and pull requests, and
11-
# the author of the pull request for the session's branch, with `gh` in
12-
# `config.repository` (default: the GitHub repository of the remote).
7+
# `~/.copilot`) and compares the session's branch (the one it last switched
8+
# to, according to the reflog of `HEAD`, or else the one it started on, under
9+
# the name it was last renamed to) with the commit the session started from:
10+
# the working tree if the branch is checked out, or else the tip of the
11+
# branch, local or on `config.remote` (default: `origin`), in a temporary
12+
# worktree. Looks up modified issues and pull requests, and the author of the
13+
# pull request for the session's branch, with `gh` in `config.repository`
14+
# (default: the GitHub repository of the remote).
1315
- id: file://src/provider.ts
1416
label: copilot-session
1517
defaultTest:

‎evals/src/post-report.ts‎

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import * as os from "node:os";
2020
import * as path from "node:path";
2121
import { fileURLToPath } from "node:url";
2222
import {
23+
auditedNoChanges,
2324
findReport,
2425
formatComment,
2526
markFailed,
@@ -28,7 +29,7 @@ import {
2829
import type { Comment } from "./report-comment.ts";
2930

3031
type Result = EvalResult & {
31-
response?: { metadata?: { endCommit?: string } };
32+
response?: { output?: unknown; metadata?: { endCommit?: string } };
3233
};
3334

3435
/** Subset of the file that `promptfoo eval --output <file>.json` writes */
@@ -73,6 +74,21 @@ function auditedCommit(results: Result[]): string | undefined {
7374
return git("rev-parse", "HEAD").trim();
7475
}
7576

77+
/**
78+
* Returns the login that comments will be posted as, which may differ from the
79+
* author of the pull request, e.g. when an agent opened it on behalf of a user.
80+
*/
81+
function commenter(number: number): string {
82+
try {
83+
return gh("api", "user", "--jq", ".login").trim();
84+
} catch (_) {
85+
// GitHub App installation tokens cannot read `/user`; the agent posts as
86+
// the author of its pull request. Unlike `gh pr view`, this matches the
87+
// logins of comments, e.g. `Copilot`
88+
return ghApi(`pulls/${number}`, "--jq", ".user.login").trim();
89+
}
90+
}
91+
7692
function findComment(
7793
number: number | string,
7894
author: string
@@ -103,8 +119,7 @@ function main(args: string[]): void {
103119
const pr = JSON.parse(
104120
gh("pr", "view", ...(number ? [number] : []), "--json", "number,headRefOid")
105121
) as { number: number; headRefOid: string };
106-
// Unlike `gh pr view`, matches the logins of comments, e.g. `Copilot`
107-
const author = ghApi(`pulls/${pr.number}`, "--jq", ".user.login").trim();
122+
const author = commenter(pr.number);
108123

109124
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "agent-evals-"));
110125
try {
@@ -143,8 +158,11 @@ function main(args: string[]): void {
143158
const audited = auditedCommit(results);
144159
// Without the session, every rule is skipped or unchecked
145160
const statuses = results.map(statusOf);
161+
// Without changes, the workflow should replace the report with an audit
162+
// of the diff
146163
hasLog =
147164
audited === pr.headRefOid &&
165+
!auditedNoChanges(results) &&
148166
!statuses.includes("skipped") &&
149167
(statuses.includes("passed") || statuses.includes("failed"));
150168
body = formatComment(results, pr.headRefOid, audited, hasLog, pr.number);

‎evals/src/report-comment.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,25 @@ export function findReport(
4545
return fallback;
4646
}
4747

48+
type AuditResult = EvalResult & { response?: { output?: unknown } };
49+
50+
/**
51+
* Returns whether the audit found no changed files. The provider's output is
52+
* an `AgentRun`, which promptfoo may have serialized.
53+
*/
54+
export function auditedNoChanges(results: AuditResult[]): boolean {
55+
const result = results.find((result) => result.response?.output);
56+
if (!result) {
57+
return false;
58+
}
59+
60+
const output = result.response?.output;
61+
const run = typeof output === "string" ? JSON.parse(output) : output;
62+
return Array.isArray(run?.files) && run.files.length === 0;
63+
}
64+
4865
export function formatComment(
49-
results: EvalResult[] | undefined,
66+
results: AuditResult[] | undefined,
5067
head: string,
5168
audited: string | undefined,
5269
hasLog: boolean,
@@ -72,6 +89,13 @@ export function formatComment(
7289
"- Copilot CLI: `yarn eval:report` on the branch, on the machine that ran the session"
7390
);
7491
}
92+
if (results && auditedNoChanges(results)) {
93+
lines.push(
94+
"",
95+
"> [!WARNING]",
96+
"> This audited no changes, so the rules had nothing to check. If the session made changes, check out its branch and run `yarn eval:report` again."
97+
);
98+
}
7599
const subject = audited ?? "uncommitted changes";
76100
if (results && audited !== head) {
77101
lines.push(

‎evals/test/report-comment.test.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type { EvalResult } from "@rnx-kit/agent-evals/report";
22
import { equal, match } from "node:assert/strict";
33
import { describe, it } from "node:test";
44
import {
5+
auditedNoChanges,
56
findReport,
67
formatComment,
78
markFailed,
@@ -72,6 +73,20 @@ describe("findReport()", () => {
7273
});
7374
});
7475

76+
describe("auditedNoChanges()", () => {
77+
it("returns whether the provider's output has no changed files", () => {
78+
const withOutput = (output: unknown) => [
79+
{ ...passed, response: { output } },
80+
];
81+
82+
equal(auditedNoChanges(withOutput({ files: [] })), true);
83+
equal(auditedNoChanges(withOutput(JSON.stringify({ files: [] }))), true);
84+
equal(auditedNoChanges(withOutput({ files: [{ path: "a" }] })), false);
85+
// Without output, e.g. if the provider failed, nothing is known
86+
equal(auditedNoChanges([passed]), false);
87+
});
88+
});
89+
7590
describe("formatComment()", () => {
7691
it("starts with the marker", () => {
7792
const body = formatComment([passed], HEAD, HEAD, true, 1);
@@ -98,6 +113,20 @@ describe("formatComment()", () => {
98113
match(dirty, /<sub>Audited uncommitted changes\./);
99114
});
100115

116+
it("warns if the audit found no changes", () => {
117+
const output = (files: string[]) => ({
118+
...passed,
119+
response: { output: { files } },
120+
});
121+
const empty = formatComment([output([])], HEAD, HEAD, false, 1);
122+
123+
match(empty, /This audited no changes/);
124+
125+
const changed = formatComment([output(["a.ts"])], HEAD, HEAD, true, 1);
126+
127+
equal(changed.includes("This audited no changes"), false);
128+
});
129+
101130
it("says so if the audit did not produce a report", () => {
102131
const body = formatComment(undefined, HEAD, undefined, false, 1);
103132

‎incubator/agent-evals/README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,9 @@ it changed, and its requests and replies. What it audits depends on the vars:
100100
(default: `~/.copilot`). If empty, the session running the evals, or if there
101101
is none, the most recently updated session in the repository that is not in
102102
use; `previous` always picks the latter. The changes are those on the
103-
session's branch since it started.
103+
session's branch since it started. The session's branch is the one it last
104+
switched to, according to the reflog of `HEAD`, or else the one it started
105+
on, under the name it was last renamed to.
104106
- `pullRequest`: number of a pull request. Its Copilot cloud agent sessions are
105107
read from GitHub, and the changes are those since it branched off its base
106108
branch. If the sessions cannot be read, e.g. if the pull request was made in

‎incubator/agent-evals/src/provider/provider.ts‎

Lines changed: 78 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,70 @@ async function resolveBranch(
9494
return "";
9595
}
9696

97+
/**
98+
* Returns the branch the session ended on, given the branch it started on,
99+
* when it ran (`startTime` to `endTime`, in milliseconds since the epoch), and
100+
* the output of `git reflog show --date=unix --format=%gd%x09%gs`, which lists
101+
* the newest entry first. That is the branch the session last switched to, if
102+
* any, under the name it was last renamed to, even after the session.
103+
*/
104+
export function endBranch(
105+
reflog: string,
106+
startBranch: string | undefined,
107+
startTime: number,
108+
endTime: number
109+
): string | undefined {
110+
const start = Math.floor(startTime / 1000);
111+
const end = Math.ceil(endTime / 1000);
112+
let branch = startBranch;
113+
for (const line of reflog.split("\n").reverse()) {
114+
// Refs cannot contain spaces; matching `\S+` keeps this linear
115+
const match = line.match(
116+
/^[^@]*@\{(\d+)\}\t(?:checkout: moving from \S+ to (\S+)|Branch: renamed refs\/heads\/(\S+) to refs\/heads\/(\S+))$/
117+
);
118+
const time = Number(match?.[1]);
119+
if (!match || time < start) {
120+
continue;
121+
}
122+
123+
if (match[2] !== undefined) {
124+
if (time <= end) {
125+
branch = match[2];
126+
}
127+
} else if (match[3] === branch) {
128+
branch = match[4];
129+
}
130+
}
131+
return branch;
132+
}
133+
134+
/**
135+
* Returns the branch the session ended on, according to the reflog of `HEAD`
136+
* in `root`, or else the branch it started on. Branch switches by others while
137+
* the session ran are attributed to the session.
138+
*/
139+
async function sessionBranch(
140+
root: string,
141+
{ branch, startTime, endTime }: Session
142+
): Promise<string | undefined> {
143+
if (startTime === undefined || endTime === undefined) {
144+
return branch;
145+
}
146+
147+
try {
148+
const reflog = await git(root, [
149+
"reflog",
150+
"show",
151+
"--date=unix",
152+
"--format=%gd%x09%gs",
153+
"HEAD",
154+
]);
155+
return endBranch(reflog, branch, startTime, endTime);
156+
} catch (_) {
157+
return branch;
158+
}
159+
}
160+
97161
async function collectRun(
98162
repository: string,
99163
session: Pick<
@@ -224,7 +288,9 @@ async function replay(
224288
throw new Error(`Session ${session.id} did not record its start commit`);
225289
}
226290

227-
const { branch } = session;
291+
// The session may have started on another branch, e.g. `main`, and
292+
// switched to the branch of its pull request later
293+
const branch = await sessionBranch(root, session);
228294
if (!branch) {
229295
throw new Error(`Session ${session.id} did not record its branch`);
230296
}
@@ -243,7 +309,6 @@ async function replay(
243309
// (local, or else on the remote) in a temporary worktree.
244310
const remote = config.remote ?? "origin";
245311
const repository = await resolveRepository(root, config);
246-
let workdir = root;
247312
let endCommit = "WORKING_TREE";
248313
const current = (await git(root, ["branch", "--show-current"])).trim();
249314
if (current !== branch) {
@@ -253,9 +318,19 @@ async function replay(
253318
`Branch '${branch}' of session ${session.id} was not found locally or on '${remote}'`
254319
);
255320
}
256-
workdir = await addWorktree(root, endCommit);
257321
}
258322

323+
const workingTree = endCommit === "WORKING_TREE";
324+
try {
325+
const head = workingTree ? "HEAD" : endCommit;
326+
await git(root, ["merge-base", "--is-ancestor", baseCommit, head]);
327+
} catch (_) {
328+
throw new Error(
329+
`Branch '${branch}' does not contain start commit ${baseCommit} of session ${session.id}`
330+
);
331+
}
332+
333+
const workdir = workingTree ? root : await addWorktree(root, endCommit);
259334
return {
260335
output: await collectRun(repository, session, workdir, baseCommit),
261336
metadata: { copilotSession: session.id, branch, baseCommit, endCommit },

‎incubator/agent-evals/src/provider/session.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ const ps = makeCommandSync("ps");
1919
* Note: The file format is not documented; these match `SessionEvent` in
2020
* `@github/copilot-sdk`.
2121
*/
22-
export type SessionEvent =
22+
export type SessionEvent = { timestamp?: string } & (
2323
| {
2424
type: "session.start" | "session.resume";
2525
data: {
@@ -43,7 +43,8 @@ export type SessionEvent =
4343
mcpToolName?: string;
4444
};
4545
}
46-
| { type: "other"; data: unknown };
46+
| { type: "other"; data: unknown }
47+
);
4748

4849
export type SessionToolCall = AgentToolCall & {
4950
/** Name of the MCP server providing the tool, if any */
@@ -62,6 +63,10 @@ export type Session = {
6263
branch?: string;
6364
/** Commit checked out when the session started */
6465
baseCommit?: string;
66+
/** When the session started, in milliseconds since the epoch */
67+
startTime?: number;
68+
/** When the session last recorded an event, in milliseconds since the epoch */
69+
endTime?: number;
6570
/** Inputs to shell tools, in order */
6671
shellInputs: string[];
6772
/** Calls to other tools, in order */
@@ -269,6 +274,11 @@ export function applyEvents(
269274
): void {
270275
const toolCallIds = new Set<string>();
271276
for (const event of events) {
277+
const time = event?.timestamp ? Date.parse(event.timestamp) : NaN;
278+
if (!Number.isNaN(time)) {
279+
session.endTime = time;
280+
}
281+
272282
switch (event?.type) {
273283
case "session.start":
274284
case "session.resume": {
@@ -277,6 +287,7 @@ export function applyEvents(
277287
session.root = context?.gitRoot ?? context?.cwd ?? session.root;
278288
session.cwd = context?.cwd ?? session.root;
279289
session.baseCommit = context?.headCommit;
290+
session.startTime = Number.isNaN(time) ? undefined : time;
280291
}
281292
session.branch = context?.branch ?? session.branch;
282293
break;

0 commit comments

Comments
 (0)