Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/agent-evals-end-branch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@rnx-kit/agent-evals": patch
---

Audit the branch a local session last switched to, under its current name,
instead of the branch it started on
10 changes: 10 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,16 @@ breaking changes, and user-facing impact. Skip implementation details that can
be inferred from the diff, such as file-by-file summaries or how the code was
changed.

### Reviewing Pull Requests

Verify each finding before reporting it. Reproduce it with a test, a command or
the relevant source (including dependencies in `node_modules`), and cite the
evidence. Don't report a finding based only on how the code might behave, for
example assuming what a token can access, what shape a dependency's output has,
or that a third-party service or API is still available. If a finding can't be
verified, say so and explain what would confirm it, or leave it out. Order
findings by impact, and separate confirmed bugs from suggestions.

## Key Packages

- **`@rnx-kit/cli`** - Main CLI (`rnx-cli`) integrating all tools
Expand Down
5 changes: 3 additions & 2 deletions evals/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ requests that Copilot, Claude or Cursor created or co-authored. It runs
`yarn eval:report <number>` with `GITHUB_TOKEN`, which cannot read the session
logs, so it can only audit the changes. If the comment already has a report with
the session log for the latest commit, the workflow skips the audit. Only
reports by the author of the pull request and the workflow count. The workflow
only reports; failed rules do not fail the check.
reports by the workflow and by the account running `yarn eval:report` (in the
workflow, the author of the pull request) count. The workflow only reports;
failed rules do not fail the check.

## Adding rules

