diff --git a/.changeset/agent-evals-end-branch.md b/.changeset/agent-evals-end-branch.md new file mode 100644 index 0000000000..45bfad003f --- /dev/null +++ b/.changeset/agent-evals-end-branch.md @@ -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 diff --git a/AGENTS.md b/AGENTS.md index 429b10780f..526f445d9a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 diff --git a/evals/README.md b/evals/README.md index aba6002852..e6070f3125 100644 --- a/evals/README.md +++ b/evals/README.md @@ -35,8 +35,9 @@ requests that Copilot, Claude or Cursor created or co-authored. It runs `yarn eval:report ` 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 diff --git a/evals/promptfooconfig.yaml b/evals/promptfooconfig.yaml index 4a867f5854..3dcbf78822 100644 --- a/evals/promptfooconfig.yaml +++ b/evals/promptfooconfig.yaml @@ -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: diff --git a/evals/src/post-report.ts b/evals/src/post-report.ts index 1da82d1a40..92f97c91ec 100644 --- a/evals/src/post-report.ts +++ b/evals/src/post-report.ts @@ -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, @@ -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 .json` writes */ @@ -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 @@ -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 { @@ -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); diff --git a/evals/src/report-comment.ts b/evals/src/report-comment.ts index 7f86f9e674..ef348cb803 100644 --- a/evals/src/report-comment.ts +++ b/evals/src/report-comment.ts @@ -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, @@ -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( diff --git a/evals/test/report-comment.test.ts b/evals/test/report-comment.test.ts index 6b4c520ad2..2c78121d18 100644 --- a/evals/test/report-comment.test.ts +++ b/evals/test/report-comment.test.ts @@ -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, @@ -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); @@ -98,6 +113,20 @@ describe("formatComment()", () => { match(dirty, /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); diff --git a/evals/tests/audit.yaml b/evals/tests/audit.yaml index 01b675ed40..2bfa711eba 100644 --- a/evals/tests/audit.yaml +++ b/evals/tests/audit.yaml @@ -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 } diff --git a/incubator/agent-evals/README.md b/incubator/agent-evals/README.md index b599ca476e..2d57a42f15 100644 --- a/incubator/agent-evals/README.md +++ b/incubator/agent-evals/README.md @@ -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 diff --git a/incubator/agent-evals/src/provider/provider.ts b/incubator/agent-evals/src/provider/provider.ts index 01ab213010..a4c96655a3 100644 --- a/incubator/agent-evals/src/provider/provider.ts +++ b/incubator/agent-evals/src/provider/provider.ts @@ -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+))$/ + ); + 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 { + 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< @@ -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`); } @@ -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) { @@ -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 }, diff --git a/incubator/agent-evals/src/provider/session.ts b/incubator/agent-evals/src/provider/session.ts index 837317d478..d22408f561 100644 --- a/incubator/agent-evals/src/provider/session.ts +++ b/incubator/agent-evals/src/provider/session.ts @@ -19,7 +19,7 @@ const ps = makeCommandSync("ps"); * Note: The file format is not documented; these match `SessionEvent` in * `@github/copilot-sdk`. */ -export type SessionEvent = +export type SessionEvent = { timestamp?: string } & ( | { type: "session.start" | "session.resume"; data: { @@ -43,7 +43,8 @@ export type SessionEvent = mcpToolName?: string; }; } - | { type: "other"; data: unknown }; + | { type: "other"; data: unknown } +); export type SessionToolCall = AgentToolCall & { /** Name of the MCP server providing the tool, if any */ @@ -62,6 +63,10 @@ export type Session = { branch?: string; /** Commit checked out when the session started */ baseCommit?: string; + /** When the session started, in milliseconds since the epoch */ + startTime?: number; + /** When the session last recorded an event, in milliseconds since the epoch */ + endTime?: number; /** Inputs to shell tools, in order */ shellInputs: string[]; /** Calls to other tools, in order */ @@ -269,6 +274,11 @@ export function applyEvents( ): void { const toolCallIds = new Set(); for (const event of events) { + const time = event?.timestamp ? Date.parse(event.timestamp) : NaN; + if (!Number.isNaN(time)) { + session.endTime = time; + } + switch (event?.type) { case "session.start": case "session.resume": { @@ -277,6 +287,7 @@ export function applyEvents( session.root = context?.gitRoot ?? context?.cwd ?? session.root; session.cwd = context?.cwd ?? session.root; session.baseCommit = context?.headCommit; + session.startTime = Number.isNaN(time) ? undefined : time; } session.branch = context?.branch ?? session.branch; break; diff --git a/incubator/agent-evals/test/provider.test.ts b/incubator/agent-evals/test/provider.test.ts index a1632832a9..3ab0b1d1ce 100644 --- a/incubator/agent-evals/test/provider.test.ts +++ b/incubator/agent-evals/test/provider.test.ts @@ -2,6 +2,7 @@ import { equal, rejects } from "node:assert/strict"; import { describe, it } from "node:test"; import { fileURLToPath } from "node:url"; import CopilotSessionProvider, { + endBranch, parseRepository, resolveRepository, } from "../src/provider/provider.ts"; @@ -56,6 +57,37 @@ describe("resolveRepository()", () => { }); }); +describe("endBranch()", () => { + // Newest entry first, as listed by `git reflog` + const reflog = [ + "HEAD@{600}\tBranch: renamed refs/heads/fix/bug to refs/heads/fix/crash", + "HEAD@{500}\tBranch: renamed refs/heads/other to refs/heads/fix/bug", + "HEAD@{400}\tcommit: Fix bug", + "HEAD@{300}\tcheckout: moving from feature to fix/bug", + "HEAD@{200}\tcheckout: moving from main to feature", + "HEAD@{100}\tcheckout: moving from feature to main", + "", + ].join("\n"); + + it("returns the branch of the last checkout during the session", () => { + equal(endBranch(reflog, "main", 150_000, 250_000), "feature"); + // Times are rounded outwards to whole seconds + equal(endBranch(reflog, "main", 200_999, 299_000), "feature"); + equal(endBranch(reflog, "main", 200_999, 299_001), "fix/crash"); + }); + + it("follows renames of the branch, also after the session", () => { + equal(endBranch(reflog, "main", 150_000, 450_000), "fix/crash"); + equal(endBranch(reflog, "fix/bug", 550_000, 650_000), "fix/crash"); + }); + + it("returns the start branch if the session did not switch branches", () => { + equal(endBranch(reflog, "main", 310_000, 450_000), "main"); + equal(endBranch(reflog, "main", 0, 50_000), "main"); + equal(endBranch("", undefined, 0, 500_000), undefined); + }); +}); + describe("CopilotSessionProvider.callApi()", () => { it("rejects invalid pull request numbers", async () => { const provider = new CopilotSessionProvider(); diff --git a/incubator/agent-evals/test/session.test.ts b/incubator/agent-evals/test/session.test.ts index d0b42aec95..e69f3f40b0 100644 --- a/incubator/agent-evals/test/session.test.ts +++ b/incubator/agent-evals/test/session.test.ts @@ -79,6 +79,28 @@ describe("applyEvents()", () => { deepEqual(session.toolCalls, [{ name: "view", arguments: { path: "a" } }]); }); + it("records when the session started and last recorded an event", () => { + const session = newSession("id", "/repo"); + + applyEvents(session, [ + { + type: "session.start", + data: {}, + timestamp: "2026-11-13T10:00:00.000Z", + }, + { type: "user.message", data: { content: "Hi" } }, + { + type: "assistant.message", + data: { content: "Hello" }, + timestamp: "2026-11-13T10:05:00.000Z", + }, + { type: "user.message", data: { content: "Bye" } }, + ]); + + equal(session.startTime, Date.parse("2026-11-13T10:00:00.000Z")); + equal(session.endTime, Date.parse("2026-11-13T10:05:00.000Z")); + }); + it("keeps the root if the session did not record where it started", () => { const session = newSession("id", "/repo");