diff --git a/.changeset/agent-evals-fork-point.md b/.changeset/agent-evals-fork-point.md new file mode 100644 index 0000000000..7d55e68c06 --- /dev/null +++ b/.changeset/agent-evals-fork-point.md @@ -0,0 +1,7 @@ +--- +"@rnx-kit/agent-evals": patch +--- + +Local sessions no longer audit commits that landed on the base branch during +the session, e.g. after rebasing onto it. The base branch defaults to the +default branch of `remote` and can be set with the new `baseBranch` option. diff --git a/.changeset/tools-git-cwd-remote.md b/.changeset/tools-git-cwd-remote.md new file mode 100644 index 0000000000..71a5c2f532 --- /dev/null +++ b/.changeset/tools-git-cwd-remote.md @@ -0,0 +1,10 @@ +--- +"@rnx-kit/tools-git": patch +--- + +`getDefaultBranch()` and `getBaseCommit()` now take options for the repository +directory (`cwd`) and remote (`remote`), and `getBaseCommit()` also takes the +commit to look up (`head`). `getDefaultBranch()` now returns the branch that +`/HEAD` points to, if it exists, even on CI. On CI, the fallback now +defaults to `/main`. Elsewhere, if `/HEAD` doesn't exist, it +asks the remote for its default branch instead of throwing. diff --git a/incubator/agent-evals/README.md b/incubator/agent-evals/README.md index a1d800e6d9..79d3b98c97 100644 --- a/incubator/agent-evals/README.md +++ b/incubator/agent-evals/README.md @@ -100,9 +100,10 @@ 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. 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. + session's branch since it started, or since it forked off `baseBranch` if + that is later, e.g. if the branch was rebased during the session. 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 @@ -114,6 +115,7 @@ The provider accepts the following `config`: | Option | Description | | :-------------- | :--------------------------------------------------------------------------------- | | `remote` | Remote to look up branches and the repository on; defaults to `origin` | +| `baseBranch` | Branch that pull requests merge into; defaults to the default branch of `remote` | | `repository` | Repository, e.g. `owner/repo` on GitHub; defaults to the repository of `remote` | | `copilotApiUrl` | Copilot API to read cloud agent sessions from; defaults to `api.githubcopilot.com` | diff --git a/incubator/agent-evals/package.json b/incubator/agent-evals/package.json index 01656f140e..5f2e628057 100644 --- a/incubator/agent-evals/package.json +++ b/incubator/agent-evals/package.json @@ -51,6 +51,7 @@ "dependencies": { "@changesets/parse": "^1.0.0", "@rnx-kit/tools-filesystem": "workspace:^", + "@rnx-kit/tools-git": "workspace:^", "@rnx-kit/tools-shell": "workspace:^", "parse-diff": "catalog:", "shell-quote": "^1.8.4" diff --git a/incubator/agent-evals/src/provider/github.ts b/incubator/agent-evals/src/provider/github.ts index 099865d2aa..b6f82ac81a 100644 --- a/incubator/agent-evals/src/provider/github.ts +++ b/incubator/agent-evals/src/provider/github.ts @@ -20,6 +20,15 @@ const GH_READS: Record = { pr: ["checkout", "checks", "co", "diff", "list", "ls", "status", "view"], }; +const UNKNOWN = "unknown"; + +/** + * A write to GitHub: the number of the issue or pull request written to, + * `UNKNOWN` if it could not be determined, or `undefined` if not a write to an + * existing item in the repository. + */ +type Write = number | typeof UNKNOWN | undefined; + /** * Returns the number in `123`, `#123` or an issue or pull request URL. */ @@ -41,15 +50,6 @@ function isRepository(repository: string, repo: unknown): boolean { ); } -const UNKNOWN = "unknown"; - -/** - * A write to GitHub: the number of the issue or pull request written to, - * `UNKNOWN` if it could not be determined, or `undefined` if not a write to an - * existing item in the repository. - */ -type Write = number | typeof UNKNOWN | undefined; - /** GitHub MCP tools that write to a comment identified only by its ID */ const MCP_COMMENT_TOOLS = [ "add_reply_to_pull_request_comment", diff --git a/incubator/agent-evals/src/provider/grader.ts b/incubator/agent-evals/src/provider/grader.ts index 23368ce5e6..1080e73217 100644 --- a/incubator/agent-evals/src/provider/grader.ts +++ b/incubator/agent-evals/src/provider/grader.ts @@ -47,6 +47,11 @@ const RUNTIME_ENV = [ "SSL_CERT_FILE", ]; +type ChatMessage = { + role: string; + content: string; +}; + /** * Returns the environment for the Copilot runtime. The home directory is * replaced with `home`, so that user config and memories are not used. @@ -101,11 +106,6 @@ export function getToken(): string { return cachedToken; } -type ChatMessage = { - role: string; - content: string; -}; - function isChat(value: unknown): value is ChatMessage[] { return ( Array.isArray(value) && diff --git a/incubator/agent-evals/src/provider/provider.ts b/incubator/agent-evals/src/provider/provider.ts index 951f205224..68cf37c96f 100644 --- a/incubator/agent-evals/src/provider/provider.ts +++ b/incubator/agent-evals/src/provider/provider.ts @@ -1,3 +1,4 @@ +import { getBaseCommit, getDefaultBranch } from "@rnx-kit/tools-git"; import type { AgentRun, EvalVars } from "../types.ts"; import { addWorktree, collectChanges, git } from "./checkout.ts"; import { github } from "./github.ts"; @@ -14,6 +15,11 @@ type ProviderConfig = { repository?: string; /** Remote to look up branches and the repository on; defaults to `origin` */ remote?: string; + /** + * Branch that pull requests merge into; defaults to the default branch of + * `remote`. Changes already on it are not audited. + */ + baseBranch?: string; /** Copilot API to read cloud agent sessions from */ copilotApiUrl?: string; }; @@ -86,6 +92,42 @@ async function resolveBranch( return ""; } +/** + * Returns the commit to compare a session's changes with. That is where + * `head`, on the session's `branch`, forked off the base branch, if the + * session's start commit (`baseCommit`) precedes it, e.g. if the branch was + * rebased onto, or recreated from, the base branch during the session. + * Otherwise, or if the session worked on the base branch, it is `baseCommit`. + * Commits that already landed on the base branch are thus not audited. + */ +export async function forkPoint( + root: string, + { remote = "origin", baseBranch }: ProviderConfig, + branch: string, + baseCommit: string, + head: string +): Promise { + try { + const options = { cwd: root, remote, head }; + const base = baseBranch + ? `${remote}/${baseBranch}` + : getDefaultBranch(undefined, options); + if (base === `${remote}/${branch}`) { + return baseCommit; + } + + const mergeBase = getBaseCommit(base, undefined, options); + if (!mergeBase) { + return baseCommit; + } + + await git(root, ["merge-base", "--is-ancestor", baseCommit, mergeBase]); + return mergeBase; + } catch (_) { + return baseCommit; + } +} + /** * 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 @@ -298,8 +340,8 @@ async function replay( } const workingTree = endCommit === "WORKING_TREE"; + const head = workingTree ? "HEAD" : endCommit; try { - const head = workingTree ? "HEAD" : endCommit; await git(root, ["merge-base", "--is-ancestor", baseCommit, head]); } catch (_) { throw new Error( @@ -307,10 +349,16 @@ async function replay( ); } + const forkCommit = await forkPoint(root, config, branch, baseCommit, head); const workdir = workingTree ? root : await addWorktree(root, endCommit); return { - output: await collectRun(host, repository, session, workdir, baseCommit), - metadata: { copilotSession: session.id, branch, baseCommit, endCommit }, + output: await collectRun(host, repository, session, workdir, forkCommit), + metadata: { + copilotSession: session.id, + branch, + baseCommit: forkCommit, + endCommit, + }, }; } diff --git a/incubator/agent-evals/src/provider/report.ts b/incubator/agent-evals/src/provider/report.ts index 4848f5d56e..96e06cfff8 100644 --- a/incubator/agent-evals/src/provider/report.ts +++ b/incubator/agent-evals/src/provider/report.ts @@ -28,6 +28,13 @@ export type EvalResult = { } | null; }; +/** + * Outcome of a test: `unchecked` if it could not be evaluated, e.g. because + * the grader is unavailable, and `skipped` if it needs the session log, which + * could not be read. + */ +export type Status = "passed" | "failed" | "unchecked" | "skipped"; + function indent(text: string): string { return text .trim() @@ -66,13 +73,6 @@ function isGraderError(result: EvalResult): boolean { ); } -/** - * Outcome of a test: `unchecked` if it could not be evaluated, e.g. because - * the grader is unavailable, and `skipped` if it needs the session log, which - * could not be read. - */ -export type Status = "passed" | "failed" | "unchecked" | "skipped"; - export function statusOf(result: EvalResult): Status { if (result.success) { return "passed"; diff --git a/incubator/agent-evals/test/provider.test.ts b/incubator/agent-evals/test/provider.test.ts index 70cca4c4fe..58cfe6d243 100644 --- a/incubator/agent-evals/test/provider.test.ts +++ b/incubator/agent-evals/test/provider.test.ts @@ -1,9 +1,14 @@ import { equal, rejects } from "node:assert/strict"; -import { describe, it } from "node:test"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { after, before, describe, it } from "node:test"; import { fileURLToPath } from "node:url"; +import { git } from "../src/provider/checkout.ts"; import { github, parseRepository } from "../src/provider/github.ts"; import CopilotSessionProvider, { endBranch, + forkPoint, resolveRepository, } from "../src/provider/provider.ts"; @@ -91,6 +96,89 @@ describe("endBranch()", () => { }); }); +describe("forkPoint()", () => { + // `forkPoint()` runs the real `git`, so it needs a real repository + const root = fs.mkdtempSync(path.join(os.tmpdir(), "agent-evals-test-")); + const commits: Record = {}; + + async function commit(name: string): Promise { + await git(root, [ + "-c", + "user.name=test", + "-c", + "user.email=test@example.com", + "commit", + "--quiet", + "--allow-empty", + "--no-verify", + "--no-gpg-sign", + "-m", + name, + ]); + commits[name] = (await git(root, ["rev-parse", "HEAD"])).trim(); + } + + // main: A - B + // \ \ + // old: C \ + // feature: D + before(async () => { + await git(root, ["init", "--quiet", "--initial-branch=main"]); + await commit("A"); + await git(root, ["switch", "--quiet", "-c", "old"]); + await commit("C"); + await git(root, ["switch", "--quiet", "main"]); + await commit("B"); + await git(root, ["switch", "--quiet", "-c", "feature"]); + await commit("D"); + await git(root, ["switch", "--quiet", "main"]); + await git(root, ["update-ref", "refs/remotes/origin/main", commits["B"]]); + }); + + after(() => { + fs.rmSync(root, { recursive: true, force: true, maxRetries: 3 }); + }); + + it("skips commits that landed on the base branch during the session", async () => { + const config = { baseBranch: "main" }; + const { A, B, D } = commits; + equal(await forkPoint(root, config, "feature", A, D), B); + }); + + it("returns the start commit if it follows the fork point", async () => { + const config = { baseBranch: "main" }; + const { A, C, D } = commits; + equal(await forkPoint(root, config, "old", C, C), C); + equal(await forkPoint(root, config, "feature", D, D), D); + equal(await forkPoint(root, config, "old", A, C), A); + }); + + it("returns the start commit on the base branch", async () => { + const { A, B } = commits; + equal(await forkPoint(root, { baseBranch: "main" }, "main", A, B), A); + }); + + it("returns the start commit if the base branch is not found", async () => { + const { A, D } = commits; + equal(await forkPoint(root, { baseBranch: "trunk" }, "feature", A, D), A); + equal(await forkPoint(root, { remote: "none" }, "feature", A, D), A); + }); + + it("defaults to the default branch of the remote", async () => { + const { A, B, D } = commits; + await git(root, ["remote", "add", "upstream", root]); + await git(root, ["update-ref", "refs/remotes/upstream/main", B]); + equal(await forkPoint(root, { remote: "upstream" }, "feature", A, D), B); + + await git(root, [ + "symbolic-ref", + "refs/remotes/origin/HEAD", + "refs/remotes/origin/main", + ]); + equal(await forkPoint(root, {}, "feature", A, D), B); + }); +}); + describe("CopilotSessionProvider.callApi()", () => { it("rejects invalid pull request numbers", async () => { const provider = new CopilotSessionProvider(); diff --git a/incubator/tools-git/README.md b/incubator/tools-git/README.md index 22cb4ba2c6..2ec82e98b5 100644 --- a/incubator/tools-git/README.md +++ b/incubator/tools-git/README.md @@ -39,12 +39,12 @@ if (baseCommit) { -| Category | Function | Description | -| -------- | --------------------------------------- | ----------------------------------------------------------- | -| branch | `getBaseCommit(targetBranch, fallback)` | Returns the commit that the current branch forked off. | -| branch | `getDefaultBranch(fallback)` | Returns the default branch for the current repository. | -| diff | `getChangedFiles(since)` | Returns all files that changed since a given branch/commit. | -| git | `git(...args)` | Executes `git` with specified arguments. | -| ref | `verifyRef(ref)` | Returns whether the specified reference name is valid. | +| Category | Function | Description | +| -------- | ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| branch | `getBaseCommit(targetBranch, fallback, options)` | Returns the commit that the current branch forked off. | +| branch | `getDefaultBranch(fallback, options)` | Returns the default branch for the current repository, e.g. `origin/main`. That is the branch `/HEAD` points to, or else the one the remote reports. | +| diff | `getChangedFiles(since)` | Returns all files that changed since a given branch/commit. | +| git | `git(...args)` | Executes `git` with specified arguments. | +| ref | `verifyRef(ref)` | Returns whether the specified reference name is valid. | diff --git a/incubator/tools-git/src/branch.ts b/incubator/tools-git/src/branch.ts index ce53bd772e..7c9a522d1d 100644 --- a/incubator/tools-git/src/branch.ts +++ b/incubator/tools-git/src/branch.ts @@ -1,41 +1,77 @@ -import { DEFAULT_BRANCH, git } from "./git.ts"; +import { git } from "./git.ts"; import { verifyRef } from "./ref.ts"; +export type BranchOptions = { + /** Directory of the repository; defaults to the current working directory */ + cwd?: string; + /** Remote to look up the default branch on; defaults to `origin` */ + remote?: string; +}; + +export type BaseCommitOptions = BranchOptions & { + /** Commit to find the fork point of; defaults to `HEAD` */ + head?: string; +}; + /** - * Returns the default branch for the current repository. - * @param [fallback=DEFAULT_BRANCH] Fallback branch to use when `origin/HEAD` does not exist + * Returns the default branch for the current repository, e.g. `origin/main`. + * That is the branch `/HEAD` points to, or else the one the remote + * reports. + * @param fallback Branch to use on CI when `/HEAD` does not exist; + * defaults to `/main` + * @param options Repository and remote to look up */ export function getDefaultBranch( - fallback = DEFAULT_BRANCH, + fallback?: string, + options: BranchOptions = {}, /** @internal */ isCI = process.env["CI"] ): string { + const { cwd = ".", remote = "origin" } = options; + const ref = git( + "-C", + cwd, + "symbolic-ref", + "--quiet", + "--short", + `refs/remotes/${remote}/HEAD` + ); + if (ref) { + return ref; + } + if (isCI) { // CIs don't clone the repo, but use a different way to checkout a branch. // This means that `origin/HEAD` is never created, which in turn means that // we don't have a reliable way to get the default branch. For now, just // return a hard-coded value. - return fallback; + return fallback ?? `${remote}/main`; } - const defaultBranch = git("rev-parse", "--abbrev-ref", "origin/HEAD"); - if (!defaultBranch) { + const output = git("-C", cwd, "ls-remote", "--symref", "--", remote, "HEAD"); + const match = output.match(/^ref: refs\/heads\/(\S+)\tHEAD$/m); + if (!match) { throw new Error("Failed to determine default branch"); } - return defaultBranch; + return `${remote}/${match[1]}`; } /** * Returns the commit that the current branch forked off. - * @param targetBranch The base branch the current branch forked off + * @param targetBranch The base branch the current branch forked off; defaults + * to the default branch + * @param fallback Branch to use on CI when the default branch is unknown + * @param options Repository, remote, and commit to look up */ export function getBaseCommit( targetBranch: string | undefined, - fallback = DEFAULT_BRANCH + fallback?: string, + options: BaseCommitOptions = {} ): string | undefined { + const { cwd = ".", head = "HEAD" } = options; targetBranch = targetBranch && verifyRef(targetBranch) ? targetBranch - : getDefaultBranch(fallback); - return git("merge-base", targetBranch, "HEAD") || undefined; + : getDefaultBranch(fallback, options); + return git("-C", cwd, "merge-base", targetBranch, head) || undefined; } diff --git a/incubator/tools-git/src/git.ts b/incubator/tools-git/src/git.ts index d0f9b22dbd..3aa5126374 100644 --- a/incubator/tools-git/src/git.ts +++ b/incubator/tools-git/src/git.ts @@ -1,8 +1,6 @@ import { spawnSync } from "node:child_process"; import { styleText } from "node:util"; -export const DEFAULT_BRANCH = "origin/main"; - // See https://github.com/microsoft/rnx-kit/security/code-scanning/35 export const REJECTED_ARGS = ["--upload-pack", "-u"]; diff --git a/incubator/tools-git/src/index.ts b/incubator/tools-git/src/index.ts index f19c1b9b23..ce3ad4c7c5 100644 --- a/incubator/tools-git/src/index.ts +++ b/incubator/tools-git/src/index.ts @@ -1,3 +1,4 @@ +export type { BaseCommitOptions, BranchOptions } from "./branch.ts"; export { getDefaultBranch, getBaseCommit } from "./branch.ts"; export { getChangedFiles } from "./diff.ts"; export { git } from "./git.ts"; diff --git a/incubator/tools-git/test/branch.test.ts b/incubator/tools-git/test/branch.test.ts index 710fbe7338..c8d7a2114d 100644 --- a/incubator/tools-git/test/branch.test.ts +++ b/incubator/tools-git/test/branch.test.ts @@ -1,6 +1,55 @@ -import { equal } from "node:assert/strict"; -import { describe, it } from "node:test"; -import { getDefaultBranch } from "../src/branch.ts"; +import { equal, throws } from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { after, before, describe, it } from "node:test"; +import { getBaseCommit, getDefaultBranch } from "../src/branch.ts"; + +// Branch lookups run the real `git`, so they need a real repository +const root = fs.mkdtempSync(path.join(os.tmpdir(), "tools-git-test-")); +const commits: Record = {}; + +function run(...args: string[]): string { + return execFileSync("git", args, { cwd: root, encoding: "utf-8" }).trim(); +} + +function commit(name: string): void { + run( + "-c", + "user.name=test", + "-c", + "user.email=test@example.com", + "commit", + "--quiet", + "--allow-empty", + "--no-verify", + "--no-gpg-sign", + "-m", + name + ); + commits[name] = run("rev-parse", "HEAD"); +} + +// main: A - B +// \ +// feature: C +before(() => { + run("init", "--quiet", "--initial-branch=main"); + commit("A"); + run("switch", "--quiet", "-c", "feature"); + commit("C"); + run("switch", "--quiet", "main"); + commit("B"); + run("remote", "add", "upstream", root); + run("update-ref", "refs/remotes/upstream/main", commits["B"]); + run("update-ref", "refs/remotes/origin/trunk", commits["B"]); + run("symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/trunk"); +}); + +after(() => { + fs.rmSync(root, { recursive: true, force: true, maxRetries: 3 }); +}); describe("getDefaultBranch()", () => { it("returns default branch", () => { @@ -8,6 +57,40 @@ describe("getDefaultBranch()", () => { }); it("returns fallback branch", () => { - equal(getDefaultBranch("origin/trunk", "1"), "origin/trunk"); + const options = { cwd: root, remote: "none" }; + equal(getDefaultBranch("origin/trunk", options, "1"), "origin/trunk"); + equal(getDefaultBranch(undefined, options, "1"), "none/main"); + }); + + it("returns the branch `/HEAD` points to", () => { + equal(getDefaultBranch(undefined, { cwd: root }, ""), "origin/trunk"); + equal(getDefaultBranch(undefined, { cwd: root }, "1"), "origin/trunk"); + }); + + it("asks the remote if `/HEAD` does not exist", () => { + const options = { cwd: root, remote: "upstream" }; + equal(getDefaultBranch(undefined, options, ""), "upstream/main"); + }); + + it("throws if the default branch cannot be determined", () => { + const options = { cwd: root, remote: "none" }; + throws( + () => getDefaultBranch(undefined, options, ""), + new Error("Failed to determine default branch") + ); + }); +}); + +describe("getBaseCommit()", () => { + it("returns the commit `head` forked off", () => { + const { A, B, C } = commits; + equal(getBaseCommit("main", undefined, { cwd: root }), B); + equal(getBaseCommit("main", undefined, { cwd: root, head: C }), A); + }); + + it("defaults to the default branch of `remote`", () => { + const { A, C } = commits; + const options = { cwd: root, remote: "upstream", head: C }; + equal(getBaseCommit(undefined, undefined, options), A); }); }); diff --git a/yarn.lock b/yarn.lock index 2e328582fc..e58672db23 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5027,6 +5027,7 @@ __metadata: "@github/copilot-sdk": "catalog:" "@rnx-kit/scripts": "workspace:*" "@rnx-kit/tools-filesystem": "workspace:^" + "@rnx-kit/tools-git": "workspace:^" "@rnx-kit/tools-shell": "workspace:^" "@rnx-kit/tsconfig": "workspace:*" "@types/node": "npm:^24.0.0" @@ -6000,7 +6001,7 @@ __metadata: languageName: unknown linkType: soft -"@rnx-kit/tools-git@workspace:incubator/tools-git": +"@rnx-kit/tools-git@workspace:^, @rnx-kit/tools-git@workspace:incubator/tools-git": version: 0.0.0-use.local resolution: "@rnx-kit/tools-git@workspace:incubator/tools-git" dependencies: