Public: anyone can read this; the crew can change it.
Re-cut a conflict in a split file mechanically instead of a full agent run (#6140, part 3) #16962
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/6155-re-cut-a-conflict-in-a-split-file-mechan → main 0 commits fork
5 files
changed +488
−1
src/actions/split_recut.ts added +248
| @@ -0,0 +1,248 @@ | ||
| 1 | /** | |
| 2 | * A pull whose only conflict is in a file that main split into one file per | |
| 3 | * entry (`src/http/mcp.ts` → `src/http/mcp/tools/*`, #5932) is re-cut by the | |
| 4 | * forge, not by an agent run (#6155): the entries it added to the old file are | |
| 5 | * written to their own files, the index gets their lines, the old file is | |
| 6 | * dropped, and the base is merged in, as one commit on the head branch. | |
| 7 | * | |
| 8 | * It does only what it can prove: a pull that changed or removed an entry | |
| 9 | * that already existed, edited the old file outside its entries and imports, | |
| 10 | * or adds an entry whose file the base already has, is left to a run. Its | |
| 11 | * check is the proof the rest holds; a red one goes the way every red check | |
| 12 | * goes, to the builder. | |
| 13 | */ | |
| 14 | ||
| 15 | import { posix } from "node:path"; | |
| 16 | import type { App } from "../app.ts"; | |
| 17 | import { forgeHost, noreplyAddress } from "../core/commit_identity.ts"; | |
| 18 | import { trackPullHead, type Pull } from "../core/pulls.ts"; | |
| 19 | import type { Repo } from "../core/repos.ts"; | |
| 20 | import { claimRun, createRun, finishRun } from "../core/runs.ts"; | |
| 21 | import { conflictedTree } from "../git/conflict-file.ts"; | |
| 22 | import { runGitCapture } from "../git/env.ts"; | |
| 23 | import { mergeable, mergeBase, resolveOid } from "../git/merge.ts"; | |
| 24 | import { repoDir } from "../git/repos.ts"; | |
| 25 | import { commitFiles, type FileWrite } from "../git/write.ts"; | |
| 26 | ||
| 27 | /** A file main split: where it was, where its entries live, and the index there. */ | |
| 28 | export interface Split { | |
| 29 | readonly file: string; | |
| 30 | readonly dir: string; | |
| 31 | readonly shared: string; | |
| 32 | } | |
| 33 | ||
| 34 | export const SPLITS: readonly Split[] = [ | |
| 35 | { file: "src/http/mcp.ts", dir: "src/http/mcp/tools", shared: "src/http/mcp/shared.ts" }, | |
| 36 | ]; | |
| 37 | ||
| 38 | /** The words a re-cut run and its commit carry, so every door says it was mechanical. */ | |
| 39 | export const RECUT_WORDS = "re-cut mechanically (no agent run)"; | |
| 40 | ||
| 41 | /** The split a conflict is confined to, if any. */ | |
| 42 | export const splitOf = (files: readonly string[]): Split | undefined => | |
| 43 | files.length === 1 ? SPLITS.find((s) => s.file === files[0]) : undefined; | |
| 44 | ||
| 45 | interface Entry { | |
| 46 | readonly name: string; | |
| 47 | readonly lines: readonly string[]; | |
| 48 | } | |
| 49 | ||
| 50 | /** The old file's entries (` {` … ` },` with `name:` first) and everything outside them. */ | |
| 51 | export function parseEntries(text: string): { entries: Entry[]; rest: string } { | |
| 52 | const lines = text.split("\n"); | |
| 53 | const entries: Entry[] = []; | |
| 54 | const rest: string[] = []; | |
| 55 | for (let i = 0; i < lines.length; i++) { | |
| 56 | const name = lines[i] === " {" ? /^ {4}name: "([a-z][a-z0-9_]*)",$/.exec(lines[i + 1] ?? "")?.[1] : undefined; | |
| 57 | const end = name === undefined ? -1 : lines.indexOf(" },", i + 1); | |
| 58 | if (name === undefined || end < 0) { | |
| 59 | rest.push(lines[i]!); | |
| 60 | continue; | |
| 61 | } | |
| 62 | entries.push({ name, lines: lines.slice(i, end + 1) }); | |
| 63 | i = end; | |
| 64 | } | |
| 65 | return { entries, rest: rest.join("\n") }; | |
| 66 | } | |
| 67 | ||
| 68 | interface Import { | |
| 69 | readonly text: string; | |
| 70 | readonly spec: string; | |
| 71 | readonly names: readonly string[]; | |
| 72 | } | |
| 73 | ||
| 74 | const IMPORT = /^import [^;]*? from "([^"]+)";$/gms; | |
| 75 | ||
| 76 | /** The import statements in a text, with the names each binds. */ | |
| 77 | export function parseImports(text: string): Import[] { | |
| 78 | return [...text.matchAll(IMPORT)].map((m) => { | |
| 79 | const braces = /\{([^}]*)\}/.exec(m[0])?.[1] ?? m[0].replace(/^import (?:type )?/, "").replace(/ from .*$/s, ""); | |
| 80 | const names = braces | |
| 81 | .split(",") | |
| 82 | .map((n) => n.trim().replace(/^type /, "").replace(/^.* as /, "").replace(/^\* as /, "")) | |
| 83 | .filter((n) => /^\w+$/.test(n)); | |
| 84 | return { text: m[0], spec: m[1]!, names }; | |
| 85 | }); | |
| 86 | } | |
| 87 | ||
| 88 | /** An import's specifier as seen from the entry's file instead of the old file's. */ | |
| 89 | function respec(spec: string, from: string, to: string): string { | |
| 90 | if (!spec.startsWith(".")) return spec; | |
| 91 | const target = posix.join(posix.dirname(from), spec); | |
| 92 | const rel = posix.relative(to, target); | |
| 93 | return rel.startsWith(".") ? rel : `./${rel}`; | |
| 94 | } | |
| 95 | ||
| 96 | /** The names a source file exports, and which of them are only types. */ | |
| 97 | function exportsOf(text: string): Map<string, boolean> { | |
| 98 | const out = new Map<string, boolean>(); | |
| 99 | for (const m of text.matchAll(/^export (?:async )?(const|function|type|interface) (\w+)/gm)) | |
| 100 | out.set(m[2]!, m[1] === "type" || m[1] === "interface"); | |
| 101 | return out; | |
| 102 | } | |
| 103 | ||
| 104 | /** | |
| 105 | * One entry as a file of its own: the head file's imports it uses, re-pointed, then | |
| 106 | * `export const tool: Tool = {…};`. | |
| 107 | */ | |
| 108 | export function entryFile( | |
| 109 | entry: Entry, | |
| 110 | imports: readonly Import[], | |
| 111 | shared: ReadonlyMap<string, boolean>, | |
| 112 | split: Split, | |
| 113 | ): string { | |
| 114 | const body = entry.lines.map((l) => l.replace(/^ {2}/, "")).join("\n"); | |
| 115 | const uses = (name: string): boolean => new RegExp(`\\b${name}\\b`).test(body); | |
| 116 | const out: string[] = []; | |
| 117 | const covered = new Set<string>(); | |
| 118 | for (const imp of imports) { | |
| 119 | if (!imp.names.some(uses)) continue; | |
| 120 | out.push(imp.text.replace(/from "[^"]+"/, `from "${respec(imp.spec, split.file, split.dir)}"`)); | |
| 121 | for (const n of imp.names) covered.add(n); | |
| 122 | } | |
| 123 | const mine = [...shared.keys()] | |
| 124 | .filter((n) => n === "Tool" || (uses(n) && !covered.has(n))) | |
| 125 | .sort(); | |
| 126 | const names = mine.map((n) => (shared.get(n) ? `type ${n}` : n)).join(", "); | |
| 127 | out.push(`import { ${names} } from "${posix.relative(split.dir, split.shared)}";`); | |
| 128 | const lines = body.split("\n"); | |
| 129 | lines[0] = "export const tool: Tool = {"; | |
| 130 | lines[lines.length - 1] = "};"; | |
| 131 | return `${out.join("\n")}\n\n${lines.join("\n")}\n`; | |
| 132 | } | |
| 133 | ||
| 134 | /** The index with a line for each new name, sorted as the generator sorts them. */ | |
| 135 | export function indexWith(index: string, names: readonly string[]): string { | |
| 136 | const lines = index.split("\n").filter((l) => l !== ""); | |
| 137 | const exportLines = lines.filter((l) => l.startsWith("export {")); | |
| 138 | const all = [...exportLines, ...names.map((n) => `export { tool as ${n} } from "./${n}.ts";`)]; | |
| 139 | const nameOf = (l: string): string => /tool as (\w+)/.exec(l)![1]!; | |
| 140 | all.sort((a, b) => (nameOf(a) < nameOf(b) ? -1 : nameOf(a) > nameOf(b) ? 1 : 0)); | |
| 141 | return `${[...lines.filter((l) => !l.startsWith("export {")), ...all].join("\n")}\n`; | |
| 142 | } | |
| 143 | ||
| 144 | /** What the pull adds to the old file, as new files; undefined when it adds anything else. */ | |
| 145 | export function recut( | |
| 146 | split: Split, | |
| 147 | base: string, | |
| 148 | head: string, | |
| 149 | shared: string, | |
| 150 | index: string, | |
| 151 | exists: (path: string) => boolean, | |
| 152 | ): { files: FileWrite[]; names: string[] } | undefined { | |
| 153 | const was = parseEntries(base); | |
| 154 | const now = parseEntries(head); | |
| 155 | const wasEntries = new Map(was.entries.map((e) => [e.name, e.lines.join("\n")])); | |
| 156 | for (const [name, text] of wasEntries) | |
| 157 | if (now.entries.find((e) => e.name === name)?.lines.join("\n") !== text) return undefined; | |
| 158 | const wasImports = parseImports(was.rest); | |
| 159 | const nowImports = parseImports(now.rest); | |
| 160 | if (wasImports.some((w) => !nowImports.some((n) => n.text === w.text))) return undefined; | |
| 161 | const bare = (rest: string): string => rest.replace(IMPORT, "").replace(/\n+/g, "\n"); | |
| 162 | if (bare(now.rest) !== bare(was.rest)) return undefined; | |
| 163 | const fresh = now.entries.filter((e) => !wasEntries.has(e.name)); | |
| 164 | if (fresh.length === 0 || fresh.some((e) => exists(`${split.dir}/${e.name}.ts`) || e.name === "index")) return undefined; | |
| 165 | const sharedNames = exportsOf(shared); | |
| 166 | const files: FileWrite[] = fresh.map((e) => ({ | |
| 167 | path: `${split.dir}/${e.name}.ts`, | |
| 168 | content: entryFile(e, nowImports, sharedNames, split), | |
| 169 | })); | |
| 170 | const names = fresh.map((e) => e.name); | |
| 171 | files.push({ path: `${split.dir}/index.ts`, content: indexWith(index, names) }); | |
| 172 | files.push({ path: split.file, content: null }); | |
| 173 | return { files, names }; | |
| 174 | } | |
| 175 | ||
| 176 | /** | |
| 177 | * Bring the pull up to date by re-cutting it onto the split. The commit id | |
| 178 | * when the head moved; undefined when the pull is not one this can settle. | |
| 179 | * The move is recorded as a finished `conflict` run, so the check lane counts | |
| 180 | * its push as a rebase's (`checks/finishing_first.ts`). | |
| 181 | */ | |
| 182 | export async function recutSplitConflict( | |
| 183 | app: App, | |
| 184 | repo: Repo, | |
| 185 | pull: Pull, | |
| 186 | builderId?: string, | |
| 187 | ): Promise<string | undefined> { | |
| 188 | if (pull.state !== "open" || pull.mergedAt !== null) return undefined; | |
| 189 | if (pull.crossRepo || pull.originHeadRepo !== null || repo.origin !== null) return undefined; | |
| 190 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 191 | const head = await resolveOid(dir, `refs/heads/${pull.headBranch}`); | |
| 192 | const tip = await resolveOid(dir, `refs/heads/${pull.baseBranch}`); | |
| 193 | if (head === undefined || tip === undefined) return undefined; | |
| 194 | const now = await mergeable(dir, tip, head); | |
| 195 | if (now.ok || now.error.kind !== "conflict") return undefined; | |
| 196 | const split = splitOf(now.error.files); | |
| 197 | if (split === undefined) return undefined; | |
| 198 | const at = await mergeBase(dir, tip, head); | |
| 199 | const tree = await conflictedTree(dir, tip, head); | |
| 200 | if (at === undefined || tree === undefined) return undefined; | |
| 201 | const show = async (oid: string, path: string): Promise<string | undefined> => { | |
| 202 | const r = await runGitCapture(["cat-file", "blob", `${oid}:${path}`], { cwd: dir }); | |
| 203 | return r.code === 0 ? r.stdout : undefined; | |
| 204 | }; | |
| 205 | // The base split it: the file is gone there and the entries' directory is not. | |
| 206 | if ((await show(tip, split.file)) !== undefined) return undefined; | |
| 207 | const [old, mine, shared, index] = await Promise.all([ | |
| 208 | show(at, split.file), | |
| 209 | show(head, split.file), | |
| 210 | show(tip, split.shared), | |
| 211 | show(tip, `${split.dir}/index.ts`), | |
| 212 | ]); | |
| 213 | if (old === undefined || mine === undefined || shared === undefined || index === undefined) return undefined; | |
| 214 | const taken = new Set<string>(); | |
| 215 | for (const e of parseEntries(mine).entries) | |
| 216 | if ((await show(tip, `${split.dir}/${e.name}.ts`)) !== undefined) taken.add(`${split.dir}/${e.name}.ts`); | |
| 217 | const cut = recut(split, old, mine, shared, index, (p) => taken.has(p)); | |
| 218 | if (cut === undefined) return undefined; | |
| 219 | const committed = await commitFiles(dir, { | |
| 220 | branch: pull.headBranch, | |
| 221 | message: `Merge ${pull.baseBranch} into ${pull.headBranch}\n\nRe-cut onto the split of ${split.file}: ${cut.names.join(", ")} moved to ${split.dir}/ and the index regenerated (${RECUT_WORDS}).`, | |
| 222 | files: cut.files, | |
| 223 | seedTree: tree, | |
| 224 | mergeParents: [tip], | |
| 225 | expectTip: head, | |
| 226 | author: { name: "forge", email: noreplyAddress("forge", forgeHost(app.config)) }, | |
| 227 | }); | |
| 228 | if (!committed.ok) return undefined; | |
| 229 | const commitOid = committed.value.commitOid; | |
| 230 | trackPullHead(app.db, repo.id, pull.headBranch, commitOid); | |
| 231 | const run = createRun(app.db, { | |
| 232 | repoId: repo.id, | |
| 233 | kind: "agent", | |
| 234 | issueId: pull.id, | |
| 235 | branch: pull.headBranch, | |
| 236 | reason: "conflict", | |
| 237 | ...(builderId === undefined ? {} : { actorId: builderId }), | |
| 238 | summary: `${RECUT_WORDS}: ${cut.names.join(", ")}`, | |
| 239 | }); | |
| 240 | claimRun(app.db, run.id); | |
| 241 | finishRun(app.db, run.id, { state: "ok", summary: `${RECUT_WORDS}: ${cut.names.join(", ")}`, pushed: true, commitOid }); | |
| 242 | app.bus.append({ | |
| 243 | kind: "push", | |
| 244 | repoId: repo.id, | |
| 245 | payload: { updates: [{ ref: `refs/heads/${pull.headBranch}`, newOid: commitOid }], viaApi: true }, | |
| 246 | }); | |
| 247 | return commitOid; | |
| 248 | } |
src/crew/conflict_sweep.ts +9
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | /** The sweep that asks the crew to bring a pull up to date when main moved under it. */ |
| 2 | 2 | |
| 3 | 3 | import { onlyListDocs, resolveListConflicts } from "../actions/list-conflicts.ts"; |
| 4 | import { recutSplitConflict, splitOf } from "../actions/split_recut.ts"; | |
| 4 | 5 | import type { App } from "../app.ts"; |
| 5 | 6 | import { getHold } from "../core/holds.ts"; |
| 6 | 7 | import { getIssueById, type Issue } from "../core/issues.ts"; |
| @@ -184,6 +185,14 @@ export async function sweepConflicts( | ||
| 184 | 185 | checked.delete(pull.id); |
| 185 | 186 | continue; |
| 186 | 187 | } |
| 188 | // A clash only in a file main split is re-cut by the forge, with no run; | |
| 189 | // one that does not apply is the run's below (#6155). | |
| 190 | if (splitOf(files) !== undefined && room > 0 && (await recutSplitConflict(app, repo, pull, agentFor(app, issue)?.user.id)) !== undefined) { | |
| 191 | room--; | |
| 192 | acted++; | |
| 193 | checked.delete(pull.id); | |
| 194 | continue; | |
| 195 | } | |
| 187 | 196 | // Its push is a check: none starts that the lane has no slot for (#4459). |
| 188 | 197 | if (room <= 0) continue; |
| 189 | 198 | if (bringUpToDate(app, repo, pull, files, since) !== undefined) { |
src/crew/dispatch.ts +2
| @@ -25,6 +25,7 @@ import { accountsSaid } from "../actions/crew_accounts.ts"; | ||
| 25 | 25 | import { redStreak } from "./red_thrice.ts"; |
| 26 | 26 | import { twinNote, twinOf, type Twin } from "./twin.ts"; |
| 27 | 27 | import { NO_MERGE } from "../checks/merged.ts"; |
| 28 | import { recutSplitConflict } from "../actions/split_recut.ts"; | |
| 28 | 29 | import { resolveListConflicts } from "../actions/list-conflicts.ts"; |
| 29 | 30 | import { markHeard } from "../core/issues.ts"; |
| 30 | 31 | import { capacityCount, noteBooted } from "../core/capacity.ts"; |
| @@ -184,6 +185,7 @@ async function bringUpAfterNoMerge(app: App, repo: Repo, issue: Issue, agent: Ag | ||
| 184 | 185 | // Only its author, a person, can push it: it waits, and is not re-picked to fail in 0s (#16510). |
| 185 | 186 | if (authorsInRepoPull(pull)) return; |
| 186 | 187 | if (await resolveListConflicts(app, repo, pull)) return; |
| 188 | if (await recutSplitConflict(app, repo, pull, agent.user.id)) return; | |
| 187 | 189 | if (activeRunFor(app.db, "agent", issue.id) !== undefined) return; |
| 188 | 190 | queueAgentRun(app, repo, issue, agent, "conflict", undefined, { |
| 189 | 191 | notBefore: new Date().toISOString(), |
src/crew/finishing.ts +24 −1
| @@ -43,6 +43,7 @@ | ||
| 43 | 43 | import type { Database } from "bun:sqlite"; |
| 44 | 44 | import type { App } from "../app.ts"; |
| 45 | 45 | import { addComment, assignIssue } from "../actions/issues.ts"; |
| 46 | import { recutSplitConflict, RECUT_WORDS, splitOf } from "../actions/split_recut.ts"; | |
| 46 | 47 | import { getAgent, listCrewRoles, type Agent } from "../core/agents.ts"; |
| 47 | 48 | import { getHold } from "../core/holds.ts"; |
| 48 | 49 | import { getIssueById, type Issue } from "../core/issues.ts"; |
| @@ -75,6 +76,8 @@ export type FinishMove = | ||
| 75 | 76 | /** The pull's own builder, when it was busy and another took the update. */ |
| 76 | 77 | readonly for?: string; |
| 77 | 78 | } |
| 79 | /** Re-cut onto a split file by the forge, with no agent run (#6155). */ | |
| 80 | | { readonly pull: number; readonly did: "re-cut mechanically" } | |
| 78 | 81 | | { readonly pull: number; readonly did: "in flight" } |
| 79 | 82 | | { readonly pull: number; readonly did: "handed to a person"; readonly to: string } |
| 80 | 83 | | { readonly pull: number; readonly did: "not moved"; readonly why: string }; |
| @@ -112,7 +115,7 @@ export function finishFields( | ||
| 112 | 115 | lane?: ConflictLane, |
| 113 | 116 | open?: number, |
| 114 | 117 | ): { finishing?: string; lane?: string } { |
| 115 | const queued = moves.filter((m) => m.did === "queued update").length; | |
| 118 | const queued = moves.filter((m) => m.did === "queued update" || m.did === "re-cut mechanically").length; | |
| 116 | 119 | const inFlight = moves.filter((m) => m.did === "in flight").length; |
| 117 | 120 | const whys = new Map<string, number>(); |
| 118 | 121 | for (const move of moves) { |
| @@ -222,6 +225,21 @@ export async function finishApproved(app: App, repo: Repo, free: number): Promis | ||
| 222 | 225 | // From here every pull is approved and conflicted: one not brought up |
| 223 | 226 | // to date says why, on its own line and on the tick line (#6237). |
| 224 | 227 | const hold = getHold(app.db, pull.id); |
| 228 | // A conflict confined to a split file is re-cut by the forge first; one | |
| 229 | // that does not apply falls through to the run below (#6155). | |
| 230 | const recut = | |
| 231 | hold === undefined && | |
| 232 | room > 0 && | |
| 233 | splitOf(conflict.files) !== undefined && | |
| 234 | activeRunFor(app.db, "agent", pull.id) === undefined && | |
| 235 | (await recutSplitConflict(app, repo, pull, ownBuilder(issue, builders, load, getRepoById(app.db, pull.headRepoId)?.ownerId)?.user.id)) !== undefined; | |
| 236 | if (recut) { | |
| 237 | room--; | |
| 238 | const move: FinishMove = { pull: pull.number, did: "re-cut mechanically" }; | |
| 239 | moves.push(move); | |
| 240 | say(repo, pull, move); | |
| 241 | continue; | |
| 242 | } | |
| 225 | 243 | const move = |
| 226 | 244 | hold !== undefined |
| 227 | 245 | ? notMoved(pull, `held by ${hold.heldByName}`) |
| @@ -381,6 +399,11 @@ function say(repo: Repo, pull: Pull, move: FinishMove): void { | ||
| 381 | 399 | }); |
| 382 | 400 | return; |
| 383 | 401 | } |
| 402 | if (move.did === "re-cut mechanically") { | |
| 403 | said.forget(key); | |
| 404 | log.info(`approved pull conflicts: ${RECUT_WORDS}`, { repo: where, pull: pull.number }); | |
| 405 | return; | |
| 406 | } | |
| 384 | 407 | if (move.did !== "not moved") return; |
| 385 | 408 | const line = `${pull.headOid}:${move.why}`; |
| 386 | 409 | if (!said.fresh(key, line)) return; |
test/split-recut.test.ts added +205
| @@ -0,0 +1,205 @@ | ||
| 1 | /** | |
| 2 | * A pull that conflicts only in a file main split into one file per entry is | |
| 3 | * re-cut by the forge with no agent run; one with another conflict still gets | |
| 4 | * the run (#6155). | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { createApp, type App } from "../src/app.ts"; | |
| 11 | import { addToCrew, createAgent } from "../src/actions/crew.ts"; | |
| 12 | import { openIssue } from "../src/actions/issues.ts"; | |
| 13 | import { openPull } from "../src/actions/pulls.ts"; | |
| 14 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 15 | import { entryFile, indexWith, parseEntries, recut, SPLITS } from "../src/actions/split_recut.ts"; | |
| 16 | import { getPull, type Pull } from "../src/core/pulls.ts"; | |
| 17 | import { getRepoById, type Repo } from "../src/core/repos.ts"; | |
| 18 | import { setCapacity } from "../src/core/capacity.ts"; | |
| 19 | import { listRuns } from "../src/core/runs.ts"; | |
| 20 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; | |
| 21 | import { rebasedPulls } from "../src/checks/finishing_first.ts"; | |
| 22 | import { finishApproved, finishFields } from "../src/crew/finishing.ts"; | |
| 23 | import { submitReview } from "../src/core/reviews.ts"; | |
| 24 | import { seatAs } from "./helpers/seat.ts"; | |
| 25 | import { sweepConflicts } from "../src/crew/conflict_sweep.ts"; | |
| 26 | import { mergeable, resolveOid } from "../src/git/merge.ts"; | |
| 27 | import { runGitCapture } from "../src/git/env.ts"; | |
| 28 | import { repoDir } from "../src/git/repos.ts"; | |
| 29 | ||
| 30 | const split = SPLITS[0]!; | |
| 31 | const OLD = split.file; | |
| 32 | const imports = `import { a } from "../actions/a.ts";\n`; | |
| 33 | const entry = (name: string, extra = "") => | |
| 34 | ` {\n name: "${name}",\n run(ctx) {\n return good(${extra || "1"});\n },\n },\n`; | |
| 35 | const monolith = (...more: string[]) => | |
| 36 | `${imports}\nexport const TOOLS = [\n${entry("one")}${more.join("")}];\n`; | |
| 37 | const SHARED = "export const good = (v: unknown) => v;\nexport interface Tool { name: string }\n"; | |
| 38 | const INDEX = `// Generated\n// One line per tool\nexport { tool as one } from "./one.ts";\n`; | |
| 39 | ||
| 40 | let dataDir: string; | |
| 41 | let app: App; | |
| 42 | let alice: User; | |
| 43 | let repo: Repo; | |
| 44 | let approvedPulled: Pull; | |
| 45 | const fresh = () => getRepoById(app.db, repo.id)!; | |
| 46 | ||
| 47 | const put = async (branch: string, files: { path: string; content: string | null }[], base?: string) => { | |
| 48 | const r = await commitToBranch(app, alice, repo, { | |
| 49 | branch, | |
| 50 | ...(base ? { base } : {}), | |
| 51 | message: `${branch} edit`, | |
| 52 | files, | |
| 53 | }); | |
| 54 | if (!r.ok) throw new Error(JSON.stringify(r.error)); | |
| 55 | }; | |
| 56 | const show = async (ref: string, path: string) => | |
| 57 | (await runGitCapture(["show", `${ref}:${path}`], { cwd: repoDir(app.reposRoot, alice.username, repo.name) })).stdout; | |
| 58 | ||
| 59 | async function pullOn(branch: string, files: { path: string; content: string }[]) { | |
| 60 | const mason = getUserByName(app.db, "mason")!; | |
| 61 | await put(branch, files, "main"); | |
| 62 | const ask = openIssue(app, alice, repo, { title: branch }); | |
| 63 | if (!ask.ok) throw new Error(String(ask.error)); | |
| 64 | const o = await openPull(app, mason, repo, { | |
| 65 | title: branch, | |
| 66 | body: `Closes #${ask.value.number}`, | |
| 67 | baseBranch: "main", | |
| 68 | headBranch: branch, | |
| 69 | }); | |
| 70 | if (!o.ok) throw new Error(String(o.error)); | |
| 71 | return o.value; | |
| 72 | } | |
| 73 | const conflictRuns = (id: string) => | |
| 74 | listRuns(app.db, repo.id, { kind: "agent" }).filter((r) => r.issueId === id && r.reason === "conflict"); | |
| 75 | ||
| 76 | beforeAll(async () => { | |
| 77 | dataDir = await mkdtemp(join(tmpdir(), "forge-recut-")); | |
| 78 | app = createApp({ dataDir, port: 0 }); | |
| 79 | const a = await createUser(app.db, { | |
| 80 | origin: "seed", trusted: true, username: "alice", email: "[email protected]", | |
| 81 | password: "a-good-passphrase", adminIfFirst: true, | |
| 82 | }); | |
| 83 | if (!a.ok) throw new Error(a.error); | |
| 84 | alice = a.value; | |
| 85 | const made = await createRepo(app, alice, { name: "engine", visibility: "private" }); | |
| 86 | if (!made.ok) throw new Error(String(made.error)); | |
| 87 | repo = made.value; | |
| 88 | await put("main", [ | |
| 89 | { path: OLD, content: monolith() }, | |
| 90 | { path: "other.ts", content: "export const other = 0;\n" }, | |
| 91 | ]); | |
| 92 | setCapacity(app.db, "checks.concurrency", "5", alice.id); | |
| 93 | for (const name of ["mason", "quill"]) { | |
| 94 | const agent = await createAgent(app, alice, { username: name }); | |
| 95 | if (!agent.ok) throw new Error(String(agent.error)); | |
| 96 | expect(addToCrew(app, alice, repo, name).ok).toBe(true); | |
| 97 | } | |
| 98 | seatAs(app.db, repo.id, getUserByName(app.db, "quill")!.id, "reviewer"); | |
| 99 | app.db.query("UPDATE repo SET autonomy = 'autonomous', autonomy_by = ?2 WHERE id = ?1").run(repo.id, alice.id); | |
| 100 | }); | |
| 101 | afterAll(async () => { | |
| 102 | app.db.close(); | |
| 103 | await rm(dataDir, { recursive: true, force: true }); | |
| 104 | }); | |
| 105 | ||
| 106 | test("the pure re-cut: an added entry becomes its file, the index a line, changed entries are refused", () => { | |
| 107 | const base = monolith(); | |
| 108 | const head = `${imports}import { b } from "./b.ts";\n\nexport const TOOLS = [\n${entry("one")}${entry("two", "b")}];\n`; | |
| 109 | const cut = recut(split, base, head, SHARED, INDEX, () => false)!; | |
| 110 | expect(cut.names).toEqual(["two"]); | |
| 111 | const file = cut.files.find((f) => f.path === `${split.dir}/two.ts`)!.content as string; | |
| 112 | expect(file).toContain('import { b } from "../../b.ts";'); | |
| 113 | expect(file).not.toContain("actions/a.ts"); | |
| 114 | expect(file).toContain('import { type Tool, good } from "../shared.ts";'); | |
| 115 | expect(file).toContain("export const tool: Tool = {\n name: \"two\","); | |
| 116 | expect(file.trimEnd().endsWith("};")).toBe(true); | |
| 117 | expect(cut.files.find((f) => f.path === `${split.dir}/index.ts`)!.content).toContain('export { tool as two } from "./two.ts";'); | |
| 118 | expect(cut.files.at(-1)).toEqual({ path: OLD, content: null }); | |
| 119 | // A changed entry, a taken file or an edit outside the entries is a run's. | |
| 120 | expect(recut(split, base, head.replace('good(b)', "good(2)").replace(entry("one"), entry("one", "9")), SHARED, INDEX, () => false)).toBeUndefined(); | |
| 121 | expect(recut(split, base, head, SHARED, INDEX, () => true)).toBeUndefined(); | |
| 122 | expect(recut(split, base, `${head}const extra = 1;\n`, SHARED, INDEX, () => false)).toBeUndefined(); | |
| 123 | expect(parseEntries(base).entries.map((e) => e.name)).toEqual(["one"]); | |
| 124 | expect(entryFile(parseEntries(base).entries[0]!, [], new Map(), split)).toContain("export const tool: Tool"); | |
| 125 | expect(indexWith(INDEX, ["zed", "alpha"]).split("\n").filter((l) => l.startsWith("export")).map((l) => /as (\w+)/.exec(l)![1])).toEqual(["alpha", "one", "zed"]); | |
| 126 | }); | |
| 127 | ||
| 128 | test("an entry keeps the imports the old file already had, value and type-only, re-pointed", () => { | |
| 129 | const old = `import { a } from "../actions/a.ts";\nimport type { T } from "../core/t.ts";\n`; | |
| 130 | const body = ` {\n name: "two",\n run(ctx) {\n const t: T = a(1);\n return good(t);\n },\n },\n`; | |
| 131 | const base = `${old}\nexport const TOOLS = [\n${entry("one")}];\n`; | |
| 132 | const head = `${old}\nexport const TOOLS = [\n${entry("one")}${body}];\n`; | |
| 133 | const cut = recut(split, base, head, SHARED, INDEX, () => false)!; | |
| 134 | const file = cut.files.find((f) => f.path === `${split.dir}/two.ts`)!.content as string; | |
| 135 | expect(file).toContain('import { a } from "../../../actions/a.ts";'); | |
| 136 | expect(file).toContain('import type { T } from "../../../core/t.ts";'); | |
| 137 | expect(file).toContain('import { type Tool, good } from "../shared.ts";'); | |
| 138 | }); | |
| 139 | ||
| 140 | test("a pull conflicting only on the split file is brought up to date with no agent run; one with another conflict still gets the run", async () => { | |
| 141 | const only = await pullOn("feature/only", [{ path: OLD, content: `${imports}import { b } from "./b.ts";\n\nexport const TOOLS = [\n${entry("one")}${entry("two", "b")}];\n` }]); | |
| 142 | const both = await pullOn("feature/both", [ | |
| 143 | { path: OLD, content: monolith(entry("three")) }, | |
| 144 | { path: "other.ts", content: "export const other = 'branch';\n" }, | |
| 145 | ]); | |
| 146 | const changed = await pullOn("feature/changed", [{ path: OLD, content: monolith().replace("good(1)", "good(5)") }]); | |
| 147 | const approved = (approvedPulled = await pullOn("feature/approved", [{ path: OLD, content: monolith(entry("four")) }])); | |
| 148 | const ok = submitReview(app.db, { | |
| 149 | issueId: approved.id, | |
| 150 | authorId: getUserByName(app.db, "quill")!.id, | |
| 151 | state: "approved", | |
| 152 | commitOid: approved.headOid, | |
| 153 | }); | |
| 154 | if (!ok.ok) throw new Error(ok.error); | |
| 155 | expect(await sweepConflicts(app, fresh())).toBe(0); | |
| 156 | // Main splits the file and moves other.ts. | |
| 157 | await put("main", [ | |
| 158 | { path: OLD, content: null }, | |
| 159 | { path: split.shared, content: SHARED }, | |
| 160 | { path: `${split.dir}/index.ts`, content: INDEX }, | |
| 161 | { path: `${split.dir}/one.ts`, content: entryFile(parseEntries(monolith()).entries[0]!, [], new Map(), split) }, | |
| 162 | { path: "other.ts", content: "export const other = 'main';\n" }, | |
| 163 | ]); | |
| 164 | const dir = repoDir(app.reposRoot, alice.username, repo.name); | |
| 165 | const before = (await resolveOid(dir, "refs/heads/feature/only"))!; | |
| 166 | expect(await sweepConflicts(app, fresh())).toBe(3); | |
| 167 | ||
| 168 | const onlyAfter = getPull(app.db, repo.id, only.number)!; | |
| 169 | expect(onlyAfter.headOid).not.toBe(before); | |
| 170 | expect(await show("feature/only", `${split.dir}/two.ts`)).toContain('name: "two"'); | |
| 171 | expect(await show("feature/only", `${split.dir}/index.ts`)).toContain("tool as two"); | |
| 172 | expect(await show("feature/only", `${split.dir}/one.ts`)).toContain('name: "one"'); | |
| 173 | const tip = (await resolveOid(dir, "refs/heads/main"))!; | |
| 174 | expect((await mergeable(dir, tip, onlyAfter.headOid)).ok).toBe(true); | |
| 175 | // One run, finished and mechanical, and the lane counts it as a rebase. | |
| 176 | const runs = conflictRuns(only.id); | |
| 177 | expect(runs.length).toBe(1); | |
| 178 | expect(runs[0]!.state).toBe("ok"); | |
| 179 | expect(runs[0]!.summary).toContain("re-cut mechanically"); | |
| 180 | expect(rebasedPulls(app.db, [only.id]).has(only.id)).toBe(true); | |
| 181 | ||
| 182 | // The one with another conflict is left to the agent's run, untouched. | |
| 183 | expect(getPull(app.db, repo.id, both.number)!.headOid).toBe(both.headOid); | |
| 184 | const queued = conflictRuns(both.id); | |
| 185 | expect(queued.length).toBe(1); | |
| 186 | expect(queued[0]!.state).toBe("queued"); | |
| 187 | expect(queued[0]!.summary).not.toContain("re-cut"); | |
| 188 | ||
| 189 | // A changed entry on the split file is the run's too. | |
| 190 | expect(getPull(app.db, repo.id, changed.number)!.headOid).toBe(changed.headOid); | |
| 191 | expect(conflictRuns(changed.id).map((r) => r.state)).toEqual(["queued"]); | |
| 192 | }); | |
| 193 | ||
| 194 | test("the finishing pass re-cuts an approved pull on the split file with no run, and says so", async () => { | |
| 195 | const pass = await finishApproved(app, fresh(), 3); | |
| 196 | const approvedPull = getPull(app.db, repo.id, approvedPulled.number)!; | |
| 197 | expect(pass.moves.map((m) => m.did)).toContain("re-cut mechanically"); | |
| 198 | expect(finishFields(pass.moves).finishing).toContain("queued 1"); | |
| 199 | expect(await show("feature/approved", `${split.dir}/four.ts`)).toContain('name: "four"'); | |
| 200 | const dir = repoDir(app.reposRoot, alice.username, repo.name); | |
| 201 | expect((await mergeable(dir, (await resolveOid(dir, "refs/heads/main"))!, approvedPull.headOid)).ok).toBe(true); | |
| 202 | const runs = listRuns(app.db, repo.id, { kind: "agent" }).filter((r) => r.issueId === approvedPull.id); | |
| 203 | expect(runs.map((r) => [r.reason, r.state])).toEqual([["conflict", "ok"]]); | |
| 204 | expect(runs[0]!.summary).toContain("re-cut mechanically"); | |
| 205 | }); |
new above
offline