Skip to content

An open-source, faster Devin alternative

TypeScript

Work index: take an advance's commits from compare, so a merged branch's commits are detailed

Igor Zalutski via Computerc932e0d200b6
diff --git a/services/managed-agents/src/computer/work/github.ts b/services/managed-agents/src/computer/work/github.ts
index 5e9624b0..ed9555ae 100644
--- a/services/managed-agents/src/computer/work/github.ts
+++ b/services/managed-agents/src/computer/work/github.ts
@@ -121,6 +121,8 @@ export interface CommitInfo {
authorEmail: string | null;
/** The author date, ISO; null when GitHub gave none. */
at: string | null;
+ /** More than one parent: its files against the first parent repeat the merged branch's. */
+ merge: boolean;
}
export interface FileChange {
@@ -407,11 +409,11 @@ export class WorkGitHub {
}
/**
- * `base...head`, one page of PER_PAGE_MAX commits (the oldest) and at most 300 files; null when
- * GitHub no longer knows `base` (a rewritten history).
+ * `base...head`, one page of PER_PAGE_MAX commits (oldest first; page 1 the oldest) and, on the
+ * first page, at most 300 files; null when GitHub no longer knows `base` (a rewritten history).
*/
- async compare(base: string, head: string): Promise<Comparison | null> {
- const answer = await this.request(this.repoPath(`/compare/${base}...${head}?per_page=${PER_PAGE_MAX}`));
+ async compare(base: string, head: string, page = 1): Promise<Comparison | null> {
+ const answer = await this.request(this.repoPath(`/compare/${base}...${head}?per_page=${PER_PAGE_MAX}${page > 1 ? `&page=${page}` : ""}`));
if (answer.status === 404) return null;
const body = this.json<{ status?: unknown; total_commits?: unknown; commits?: unknown; files?: unknown }>(answer);
const status = body.status;
@@ -568,7 +570,7 @@ function grantedOf(raw: unknown): GrantedRepository | null {
}
function commitOf(raw: unknown): CommitInfo | null {
- const c = raw as { sha?: unknown; commit?: { message?: unknown; author?: { name?: unknown; email?: unknown; date?: unknown } } };
+ const c = raw as { sha?: unknown; parents?: unknown; commit?: { message?: unknown; author?: { name?: unknown; email?: unknown; date?: unknown } } };
if (typeof c?.sha !== "string" || typeof c.commit?.message !== "string") return null;
const author = c.commit.author;
const at = typeof author?.date === "string" && Number.isFinite(Date.parse(author.date)) ? author.date : null;
@@ -578,6 +580,7 @@ function commitOf(raw: unknown): CommitInfo | null {
authorName: typeof author?.name === "string" ? author.name : "",
authorEmail: typeof author?.email === "string" ? author.email : null,
at,
+ merge: Array.isArray(c.parents) && c.parents.length > 1,
};
}
diff --git a/services/managed-agents/src/computer/work/index.ts b/services/managed-agents/src/computer/work/index.ts
index 8ac6b0d7..c2e292c3 100644
--- a/services/managed-agents/src/computer/work/index.ts
+++ b/services/managed-agents/src/computer/work/index.ts
@@ -10,16 +10,19 @@
// 3. The blobs of the changed items only, then rows, files and the cursor in one transaction.
// Changed rows lose `updatedAt`, a new close loses `closedAt`/`closedBy`: null until the walk
// fills them, never a guess. A range of one commit fills them at once from compare's files.
-// 4. The walk (below) gets the range: a page of each changed folder's commits and up to
-// ADVANCE_DETAILS commit details now, the rest from the alarm.
+// 4. The walk (below) gets the range when it changed an item file: compare's commits (the first
+// page is in hand, the rest are a range task) and up to ADVANCE_DETAILS commit details now,
+// the rest from the alarm. The range is compare's, not the folders' listings back to a commit
+// already listed: those are ordered by date, and a merged branch's commits dated before the
+// cursor would be missed. Merge commits are not detailed: their files repeat the branch's.
// Whatever the range's size, an advance never rebuilds and stays within those calls.
// - Build (no cursor, or a rewritten history): list the two folders at the head; open items are
// read in batches of 50 continued by the alarm, and the cursor is set when they are done. Closed
// items get a row from the listing and are read when a page of them is asked for. Dates,
// authors and links come from the walk.
-// - The walk: `commits?path=work` and `commits?path=done` from a head, back to the newest commit of
-// that folder already listed (a page of 100 at a time); then each listed commit's files (one call
-// each, newest first, within the quota). A commit's files give its items' revisions (history),
+// - The walk: after a build, `commits?path=work` and `commits?path=done` from its head to the root
+// (a page of 100 at a time); after an advance, the range's commits from compare. Then each listed
+// commit's files (one call each, newest first, within the quota). A commit's files give its items' revisions (history),
// links (`Session:` trailers), the add (author, created), the move into done/ (closed) and the
// latest change (updated).
// - Duplicate numbers: `files` holds every item file at the cursor; the row of a number is its open
@@ -198,15 +201,17 @@ const DIRS: Dir[] = ["work", "done"];
interface StoredRepo extends WorkRepo {}
/**
- * The walk's listing of one folder's commits: from `head` back to the first commit already listed
- * for that folder (everything older is listed, or is the range of a task still running).
+ * The walk's listing: one folder's commits from a build's `head` back to the first commit already
+ * listed for that folder, or (`range`) an advance's commits `base...head` from compare.
*/
-interface WalkTask {
+interface DirTask {
+ kind?: "dir";
dir: Dir;
head: string;
/** The next page to ask. */
page: number;
}
+type WalkTask = DirTask | { kind: "range"; base: string; head: string; page: number };
interface WalkState {
tasks: WalkTask[];
@@ -1003,8 +1008,9 @@ export class WorkIndex {
if (only) {
this.apply(only, cmp.files);
this.store.exec("UPDATE commits SET listed = ? WHERE sha = ?", [...touchedDirs].map((d) => `,${d},`).join(""), only.sha);
- } else {
- for (const dir of touchedDirs) addTask(walk, dir, head);
+ } else if (touchedDirs.size) {
+ for (const c of cmp.commits) this.listCommit(c);
+ if (cmp.totalCommits > cmp.commits.length) walk.tasks.unshift({ kind: "range", base, head, page: 2 });
}
this.setMeta("walk", JSON.stringify(walk));
this.setMeta("dirs", dirsNow ? JSON.stringify(dirsNow) : null);
@@ -1012,8 +1018,8 @@ export class WorkIndex {
this.setMeta("as_of", this.now());
this.bump();
});
- // The range's commits: a page of each folder and a few details now, the rest from the alarm.
- if (!only && touchedDirs.size) await this.walkStep(touchedDirs.size, ADVANCE_DETAILS);
+ // The range's commits: a page more of them and a few details now, the rest from the alarm.
+ if (!only && touchedDirs.size) await this.walkStep(1, ADVANCE_DETAILS);
return "done";
}
@@ -1050,10 +1056,24 @@ export class WorkIndex {
const walk = this.walkState();
const task = walk.tasks[0];
if (!task) break;
+ if (task.kind === "range") {
+ // Null: the base is gone (a rewritten history); the rebuild that follows lists everything.
+ const cmp = await gh.compare(task.base, task.head, task.page);
+ this.store.transaction(() => {
+ const now = this.walkState();
+ const t = now.tasks.find((x) => x.kind === "range" && x.base === task.base && x.head === task.head && x.page === task.page);
+ if (!t) return;
+ for (const c of cmp?.commits ?? []) this.listCommit(c);
+ if (!cmp || cmp.commits.length < PER_PAGE_MAX || task.page * PER_PAGE_MAX >= cmp.totalCommits) now.tasks.splice(now.tasks.indexOf(t), 1);
+ else t.page += 1;
+ this.setMeta("walk", JSON.stringify(now));
+ });
+ continue;
+ }
const list = await gh.commits({ sha: task.head, path: task.dir, page: task.page, perPage: PER_PAGE_MAX });
this.store.transaction(() => {
const now = this.walkState();
- const t = now.tasks.find((x) => x.dir === task.dir && x.head === task.head && x.page === task.page);
+ const t = now.tasks.find((x): x is DirTask => x.kind !== "range" && x.dir === task.dir && x.head === task.head && x.page === task.page);
if (!t) return;
const mark = `,${t.dir},`;
let done = list.length < PER_PAGE_MAX;
@@ -1090,6 +1110,19 @@ export class WorkIndex {
}
}
+ /** A commit of an advance's range, to detail (a merge's files repeat its branch's: not detailed). */
+ private listCommit(c: CommitInfo): void {
+ if (c.merge) return;
+ this.store.exec(
+ "INSERT INTO commits (sha, at, author_name, author_email, message, detailed) VALUES (?, ?, ?, ?, ?, 0) ON CONFLICT (sha) DO NOTHING",
+ c.sha,
+ c.at,
+ c.authorName.slice(0, 200),
+ c.authorEmail,
+ c.message.slice(0, 10_000),
+ );
+ }
+
/**
* One commit's item files: a revision of each item, its links, and the dates and names the
* commit settles (the add, the move into done/, the latest change). Order-free: the walk may
@@ -1307,13 +1340,6 @@ function dirOf(path: string): Dir | null {
return path.startsWith("work/") ? "work" : path.startsWith("done/") ? "done" : null;
}
-/** A folder's range to list: a task not started yet takes the newer head (it covers the older), else a new task first. */
-function addTask(walk: WalkState, dir: Dir, head: string): void {
- const waiting = walk.tasks.find((t) => t.dir === dir && t.page === 1);
- if (waiting) waiting.head = head;
- else walk.tasks.unshift({ dir, head, page: 1 });
-}
-
/** The row of each number: its open file before a closed one, then the first path. */
function pickWinners(files: { path: string; number: number; blob: string }[]): Map<number, { path: string; number: number; blob: string }> {
const out = new Map<number, { path: string; number: number; blob: string }>();
diff --git a/services/managed-agents/test/fixtures/fake-github-repo.ts b/services/managed-agents/test/fixtures/fake-github-repo.ts
index 2d4ba77f..fd136791 100644
--- a/services/managed-agents/test/fixtures/fake-github-repo.ts
+++ b/services/managed-agents/test/fixtures/fake-github-repo.ts
@@ -14,7 +14,10 @@ import { createHash } from "node:crypto";
export interface FakeCommit {
sha: string;
+ /** The first parent. */
parent: string | null;
+ /** Every parent: two for a merge. */
+ parents: string[];
message: string;
author: { name: string; email: string };
at: string;
@@ -76,7 +79,41 @@ export class FakeRepo {
this.clock += 60_000;
for (const text of files.values()) this.blobStore.set(this.blobSha(text), text);
const sha = sha1(`${this.head}\n${message}\n${this.clock}\n${[...files].join("\n")}`);
- this.commits.set(sha, { sha, parent: this.head, message, author, at: new Date(this.clock).toISOString(), files });
+ this.commits.set(sha, { sha, parent: this.head, parents: this.head ? [this.head] : [], message, author, at: new Date(this.clock).toISOString(), files });
+ this.head = sha;
+ return sha;
+ }
+
+ /** A commit on a branch off `from` (a pull request's branch): the head does not move. */
+ branchCommit(from: string, changes: Record<string, string | null>, message = "Branch", author = { name: "Ana", email: "[email protected]" }): string {
+ const files = new Map(this.commits.get(from)!.files);
+ for (const [path, text] of Object.entries(changes)) {
+ if (text === null) files.delete(path);
+ else files.set(path, text);
+ }
+ this.clock += 60_000;
+ for (const text of files.values()) this.blobStore.set(this.blobSha(text), text);
+ const sha = sha1(`${from}\n${message}\n${this.clock}\n${[...files].join("\n")}`);
+ this.commits.set(sha, { sha, parent: from, parents: [from], message, author, at: new Date(this.clock).toISOString(), files });
+ return sha;
+ }
+
+ /** A merge commit of `branch` into the head: its first parent is the head; the branch's changes since the fork are applied. */
+ merge(branch: string, message = "Merge pull request"): string {
+ const mine = new Set(this.ancestors(this.head!));
+ let fork = branch;
+ while (!mine.has(fork)) fork = this.commits.get(fork)!.parent!;
+ const files = new Map(this.commits.get(this.head!)!.files);
+ for (const f of this.diff(this.commits.get(fork)!.files, this.commits.get(branch)!.files)) {
+ if (f.status === "removed") files.delete(f.filename);
+ else {
+ if (f.previous_filename) files.delete(f.previous_filename);
+ files.set(f.filename, this.commits.get(branch)!.files.get(f.filename)!);
+ }
+ }
+ this.clock += 60_000;
+ const sha = sha1(`${this.head}\n${branch}\n${message}\n${this.clock}`);
+ this.commits.set(sha, { sha, parent: this.head, parents: [this.head!, branch], message, author: { name: "Ana", email: "[email protected]" }, at: new Date(this.clock).toISOString(), files });
this.head = sha;
return sha;
}
@@ -92,9 +129,22 @@ export class FakeRepo {
return sha1(`blob\n${text}`);
}
+ /** Every commit reachable from `sha`, as `git log` lists them: newest date first among those reached. */
private ancestors(sha: string): string[] {
const out: string[] = [];
- for (let c: string | null = sha; c; c = this.commits.get(c)?.parent ?? null) out.push(c);
+ const seen = new Set([sha]);
+ const queue = [sha];
+ while (queue.length) {
+ queue.sort((a, b) => (this.commits.get(a)!.at < this.commits.get(b)!.at ? 1 : -1));
+ const c = queue.shift()!;
+ out.push(c);
+ for (const p of this.commits.get(c)?.parents ?? []) {
+ if (!seen.has(p) && this.commits.has(p)) {
+ seen.add(p);
+ queue.push(p);
+ }
+ }
+ }
return out;
}
@@ -117,13 +167,17 @@ export class FakeRepo {
}
private commitJson(c: FakeCommit) {
- return { sha: c.sha, commit: { message: c.message, author: { name: c.author.name, email: c.author.email, date: c.at } } };
+ return { sha: c.sha, parents: c.parents.map((sha) => ({ sha })), commit: { message: c.message, author: { name: c.author.name, email: c.author.email, date: c.at } } };
}
private changed(c: FakeCommit) {
return this.diff(c.parent ? this.commits.get(c.parent)!.files : new Map(), c.files);
}
+ private under(files: Map<string, string>, path: string): string {
+ return JSON.stringify([...files].filter(([p]) => p === path || p.startsWith(`${path}/`)).sort());
+ }
+
/** Renames the repository; the old name redirects (or 404s when `redirects` is false). */
rename(name: string): void {
this.formerNames.push(this.name);
@@ -222,14 +276,16 @@ export class FakeRepo {
const [baseSha, headSha] = [m[1]!, m[2]!];
if (!this.commits.has(baseSha) || !this.commits.has(headSha)) return json(404, { message: "Not Found" });
const line = this.ancestors(headSha);
- const at = line.indexOf(baseSha);
- if (at === -1) return json(200, { status: "diverged", total_commits: 0, commits: [], files: [] });
- if (at === 0) return json(200, { status: "identical", total_commits: 0, commits: [], files: [] });
- const range = line.slice(0, at).reverse().map((s) => this.commits.get(s)!);
+ if (!line.includes(baseSha)) return json(200, { status: "diverged", total_commits: 0, commits: [], files: [] });
+ if (baseSha === headSha) return json(200, { status: "identical", total_commits: 0, commits: [], files: [] });
+ const before = new Set(this.ancestors(baseSha));
+ // Oldest first, as GitHub lists a comparison's commits; paged.
+ const range = line.filter((s) => !before.has(s)).reverse().map((s) => this.commits.get(s)!);
+ const page = Number(url.searchParams.get("page") ?? "1");
return json(200, {
status: "ahead",
total_commits: range.length,
- commits: range.slice(0, perPage()).map((c) => this.commitJson(c)),
+ commits: range.slice((page - 1) * perPage(), page * perPage()).map((c) => this.commitJson(c)),
// GitHub lists at most 300 files.
files: this.diff(this.commits.get(baseSha)!.files, this.commits.get(headSha)!.files).slice(0, 300),
});
@@ -251,7 +307,9 @@ export class FakeRepo {
const touching = this.ancestors(from)
.map((s) => this.commits.get(s)!)
.filter((c) => !until || c.at <= until)
- .filter((c) => this.changed(c).some((f) => f.filename === path || f.filename.startsWith(`${path}/`) || f.previous_filename === path || f.previous_filename?.startsWith(`${path}/`)));
+ .filter((c) => this.changed(c).some((f) => f.filename === path || f.filename.startsWith(`${path}/`) || f.previous_filename === path || f.previous_filename?.startsWith(`${path}/`)))
+ // git's history simplification: a merge the path is unchanged by on one side is left out.
+ .filter((c) => c.parents.length < 2 || !c.parents.some((p) => this.under(this.commits.get(p)!.files, path) === this.under(c.files, path)));
return json(200, touching.slice((page - 1) * size, page * size).map((c) => this.commitJson(c)));
}
m = /^\/git\/trees\/(.+)$/.exec(rest);
diff --git a/services/managed-agents/test/work-index.test.ts b/services/managed-agents/test/work-index.test.ts
index 1d89de66..9e443a2a 100644
--- a/services/managed-agents/test/work-index.test.ts
+++ b/services/managed-agents/test/work-index.test.ts
@@ -862,10 +862,10 @@ describe("call budgets", () => {
await s.index.poke(ORG);
await s.settle();
const calls = repo.take();
- // ref + compare + root and work/ trees + 100 changed blobs + a page of work/ commits + 10 details.
+ // ref + compare + root and work/ trees + 100 changed blobs + the range's second page of commits + 10 details.
const budget = 1 + 1 + 2 + 100 + 1 + ADVANCE_DETAILS;
expect(calls.length).toBeLessThanOrEqual(budget);
- expect(count(calls, /\/compare\//)).toBe(1);
+ expect(count(calls, /\/compare\//)).toBe(2);
expect(count(calls, /\/git\/trees\//)).toBe(2);
expect(count(calls, /\/git\/blobs\//)).toBe(100);
expect(count(calls, /\/commits\/[0-9a-f]{40}/)).toBeLessThanOrEqual(ADVANCE_DETAILS);
@@ -1052,3 +1052,33 @@ describe("large and unstorable files", () => {
expect(byNumber(after).get(2)!.warnings).toEqual(["The file could not be stored; only its name is shown."]);
});
});
+
+describe("merge commits", () => {
+ it("details a pull request branch's commits dated before the cursor but merged after it", async () => {
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A") });
+ const s = await connect(repo);
+ s.tick(11 * 60_000);
+ await s.drain();
+ // A branch commit, then main moves on (the cursor passes it by date), then the merge.
+ const fork = repo.head!;
+ const onBranch = repo.branchCommit(fork, { "work/2-b.md": item(2, "B") }, "Add 2\n\nSession: cs_branch", { name: "Bob", email: "[email protected]" });
+ repo.commit({ "work/1-a.md": item(1, "A", "edited") }, "Edit 1");
+ await s.index.poke(ORG);
+ await s.settle();
+ s.tick(11 * 60_000);
+ await s.drain();
+ repo.merge(onBranch);
+ await s.index.poke(ORG);
+ await s.settle();
+ s.tick(11 * 60_000);
+ await s.drain();
+ expect(s.walkDone()).toBe(true);
+ const two = byNumber(await open(s)).get(2)!;
+ expect(two.sessionIds).toEqual(["cs_branch"]);
+ expect(two.createdAt).toBe(repo.commits.get(onBranch)!.at);
+ expect(two.author).toEqual({ name: "Bob", email: "[email protected]" });
+ expect(two.updatedAt).toBe(repo.commits.get(onBranch)!.at);
+ const history = await s.index.history(ORG, 2);
+ expect(history.ok && history.revisions.map((r) => r.summary)).toEqual(["Add 2"]);
+ });
+});