Public: anyone can read this; the crew can change it.

Conflicts, by hand: an editor on the forge that makes a merge conflict a ten-second job, inexpensive, and a one-click way to have the crew propose the resolution #1351

Closed opened this in answer to
Closed without merging

scout/forge:scout/1134-conflicts-by-hand-an-editor-on-the-forge → main 6 commits fork 7 threads · 7 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
17 files changed +1790 −6
README.md +7
@@ -589,6 +589,13 @@ work here.
589589 highlighting composed with intra-line word highlighting, mobile-first,
590590 collapsible files), merge-commit and squash strategies, conflict detection,
591591 and merge commits kept reachable forever via `refs/pull/N/merged`.
592 - **Conflicts, by hand** — a conflicted pull's merge box has **Resolve**: an
593 editor with each block as ours / theirs / both / your own text, a running
594 count, and **Have the crew propose** for the one-tap alternative (it commits
595 a merge onto the pull's branch; forks and mirrors are settled where the
596 branch lives). In the terminal, press `p` on a conflicted pull to have the
597 crew resolve it; over MCP, call `propose_conflict_resolution`. Resolving
598 block by block is web-only for now. See `docs/PULLS.md`.
592599 - **Review comments** — anchored to a diff line by content hash, so a
593600 force-push re-anchors them or marks them outdated, never misplaces them.
594601 - **Forks** — alternates-backed (instant, storage-bounded), with cross-repo
docs/PULLS.md added +25
@@ -0,0 +1,25 @@
1 # Pulls: conflicts

Fine as a reference. The README is where people look, though, so it needs a pointer here and the terminal equivalent.