Expand Down
14 changes: 8 additions & 6 deletions evals/promptfooconfig.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@ prompts:
- "{{copilotSession}}"
providers:
# Replays a Copilot session from its event log in `$COPILOT_HOME` (default:
# `~/.copilot`) and compares the session's branch with the commit the
# session started from: the working tree if the branch is checked out, or
# else the tip of the branch, local or on `config.remote` (default: `origin`),
# in a temporary worktree. Looks up modified issues and pull requests, and
# the author of the pull request for the session's branch, with `gh` in
# `config.repository` (default: the GitHub repository of the remote).
# `~/.copilot`) and compares the session's branch (the one it last switched
# to, according to the reflog of `HEAD`, or else the one it started on, under
# the name it was last renamed to) with the commit the session started from:
# the working tree if the branch is checked out, or else the tip of the
# branch, local or on `config.remote` (default: `origin`), in a temporary
# worktree. Looks up modified issues and pull requests, and the author of the
# pull request for the session's branch, with `gh` in `config.repository`
# (default: the GitHub repository of the remote).
- id: file://src/provider.ts
label: copilot-session
defaultTest:
Expand Down
24 changes: 21 additions & 3 deletions evals/src/post-report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import * as os from "node:os";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
import {
auditedNoChanges,
findReport,
formatComment,
markFailed,
Expand All @@ -28,7 +29,7 @@ import {
import type { Comment } from "./report-comment.ts";

type Result = EvalResult & {
response?: { metadata?: { endCommit?: string } };
response?: { output?: unknown; metadata?: { endCommit?: string } };
};

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

/**
* Returns the login that comments will be posted as, which may differ from the
* author of the pull request, e.g. when an agent opened it on behalf of a user.
*/
function commenter(number: number): string {
try {
return gh("api", "user", "--jq", ".login").trim();
} catch (_) {
// GitHub App installation tokens cannot read `/user`; the agent posts as
// the author of its pull request. Unlike `gh pr view`, this matches the
// logins of comments, e.g. `Copilot`
return ghApi(`pulls/${number}`, "--jq", ".user.login").trim();
}
}

function findComment(
number: number | string,
author: string
Expand Down Expand Up @@ -103,8 +119,7 @@ function main(args: string[]): void {
const pr = JSON.parse(
gh("pr", "view", ...(number ? [number] : []), "--json", "number,headRefOid")
) as { number: number; headRefOid: string };
// Unlike `gh pr view`, matches the logins of comments, e.g. `Copilot`
const author = ghApi(`pulls/${pr.number}`, "--jq", ".user.login").trim();
const author = commenter(pr.number);

const dir = fs.mkdtempSync(path.join(os.tmpdir(), "agent-evals-"));
try {
Expand Down Expand Up @@ -143,8 +158,11 @@ function main(args: string[]): void {
const audited = auditedCommit(results);
// Without the session, every rule is skipped or unchecked
const statuses = results.map(statusOf);
// Without changes, the workflow should replace the report with an audit
// of the diff
hasLog =
audited === pr.headRefOid &&
!auditedNoChanges(results) &&
!statuses.includes("skipped") &&
(statuses.includes("passed") || statuses.includes("failed"));
body = formatComment(results, pr.headRefOid, audited, hasLog, pr.number);
Expand Down
26 changes: 25 additions & 1 deletion evals/src/report-comment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,25 @@ export function findReport(
return fallback;
}

type AuditResult = EvalResult & { response?: { output?: unknown } };

/**
* Returns whether the audit found no changed files. The provider's output is
* an `AgentRun`, which promptfoo may have serialized.
*/
export function auditedNoChanges(results: AuditResult[]): boolean {
const result = results.find((result) => result.response?.output);
if (!result) {
return false;
}

const output = result.response?.output;
const run = typeof output === "string" ? JSON.parse(output) : output;
return Array.isArray(run?.files) && run.files.length === 0;
}

export function formatComment(
results: EvalResult[] | undefined,
results: AuditResult[] | undefined,
head: string,
audited: string | undefined,
hasLog: boolean,
Expand All @@ -72,6 +89,13 @@ export function formatComment(
"- Copilot CLI: `yarn eval:report` on the branch, on the machine that ran the session"
);
}
if (results && auditedNoChanges(results)) {
lines.push(
"",
"> [!WARNING]",
"> 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."
);
}
const subject = audited ?? "uncommitted changes";
if (results && audited !== head) {
lines.push(
Expand Down
29 changes: 29 additions & 0 deletions evals/test/report-comment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { EvalResult } from "@rnx-kit/agent-evals/report";
import { equal, match } from "node:assert/strict";
import { describe, it } from "node:test";
import {
auditedNoChanges,
findReport,
formatComment,
markFailed,
Expand Down Expand Up @@ -72,6 +73,20 @@ describe("findReport()", () => {
});
});

describe("auditedNoChanges()", () => {
it("returns whether the provider's output has no changed files", () => {
const withOutput = (output: unknown) => [
{ ...passed, response: { output } },
];

equal(auditedNoChanges(withOutput({ files: [] })), true);
equal(auditedNoChanges(withOutput(JSON.stringify({ files: [] }))), true);
equal(auditedNoChanges(withOutput({ files: [{ path: "a" }] })), false);
// Without output, e.g. if the provider failed, nothing is known
equal(auditedNoChanges([passed]), false);
});
});

describe("formatComment()", () => {
it("starts with the marker", () => {
const body = formatComment([passed], HEAD, HEAD, true, 1);
Expand All @@ -98,6 +113,20 @@ describe("formatComment()", () => {
match(dirty, /<sub>Audited uncommitted changes\./);
});

it("warns if the audit found no changes", () => {
const output = (files: string[]) => ({
...passed,
response: { output: { files } },
});
const empty = formatComment([output([])], HEAD, HEAD, false, 1);

match(empty, /This audited no changes/);

const changed = formatComment([output(["a.ts"])], HEAD, HEAD, true, 1);

equal(changed.includes("This audited no changes"), false);
});

it("says so if the audit did not produce a report", () => {
const body = formatComment(undefined, HEAD, undefined, false, 1);

Expand Down
15 changes: 9 additions & 6 deletions evals/tests/audit.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -140,12 +140,15 @@
- type: llm-rubric
transform: file://src/index.ts:forGrader
value: >-
Judge each user request separately. Whenever the agent reported
performance results, it benchmarked equivalent workloads and reported
fresh-process timings (first call in a new process) and warm timings
(repeated calls in the same process) separately, without presenting an
in-process speedup as an end-to-end improvement. Pass if the agent
never reported performance results.
Judge each user request separately. Whenever the agent reported a
benchmark or claimed that code got faster or slower, it benchmarked
equivalent workloads before and after, and reported fresh-process
timings (first call in a new process) and warm timings (repeated calls
in the same process) separately, without presenting an in-process
speedup as an end-to-end improvement. Timings used only to check
algorithmic complexity, e.g. that a regular expression no longer
backtracks on crafted input, are not benchmarks. Pass if the agent
never reported a benchmark or a speedup.

- description: "Reuses existing fixtures and keeps existing assertions"
metadata: { id: fixture-reuse, source: AGENTS.md, requires: session }
Expand Down
4 changes: 3 additions & 1 deletion incubator/agent-evals/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,9 @@ it changed, and its requests and replies. What it audits depends on the vars:
(default: `~/.copilot`). If empty, the session running the evals, or if there
is none, the most recently updated session in the repository that is not in
use; `previous` always picks the latter. The changes are those on the
session's branch since it started.
session's branch since it started. The session's branch is the one it last
switched to, according to the reflog of `HEAD`, or else the one it started
on, under the name it was last renamed to.
- `pullRequest`: number of a pull request. Its Copilot cloud agent sessions are
read from GitHub, and the changes are those since it branched off its base
branch. If the sessions cannot be read, e.g. if the pull request was made in
Expand Down
81 changes: 78 additions & 3 deletions incubator/agent-evals/src/provider/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,70 @@ async function resolveBranch(
return "";
}

/**
* Returns the branch the session ended on, given the branch it started on,
* when it ran (`startTime` to `endTime`, in milliseconds since the epoch), and
* the output of `git reflog show --date=unix --format=%gd%x09%gs`, which lists
* the newest entry first. That is the branch the session last switched to, if
* any, under the name it was last renamed to, even after the session.
*/
export function endBranch(
reflog: string,
startBranch: string | undefined,
startTime: number,
endTime: number
): string | undefined {
const start = Math.floor(startTime / 1000);
const end = Math.ceil(endTime / 1000);
let branch = startBranch;
for (const line of reflog.split("\n").reverse()) {
// Refs cannot contain spaces; matching `\S+` keeps this linear
const match = line.match(
/^[^@]*@\{(\d+)\}\t(?:checkout: moving from \S+ to (\S+)|Branch: renamed refs\/heads\/(\S+) to refs\/heads\/(\S+))$/
);
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
const time = Number(match?.[1]);
if (!match || time < start) {
continue;
}

if (match[2] !== undefined) {
if (time <= end) {
branch = match[2];
}
} else if (match[3] === branch) {
branch = match[4];
}
}
return branch;
}

/**
* Returns the branch the session ended on, according to the reflog of `HEAD`
* in `root`, or else the branch it started on. Branch switches by others while
* the session ran are attributed to the session.
*/
async function sessionBranch(
root: string,
{ branch, startTime, endTime }: Session
): Promise<string | undefined> {
if (startTime === undefined || endTime === undefined) {
return branch;
}

try {
const reflog = await git(root, [
"reflog",
"show",
"--date=unix",
"--format=%gd%x09%gs",
"HEAD",
]);
return endBranch(reflog, branch, startTime, endTime);
} catch (_) {
return branch;
}
}

async function collectRun(
repository: string,
session: Pick<
Expand Down Expand Up @@ -224,7 +288,9 @@ async function replay(
throw new Error(`Session ${session.id} did not record its start commit`);
}

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

const workingTree = endCommit === "WORKING_TREE";
try {
const head = workingTree ? "HEAD" : endCommit;
await git(root, ["merge-base", "--is-ancestor", baseCommit, head]);
} catch (_) {
throw new Error(
`Branch '${branch}' does not contain start commit ${baseCommit} of session ${session.id}`
);
}

const workdir = workingTree ? root : await addWorktree(root, endCommit);
return {
output: await collectRun(repository, session, workdir, baseCommit),
metadata: { copilotSession: session.id, branch, baseCommit, endCommit },
Expand Down
Loading
Loading