2
3 A conflicted open pull has a **Resolve** door on its page, to
4 `/:owner/:repo/pulls/:n/resolve`.
5
6 - **The editor** (`src/web/pages/conflicts.ts`) shows one file at a time. Each
7 conflict block is a card naming its sides by branch, with three choices —
8 ours (the pull's branch), theirs (the base), both — and a text box whose
9 content is kept verbatim. A running count ("2 of 3 resolved") and the merged
10 file beneath. Blocks scroll in their own list; a hundred do not flood.
11 - **Finish** (`resolveConflicts`, `src/actions/conflicts.ts`) takes the
12 `git merge-tree --write-tree` result, applies the choices (`src/git/markers.ts`),
13 writes a merge commit with `commit-tree` as the person and moves the pull's
14 head branch to it (compare-and-swap on the head and base the editor saw; if
15 either moved, nothing is written and the editor reloads). No clone, no work
16 tree, no agent, no tokens. Finish refuses while any block has no choice.
17 - **Have the crew propose** (`proposeResolution`) queues a `conflict` run on the
18 pull's own branch. Its brief (`src/crew/conflict_brief.ts`) carries both
19 sides' commits since the merge base, the conflicted files with markers, and
20 the tests that cover them. The agent commits to the branch and notes what it
21 chose; the person lands it or edits it in the same editor.
22
23 Not covered: pulls from forks or mirrors (their branch is not ours to write),
24 binary or delete/modify conflicts (the editor says so and offers the crew), and
25 more than 100 conflicted files (the crew takes those).
scripts/gate.ts +1
@@ -252,6 +252,7 @@ export const GATE: readonly string[] = [
252252 "test/ssh-site.test.ts",
253253 "test/web-code.test.ts",
254254 "test/web-origins.test.ts",
255 "test/conflicts.test.ts",
255256 ];
256257
257258 export const EXCLUDED: readonly Exclusion[] = [
src/actions/conflicts.ts added +254
@@ -0,0 +1,254 @@
1 /**
2 * Conflicts, by hand or by the crew. A conflicted pull is read as data
3 * (`loadConflicts`), settled by a person's choices into a merge commit on the
4 * pull's own branch (`resolveConflicts`), or handed to the crew with the
5 * whole git state in its brief (`proposeResolution`). No clone, no work tree.
6 */
7
8 import type { App } from "../app.ts";
9 import { crewRole, listCrew, type Agent } from "../core/agents.ts";
10 import { commitIdentity } from "../core/commit_identity.ts";
11 import { getIssueById } from "../core/issues.ts";
12 import { trackPullHead, type Pull } from "../core/pulls.ts";
13 import type { Repo } from "../core/repos.ts";
14 import { activeRunFor } from "../core/runs.ts";
15 import type { User } from "../core/users.ts";
16 import { agentFor, queueAgentRun } from "../crew/dispatch.ts";
17 import {
18 countBlocks,
19 resolveSegments,
20 type Choice,
21 type Segment,
22 parseMarkers,
23 } from "../git/markers.ts";
24 import {
25 commitResolution,
26 readTreeText,
27 resolveOid,
28 writeMergeTree,
29 } from "../git/merge.ts";
30 import { repoDir } from "../git/repos.ts";
31 import { err, ok, type Result } from "../kernel/result.ts";
32 import { requireWriter, type AccessError } from "./access.ts";
33
34 /** A conflict the editor would flood rather than show; the crew takes it. */
35 export const MAX_CONFLICT_FILES = 100;
36
37 export interface ConflictFile {
38 readonly path: string;
39 /** Undefined: not text with markers (binary, deleted on one side). */
40 readonly segments: readonly Segment[] | undefined;
41 }
42
43 export interface Conflicts {
44 readonly headBranch: string;
45 readonly baseBranch: string;
46 readonly headOid: string;
47 readonly baseOid: string;
48 readonly treeOid: string;
49 readonly files: readonly ConflictFile[];
50 }
51
52 export type ConflictError =
53 | AccessError
54 | "not_open"
55 | "not_here"
56 | "no_conflict"
57 | "too_many"
58 | "moved"
59 | "unresolved"
60 | "no_crew"
61 | "already_running"
62 | "not_queued"
63 | { kind: "git"; message: string };
64
65 /** Whether this pull's branch is ours to commit to: not a fork's, not a mirror's. */
66 export const resolvableHere = (repo: Repo, pull: Pull): boolean =>

High: a pull whose head is the default branch passes this check, so resolveConflicts update-refs main directly. That skips the receive hook's agent rule and protectDefault, and an agent's rw token is enough to do it. Add && pull.headBranch !== repo.defaultBranch here, and add a test that main does not move.

67 !pull.crossRepo && pull.originHeadRepo === null && repo.origin === null;
68
69 const guard = (
70 app: App,
71 actor: User | undefined,
72 repo: Repo,
73 pull: Pull,
74 ): Result<User, ConflictError> => {
75 const writer = requireWriter(app, actor, repo);
76 if (!writer.ok) return writer;
77 if (pull.repoId !== repo.id) return err("not_found");
78 if (pull.state !== "open" || pull.mergedAt !== null) return err("not_open");
79 // A fork's branch, or a mirror's, is not ours to commit to.
80 if (!resolvableHere(repo, pull)) return err("not_here");
81 return writer;
82 };
83
84 /** The conflicts of an open pull, read from the merge of its branch with base. */
85 export async function loadConflicts(
86 app: App,
87 actor: User | undefined,
88 repo: Repo,
89 pull: Pull,
90 ): Promise<Result<Conflicts, ConflictError>> {
91 const allowed = guard(app, actor, repo, pull);
92 if (!allowed.ok) return allowed;
93 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
94 const headOid = await resolveOid(dir, `refs/heads/${pull.headBranch}`);
95 const baseOid = await resolveOid(dir, `refs/heads/${pull.baseBranch}`);
96 if (headOid === undefined || baseOid === undefined) return err("not_found");
97 const merged = await writeMergeTree(dir, headOid, baseOid);
98 if (merged.ok) return err("no_conflict");
99 if (
100 merged.error.kind !== "conflict" ||
101 merged.error.treeOid === undefined ||
102 merged.error.files.length === 0
103 )
104 return err({
105 kind: "git",
106 message: merged.error.kind === "git" ? merged.error.message : "unmergeable",
107 });
108 const { treeOid, files } = merged.error;
109 if (files.length > MAX_CONFLICT_FILES) return err("too_many");
110 const read: ConflictFile[] = [];
111 for (const path of files) {
112 const text = await readTreeText(dir, treeOid, path);
113 read.push({
114 path,
115 segments: text === undefined ? undefined : parseMarkers(text),
116 });
117 }
118 return ok({
119 headBranch: pull.headBranch,
120 baseBranch: pull.baseBranch,
121 headOid,
122 baseOid,
123 treeOid,
124 files: read,
125 });
126 }
127
128 export interface Resolution {
129 /** The tips the person was shown; if either moved, nothing is written. */
130 readonly headOid: string;
131 readonly baseOid: string;
132 /** Per path, the choice for each block in order (undefined: not chosen). */
133 readonly choices: ReadonlyMap<string, readonly (Choice | undefined)[]>;
134 }
135
136 /** A text box's content: browsers send CRLF; the file gets LF, and ends a line. */
137 export function normalizeText(text: string): string {
138 const lf = text.replace(/\r\n?/g, "\n");
139 return lf === "" || lf.endsWith("\n") ? lf : `${lf}\n`;
140 }
141
142 /**
143 * Write the person's choices as a merge commit on the pull's branch: the
144 * branch's tip, then the base's, so the pull merges clean the moment it is
145 * pushed. Refuses unless every block of every file has a choice.
146 */
147 export async function resolveConflicts(
148 app: App,
149 actor: User | undefined,
150 repo: Repo,
151 pull: Pull,
152 resolution: Resolution,
153 ): Promise<Result<{ commitOid: string }, ConflictError>> {
154 const found = await loadConflicts(app, actor, repo, pull);
155 if (!found.ok) return found;
156 const conflicts = found.value;
157 if (
158 conflicts.headOid !== resolution.headOid ||
159 conflicts.baseOid !== resolution.baseOid
160 )
161 return err("moved");
162 const files: { path: string; content: string }[] = [];
163 for (const file of conflicts.files) {
164 if (file.segments === undefined) return err("unresolved");
165 const content = resolveSegments(
166 file.segments,
167 resolution.choices.get(file.path) ?? [],
168 );
169 if (content === undefined) return err("unresolved");
170 files.push({ path: file.path, content });
171 }
172 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
173 const author = commitIdentity(app.config, actor!);
174 const blocks = conflicts.files.reduce(
175 (n, f) => n + countBlocks(f.segments ?? []),
176 0,
177 );
178 const committed = await commitResolution(dir, {
179 branch: conflicts.headBranch,
180 headOid: conflicts.headOid,
181 baseOid: conflicts.baseOid,
182 treeOid: conflicts.treeOid,
183 files,
184 message: `Merge ${conflicts.baseBranch} into ${conflicts.headBranch}\n\nResolved ${blocks} conflict${blocks === 1 ? "" : "s"} in ${files.map((f) => f.path).join(", ")}.`,
185 author,
186 });
187 if (!committed.ok)
188 return err(
189 committed.error.kind === "base_moved"
190 ? "moved"
191 : { kind: "git", message: committed.error.kind },
192 );
193 trackPullHead(app.db, repo.id, conflicts.headBranch, committed.value.commitOid);
194 // `update-ref` runs no hooks; announce the push as a `git push` would.
195 app.bus.append({
196 kind: "push",
197 repoId: repo.id,
198 actorId: actor!.id,
199 payload: {
200 updates: [
201 {
202 ref: `refs/heads/${conflicts.headBranch}`,
203 newOid: committed.value.commitOid,
204 },
205 ],
206 viaApi: true,
207 },
208 });
209 return ok({ commitOid: committed.value.commitOid });
210 }
211
212 /** Who the crew would send: the pull's own agent, else the repo's builder. */
213 function crewFor(app: App, repo: Repo, pull: Pull): Agent | undefined {
214 const issue = getIssueById(app.db, pull.id);
215 if (issue === undefined) return undefined;
216 return (
217 agentFor(app, issue) ??
218 listCrew(app.db, repo.id).find(
219 (a) => (crewRole(app.db, repo.id, a.user.id) ?? "builder") === "builder",
220 )
221 );
222 }
223
224 /** One tap: queue a conflict run on the pull's own branch. */
225 export async function proposeResolution(
226 app: App,
227 actor: User | undefined,
228 repo: Repo,
229 pull: Pull,
230 ): Promise<Result<{ agent: string }, ConflictError>> {
231 const found = await loadConflicts(app, actor, repo, pull);
232 if (!found.ok) return found;
233 const issue = getIssueById(app.db, pull.id);
234 const agent = crewFor(app, repo, pull);
235 if (issue === undefined || agent === undefined) return err("no_crew");
236 if (activeRunFor(app.db, "agent", issue.id) !== undefined)
237 return err("already_running");
238 const run = queueAgentRun(
239 app,
240 repo,
241 issue,
242 agent,
243 "conflict",
244 actor?.id,
245 {
246 notBefore: new Date().toISOString(),
247 attempt: 0,
248 summary: `${pull.baseBranch} moved: ${found.value.files.map((f) => f.path).join(", ")}`,
outdated

The base branch is hardcoded as main. Use ${pull.baseBranch} moved: … so a pull against another base reads right in the run list.

249 },
250 );
251 return run === undefined
252 ? err("not_queued")
253 : ok({ agent: agent.user.username });
254 }
src/crew/brief.ts +12 −1
@@ -170,6 +170,8 @@ export interface TaskInput extends BriefInput {
170170 readonly checkKind?: "deploy" | "check" | undefined;
171171 /** For `conflict` and `converge`: the files both sides changed. */
172172 readonly conflictFiles?: readonly string[] | undefined;
173 /** For `conflict`: the whole git state of the conflict (`conflict_brief.ts`). */
174 readonly conflictState?: string | undefined;
173175 /** For `converge`: the parent this repository follows, and its branch. */
174176 readonly following?:
175177 | { readonly parent: string; readonly branch: string }
@@ -356,8 +358,17 @@ function taskBody(input: TaskInput): string {
356358 out.push(
357359 `Your pull #${issue.number} is green, but \`main\` moved and the branch no longer merges cleanly${files.length > 0 ? `: ${files.join(", ")}` : "."}`,
358360 "",
359 `Merge \`main\` into \`${input.branch}\`, resolve the conflicts keeping what both sides meant, make sure the tests pass, and push again.`,
361 `Merge \`${input.pull?.baseBranch ?? "main"}\` into \`${input.branch}\`, resolve the conflicts keeping what both sides meant, make sure the tests pass, and push again.`,
360362 );
363 if (input.conflictState)
364 out.push(
365 "",
366 `Here is the whole state, read from git, so you need not rediscover it:`,
367 "",
368 input.conflictState,
369 "",
370 `When you are done, say per file which side you kept and why, in a few lines: it is posted on the pull for the person who lands it, and they may open the same conflict in the editor to change a choice.`,
371 );
361372 return out.join("\n");
362373 }
363374
src/crew/conflict_brief.ts added +161
@@ -0,0 +1,161 @@
1 /**
2 * The git state of a conflicted pull, written down for the agent asked to
3 * resolve it: what each side did since they parted, which of the conflicted
4 * files each touched, the blocks as the merge leaves them, and the tests
5 * that name those files. Read from the bare repository, nothing written; a
6 * brief that carries this gets the resolution right the first time instead of
7 * spending a run finding it out.
8 */
9
10 import { runGit } from "../git/env.ts";
11 import { isSafeOid, isSafeTreePath } from "../git/guard.ts";
12 import { mergeBase, readTreeText, writeMergeTree } from "../git/merge.ts";
13 import { countBlocks, isBlock, parseMarkers } from "../git/markers.ts";
14
15 const COMMITS = 30;
16 const BLOCKS_SHOWN = 6;
17 const BLOCK_LINES = 20;
18 const TESTS_PER_FILE = 4;
19 export const BRIEF_MAX_CHARS = 9_000;
20
21 const lines = (text: string, n: number): string => {
22 const all = text.split("\n");
23 if (all.at(-1) === "") all.pop();
24 return all.length <= n
25 ? all.join("\n")
26 : `${all.slice(0, n).join("\n")}\n… (${all.length - n} more lines)`;
27 };
28
29 async function commitsSince(
30 dir: string,
31 from: string,
32 tip: string,
33 ): Promise<string> {
34 const out = await runGit(
35 ["log", `--max-count=${COMMITS}`, "--format=%h %an: %s", `${from}..${tip}`],
36 { cwd: dir },
37 );
38 return out.ok && out.value !== "" ? out.value : "(none)";
39 }
40
41 async function touched(
42 dir: string,
43 from: string,
44 tip: string,
45 ): Promise<Set<string>> {
46 const out = await runGit(["diff", "--name-only", from, tip], { cwd: dir });
47 return new Set(out.ok ? out.value.split("\n").filter(Boolean) : []);
48 }
49
50 /** Test files whose path carries the file's stem: the cheap, honest cover. */
51 export function testsFor(
52 tree: readonly string[],
53 path: string,
54 ): string[] {
55 const stem = (path.split("/").at(-1) ?? "").replace(/\.[^.]+$/, "");
56 if (stem.length < 3) return [];
57 return tree
58 .filter(
59 (p) =>
60 p !== path &&
61 /(^|\/)(test|tests|__tests__|spec)(\/|$)|\.(test|spec)\./.test(p) &&
62 (p.split("/").at(-1) ?? "").includes(stem),
63 )
64 .slice(0, TESTS_PER_FILE);
65 }
66
67 /**
68 * The state of `head` against `base`, as prose and fenced blocks. Empty when
69 * the pull is not in conflict (the caller then has nothing extra to say).
70 */
71 export async function conflictBrief(
72 dir: string,
73 input: {
74 headBranch: string;
75 baseBranch: string;
76 headOid: string;
77 baseOid: string;
78 },
79 ): Promise<string> {
80 const { headOid, baseOid } = input;
81 if (!isSafeOid(headOid) || !isSafeOid(baseOid)) return "";
82 const merged = await writeMergeTree(dir, headOid, baseOid);
83 if (merged.ok || merged.error.kind !== "conflict") return "";
84 const { files, treeOid } = merged.error;
85 const fork = await mergeBase(dir, headOid, baseOid);
86 const out: string[] = [];
87 if (fork !== undefined) {
88 const [mine, theirs, mineFiles, theirFiles] = await Promise.all([
89 commitsSince(dir, fork, headOid),
90 commitsSince(dir, fork, baseOid),
91 touched(dir, fork, headOid),
92 touched(dir, fork, baseOid),
93 ]);
94 out.push(
95 `The branches parted at ${fork.slice(0, 7)}.`,
96 "",
97 `On \`${input.headBranch}\` since then:`,
98 "```",
99 mine,
100 "```",
101 `On \`${input.baseBranch}\` since then:`,
102 "```",
103 theirs,
104 "```",
105 "",
106 );
107 out.push(
108 "Conflicted files, and who changed them:",
109 ...files.map(
110 (f) =>
111 `- ${f}: ${mineFiles.has(f) ? `\`${input.headBranch}\`` : ""}${
112 mineFiles.has(f) && theirFiles.has(f) ? " and " : ""
113 }${theirFiles.has(f) ? `\`${input.baseBranch}\`` : ""}`,
114 ),
115 "",
116 );
117 }
118 const tree = await runGit(["ls-tree", "-r", "--name-only", headOid], {
119 cwd: dir,
120 });
121 const names = tree.ok ? tree.value.split("\n") : [];
122 const covering = files.map((f) => [f, testsFor(names, f)] as const);
123 if (covering.some(([, t]) => t.length > 0))
124 out.push(
125 "Tests that name these files (run them):",
126 ...covering
127 .filter(([, t]) => t.length > 0)
128 .map(([f, t]) => `- ${f}: ${t.join(", ")}`),
129 "",
130 );
131 if (treeOid !== undefined) {
132 for (const path of files) {
133 if (!isSafeTreePath(path)) continue;
134 const text = await readTreeText(dir, treeOid, path);
135 const segments = text === undefined ? undefined : parseMarkers(text);
136 if (segments === undefined) {
137 out.push(`${path}: not text git can mark up (binary, deleted on one side); decide it by hand.`, "");
138 continue;
139 }
140 out.push(`${path}: ${countBlocks(segments)} conflict(s). Ours is \`${input.headBranch}\`, theirs is \`${input.baseBranch}\`.`);
141 let shown = 0;
142 for (const segment of segments) {
143 if (!isBlock(segment) || shown++ >= BLOCKS_SHOWN) continue;
144 out.push(
145 "```",
146 `<<<<<<< ${input.headBranch}`,
147 lines(segment.ours, BLOCK_LINES),
148 "=======",
149 lines(segment.theirs, BLOCK_LINES),
150 `>>>>>>> ${input.baseBranch}`,
151 "```",
152 );
153 }
154 out.push("");
155 }
156 }
157 const text = out.join("\n");
158 return text.length <= BRIEF_MAX_CHARS
159 ? text
160 : `${text.slice(0, BRIEF_MAX_CHARS)}\n… (cut; read the rest in the clone)`;
161 }
src/crew/runner.ts +14
@@ -76,6 +76,7 @@ import {
7676 type RunReason,
7777 } from "./brief.ts";
7878 import { policyBrief } from "../contract/audit.ts";
79 import { conflictBrief } from "./conflict_brief.ts";
7980 import { BUDGET_REACHED, runClaude, type ClaudeOutcome } from "./claude.ts";
8081 import {
8182 isRateLimited,
@@ -828,6 +829,19 @@ async function work(
828829 .split(", ")
829830 .filter((f) => f !== "")
830831 : undefined,
832 conflictState:
833 reason === "conflict" && pull !== undefined && !pull.crossRepo
834 ? await conflictBrief(bare, {
835 headBranch: pull.headBranch,
836 baseBranch: pull.baseBranch,
837 headOid:
838 (await resolveOid(bare, `refs/heads/${pull.headBranch}`)) ??
839 pull.headOid,
840 baseOid:
841 (await resolveOid(bare, `refs/heads/${pull.baseBranch}`)) ??
842 pull.baseOid,
843 })
844 : undefined,
831845 following:
832846 reason === "converge"
833847 ? (() => {
src/git/markers.ts added +102
@@ -0,0 +1,102 @@
1 /**
2 * Conflict markers as data. `merge-tree --write-tree` leaves each conflicted
3 * file in the merged tree with `<<<<<<<` / `=======` / `>>>>>>>` blocks; the
4 * editor needs the blocks apart from the text around them, and a person's
5 * choice per block turned back into a file. Pure strings in, strings out.
6 */
7
8 export interface ConflictBlock {
9 readonly ours: string;
10 readonly theirs: string;
11 }
12
13 /** A run of untouched text, or one conflict between two sides. */
14 export type Segment = string | ConflictBlock;
15
16 /** What a person chose for one block. `text` is kept verbatim. */
17 export type Choice =
18 | { readonly pick: "ours" | "theirs" | "both" }
19 | { readonly pick: "text"; readonly text: string };
20
21 export const isBlock = (segment: Segment): segment is ConflictBlock =>
22 typeof segment !== "string";
23
24 const START = /^<{7}(?: .*)?\r?\n?$/;
25 const MIDDLE = /^={7}\r?\n?$/;
26 const END = /^>{7}(?: .*)?\r?\n?$/;
27
28 /**
29 * Split a file into text and conflict blocks. Undefined when there are no
30 * markers or they do not close — a file the editor cannot honestly offer.
31 */
32 export function parseMarkers(text: string): Segment[] | undefined {
33 const lines = text.split(/(?<=\n)/);
34 const out: Segment[] = [];
35 let plain = "";
36 let side: "ours" | "theirs" | undefined;
37 let ours = "";
38 let theirs = "";
39 let blocks = 0;
40 for (const line of lines) {
41 if (side === undefined) {
42 if (START.test(line)) {
43 if (plain !== "") out.push(plain);
44 plain = "";
45 side = "ours";
46 ours = theirs = "";
47 } else plain += line;
48 } else if (side === "ours") {
49 if (MIDDLE.test(line)) side = "theirs";
50 else if (START.test(line)) return undefined;
51 else ours += line;
52 } else if (END.test(line)) {
53 out.push({ ours, theirs });
54 blocks++;
55 side = undefined;
56 } else if (START.test(line) || MIDDLE.test(line)) return undefined;
57 else theirs += line;
58 }
59 if (side !== undefined || blocks === 0) return undefined;
60 if (plain !== "") out.push(plain);
61 return out;
62 }
63
64 /** The text one choice stands for. */
65 export function choose(block: ConflictBlock, choice: Choice): string {
66 switch (choice.pick) {
67 case "ours":
68 return block.ours;
69 case "theirs":
70 return block.theirs;
71 case "both":
72 return block.ours + block.theirs;
73 case "text":
74 return choice.text;
75 }
76 }
77
78 /** How many blocks a file has. */
79 export const countBlocks = (segments: readonly Segment[]): number =>
80 segments.filter(isBlock).length;
81
82 /**
83 * The file with every block settled, or undefined while any block has no
84 * choice (`choices[i]` is the i-th block's). Never guesses.
85 */
86 export function resolveSegments(
87 segments: readonly Segment[],
88 choices: readonly (Choice | undefined)[],
89 ): string | undefined {
90 let out = "";
91 let i = 0;
92 for (const segment of segments) {
93 if (!isBlock(segment)) {
94 out += segment;
95 continue;
96 }
97 const choice = choices[i++];
98 if (choice === undefined) return undefined;
99 out += choose(segment, choice);
100 }
101 return out;
102 }
src/git/merge.ts +129 −4
@@ -5,8 +5,11 @@
55 * `update-ref` lands it only if the base hasn't moved under us.
66 */
77
8 import { rm } from "node:fs/promises";
9 import { join } from "node:path";
10 import { id } from "../kernel/id.ts";
811 import { err, ok, type Result } from "../kernel/result.ts";
9 import { runGit, runGitCapture } from "./env.ts";
12 import { runGit, runGitCapture, runGitRaw } from "./env.ts";
1013 import { isSafeOid, isSafeRef, isSafeTreePath } from "./guard.ts";
1114
1215 export type MergeStrategy = "merge" | "squash";
@@ -17,7 +20,7 @@ export interface MergeIdentity {
1720 }
1821
1922 export type MergeError =
20 | { kind: "conflict"; files: string[] }
23 | { kind: "conflict"; files: string[]; treeOid?: string }
2124 | { kind: "unsafe" }
2225 | { kind: "base_moved" }
2326 | { kind: "git"; message: string };
@@ -56,11 +59,17 @@ function parseWriteTree(
5659 }
5760 if (out.code === 1) {
5861 const files: string[] = [];
62 const treeOid = out.stdout.split("\n")[0]!.trim();
5963 for (const line of out.stdout.split("\n").slice(1)) {
6064 if (line.trim() === "") break; // blank line ends the conflict-file block
61 if (isSafeTreePath(line)) files.push(line);
65 if (isSafeTreePath(line) && !files.includes(line)) files.push(line);
6266 }
63 return err({ kind: "conflict", files });
67 // The tree of a conflicted merge holds the markers; the editor reads it.
68 return err({
69 kind: "conflict",
70 files,
71 ...(isSafeOid(treeOid) ? { treeOid } : {}),
72 });
6473 }
6574 return err({
6675 kind: "git",
@@ -351,3 +360,119 @@ export async function writeRef(
351360 const result = await runGit(["update-ref", ref, oid], { cwd: dir });
352361 return result.ok;
353362 }
363
364 /** A file's bytes as text at a tree, or undefined (missing, binary, huge). */
365 export async function readTreeText(
366 dir: string,
367 treeOid: string,
368 path: string,
369 maxBytes = 1024 * 1024,
370 ): Promise<string | undefined> {
371 if (!isSafeOid(treeOid) || !isSafeTreePath(path)) return undefined;
372 const size = await runGit(["cat-file", "-s", `${treeOid}:${path}`], {
373 cwd: dir,
374 });
375 if (!size.ok || Number(size.value) > maxBytes) return undefined;
376 const blob = await runGitRaw(["cat-file", "blob", `${treeOid}:${path}`], {
377 cwd: dir,
378 });
379 if (!blob.ok || blob.value.includes(0)) return undefined;
380 return new TextDecoder().decode(blob.value);
381 }
382
383 export interface ResolvedFile {
384 readonly path: string;
385 readonly content: string;
386 }
387
388 /**
389 * Seal a conflict as a merge commit on `branch`: the conflicted merge tree
390 * with each resolved file put in place of its markers, parents `headOid` then
391 * `baseOid`, landed with a CAS on the branch so a push in between wins and
392 * this says `base_moved`. Plumbing only — a throwaway index file, no work
393 * tree. The branch name is checked here; the caller has checked the person.
394 */
395 export async function commitResolution(
396 dir: string,
397 input: {
398 branch: string;
399 headOid: string;
400 baseOid: string;
401 treeOid: string;
402 files: readonly ResolvedFile[];
403 message: string;
404 author: MergeIdentity;
405 },
406 ): Promise<Result<{ commitOid: string }, MergeError>> {
407 if (
408 !isSafeRef(input.branch) ||
409 !isSafeOid(input.headOid) ||
410 !isSafeOid(input.baseOid) ||
411 !isSafeOid(input.treeOid) ||
412 input.files.some((f) => !isSafeTreePath(f.path))
413 )
414 return err({ kind: "unsafe" });
415 const indexFile = join(dir, `.forge-resolve-${id()}.index`);
416 const env = { GIT_INDEX_FILE: indexFile };
417 const fail = (e: { stderr: string }): Result<never, MergeError> =>
418 err({ kind: "git", message: e.stderr });
419 try {
420 const seed = await runGit(["read-tree", input.treeOid], { cwd: dir, env });
421 if (!seed.ok) return fail(seed.error);
422 for (const file of input.files) {
423 const entry = await runGit(
424 ["ls-tree", input.treeOid, "--", file.path],
425 { cwd: dir },
426 );
427 const mode = /^(100644|100755) blob /.exec(entry.ok ? entry.value : "");
428 const hashed = await runGit(["hash-object", "-w", "--stdin"], {
429 cwd: dir,
430 stdin: file.content,
431 });
432 if (!hashed.ok) return fail(hashed.error);
433 const staged = await runGit(
434 [
435 "update-index",
436 "--add",
437 "--cacheinfo",
438 `${mode?.[1] ?? "100644"},${hashed.value.trim()},${file.path}`,
439 ],
440 { cwd: dir, env },
441 );
442 if (!staged.ok) return fail(staged.error);
443 }
444 const tree = await runGit(["write-tree"], { cwd: dir, env });
445 if (!tree.ok) return fail(tree.error);
446 const commit = await runGit(
447 [
448 "commit-tree",
449 tree.value.trim(),
450 "-p",
451 input.headOid,
452 "-p",
453 input.baseOid,
454 "-m",
455 input.message,
456 ],
457 {
458 cwd: dir,
459 env: {
460 GIT_AUTHOR_NAME: input.author.name,
461 GIT_AUTHOR_EMAIL: input.author.email,
462 GIT_COMMITTER_NAME: input.author.name,
463 GIT_COMMITTER_EMAIL: input.author.email,
464 },
465 },
466 );
467 if (!commit.ok) return fail(commit.error);
468 const commitOid = commit.value.trim();
469 const update = await runGit(
470 ["update-ref", `refs/heads/${input.branch}`, commitOid, input.headOid],
471 { cwd: dir },
472 );
473 if (!update.ok) return err({ kind: "base_moved" });
474 return ok({ commitOid });
475 } finally {
476 await rm(indexFile, { force: true });
477 }
478 }
src/http/mcp.ts +38
@@ -32,6 +32,7 @@ import {
3232 linkIssue,
3333 unlinkIssue,
3434 } from "../actions/dependencies.ts";
35 import { proposeResolution } from "../actions/conflicts.ts";
3536 import { holdPull, releasePull } from "../actions/holds.ts";
3637 import { openPlan, parsePlan, PLAN_MAX } from "../actions/plan.ts";
3738 import { cancelRepoRun } from "../actions/runs.ts";
@@ -1683,6 +1684,43 @@ const TOOLS: readonly Tool[] = [
16831684 });
16841685 },
16851686 },
1687 {
1688 name: "propose_conflict_resolution",
1689 description:
1690 "Have the crew resolve a merge conflict on an open pull: queues a run on the pull's own branch, which pushes a merge commit and says what it chose and why. For a person or agent who can write the app; refused on forks and mirrors, when the pull merges cleanly, or when the crew is already on it. Answers with the agent's name.",
1691 inputSchema: {
1692 type: "object",
1693 properties: {
1694 app: APP_ARG,
1695 pull: { type: "integer", description: "The pull's number." },
1696 },
1697 required: ["app", "pull"],
1698 },
1699 writes: true,
1700 async run(ctx, user, args) {
1701 const repo = planRepo(ctx, user, args);
1702 if (isAnswer(repo)) return repo;
1703 const n = args["pull"];
1704 const pull =
1705 typeof n === "number" && Number.isInteger(n) && n > 0
1706 ? getPull(ctx.app.db, repo.id, n)
1707 : undefined;
1708 if (pull === undefined)
1709 return bad("no_such_pull", `no pull #${String(n)}`);
1710 const asked = await proposeResolution(ctx.app, user, repo, pull);
1711 if (!asked.ok)
1712 return bad(
1713 typeof asked.error === "string" ? asked.error : "git",
1714 typeof asked.error === "string"
1715 ? `the crew could not be asked: ${asked.error}`
1716 : asked.error.message,
1717 );
1718 return good({
1719 says: `${asked.value.agent} is resolving the conflict on ${repo.ownerName}/${repo.name}#${pull.number}.`,
1720 agent: asked.value.agent,
1721 });
1722 },
1723 },
16861724 {
16871725 name: "plan",
16881726 description: `Open several small issues and link them in one call: all of them or none. Each item has a key, a title, a body and optionally blockedBy, a list of keys of this plan or numbers of issues already open. Where the app has pillars (umbrella issues titled like "P0 Trust: …"), each item also says what it is for: pillar, the one it serves, or later: true with why, one sentence, which puts it behind the Later gate instead of on the ready list; an item that says neither is refused. A bad link (loop, unknown key) refuses the whole plan and names the item. At most ${PLAN_MAX} issues. Answers with the numbers opened, by key, what is ready now, and what waits for later.`,
src/http/server.ts +12
@@ -252,6 +252,11 @@ import {
252252 agentUpdate,
253253 crewPage,
254254 } from "../web/pages/crew.ts";
255 import {
256 resolveCrewSubmit,
257 resolvePage,
258 resolveSubmit,
259 } from "../web/pages/conflicts.ts";
255260 import { newPullPage, newPullSubmit } from "../web/pages/pulls.ts";
256261 import {
257262 changePage,
@@ -951,6 +956,13 @@ export function buildRouter(): Router<Handler> {
951956 threadResolveSubmit(false),
952957 );
953958 router.add("POST", "/:owner/:name/pulls/:number/merge", pullMergeSubmit);
959 router.add("GET", "/:owner/:name/pulls/:number/resolve", resolvePage);
960 router.add("POST", "/:owner/:name/pulls/:number/resolve", resolveSubmit);
961 router.add(
962 "POST",
963 "/:owner/:name/pulls/:number/resolve/crew",
964 resolveCrewSubmit,
965 );
954966 router.add("POST", "/:owner/:name/pulls/:number/state", (ctx) =>
955967 stateSubmit(ctx, "pull"),
956968 );
src/tui/screens/pull.ts +37
@@ -37,6 +37,7 @@ import {
3737 resolveReviewThread,
3838 submitReview,
3939 } from "../../actions/pulls.ts";
40 import { proposeResolution, resolvableHere } from "../../actions/conflicts.ts";
4041 import { openEnvUrl } from "../../actions/apps.ts";
4142 import { listRepoRuns } from "../../actions/runs.ts";
4243 import { previewEnv } from "../../apps/data.ts";
@@ -588,6 +589,35 @@ export function pullScreen(
588589 });
589590 };
590591
592 /** `p`: queue the crew on a conflicted pull and say who took it. */
593 const propose = (): void => {
594 if (repo === undefined) return;
595 const target = repo;
596 const row = getPull(f.db, target.id, number);
597 if (row === undefined) return;
598 runAsync(ctx, async () => {
599 const asked = await proposeResolution(f.app, f.user, target, row);
600 if (!asked.ok) {
601 ctx.toast(
602 typeof asked.error === "string"
603 ? errorText(asked.error)
604 : asked.error.message,
605 "danger",
606 );
607 return;
608 }
609 ctx.toast(`${asked.value.agent} is resolving the conflict`, "success");
610 });
611 };
612
613 /** The crew can resolve here: a writer, on a pull whose branch is this repo's. */
614 const canResolve = (): boolean => {
615 if (!mayWrite() || repo === undefined || state() !== "conflicts")
616 return false;
617 const row = getPull(f.db, repo.id, number);
618 return row !== undefined && resolvableHere(repo, row);
619 };
620
591621 const mirrored = (): boolean => repo === undefined || repo.origin !== null;
592622 const state = (): MergeState =>
593623 mergeState(detail?.issue, facts, mirrored(), gated(), checksGated());
@@ -615,6 +645,9 @@ export function pullScreen(
615645 binding(["R"], "review"),
616646 binding(["a"], "assign"),
617647 binding(["m"], "merge", { disabled: state() !== "ready" }),
648 ...(canResolve()
649 ? [binding(["p"], "have the crew resolve the conflict")]
650 : []),
618651 ...(tab === 1 && view.threadHere() !== null
619652 ? [
620653 binding(
@@ -835,6 +868,10 @@ export function pullScreen(
835868 }
836869 return true;
837870 }
871 if (e.key === "p" && canResolve()) {
872 propose();
873 return true;
874 }
838875 // A merge the gate would refuse says so here rather than going quiet:
839876 // `m` doing nothing is indistinguishable from `m` being unbound.
840877 if (e.key === "m" && mayWrite() && state() === "review_required") {
src/web/pages/conflicts.ts added +360
@@ -0,0 +1,360 @@
1 /**
2 * The conflict editor: a conflicted pull, one file at a time, each block a
3 * card with the two sides named by their branch — ours, theirs, both, or
4 * your own text — a running count, and the merged file beneath. It works
5 * with no script (every file stacked, radios and a form); the little script
6 * adds the tabs, the live result, the count and the o/t/b keys.
7 */
8
9 import {
10 loadConflicts,
11 normalizeText,
12 proposeResolution,
13 resolveConflicts,
14 type ConflictError,
15 type Conflicts,
16 } from "../../actions/conflicts.ts";
17 import type { Choice } from "../../git/markers.ts";
18 import { countBlocks, isBlock } from "../../git/markers.ts";
19 import type { Ctx } from "../../http/context.ts";
20 import { crumbsFor, pageHead, repoBase, repoPalette } from "../chrome.ts";
21 import { field, readForm } from "../form.ts";
22 import { html, type Html } from "../html.ts";
23 import { flashTo, page } from "../layout.ts";
24 import { btn, card, icon } from "../ui.ts";
25 import { pullContext } from "../studio/change.ts";
26 import { signInFirst } from "../chrome.ts";
27
28 /** Lines of untouched text shown before the merged view folds the middle. */
29 const KEEP = 3;
30
31 const WORDS: Record<string, string> = {
32 not_open: "This pull is no longer open.",
33 not_here:
34 "Conflicts on a fork or a mirror are settled where the branch lives.",
35 no_conflict: "No conflicts any more — the branches merge cleanly.",
36 too_many:
37 "Too many conflicted files for a page; have the crew propose a resolution.",
38 moved: "The branch moved while you edited. Open the editor again.",
39 unresolved: "Every block needs a choice before Finish.",
40 no_crew: "No one on the crew can take this: add a builder to the repository.",
41 already_running: "The crew is already working on this pull.",
42 not_queued: "The crew did not take the run (paused, parked or at its limit).",
43 forbidden: "You cannot write to this repository.",
44 unauthorized: "Sign in first.",
45 not_found: "Not found.",
46 };
47
48 const say = (error: ConflictError): string =>
49 typeof error === "string"
50 ? (WORDS[error] ?? error)
51 : `Git said no: ${error.message}`;
52
53 const CSS = `
54 .cf-bar{position:sticky;top:var(--topbar-h);z-index:5;display:flex;flex-wrap:wrap;gap:.5rem;align-items:center;justify-content:space-between;padding:.6rem .8rem;margin:.75rem 0;background:var(--card);border:1px solid var(--border);border-radius:var(--radius)}
55 .cf-count{font-weight:600}
56 .cf-tabs{display:flex;gap:.4rem;overflow-x:auto;padding-bottom:.25rem;margin-bottom:.75rem}
57 .cf-tab{white-space:nowrap;font:inherit;padding:.3rem .6rem;border:1px solid var(--border);border-radius:var(--radius-sm);background:var(--card);color:var(--fg);cursor:pointer}
58 .cf-tab[aria-current=true]{border-color:var(--accent);font-weight:600}
59 .cf-tab[data-done=true]::after{content:" ✓";color:var(--success)}
60 .cf-file{margin-bottom:2rem}
61 .cf-file[hidden]{display:none}
62 .cf-block{border:1px solid var(--border);border-radius:var(--radius);margin:0 0 .75rem;padding:.6rem;content-visibility:auto;contain-intrinsic-size:auto 14rem}
63 .cf-block:focus-within{border-color:var(--accent)}
64 .cf-block[data-done=true]{border-left:3px solid var(--success)}
65 .cf-block legend{padding:0 .3rem;font-size:.85em;color:var(--muted-fg)}
66 .cf-sides{display:grid;grid-template-columns:1fr 1fr;gap:.5rem}
67 @media (max-width:40rem){.cf-sides{grid-template-columns:1fr}}
68 .cf-side{display:block;min-width:0;border:1px solid var(--border);border-radius:var(--radius-sm);padding:.4rem;cursor:pointer}
69 .cf-side:has(input:checked),.cf-more:has(input:checked){border-color:var(--accent);background:color-mix(in srgb,var(--accent) 8%,transparent)}
70 .cf-name{font-weight:600}
71 .cf-side pre,.cf-merged{margin:.3rem 0 0;overflow-x:auto;font:.85em/1.45 var(--mono);white-space:pre}
72 .cf-more{display:block;margin-top:.5rem;border:1px solid var(--border);border-radius:var(--radius-sm);padding:.4rem}
73 .cf-more textarea{display:block;width:100%;box-sizing:border-box;margin-top:.4rem;font:.85em/1.45 var(--mono);min-height:4rem}
74 .cf-merged{border:1px solid var(--border);border-radius:var(--radius);padding:.6rem;max-height:28rem;overflow:auto}
75 .cf-merged .mb{background:color-mix(in srgb,var(--danger) 12%,transparent)}
76 .cf-merged .mb[data-done=true]{background:color-mix(in srgb,var(--success) 14%,transparent)}
77 .cf-fold{color:var(--muted-fg)}
78 `;
79
80 const SCRIPT = `
81 (() => {
82 const form = document.getElementById("cf-form");
83 if (!form) return;
84 const files = [...form.querySelectorAll(".cf-file")];
85 const blocks = [...form.querySelectorAll(".cf-block")];
86 const finish = document.getElementById("cf-finish");
87 const total = document.getElementById("cf-total");
88 const picked = (b) => b.querySelector("input[type=radio]:checked");
89 const text = (b, v) => {
90 const side = (s) => b.querySelector(".cf-" + s + " pre").textContent;
91 if (v === "ours") return side("ours");
92 if (v === "theirs") return side("theirs");
93 if (v === "both") return side("ours") + side("theirs");
94 const t = b.querySelector("textarea").value.replace(/\\r\\n?/g, "\\n");
95 return t === "" || t.endsWith("\\n") ? t : t + "\\n";
96 };
97 const show = (i) => {
98 files.forEach((f, n) => (f.hidden = n !== i));
99 form.querySelectorAll(".cf-tab").forEach((t, n) =>
100 t.setAttribute("aria-current", String(n === i)));
101 };
102 const refresh = () => {
103 let done = 0;
104 for (const b of blocks) {
105 const p = picked(b);
106 const ok = !!p;
107 if (ok) done++;
108 b.dataset.done = String(ok);
109 const span = form.querySelector('.mb[data-b="' + b.dataset.b + '"]');
110 if (span) {
111 span.dataset.done = String(ok);
112 if (ok) span.textContent = text(b, p.value);
113 }
114 }
115 files.forEach((f, n) => {
116 const mine = [...f.querySelectorAll(".cf-block")];
117 const d = mine.filter(picked).length;
118 f.querySelector(".cf-fcount").textContent = d + " of " + mine.length + " resolved";
119 const tab = form.querySelector('.cf-tab[data-i="' + n + '"]');
120 if (tab) tab.dataset.done = String(d === mine.length);
121 });
122 total.textContent = done + " of " + blocks.length + " resolved";
123 finish.disabled = done !== blocks.length;
124 };
125 form.addEventListener("change", refresh);
126 form.addEventListener("input", (e) => {
127 const t = e.target;
128 if (t.tagName === "TEXTAREA") {
129 t.closest(".cf-block").querySelector('input[value="text"]').checked = true;
130 refresh();
131 }
132 });
133 form.addEventListener("click", (e) => {
134 const tab = e.target.closest(".cf-tab");
135 if (tab) show(Number(tab.dataset.i));
136 });
137 document.addEventListener("keydown", (e) => {
138 if (e.target.tagName === "TEXTAREA" || e.metaKey || e.ctrlKey || e.altKey) return;
139 const b = document.activeElement && document.activeElement.closest(".cf-block");
140 const v = { o: "ours", t: "theirs", b: "both" }[e.key];
141 if (!b || !v) return;
142 b.querySelector('input[value="' + v + '"]').checked = true;
143 refresh();
144 const next = blocks.slice(blocks.indexOf(b) + 1).find((x) => !picked(x));
145 if (next) { const f = next.closest(".cf-file"); show(files.indexOf(f)); next.querySelector("input").focus(); next.scrollIntoView({ block: "center" }); }
146 });
147 files.forEach((f) => f.dataset.js = "1");
148 show(0);
149 refresh();
150 })();
151 `;
152
153 /** The merged file beneath: long untouched runs fold, blocks wait to be chosen. */
154 function mergedView(file: Conflicts["files"][number], fi: number): Html {
155 let b = 0;
156 return html`<pre class="cf-merged" aria-label="Merged file">${(
157 file.segments ?? []
158 ).map((segment) => {
159 if (isBlock(segment))
160 return html`<span class="mb" data-b="${fi}-${b++}" data-done="false"
161 >${"<<<<<<<\n"}${segment.ours}${"=======\n"}${segment.theirs}${">>>>>>>\n"}</span
162 >`;
163 const rows = segment.split(/(?<=\n)/);
164 return rows.length <= KEEP * 2 + 2
165 ? html`${segment}`
166 : html`${rows.slice(0, KEEP).join("")}<span class="cf-fold"
167 >… ${rows.length - KEEP * 2} unchanged lines
168 </span>${rows.slice(-KEEP).join("")}`;
169 })}</pre>`;
170 }
171
172 function blockCard(
173 c: Conflicts,
174 fi: number,
175 bi: number,
176 of: number,
177 ours: string,
178 theirs: string,
179 ): Html {
180 const name = `c-${fi}-${bi}`;
181 return html`<fieldset class="cf-block" data-b="${fi}-${bi}">
182 <legend>Conflict ${bi + 1} of ${of}</legend>
183 <div class="cf-sides">
184 <label class="cf-side cf-ours">
185 <input type="radio" name="${name}" value="ours" />
186 <span class="cf-name">${c.headBranch}</span> <span class="muted small">ours · tap o</span>
187 <pre>${ours}</pre>
188 </label>
189 <label class="cf-side cf-theirs">
190 <input type="radio" name="${name}" value="theirs" />
191 <span class="cf-name">${c.baseBranch}</span> <span class="muted small">theirs · tap t</span>
192 <pre>${theirs}</pre>
193 </label>
194 </div>
195 <label class="cf-more">
196 <input type="radio" name="${name}" value="both" />
197 Keep both, ours then theirs <span class="muted small">tap b</span>
198 </label>
199 <label class="cf-more">
200 <input type="radio" name="${name}" value="text" />
201 Write my own
202 <textarea name="t-${fi}-${bi}" rows="3" spellcheck="false" maxlength="100000"></textarea>
203 </label>
204 </fieldset>`;
205 }
206
207 function fileSection(c: Conflicts, fi: number): Html {
208 const file = c.files[fi]!;
209 if (file.segments === undefined)
210 return html`<section class="cf-file" id="f-${fi}">
211 <h2 class="mono">${file.path}</h2>
212 <p class="error-note" role="alert">
213 ${icon("alert")}<span
214 >This file is binary, or deleted on one side — it cannot be settled
215 here. Have the crew propose, or resolve it in a clone.</span
216 >
217 </p>
218 </section>`;
219 const n = countBlocks(file.segments);
220 let bi = 0;
221 return html`<section class="cf-file" id="f-${fi}">
222 <h2><span class="mono">${file.path}</span>
223 <span class="muted small cf-fcount">0 of ${n} resolved</span></h2>
224 ${file.segments.map((s) =>
225 isBlock(s) ? blockCard(c, fi, bi++, n, s.ours, s.theirs) : html``,
226 )}
227 <h3 class="small muted">The merged file</h3>
228 ${mergedView(file, fi)}
229 </section>`;
230 }
231
232 // GET /:owner/:name/pulls/:number/resolve
233 export async function resolvePage(ctx: Ctx): Promise<Response> {
234 const found = pullContext(ctx);
235 if (found instanceof Response) return found;
236 if (!ctx.auth.user) return signInFirst(ctx);
237 const { repo, pull } = found;
238 const base = repoBase(repo);
239 const back = `${base}/pulls/${pull.number}/files`;
240 const loaded = await loadConflicts(ctx.app, ctx.auth.user, repo, pull);
241 if (!loaded.ok)
242 return flashTo(ctx, back, {
243 tone: loaded.error === "no_conflict" ? "attn" : "danger",
244 message: say(loaded.error),
245 });
246 const c = loaded.value;
247 const blocks = c.files.reduce((n, f) => n + countBlocks(f.segments ?? []), 0);
248 const settleable = c.files.every((f) => f.segments !== undefined);
249 const action = `${base}/pulls/${pull.number}/resolve`;
250 const body = html`${pageHead(html`${icon("alert")}Resolve conflicts`, {
251 sub: html`<span class="mono">${c.headBranch}</span> ← merging
252 <span class="mono">${c.baseBranch}</span> · ${blocks}
253 conflict${blocks === 1 ? "" : "s"} in ${c.files.length}
254 file${c.files.length === 1 ? "" : "s"}`,
255 })}
256 <form id="cf-form" method="post" action="${action}">
257 <input type="hidden" name="head" value="${c.headOid}" />
258 <input type="hidden" name="base" value="${c.baseOid}" />
259 <div class="cf-bar">
260 <span class="cf-count" id="cf-total" aria-live="polite">0 of ${blocks} resolved</span>
261 <span>
262 ${btn("Have the crew propose", {
263 variant: "outline",
264 icon: "bot",
265 form: "cf-crew",
266 })}
267 ${btn("Finish", { variant: "primary", icon: "check" })}
268 </span>
269 </div>
270 ${c.files.length > 1
271 ? html`<nav class="cf-tabs" aria-label="Files">${c.files.map(
272 (f, i) =>
273 html`<a class="cf-tab" data-i="${i}" href="#f-${i}" role="button" aria-current="false">${f.path}</a>`,
274 )}</nav>`
275 : html``}
276 ${c.files.map((_, i) => fileSection(c, i))}
277 </form>
278 <form id="cf-crew" method="post" action="${action}/crew"></form>
279 ${settleable
280 ? html``
281 : card(html`<p class="muted small">Some files cannot be edited here; Finish will refuse until the crew or a clone settles them.</p>`)}`;
282 return page({
283 ctx,
284 title: `Resolve · ${pull.title} · ${repo.name}`,
285 crumbs: crumbsFor(repo),
286 palette: repoPalette(ctx, repo),
287 body,
288 styleCss: CSS,
289 scriptJs: SCRIPT,
290 });
291 }
292
293 const CHOICES = new Set(["ours", "theirs", "both", "text"]);
294
295 // POST /:owner/:name/pulls/:number/resolve
296 export async function resolveSubmit(ctx: Ctx): Promise<Response> {
297 const found = pullContext(ctx);
298 if (found instanceof Response) return found;
299 if (!ctx.auth.user) return new Response("forbidden", { status: 403 });
300 const form = await readForm(ctx, "rw");
301 if (form instanceof Response) return form;
302 const { repo, pull } = found;
303 const base = repoBase(repo);
304 const here = `${base}/pulls/${pull.number}`;
305 const loaded = await loadConflicts(ctx.app, ctx.auth.user, repo, pull);
306 if (!loaded.ok)
307 return flashTo(ctx, `${here}/files`, {
308 tone: "danger",
309 message: say(loaded.error),
310 });
311 const choices = new Map<string, (Choice | undefined)[]>();
312 loaded.value.files.forEach((file, fi) => {
313 const mine: (Choice | undefined)[] = [];
314 for (let bi = 0; bi < countBlocks(file.segments ?? []); bi++) {
315 const pick = field(form, `c-${fi}-${bi}`);
316 mine.push(
317 !CHOICES.has(pick)
318 ? undefined
319 : pick === "text"
320 ? { pick, text: normalizeText(field(form, `t-${fi}-${bi}`)) }
321 : { pick: pick as "ours" | "theirs" | "both" },
322 );
323 }
324 choices.set(file.path, mine);
325 });
326 const done = await resolveConflicts(ctx.app, ctx.auth.user, repo, pull, {
327 headOid: field(form, "head"),
328 baseOid: field(form, "base"),
329 choices,
330 });
331 if (!done.ok)
332 return flashTo(
333 ctx,
334 done.error === "unresolved" ? `${here}/resolve` : `${here}/files`,
335 { tone: "danger", message: say(done.error) },
336 );
337 return flashTo(ctx, `${here}/files`, {
338 message: "Conflicts resolved — the branch now merges cleanly.",
339 });
340 }
341
342 // POST /:owner/:name/pulls/:number/resolve/crew
343 export async function resolveCrewSubmit(ctx: Ctx): Promise<Response> {
344 const found = pullContext(ctx);
345 if (found instanceof Response) return found;
346 if (!ctx.auth.user) return new Response("forbidden", { status: 403 });
347 const form = await readForm(ctx, "rw");
348 if (form instanceof Response) return form;
349 const { repo, pull } = found;
350 const here = `${repoBase(repo)}/pulls/${pull.number}`;
351 const asked = await proposeResolution(ctx.app, ctx.auth.user, repo, pull);
352 if (!asked.ok)
353 return flashTo(ctx, `${here}/files`, {
354 tone: "danger",
355 message: say(asked.error),
356 });
357 return flashTo(ctx, here, {
358 message: `${asked.value.agent} is resolving the conflict on this branch. It will push a commit and say what it chose and why; open the editor to change a choice.`,
359 });
360 }
src/web/pages/pull.ts +13 −1
@@ -8,6 +8,7 @@
88 * it needs.
99 */
1010
11 import { resolvableHere } from "../../actions/conflicts.ts";
1112 import { askCheck } from "../../checks/again.ts";
1213 import { addCommentThrough } from "../../actions/issues.ts";
1314 import type { AccessError } from "../../actions/access.ts";
@@ -414,7 +415,18 @@ function mergeBox(
414415 <div class="merge-headline">Can't merge.</div>
415416 <p class="merge-sub">${reason}</p>
416417 ${reviewsChip(status.reviews, by)} ${checks}
417 </div>`,
418 </div>
419 ${when(
420 mayMerge && status.conflicts.length > 0 && resolvableHere(repo, pull),
421 () =>
422 html`<span class="merge-form"
423 >${btn("Resolve", {
424 href: `${repoBase(repo)}/pulls/${pull.number}/resolve`,
425 variant: "primary",
426 icon: "merge",
427 })}</span
428 >`,
429 )}`,
418430 { tone: "danger", extra: "merge-box" },
419431 );
420432 }
test/conflicts.test.ts added +511
@@ -0,0 +1,511 @@
1 /**
2 * Conflicts, by hand and by the crew: a two-block conflict settled with
3 * "both" gives the expected file and a mergeable pull; a text-box answer is
4 * kept as typed; a stale editor writes nothing; the crew's run carries the
5 * whole git state, and a resolution lands as a commit on the head branch.
6 */
7
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import {
14 loadConflicts,
15 proposeResolution,
16 resolveConflicts,
17 } from "../src/actions/conflicts.ts";
18 import { addToCrew, createAgent } from "../src/actions/crew.ts";
19 import { openPull } from "../src/actions/pulls.ts";
20 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
21 import { conflictBrief } from "../src/crew/conflict_brief.ts";
22 import { taskPrompt } from "../src/crew/brief.ts";
23 import { getAgent } from "../src/core/agents.ts";
24 import { createToken } from "../src/core/tokens.ts";
25 import { getPull, pullStatus, type Pull } from "../src/core/pulls.ts";
26 import type { Repo } from "../src/core/repos.ts";
27 import { listRuns } from "../src/core/runs.ts";
28 import { createUser, getUserByName, type User } from "../src/core/users.ts";
29 import { runGit } from "../src/git/env.ts";
30 import { parseMarkers, resolveSegments } from "../src/git/markers.ts";
31 import { resolveOid } from "../src/git/merge.ts";
32 import { repoDir } from "../src/git/repos.ts";
33 import { forgeHttp, serve, type ForgeHttp, type Servers } from "../src/http/server.ts";
34
35 const BASE = "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\n";
36 const edit = (lines: Record<string, string>): string =>
37 BASE.split("\n")
38 .map((l) => lines[l] ?? l)
39 .join("\n");
40
41 describe("markers", () => {
42 test("blocks come apart from the text around them, and choices put them back", () => {
43 const segments = parseMarkers(
44 "a\n<<<<<<< x\nours\n=======\ntheirs\n>>>>>>> y\nb\n",
45 )!;
46 expect(segments).toEqual(["a\n", { ours: "ours\n", theirs: "theirs\n" }, "b\n"]);
47 expect(resolveSegments(segments, [{ pick: "both" }])).toBe(
48 "a\nours\ntheirs\nb\n",
49 );
50 expect(resolveSegments(segments, [{ pick: "text", text: "mine\n" }])).toBe(
51 "a\nmine\nb\n",
52 );
53 // No guess while a block has no choice.
54 expect(resolveSegments(segments, [undefined])).toBeUndefined();
55 expect(parseMarkers("plain\n")).toBeUndefined();
56 expect(parseMarkers("<<<<<<< x\nunclosed\n")).toBeUndefined();
57 });
58 });
59
60 describe("a conflicted pull", () => {
61 let dataDir: string;
62 let app: App;
63 let servers: Servers;
64 let alice: User;
65 let atlas: User;
66 let repo: Repo;
67 let pull: Pull;
68 const dir = () => repoDir(app.reposRoot, repo.ownerName, repo.name);
69
70 const put = async (branch: string, content: string, message: string) => {
71 const done = await commitToBranch(app, alice, repo, {
72 branch,
73 message,
74 files: [{ path: "list.txt", content }],
75 });
76 if (!done.ok) throw new Error(JSON.stringify(done.error));
77 };
78
79 beforeAll(async () => {
80 dataDir = await mkdtemp(join(tmpdir(), "forge-conflicts-"));
81 app = createApp({ dataDir, port: 0 });
82 servers = await serve(app);
83 const a = await createUser(app.db, {
84 trusted: true,
85 username: "alice",
86 email: "[email protected]",
87 password: "a-good-passphrase",
88 adminIfFirst: true,
89 });
90 if (!a.ok) throw new Error(a.error);
91 alice = a.value;
92 const made = await createRepo(app, alice, { name: "lists", visibility: "private" });
93 if (!made.ok) throw new Error(String(made.error));
94 repo = made.value;
95 await put("main", BASE, "Start");
96 await commitToBranch(app, alice, repo, {
97 branch: "main",
98 message: "A test that names list",
99 files: [{ path: "test/list.test.ts", content: "// list\n" }],
100 });
101 const agent = await createAgent(app, alice, { username: "atlas" });
102 if (!agent.ok) throw new Error(String(agent.error));
103 const added = addToCrew(app, alice, repo, "atlas");
104 if (!added.ok) throw new Error(`crew: ${added.error}`);
105 atlas = getUserByName(app.db, "atlas")!;
106 // The branch adds a line after "two" and after "eight"; main adds
107 // different lines in the same two places.
108 await commitToBranch(app, alice, repo, {
109 branch: "feature/both",
110 base: "main",
111 message: "Branch adds lines",
112 files: [
113 {
114 path: "list.txt",
115 content: edit({ two: "two\ntwo-branch", eight: "eight\neight-branch" }),
116 },
117 ],
118 });
119 await put(
120 "main",
121 edit({ two: "two\ntwo-main", eight: "eight\neight-main" }),
122 "Main adds lines",
123 );
124 const opened = await openPull(app, alice, repo, {
125 title: "Both add",
126 baseBranch: "main",
127 headBranch: "feature/both",
128 });
129 if (!opened.ok) throw new Error(String(opened.error));
130 pull = opened.value;
131 });
132
133 afterAll(async () => {
134 await servers.stop();
135 await rm(dataDir, { recursive: true, force: true });
136 });
137
138 test("the conflict is read as two blocks, ours the branch, theirs the base", async () => {
139 const found = await loadConflicts(app, alice, repo, pull);
140 if (!found.ok) throw new Error(String(found.error));
141 expect(found.value.files.map((f) => f.path)).toEqual(["list.txt"]);
142 const blocks = found.value.files[0]!.segments!.filter((s) => typeof s !== "string");
143 expect(blocks).toEqual([
144 { ours: "two-branch\n", theirs: "two-main\n" },
145 { ours: "eight-branch\n", theirs: "eight-main\n" },
146 ]);
147 });
148
149 test("the editor page renders, with both branches named and the count", async () => {
150 const { token } = createToken(app.db, alice.id, "t", "rw");
151 const res = await fetch(
152 `${servers.url}/alice/lists/pulls/${pull.number}/resolve`,
153 { headers: { authorization: `Bearer ${token}` } },
154 );
155 expect(res.status).toBe(200);
156 const text = await res.text();
157 expect(text).toContain("feature/both");
158 expect(text).toContain("0 of 2 resolved");
159 expect(text).toContain("two-main");
160 expect(text).toContain('name="c-0-1"');
161 });
162
163 test("an unfinished editor, or a stale one, writes nothing", async () => {
164 const head = await resolveOid(dir(), "refs/heads/feature/both");
165 const found = await loadConflicts(app, alice, repo, pull);
166 if (!found.ok) throw new Error("load");
167 const c = found.value;
168 const half = await resolveConflicts(app, alice, repo, pull, {
169 headOid: c.headOid,
170 baseOid: c.baseOid,
171 choices: new Map([["list.txt", [{ pick: "ours" as const }, undefined]]]),
172 });
173 expect(half).toEqual({ ok: false, error: "unresolved" });
174 const stale = await resolveConflicts(app, alice, repo, pull, {
175 headOid: "0".repeat(40),
176 baseOid: c.baseOid,
177 choices: new Map(),
178 });
179 expect(stale).toEqual({ ok: false, error: "moved" });
180 expect(await resolveOid(dir(), "refs/heads/feature/both")).toBe(head!);
181 });
182
183 test("the crew's brief carries both sides, the files and the tests", async () => {
184 const state = await conflictBrief(dir(), {
185 headBranch: "feature/both",
186 baseBranch: "main",
187 headOid: (await resolveOid(dir(), "refs/heads/feature/both"))!,
188 baseOid: (await resolveOid(dir(), "refs/heads/main"))!,
189 });
190 expect(state).toContain("Branch adds lines");
191 expect(state).toContain("Main adds lines");
192 expect(state).toContain("list.txt");
193 expect(state).toContain("test/list.test.ts");
194 expect(state).toContain("<<<<<<< feature/both");
195 const agent = getAgent(app.db, atlas.id)!;
196 const prompt = taskPrompt({
197 agent,
198 repo,
199 issue: pull,
200 pull,
201 branch: "feature/both",
202 forgeUrl: "http://forge.test",
203 isApp: false,
204 resuming: false,
205 reason: "conflict",
206 comments: [],
207 reviews: [],
208 reviewComments: [],
209 since: "",
210 conflictFiles: ["list.txt"],
211 conflictState: state,
212 });
213 expect(prompt).toContain("Main adds lines");
214 expect(prompt).toContain("which side you kept and why");
215 });
216
217 test("one tap queues a conflict run on the pull's own branch", async () => {
218 const asked = await proposeResolution(app, alice, repo, pull);
219 expect(asked).toEqual({ ok: true, value: { agent: "atlas" } });
220 const runs = listRuns(app.db, repo.id, { kind: "agent" }).filter(
221 (r) => r.issueId === pull.id && r.reason === "conflict",
222 );
223 expect(runs.length).toBe(1);
224 expect(runs[0]!.summary).toBe("main moved: list.txt");
225 // A second tap does not queue a second run.
226 const again = await proposeResolution(app, alice, repo, pull);
227 expect(again).toEqual({ ok: false, error: "already_running" });
228 });
229
230 test("'both' on two blocks gives the expected file and a mergeable pull", async () => {
231 const found = await loadConflicts(app, alice, repo, pull);
232 if (!found.ok) throw new Error("load");
233 const c = found.value;
234 const done = await resolveConflicts(app, alice, repo, pull, {
235 headOid: c.headOid,
236 baseOid: c.baseOid,
237 choices: new Map([
238 ["list.txt", [{ pick: "both" as const }, { pick: "both" as const }]],
239 ]),
240 });
241 if (!done.ok) throw new Error(JSON.stringify(done.error));
242 const file = await runGit(["show", "feature/both:list.txt"], { cwd: dir() });
243 expect(file.ok && file.value + "\n").toBe(
244 edit({
245 two: "two\ntwo-branch\ntwo-main",
246 eight: "eight\neight-branch\neight-main",
247 }),
248 );
249 const parents = await runGit(["rev-list", "--parents", "-n1", "feature/both"], {
250 cwd: dir(),
251 });
252 expect(parents.ok && parents.value.split(" ").length).toBe(3);
253 const author = await runGit(["log", "-1", "--format=%an", "feature/both"], {
254 cwd: dir(),
255 });
256 expect(author.ok && author.value).toBe(alice.displayName || alice.username);
257 const status = await pullStatus(dir(), getPull(app.db, repo.id, pull.number)!);
258 expect(status.mergeable).toBe(true);
259 expect(getPull(app.db, repo.id, pull.number)!.headOid).toBe(
260 done.value.commitOid,
261 );
262 });
263 });
264
265 describe("a text-box answer, and a crew resolution", () => {
266 let dataDir: string;
267 let app: App;
268 let alice: User;
269 let repo: Repo;
270 let pull: Pull;
271 const dir = () => repoDir(app.reposRoot, repo.ownerName, repo.name);
272
273 beforeAll(async () => {
274 dataDir = await mkdtemp(join(tmpdir(), "forge-conflicts2-"));
275 app = createApp({ dataDir, port: 0 });
276 const a = await createUser(app.db, {
277 trusted: true,
278 username: "alice",
279 email: "[email protected]",
280 password: "a-good-passphrase",
281 adminIfFirst: true,
282 });
283 if (!a.ok) throw new Error(a.error);
284 alice = a.value;
285 const made = await createRepo(app, alice, { name: "notes", visibility: "private" });
286 if (!made.ok) throw new Error(String(made.error));
287 repo = made.value;
288 const put = (branch: string, content: string, base?: string) =>
289 commitToBranch(app, alice, repo, {
290 branch,
291 ...(base === undefined ? {} : { base }),
292 message: `${branch} says`,
293 files: [{ path: "n.txt", content }],
294 });
295 await put("main", "top\nmiddle\nbottom\n");
296 await put("feature/x", "top\nbranch middle\nbottom\n", "main");
297 await put("main", "top\nmain middle\nbottom\n");
298 const opened = await openPull(app, alice, repo, {
299 title: "X",
300 baseBranch: "main",
301 headBranch: "feature/x",
302 });
303 if (!opened.ok) throw new Error(String(opened.error));
304 pull = opened.value;
305 });
306
307 afterAll(() => rm(dataDir, { recursive: true, force: true }));
308
309 test("typed text is kept verbatim, and the resolution lands on the head branch", async () => {
310 const found = await loadConflicts(app, alice, repo, pull);
311 if (!found.ok) throw new Error("load");
312 const c = found.value;
313 const text = " mine: <b>&amp;</b>\tkept\n\nas typed\n";
314 const done = await resolveConflicts(app, alice, repo, pull, {
315 headOid: c.headOid,
316 baseOid: c.baseOid,
317 choices: new Map([["n.txt", [{ pick: "text" as const, text }]]]),
318 });
319 if (!done.ok) throw new Error(JSON.stringify(done.error));
320 const file = await runGit(["show", "feature/x:n.txt"], { cwd: dir() });
321 expect(file.ok && file.value).toBe(`top\n${text}bottom`);
322 const tip = await resolveOid(dir(), "refs/heads/feature/x");
323 expect(tip).toBe(done.value.commitOid);
324 expect((await pullStatus(dir(), pull)).mergeable).toBe(true);
325 // Settled: the editor has nothing left to show.
326 const after = await loadConflicts(app, alice, repo, pull);
327 expect(after).toEqual({ ok: false, error: "no_conflict" });
328 });
329 });
330
331 describe("the doors that write", () => {
332 let dataDir: string;
333 let app: App;
334 let http: ForgeHttp;
335 const ORIGIN = "http://forge.test";
336 let alice: User;
337 let repo: Repo;
338 let pull: Pull;
339 let rw: string;
340 let ro: string;
341 let bob: string;
342 const dir = () => repoDir(app.reposRoot, repo.ownerName, repo.name);
343 const url = (tail: string) =>
344 `${ORIGIN}/alice/pub/pulls/${pull.number}/${tail}`;
345 const post = (
346 tail: string,
347 body: URLSearchParams,
348 headers: Record<string, string> = {},
349 ) =>
350 http.handle(
351 new Request(url(tail), { method: "POST", body, headers }),
352 );
353 const tip = () => resolveOid(dir(), "refs/heads/feature/both");
354
355 beforeAll(async () => {
356 dataDir = await mkdtemp(join(tmpdir(), "forge-conflicts3-"));
357 app = createApp({ dataDir, port: 0 });
358 http = forgeHttp(app);
359 const make = async (username: string) => {
360 const u = await createUser(app.db, {
361 trusted: true,
362 username,
363 email: `${username}@forge.local`,
364 password: "a-good-passphrase",
365 adminIfFirst: username === "alice",
366 });
367 if (!u.ok) throw new Error(u.error);
368 return u.value;
369 };
370 alice = await make("alice");
371 const other = await make("bob");
372 rw = createToken(app.db, alice.id, "rw", "rw").token;
373 ro = createToken(app.db, alice.id, "ro", "ro").token;
374 bob = createToken(app.db, other.id, "rw", "rw").token;
375 const made = await createRepo(app, alice, { name: "pub", visibility: "public" });
376 if (!made.ok) throw new Error(String(made.error));
377 repo = made.value;
378 const put = async (branch: string, content: string, base?: string) => {
379 const done = await commitToBranch(app, alice, repo, {
380 branch,
381 ...(base === undefined ? {} : { base }),
382 message: `${branch} says`,
383 files: [{ path: "list.txt", content }],
384 });
385 if (!done.ok) throw new Error(JSON.stringify(done.error));
386 };
387 await put("main", BASE);
388 await put(
389 "feature/both",
390 edit({ two: "two\ntwo-branch", eight: "eight\neight-branch" }),
391 "main",
392 );
393 await put("main", edit({ two: "two\ntwo-main", eight: "eight\neight-main" }));
394 const opened = await openPull(app, alice, repo, {
395 title: "Both add",
396 baseBranch: "main",
397 headBranch: "feature/both",
398 });
399 if (!opened.ok) throw new Error(String(opened.error));
400 pull = opened.value;
401 });
402
403 afterAll(async () => {
404 await rm(dataDir, { recursive: true, force: true });
405 });
406
407 const fields = async (): Promise<URLSearchParams> => {
408 const c = await loadConflicts(app, alice, repo, pull);
409 if (!c.ok) throw new Error("load");
410 return new URLSearchParams({
411 head: c.value.headOid,
412 base: c.value.baseOid,
413 "c-0-0": "both",
414 "c-0-1": "text",
415 "t-0-1": "mine\r\nlines",
416 });
417 };
418
419 test("a guest, a reader and a read-only token are refused, and nothing moves", async () => {
420 const before = await tip();
421 const body = await fields();
422 for (const tail of ["resolve", "resolve/crew"]) {
423 expect((await post(tail, body)).status).toBe(403);
424 expect(
425 (await post(tail, body, { authorization: `Bearer ${ro}` })).status,
426 ).toBe(403);
427 const reader = await post(tail, body, { authorization: `Bearer ${bob}` });
428 expect(reader.status).not.toBe(200);
429 expect(reader.headers.get("location") ?? "").not.toContain("/resolve/");
430 }
431 expect(await tip()).toBe(before!);
432 expect(
433 listRuns(app.db, repo.id, { kind: "agent" }).filter(
434 (r) => r.reason === "conflict",
435 ),
436 ).toEqual([]);
437 });
438
439 test("a cross-origin POST is a 403 and nothing moves", async () => {
440 const before = await tip();
441 const res = await post("resolve", await fields(), {
442 authorization: `Bearer ${rw}`,
443 origin: "https://evil.example",
444 });
445 expect(res.status).toBe(403);
446 const crew = await post("resolve/crew", new URLSearchParams(), {
447 authorization: `Bearer ${rw}`,
448 origin: "https://evil.example",
449 });
450 expect(crew.status).toBe(403);
451 expect(await tip()).toBe(before!);
452 });
453
454 test("the MCP tool asks the crew once, and a reader is refused", async () => {
455 const agent = await createAgent(app, alice, { username: "atlas" });
456 if (!agent.ok) throw new Error(String(agent.error));
457 const added = addToCrew(app, alice, repo, "atlas");
458 if (!added.ok) throw new Error(`crew: ${added.error}`);
459 const tool = async (token: string) => {
460 const res = await http.handle(
461 new Request(`${ORIGIN}/mcp`, {
462 method: "POST",
463 headers: {
464 "content-type": "application/json",
465 accept: "application/json, text/event-stream",
466 authorization: `Bearer ${token}`,
467 },
468 body: JSON.stringify({
469 jsonrpc: "2.0",
470 id: 1,
471 method: "tools/call",
472 params: {
473 name: "propose_conflict_resolution",
474 arguments: { app: "alice/pub", pull: pull.number },
475 },
476 }),
477 }),
478 );
479 return ((await res.json()) as { result: any }).result;
480 };
481 const refused = await tool(bob);
482 expect(refused.isError).toBe(true);
483 expect(listRuns(app.db, repo.id, { kind: "agent" }).length).toBe(0);
484 const asked = await tool(rw);
485 expect(JSON.parse(asked.content[0].text).agent).toBe("atlas");
486 expect((await tool(rw)).isError).toBe(true);
487 expect(
488 listRuns(app.db, repo.id, { kind: "agent" }).filter(
489 (r) => r.reason === "conflict",
490 ).length,
491 ).toBe(1);
492 });
493
494 test("real form fields resolve the conflict, CRLF and all", async () => {
495 const res = await post("resolve", await fields(), {
496 authorization: `Bearer ${rw}`,
497 origin: ORIGIN,
498 });
499 expect(res.status).toBe(303);
500 const file = await runGit(["show", "feature/both:list.txt"], { cwd: dir() });
501 expect(file.ok && file.value + "\n").toBe(
502 edit({
503 two: "two\ntwo-branch\ntwo-main",
504 eight: "eight\nmine\nlines",
505 }),
506 );
507 expect((await pullStatus(dir(), getPull(app.db, repo.id, pull.number)!)).mergeable).toBe(
508 true,
509 );
510 });
511 });
test/mcp.test.ts +1
@@ -195,6 +195,7 @@ describe("the forge over MCP", () => {
195195 "unlink",
196196 "attach_look",
197197 "hold",
198 "propose_conflict_resolution",
198199 "plan",
199200 "capacity",
200201 "report",
test/tui-workflows.test.ts +113
@@ -17,6 +17,8 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
1717 import { mkdtemp, rm } from "node:fs/promises";
1818 import { tmpdir } from "node:os";
1919 import { join } from "node:path";
20 import { addToCrew, createAgent } from "../src/actions/crew.ts";
21 import { listRuns } from "../src/core/runs.ts";
2022 import { addComment, openIssue } from "../src/actions/issues.ts";
2123 import { addTeamMember, createOrg, createTeam } from "../src/actions/orgs.ts";
2224 import { openPull } from "../src/actions/pulls.ts";
@@ -519,3 +521,114 @@ describe("reviews, threads and the merge gate", () => {
519521 }
520522 });
521523 });
524
525 // ---------------------------------------------------------------------------
526
527 describe("have the crew resolve a conflict", () => {
528 let dataDir: string;
529 let forge: Forge;
530 let alice: User;
531 let carol: User;
532 let repo: Repo;
533
534 const openThePull = async (h: Harness): Promise<void> => {
535 await h.settle();
536 await h.until("acme/lamps");
537 await h.press("enter");
538 await h.until("README");
539 await h.press("p");
540 await h.until("Both edit");
541 await h.press("enter");
542 await h.until("#1");
543 };
544
545 const queued = (): number =>
546 listRuns(forge.db, repo.id, { kind: "agent" }).filter(
547 (r) => r.reason === "conflict",
548 ).length;
549
550 beforeAll(async () => {
551 dataDir = await mkdtemp(join(tmpdir(), "forge-tuiconflict-"));
552 forge = createApp({ dataDir, port: 0 });
553 const one = await signUp(forge, {
554 username: "alice",
555 email: "[email protected]",
556 password: "a-long-passphrase",
557 });
558 const two = await signUp(forge, {
559 username: "carol",
560 email: "[email protected]",
561 password: "another-long-passphrase",
562 });
563 if (!one.ok || !two.ok) throw new Error("signup failed");
564 alice = one.value;
565 carol = two.value;
566 const org = createOrg(forge, alice, "acme");
567 if (!org.ok) throw new Error("org failed");
568 const readers = createTeam(forge, alice, org.value, "Readers", "read");
569 if (!readers.ok) throw new Error("team failed");
570 addTeamMember(forge, alice, org.value, readers.value, "carol");
571 const made = await createRepo(forge, alice, {
572 owner: "acme",
573 name: "lamps",
574 visibility: "public",
575 });
576 if (!made.ok) throw new Error("repo failed");
577 repo = made.value;
578 const agent = await createAgent(forge, alice, { username: "atlas" });
579 if (!agent.ok) throw new Error("agent failed");
580 if (!addToCrew(forge, alice, repo, "atlas").ok) throw new Error("crew");
581 const write = (branch: string, base: string | undefined, text: string) =>
582 commitToBranch(forge, alice, repo, {
583 branch,
584 ...(base === undefined ? {} : { base }),
585 message: `lamp ${text}`,
586 files: [
587 { path: "README.md", content: "# Lamps\n" },
588 { path: "lamp.txt", content: text },
589 ],
590 });
591 await write("main", undefined, "one\n");
592 await write("fix", "main", "branch\n");
593 await write("main", undefined, "main\n");
594 const pull = await openPull(forge, alice, repo, {
595 title: "Both edit",
596 baseBranch: "main",
597 headBranch: "fix",
598 });
599 if (!pull.ok) throw new Error("pull failed");
600 }, 60_000);
601
602 afterAll(async () => {
603 forge.close();
604 await rm(dataDir, { recursive: true, force: true });
605 });
606
607 test("a reader is not offered the key and queues nothing", async () => {
608 const h = boot(forge, identityFor(carol));
609 try {
610 await openThePull(h);
611 expect(h.text()).not.toContain("have the crew resolve");
612 await h.press("p");
613 expect(queued()).toBe(0);
614 } finally {
615 h.stop();
616 }
617 }, 60_000);
618
619 test("a writer queues exactly one run, and a second press queues nothing", async () => {
620 const h = boot(forge, identityFor(alice));
621 try {
622 await openThePull(h);
623 await h.press("p");
624 await h.until("atlas is resolving the conflict");
625 expect(queued()).toBe(1);
626 await h.press("p");
627 await h.settle();
628 expect(queued()).toBe(1);
629 expect(h.text()).not.toContain("is resolving the conflict");
630 } finally {
631 h.stop();
632 }
633 }, 60_000);
634 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs