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 #1925

Parked opened this in answer to
Closed without merging

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

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
18 files changed +2169 −6
README.md +8
@@ -870,6 +870,14 @@ work here.
870870 highlighting composed with intra-line word highlighting, mobile-first,
871871 collapsible files), merge-commit and squash strategies, conflict detection,
872872 and merge commits kept reachable forever via `refs/pull/N/merged`.
873 - **Conflicts, by hand** — a conflicted pull's merge box has **Resolve**: an
874 editor with each block as ours / theirs / both / your own text, a running
875 count, and **Have the crew propose** for the one-tap alternative (it commits
876 a merge onto the pull's branch; forks and mirrors are settled where the
877 branch lives). In the terminal, press `e` on a conflicted pull to settle it
878 block by block (`o`/`t`/`b`, Enter to finish; your own text stays on the web)
879 or `p` to have the crew resolve it; over MCP, call
outdated

This sentence is the gap. Resolving by hand is the heart of the issue, and the terminal has to be able to do it too: ours/theirs/both per block, then Finish through resolveConflicts. Free text can stay web-only. Remove this line once that exists.

880 `propose_conflict_resolution`. See `docs/PULLS.md`.
873881 - **Review comments** — anchored to a diff line by content hash, so a
874882 force-push re-anchors them or marks them outdated, never misplaces them.
875883 - **Forks** — alternates-backed (instant, storage-bounded), with cross-repo
docs/PULLS.md added +25
@@ -0,0 +1,25 @@
1 # Pulls: conflicts
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
@@ -332,6 +332,7 @@ export const GATE: readonly string[] = [
332332 "test/ssh-site.test.ts",
333333 "test/web-code.test.ts",
334334 "test/web-origins.test.ts",
335 "test/conflicts.test.ts",
335336 "test/roll.test.ts",
336337 "test/rehearsal.test.ts",
337338 ];
src/actions/conflicts.ts added +255
@@ -0,0 +1,255 @@
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 | "unsettleable"
61 | "no_crew"
62 | "already_running"
63 | "not_queued"
64 | { kind: "git"; message: string };
65
66 /** Whether this pull's branch is ours to commit to: not a fork's, not a mirror's. */
67 export const resolvableHere = (repo: Repo, pull: Pull): boolean =>
68 !pull.crossRepo && pull.originHeadRepo === null && repo.origin === null;
69
70 const guard = (
71 app: App,
72 actor: User | undefined,
73 repo: Repo,
74 pull: Pull,
75 ): Result<User, ConflictError> => {
76 const writer = requireWriter(app, actor, repo);
77 if (!writer.ok) return writer;
78 if (pull.repoId !== repo.id) return err("not_found");
79 if (pull.state !== "open" || pull.mergedAt !== null) return err("not_open");
80 // A fork's branch, or a mirror's, is not ours to commit to.
81 if (!resolvableHere(repo, pull)) return err("not_here");
82 return writer;
83 };
84
85 /** The conflicts of an open pull, read from the merge of its branch with base. */
86 export async function loadConflicts(
87 app: App,
88 actor: User | undefined,
89 repo: Repo,
90 pull: Pull,
91 ): Promise<Result<Conflicts, ConflictError>> {
92 const allowed = guard(app, actor, repo, pull);
93 if (!allowed.ok) return allowed;
94 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
95 const headOid = await resolveOid(dir, `refs/heads/${pull.headBranch}`);
96 const baseOid = await resolveOid(dir, `refs/heads/${pull.baseBranch}`);
97 if (headOid === undefined || baseOid === undefined) return err("not_found");
98 const merged = await writeMergeTree(dir, headOid, baseOid);
99 if (merged.ok) return err("no_conflict");
100 if (
101 merged.error.kind !== "conflict" ||
102 merged.error.treeOid === undefined ||
103 merged.error.files.length === 0
104 )
105 return err({
106 kind: "git",
107 message: merged.error.kind === "git" ? merged.error.message : "unmergeable",
108 });
109 const { treeOid, files } = merged.error;
110 if (files.length > MAX_CONFLICT_FILES) return err("too_many");
111 const read: ConflictFile[] = [];
112 for (const path of files) {
113 const text = await readTreeText(dir, treeOid, path);
114 read.push({
115 path,
116 segments: text === undefined ? undefined : parseMarkers(text),
117 });
118 }
119 return ok({
120 headBranch: pull.headBranch,
121 baseBranch: pull.baseBranch,
122 headOid,
123 baseOid,
124 treeOid,
125 files: read,
126 });
127 }
128
129 export interface Resolution {
130 /** The tips the person was shown; if either moved, nothing is written. */
131 readonly headOid: string;
132 readonly baseOid: string;
133 /** Per path, the choice for each block in order (undefined: not chosen). */
134 readonly choices: ReadonlyMap<string, readonly (Choice | undefined)[]>;
135 }
136
137 /** A text box's content: browsers send CRLF; the file gets LF, and ends a line. */
138 export function normalizeText(text: string): string {
139 const lf = text.replace(/\r\n?/g, "\n");
140 return lf === "" || lf.endsWith("\n") ? lf : `${lf}\n`;
141 }
142
143 /**
144 * Write the person's choices as a merge commit on the pull's branch: the
145 * branch's tip, then the base's, so the pull merges clean the moment it is
146 * pushed. Refuses unless every block of every file has a choice.
147 */
148 export async function resolveConflicts(
149 app: App,
150 actor: User | undefined,
151 repo: Repo,
152 pull: Pull,
153 resolution: Resolution,
154 ): Promise<Result<{ commitOid: string }, ConflictError>> {
155 const found = await loadConflicts(app, actor, repo, pull);
156 if (!found.ok) return found;
157 const conflicts = found.value;
158 if (
159 conflicts.headOid !== resolution.headOid ||
160 conflicts.baseOid !== resolution.baseOid
161 )
162 return err("moved");
163 const files: { path: string; content: string }[] = [];
164 for (const file of conflicts.files) {
165 if (file.segments === undefined) return err("unsettleable");
166 const content = resolveSegments(
167 file.segments,
168 resolution.choices.get(file.path) ?? [],
169 );
170 if (content === undefined) return err("unresolved");
171 files.push({ path: file.path, content });
172 }
173 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
174 const author = commitIdentity(app.config, actor!);
175 const blocks = conflicts.files.reduce(
176 (n, f) => n + countBlocks(f.segments ?? []),
177 0,
178 );
179 const committed = await commitResolution(dir, {
180 branch: conflicts.headBranch,
181 headOid: conflicts.headOid,
182 baseOid: conflicts.baseOid,
183 treeOid: conflicts.treeOid,
184 files,
185 message: `Merge ${conflicts.baseBranch} into ${conflicts.headBranch}\n\nResolved ${blocks} conflict${blocks === 1 ? "" : "s"} in ${files.map((f) => f.path).join(", ")}.`,
186 author,
187 });
188 if (!committed.ok)
189 return err(
190 committed.error.kind === "base_moved"
191 ? "moved"
192 : { kind: "git", message: committed.error.kind },
193 );
194 trackPullHead(app.db, repo.id, conflicts.headBranch, committed.value.commitOid);
195 // `update-ref` runs no hooks; announce the push as a `git push` would.
196 app.bus.append({
197 kind: "push",
198 repoId: repo.id,
199 actorId: actor!.id,
200 payload: {
201 updates: [
202 {
203 ref: `refs/heads/${conflicts.headBranch}`,
204 newOid: committed.value.commitOid,
205 },
206 ],
207 viaApi: true,
208 },
209 });
210 return ok({ commitOid: committed.value.commitOid });
211 }
212
213 /** Who the crew would send: the pull's own agent, else the repo's builder. */
214 function crewFor(app: App, repo: Repo, pull: Pull): Agent | undefined {
215 const issue = getIssueById(app.db, pull.id);
216 if (issue === undefined) return undefined;
217 return (
218 agentFor(app, issue) ??
219 listCrew(app.db, repo.id).find(
220 (a) => (crewRole(app.db, repo.id, a.user.id) ?? "builder") === "builder",
221 )
222 );
223 }
224
225 /** One tap: queue a conflict run on the pull's own branch. */
226 export async function proposeResolution(
227 app: App,
228 actor: User | undefined,
229 repo: Repo,
230 pull: Pull,
231 ): Promise<Result<{ agent: string }, ConflictError>> {
232 const found = await loadConflicts(app, actor, repo, pull);
233 if (!found.ok) return found;
234 const issue = getIssueById(app.db, pull.id);
235 const agent = crewFor(app, repo, pull);
236 if (issue === undefined || agent === undefined) return err("no_crew");
237 if (activeRunFor(app.db, "agent", issue.id) !== undefined)
238 return err("already_running");
239 const run = queueAgentRun(
240 app,
241 repo,
242 issue,
243 agent,
244 "conflict",
245 actor?.id,
246 {
247 notBefore: new Date().toISOString(),
248 attempt: 0,
249 summary: `${pull.baseBranch} moved: ${found.value.files.map((f) => f.path).join(", ")}`,
250 },
251 );
252 return run === undefined
253 ? err("not_queued")
254 : ok({ agent: agent.user.username });
255 }
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 {
8081 isNetworkError,
8182 NETWORK_RETRY_SECONDS,
@@ -835,6 +836,19 @@ async function work(
835836 .split(", ")
836837 .filter((f) => f !== "")
837838 : undefined,
839 conflictState:
840 reason === "conflict" && pull !== undefined && !pull.crossRepo
841 ? await conflictBrief(bare, {
842 headBranch: pull.headBranch,
843 baseBranch: pull.baseBranch,
844 headOid:
845 (await resolveOid(bare, `refs/heads/${pull.headBranch}`)) ??
846 pull.headOid,
847 baseOid:
848 (await resolveOid(bare, `refs/heads/${pull.baseBranch}`)) ??
849 pull.baseOid,
850 })
851 : undefined,
838852 following:
839853 reason === "converge"
840854 ? (() => {
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
@@ -38,6 +38,7 @@ import {
3838 linkIssue,
3939 unlinkIssue,
4040 } from "../actions/dependencies.ts";
41 import { proposeResolution } from "../actions/conflicts.ts";
4142 import { holdPull, releasePull } from "../actions/holds.ts";
4243 import { openPlan, parsePlan, PLAN_MAX } from "../actions/plan.ts";
4344 import { cancelRepoRun } from "../actions/runs.ts";
@@ -1883,6 +1884,43 @@ const TOOLS: readonly Tool[] = [
18831884 });
18841885 },
18851886 },
1887 {
1888 name: "propose_conflict_resolution",
1889 description:
1890 "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.",
1891 inputSchema: {
1892 type: "object",
1893 properties: {
1894 app: APP_ARG,
1895 pull: { type: "integer", description: "The pull's number." },
1896 },
1897 required: ["app", "pull"],
1898 },
1899 writes: true,
1900 async run(ctx, user, args) {
1901 const repo = planRepo(ctx, user, args);
1902 if (isAnswer(repo)) return repo;
1903 const n = args["pull"];
1904 const pull =
1905 typeof n === "number" && Number.isInteger(n) && n > 0
1906 ? getPull(ctx.app.db, repo.id, n)
1907 : undefined;
1908 if (pull === undefined)
1909 return bad("no_such_pull", `no pull #${String(n)}`);
1910 const asked = await proposeResolution(ctx.app, user, repo, pull);
1911 if (!asked.ok)
1912 return bad(
1913 typeof asked.error === "string" ? asked.error : "git",
1914 typeof asked.error === "string"
1915 ? `the crew could not be asked: ${asked.error}`
1916 : asked.error.message,
1917 );
1918 return good({
1919 says: `${asked.value.agent} is resolving the conflict on ${repo.ownerName}/${repo.name}#${pull.number}.`,
1920 agent: asked.value.agent,
1921 });
1922 },
1923 },
18861924 {
18871925 name: "plan",
18881926 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
@@ -277,6 +277,11 @@ import {
277277 agentUpdate,
278278 crewPage,
279279 } from "../web/pages/crew.ts";
280 import {
281 resolveCrewSubmit,
282 resolvePage,
283 resolveSubmit,
284 } from "../web/pages/conflicts.ts";
280285 import { newPullPage, newPullSubmit } from "../web/pages/pulls.ts";
281286 import {
282287 changePage,
@@ -1025,6 +1030,13 @@ export function buildRouter(): Router<Handler> {
10251030 threadResolveSubmit(false),
10261031 );
10271032 router.add("POST", "/:owner/:name/pulls/:number/merge", pullMergeSubmit);
1033 router.add("GET", "/:owner/:name/pulls/:number/resolve", resolvePage);
1034 router.add("POST", "/:owner/:name/pulls/:number/resolve", resolveSubmit);
1035 router.add(
1036 "POST",
1037 "/:owner/:name/pulls/:number/resolve/crew",
1038 resolveCrewSubmit,
1039 );
10281040 router.add("POST", "/:owner/:name/pulls/:number/state", (ctx) =>
10291041 stateSubmit(ctx, "pull"),
10301042 );
src/tui/screens/conflicts.ts added +167
@@ -0,0 +1,167 @@
1 /**
2 * Conflicts, by hand, in the terminal: every block of every conflicted file
3 * as one row, `o`/`t`/`b` to keep ours, theirs or both, a running count, and
4 * Enter to write the merge commit. The same choices the web editor offers
5 * minus free text, which stays on the page. The screen only gathers choices;
6 * `resolveConflicts` decides, and refuses an unfinished or stale one.
7 */
8
9 import type { Conflicts } from "../../actions/conflicts.ts";
10 import { isBlock, type Choice, type ConflictBlock } from "../../git/markers.ts";
11 import type { Ctx, Screen } from "../app/app.ts";
12 import { binding } from "../app/keys.ts";
13 import { truncate } from "../term/width.ts";
14 import { fill, len, split } from "../ui/layout.ts";
15 import { style } from "../term/style.ts";
16 import { runAsync, ListState, drawList, type ListRow } from "./common.ts";
17
18 type Pick = "ours" | "theirs" | "both";
19
20 interface Item {
21 readonly path: string;
22 readonly index: number;
23 /** Undefined: a file that cannot be settled here (binary, deleted on a side). */
24 readonly block: ConflictBlock | undefined;
25 }
26
27 export interface ConflictsOptions {
28 readonly conflicts: Conflicts;
29 /** Write the choices; resolves to the toast to show and whether to leave. */
30 submit(choices: Map<string, (Choice | undefined)[]>): Promise<{
31 readonly text: string;
32 readonly done: boolean;
33 }>;
34 }
35
36 const WORD: Record<Pick, string> = {
37 ours: "ours ",
38 theirs: "theirs",
39 both: "both ",
40 };
41
42 const firstLine = (text: string): string =>
43 text === "" ? "(nothing)" : (text.split("\n")[0] ?? "");
44
45 export function conflictsScreen(ctx: Ctx, o: ConflictsOptions): Screen {
46 const { conflicts } = o;
47 const items: Item[] = conflicts.files.flatMap((file): Item[] => {
48 if (file.segments === undefined)
49 return [{ path: file.path, index: 0, block: undefined }];
50 const blocks = file.segments.filter(isBlock);
51 return blocks.map((block, index) => ({ path: file.path, index, block }));
52 });
53 const picks = new Map<Item, Pick>();
54 const list = new ListState();
55 let busy = false;
56
57 const settleable = items.filter((i) => i.block !== undefined);
58 const count = (): number => settleable.filter((i) => picks.has(i)).length;
59
60 const pick = (p: Pick): void => {
61 const item = items[list.index];
62 if (item?.block === undefined) {
63 ctx.toast("this file cannot be settled here", "attn");
64 return;
65 }
66 picks.set(item, p);
67 // Move on: settling a long list is one key per block.
68 list.move(1, items.length);
69 };
70
71 const finish = (): void => {
72 if (busy) return;
73 if (items.some((i) => i.block === undefined)) {
74 ctx.toast("a file here cannot be settled by hand; have the crew", "attn");
75 return;
76 }
77 const choices = new Map<string, (Choice | undefined)[]>();
78 for (const item of items) {
79 const row = choices.get(item.path) ?? [];
80 const p = picks.get(item);
81 row[item.index] = p === undefined ? undefined : { pick: p };
82 choices.set(item.path, row);
83 }
84 busy = true;
85 runAsync(ctx, async () => {
86 const out = await o.submit(choices).finally(() => {
87 busy = false;
88 });
89 ctx.toast(out.text, out.done ? "success" : "danger");
90 if (out.done) ctx.pop();
91 else ctx.invalidate();
92 });
93 };
94
95 return {
96 title: `Resolve ${conflicts.headBranch}`,
97 get keys() {
98 return [
99 binding(["j", "k"], "move"),
100 binding(["o"], "keep ours"),
101 binding(["t"], "keep theirs"),
102 binding(["b"], "keep both"),
103 binding(["enter"], busy ? "writing…" : "finish"),
104 binding(["esc"], "back"),
105 ];
106 },
107 render(area, s) {
108 const c = ctx.theme.c;
109 const [head, body, detail] = split(area, "v", [len(1), fill(1), len(6)]);
110 s.text(
111 head!.x,
112 head!.y,
113 truncate(
114 `${count()} of ${settleable.length} resolved · ${conflicts.headBranch} ← ${conflicts.baseBranch}`,
115 head!.w,
116 ),
117 style(count() === settleable.length ? c.success : c.fg, c.bg),
118 head!.x + head!.w,
119 );
120 const rows: ListRow[] = items.map((item) => {
121 const p = picks.get(item);
122 return {
123 title:
124 item.block === undefined
125 ? `${item.path} — cannot be settled here`
126 : `${p === undefined ? "[ ]" : `[${WORD[p].trim()}]`} ${item.path} #${item.index + 1}`,
127 ...(p !== undefined ? { tone: "success" as const } : {}),
128 };
129 });
130 drawList(s, body!, c, list, rows);
131 const item = items[list.index];
132 const lines =
133 item?.block === undefined
134 ? ["No text with conflict markers: the crew can propose this one."]
135 : [
136 `ours (${conflicts.headBranch}):`,
137 ...item.block.ours.split("\n").slice(0, 2).map((l) => ` ${l}`),
138 `theirs (${conflicts.baseBranch}):`,
139 ...item.block.theirs
140 .split("\n")
141 .slice(0, 2)
142 .map((l) => ` ${l}`),
143 ];
144 lines.slice(0, detail!.h).forEach((line, i) => {
145 s.text(
146 detail!.x,
147 detail!.y + i,
148 truncate(line === "" ? ` ${firstLine("")}` : line, detail!.w),
149 style(i === 0 || line.startsWith("theirs") ? c.accent : c.mutedFg, c.bg),
150 detail!.x + detail!.w,
151 );
152 });
153 },
154 key(e) {
155 if (e.key === "esc") {
156 ctx.pop();
157 return true;
158 }
159 if (e.key === "o") pick("ours");
160 else if (e.key === "t") pick("theirs");
161 else if (e.key === "b") pick("both");
162 else if (e.key === "enter") finish();
163 else list.key(e, items.length);
164 return true;
165 },
166 };
167 }
src/tui/screens/pull.ts +104
@@ -38,6 +38,13 @@ import {
3838 resolveReviewThread,
3939 submitReview,
4040 } from "../../actions/pulls.ts";
41 import {
42 loadConflicts,
43 proposeResolution,
44 resolveConflicts,
45 resolvableHere,
46 } from "../../actions/conflicts.ts";
47 import { conflictsScreen } from "./conflicts.ts";
4148 import { openEnvUrl } from "../../actions/apps.ts";
4249 import { listRepoRuns } from "../../actions/runs.ts";
4350 import { previewEnv } from "../../apps/data.ts";
@@ -632,6 +639,89 @@ export function pullScreen(
632639 });
633640 };
634641
642 /** `p`: queue the crew on a conflicted pull and say who took it. */
643 const propose = (): void => {
644 if (repo === undefined) return;
645 const target = repo;
646 const row = getPull(f.db, target.id, number);
647 if (row === undefined) return;
648 runAsync(ctx, async () => {
649 const asked = await proposeResolution(f.app, f.user, target, row);
650 if (!asked.ok) {
651 ctx.toast(
652 typeof asked.error === "string"
653 ? errorText(asked.error)
654 : asked.error.message,
655 "danger",
656 );
657 return;
658 }
659 ctx.toast(`${asked.value.agent} is resolving the conflict`, "success");
660 });
661 };
662
663 /** `e`: settle the conflict block by block, then write the merge commit. */
664 const settleByHand = (): void => {
665 if (repo === undefined) return;
666 const target = repo;
667 const row = getPull(f.db, target.id, number);
668 if (row === undefined) return;
669 runAsync(ctx, async () => {
670 const read = await loadConflicts(f.app, f.user, target, row);
671 if (!read.ok) {
672 ctx.toast(
673 typeof read.error === "string"
674 ? errorText(read.error)
675 : read.error.message,
676 "danger",
677 );
678 return;
679 }
680 const conflicts = read.value;
681 ctx.push(
682 conflictsScreen(ctx, {
683 conflicts,
684 submit: async (choices) => {
685 const done = await resolveConflicts(f.app, f.user, target, row, {
686 headOid: conflicts.headOid,
687 baseOid: conflicts.baseOid,
688 choices,
689 });
690 if (!done.ok) {
691 const e = done.error;
692 return {
693 done: false,
694 text:
695 e === "moved"
696 ? "the branch moved: open the conflicts again"
697 : e === "unresolved"
698 ? "every block needs a choice first"
699 : e === "unsettleable"
700 ? "a file here cannot be settled by hand; have the crew"
701 : typeof e === "string"
702 ? errorText(e)
703 : e.message,
704 };
705 }
706 await reload();
707 return {
708 done: true,
709 text: `merged as ${done.value.commitOid.slice(0, 8)}`,
710 };
711 },
712 }),
713 );
714 });
715 };
716
717 /** The crew can resolve here: a writer, on a pull whose branch is this repo's. */
718 const canResolve = (): boolean => {
719 if (!mayWrite() || repo === undefined || state() !== "conflicts")
720 return false;
721 const row = getPull(f.db, repo.id, number);
722 return row !== undefined && resolvableHere(repo, row);
723 };
724
635725 const mirrored = (): boolean => repo === undefined || repo.origin !== null;
636726 const state = (): MergeState =>
637727 mergeState(detail?.issue, facts, mirrored(), gated(), checksGated());
@@ -663,6 +753,12 @@ export function pullScreen(
663753 : []),
664754 binding(["a"], "assign"),
665755 binding(["m"], "merge", { disabled: state() !== "ready" }),
756 ...(canResolve()
757 ? [
758 binding(["e"], "resolve the conflict by hand"),
759 binding(["p"], "have the crew resolve the conflict"),
760 ]
761 : []),
666762 ...(tab === 1 && view.threadHere() !== null
667763 ? [
668764 binding(
@@ -918,6 +1014,14 @@ export function pullScreen(
9181014 }
9191015 return true;
9201016 }
1017 if (e.key === "e" && canResolve()) {
1018 settleByHand();
1019 return true;
1020 }
1021 if (e.key === "p" && canResolve()) {
1022 propose();
1023 return true;
1024 }
9211025 // A merge the gate would refuse says so here rather than going quiet:
9221026 // `m` doing nothing is indistinguishable from `m` being unbound.
9231027 if (e.key === "m" && mayWrite() && state() === "review_required") {
src/web/pages/conflicts.ts added +367
@@ -0,0 +1,367 @@
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 {
21 crumbsFor,
22 pageHead,
23 repoBase,
24 repoPalette,
25 signInFirst,
26 } from "../chrome.ts";
outdated

Nit: this is a second import from ../chrome.ts. Fold signInFirst into the import on line 20.

27 import { field, readForm } from "../form.ts";
28 import { html, type Html } from "../html.ts";
29 import { flashTo, page } from "../layout.ts";
30 import { btn, card, icon } from "../ui.ts";
31 import { pullContext } from "../studio/change.ts";
32
33 /** Lines of untouched text shown before the merged view folds the middle. */
34 const KEEP = 3;
35
36 const WORDS: Record<string, string> = {
37 not_open: "This pull is no longer open.",
38 not_here:
39 "Conflicts on a fork or a mirror are settled where the branch lives.",
40 no_conflict: "No conflicts any more — the branches merge cleanly.",
41 too_many:
42 "Too many conflicted files for a page; have the crew propose a resolution.",
43 moved: "The branch moved while you edited. Open the editor again.",
44 unresolved: "Every block needs a choice before Finish.",
45 unsettleable:
46 "A file here cannot be settled by hand (binary, or deleted on one side); have the crew propose.",
47 no_crew: "No one on the crew can take this: add a builder to the repository.",
48 already_running: "The crew is already working on this pull.",
49 not_queued: "The crew did not take the run (paused, parked or at its limit).",
50 forbidden: "You cannot write to this repository.",
51 unauthorized: "Sign in first.",
52 not_found: "Not found.",
53 };
54
55 const say = (error: ConflictError): string =>
56 typeof error === "string"
57 ? (WORDS[error] ?? error)
58 : `Git said no: ${error.message}`;
59
60 const CSS = `
61 .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)}
62 .cf-count{font-weight:600}
63 .cf-tabs{display:flex;gap:.4rem;overflow-x:auto;padding-bottom:.25rem;margin-bottom:.75rem}
64 .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}
65 .cf-tab[aria-current=true]{border-color:var(--accent);font-weight:600}
66 .cf-tab[data-done=true]::after{content:" ✓";color:var(--success)}
67 .cf-file{margin-bottom:2rem}
68 .cf-file[hidden]{display:none}
69 .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}
70 .cf-block:focus-within{border-color:var(--accent)}
71 .cf-block[data-done=true]{border-left:3px solid var(--success)}
72 .cf-block legend{padding:0 .3rem;font-size:.85em;color:var(--muted-fg)}
73 .cf-sides{display:grid;grid-template-columns:1fr 1fr;gap:.5rem}
74 @media (max-width:40rem){.cf-sides{grid-template-columns:1fr}}
75 .cf-side{display:block;min-width:0;border:1px solid var(--border);border-radius:var(--radius-sm);padding:.4rem;cursor:pointer}
76 .cf-side:has(input:checked),.cf-more:has(input:checked){border-color:var(--accent);background:color-mix(in srgb,var(--accent) 8%,transparent)}
77 .cf-name{font-weight:600}
78 .cf-side pre,.cf-merged{margin:.3rem 0 0;overflow-x:auto;font:.85em/1.45 var(--mono);white-space:pre}
79 .cf-more{display:block;margin-top:.5rem;border:1px solid var(--border);border-radius:var(--radius-sm);padding:.4rem}
80 .cf-more textarea{display:block;width:100%;box-sizing:border-box;margin-top:.4rem;font:.85em/1.45 var(--mono);min-height:4rem}
81 .cf-merged{border:1px solid var(--border);border-radius:var(--radius);padding:.6rem;max-height:28rem;overflow:auto}
82 .cf-merged .mb{background:color-mix(in srgb,var(--danger) 12%,transparent)}
83 .cf-merged .mb[data-done=true]{background:color-mix(in srgb,var(--success) 14%,transparent)}
84 .cf-fold{color:var(--muted-fg)}
85 `;
86
87 const SCRIPT = `
88 (() => {
89 const form = document.getElementById("cf-form");
90 if (!form) return;
91 const files = [...form.querySelectorAll(".cf-file")];
92 const blocks = [...form.querySelectorAll(".cf-block")];
93 const finish = document.getElementById("cf-finish");
94 const total = document.getElementById("cf-total");
95 const picked = (b) => b.querySelector("input[type=radio]:checked");
96 const text = (b, v) => {
97 const side = (s) => b.querySelector(".cf-" + s + " pre").textContent;
98 if (v === "ours") return side("ours");
99 if (v === "theirs") return side("theirs");
100 if (v === "both") return side("ours") + side("theirs");
101 const t = b.querySelector("textarea").value.replace(/\\r\\n?/g, "\\n");
102 return t === "" || t.endsWith("\\n") ? t : t + "\\n";
103 };
104 const show = (i) => {
105 files.forEach((f, n) => (f.hidden = n !== i));
106 form.querySelectorAll(".cf-tab").forEach((t, n) =>
107 t.setAttribute("aria-current", String(n === i)));
108 };
109 const refresh = () => {
110 let done = 0;
111 for (const b of blocks) {
112 const p = picked(b);
113 const ok = !!p;
114 if (ok) done++;
115 b.dataset.done = String(ok);
116 const span = form.querySelector('.mb[data-b="' + b.dataset.b + '"]');
117 if (span) {
118 span.dataset.done = String(ok);
119 if (ok) span.textContent = text(b, p.value);
120 }
121 }
122 files.forEach((f, n) => {
123 const mine = [...f.querySelectorAll(".cf-block")];
124 const d = mine.filter(picked).length;
125 f.querySelector(".cf-fcount").textContent = d + " of " + mine.length + " resolved";
126 const tab = form.querySelector('.cf-tab[data-i="' + n + '"]');
127 if (tab) tab.dataset.done = String(d === mine.length);
128 });
129 total.textContent = done + " of " + blocks.length + " resolved";
130 finish.disabled = done !== blocks.length;
131 };
132 form.addEventListener("change", refresh);
133 form.addEventListener("input", (e) => {
134 const t = e.target;
135 if (t.tagName === "TEXTAREA") {
136 t.closest(".cf-block").querySelector('input[value="text"]').checked = true;
137 refresh();
138 }
139 });
140 form.addEventListener("click", (e) => {
141 const tab = e.target.closest(".cf-tab");
142 if (tab) show(Number(tab.dataset.i));
143 });
144 document.addEventListener("keydown", (e) => {
145 if (e.target.tagName === "TEXTAREA" || e.metaKey || e.ctrlKey || e.altKey) return;
146 const b = document.activeElement && document.activeElement.closest(".cf-block");
147 const v = { o: "ours", t: "theirs", b: "both" }[e.key];
148 if (!b || !v) return;
149 b.querySelector('input[value="' + v + '"]').checked = true;
150 refresh();
151 const next = blocks.slice(blocks.indexOf(b) + 1).find((x) => !picked(x));
152 if (next) { const f = next.closest(".cf-file"); show(files.indexOf(f)); next.querySelector("input").focus(); next.scrollIntoView({ block: "center" }); }
153 });
154 files.forEach((f) => f.dataset.js = "1");
155 show(0);
156 refresh();
157 })();
158 `;
159
160 /** The merged file beneath: long untouched runs fold, blocks wait to be chosen. */
161 function mergedView(file: Conflicts["files"][number], fi: number): Html {
162 let b = 0;
163 return html`<pre class="cf-merged" aria-label="Merged file">${(
164 file.segments ?? []
165 ).map((segment) => {
166 if (isBlock(segment))
167 return html`<span class="mb" data-b="${fi}-${b++}" data-done="false"
168 >${"<<<<<<<\n"}${segment.ours}${"=======\n"}${segment.theirs}${">>>>>>>\n"}</span
169 >`;
170 const rows = segment.split(/(?<=\n)/);
171 return rows.length <= KEEP * 2 + 2
172 ? html`${segment}`
173 : html`${rows.slice(0, KEEP).join("")}<span class="cf-fold"
174 >… ${rows.length - KEEP * 2} unchanged lines
175 </span>${rows.slice(-KEEP).join("")}`;
176 })}</pre>`;
177 }
178
179 function blockCard(
180 c: Conflicts,
181 fi: number,
182 bi: number,
183 of: number,
184 ours: string,
185 theirs: string,
186 ): Html {
187 const name = `c-${fi}-${bi}`;
188 return html`<fieldset class="cf-block" data-b="${fi}-${bi}">
189 <legend>Conflict ${bi + 1} of ${of}</legend>
190 <div class="cf-sides">
191 <label class="cf-side cf-ours">
192 <input type="radio" name="${name}" value="ours" />
193 <span class="cf-name">${c.headBranch}</span> <span class="muted small">ours · tap o</span>
194 <pre>${ours}</pre>
195 </label>
196 <label class="cf-side cf-theirs">
197 <input type="radio" name="${name}" value="theirs" />
198 <span class="cf-name">${c.baseBranch}</span> <span class="muted small">theirs · tap t</span>
199 <pre>${theirs}</pre>
200 </label>
201 </div>
202 <label class="cf-more">
203 <input type="radio" name="${name}" value="both" />
204 Keep both, ours then theirs <span class="muted small">tap b</span>
205 </label>
206 <label class="cf-more">
207 <input type="radio" name="${name}" value="text" />
208 Write my own
209 <textarea name="t-${fi}-${bi}" rows="3" spellcheck="false" maxlength="100000"></textarea>
210 </label>
211 </fieldset>`;
212 }
213
214 function fileSection(c: Conflicts, fi: number): Html {
215 const file = c.files[fi]!;
216 if (file.segments === undefined)
217 return html`<section class="cf-file" id="f-${fi}">
218 <h2 class="mono">${file.path}</h2>
219 <p class="error-note" role="alert">
220 ${icon("alert")}<span
221 >This file is binary, or deleted on one side — it cannot be settled
222 here. Have the crew propose, or resolve it in a clone.</span
223 >
224 </p>
225 </section>`;
226 const n = countBlocks(file.segments);
227 let bi = 0;
228 return html`<section class="cf-file" id="f-${fi}">
229 <h2><span class="mono">${file.path}</span>
230 <span class="muted small cf-fcount">0 of ${n} resolved</span></h2>
231 ${file.segments.map((s) =>
232 isBlock(s) ? blockCard(c, fi, bi++, n, s.ours, s.theirs) : html``,
233 )}
234 <h3 class="small muted">The merged file</h3>
235 ${mergedView(file, fi)}
236 </section>`;
237 }
238
239 // GET /:owner/:name/pulls/:number/resolve
240 export async function resolvePage(ctx: Ctx): Promise<Response> {
241 const found = pullContext(ctx);
242 if (found instanceof Response) return found;
243 if (!ctx.auth.user) return signInFirst(ctx);
244 const { repo, pull } = found;
245 const base = repoBase(repo);
246 const back = `${base}/pulls/${pull.number}/files`;
247 const loaded = await loadConflicts(ctx.app, ctx.auth.user, repo, pull);
248 if (!loaded.ok)
249 return flashTo(ctx, back, {
250 tone: loaded.error === "no_conflict" ? "attn" : "danger",
251 message: say(loaded.error),
252 });
253 const c = loaded.value;
254 const blocks = c.files.reduce((n, f) => n + countBlocks(f.segments ?? []), 0);
255 const settleable = c.files.every((f) => f.segments !== undefined);
256 const action = `${base}/pulls/${pull.number}/resolve`;
257 const body = html`${pageHead(html`${icon("alert")}Resolve conflicts`, {
258 sub: html`<span class="mono">${c.headBranch}</span> ← merging
259 <span class="mono">${c.baseBranch}</span> · ${blocks}
260 conflict${blocks === 1 ? "" : "s"} in ${c.files.length}
261 file${c.files.length === 1 ? "" : "s"}`,
262 })}
263 <form id="cf-form" method="post" action="${action}">
264 <input type="hidden" name="head" value="${c.headOid}" />
265 <input type="hidden" name="base" value="${c.baseOid}" />
266 <div class="cf-bar">
267 <span class="cf-count" id="cf-total" aria-live="polite">0 of ${blocks} resolved</span>
268 <span>
269 ${btn("Have the crew propose", {
270 variant: "outline",
271 icon: "bot",
272 form: "cf-crew",
273 })}
274 ${btn("Finish", { variant: "primary", icon: "check" })}
275 </span>
276 </div>
277 ${c.files.length > 1
278 ? html`<nav class="cf-tabs" aria-label="Files">${c.files.map(
279 (f, i) =>
280 html`<a class="cf-tab" data-i="${i}" href="#f-${i}" role="button" aria-current="false">${f.path}</a>`,
281 )}</nav>`
282 : html``}
283 ${c.files.map((_, i) => fileSection(c, i))}
284 </form>
285 <form id="cf-crew" method="post" action="${action}/crew"></form>
286 ${settleable
287 ? html``
288 : card(html`<p class="muted small">Some files cannot be edited here; Finish will refuse until the crew or a clone settles them.</p>`)}`;
289 return page({
290 ctx,
291 title: `Resolve · ${pull.title} · ${repo.name}`,
292 crumbs: crumbsFor(repo),
293 palette: repoPalette(ctx, repo),
294 body,
295 styleCss: CSS,
296 scriptJs: SCRIPT,
297 });
298 }
299
300 const CHOICES = new Set(["ours", "theirs", "both", "text"]);
301
302 // POST /:owner/:name/pulls/:number/resolve
303 export async function resolveSubmit(ctx: Ctx): Promise<Response> {
304 const found = pullContext(ctx);
305 if (found instanceof Response) return found;
306 if (!ctx.auth.user) return new Response("forbidden", { status: 403 });
307 const form = await readForm(ctx, "rw");
308 if (form instanceof Response) return form;
309 const { repo, pull } = found;
310 const base = repoBase(repo);
311 const here = `${base}/pulls/${pull.number}`;
312 const loaded = await loadConflicts(ctx.app, ctx.auth.user, repo, pull);
313 if (!loaded.ok)
314 return flashTo(ctx, `${here}/files`, {
315 tone: "danger",
316 message: say(loaded.error),
317 });
318 const choices = new Map<string, (Choice | undefined)[]>();
319 loaded.value.files.forEach((file, fi) => {
320 const mine: (Choice | undefined)[] = [];
321 for (let bi = 0; bi < countBlocks(file.segments ?? []); bi++) {
322 const pick = field(form, `c-${fi}-${bi}`);
323 mine.push(
324 !CHOICES.has(pick)
325 ? undefined
326 : pick === "text"
327 ? { pick, text: normalizeText(field(form, `t-${fi}-${bi}`)) }
328 : { pick: pick as "ours" | "theirs" | "both" },
329 );
330 }
331 choices.set(file.path, mine);
332 });
333 const done = await resolveConflicts(ctx.app, ctx.auth.user, repo, pull, {
334 headOid: field(form, "head"),
335 baseOid: field(form, "base"),
336 choices,
337 });
338 if (!done.ok)
339 return flashTo(
340 ctx,
341 done.error === "unresolved" ? `${here}/resolve` : `${here}/files`,
342 { tone: "danger", message: say(done.error) },
343 );
344 return flashTo(ctx, `${here}/files`, {
345 message: "Conflicts resolved — the branch now merges cleanly.",
346 });
347 }
348
349 // POST /:owner/:name/pulls/:number/resolve/crew
350 export async function resolveCrewSubmit(ctx: Ctx): Promise<Response> {
351 const found = pullContext(ctx);
352 if (found instanceof Response) return found;
353 if (!ctx.auth.user) return new Response("forbidden", { status: 403 });
354 const form = await readForm(ctx, "rw");
355 if (form instanceof Response) return form;
356 const { repo, pull } = found;
357 const here = `${repoBase(repo)}/pulls/${pull.number}`;
358 const asked = await proposeResolution(ctx.app, ctx.auth.user, repo, pull);
359 if (!asked.ok)
360 return flashTo(ctx, `${here}/files`, {
361 tone: "danger",
362 message: say(asked.error),
363 });
364 return flashTo(ctx, here, {
365 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.`,
366 });
367 }
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";
@@ -422,7 +423,18 @@ function mergeBox(
422423 <div class="merge-headline">Can't merge.</div>
423424 <p class="merge-sub">${reason}</p>
424425 ${reviewsChip(status.reviews, by)} ${checks}
425 </div>`,
426 </div>
427 ${when(
428 mayMerge && status.conflicts.length > 0 && resolvableHere(repo, pull),
429 () =>
430 html`<span class="merge-form"
431 >${btn("Resolve", {
432 href: `${repoBase(repo)}/pulls/${pull.number}/resolve`,
433 variant: "primary",
434 icon: "merge",
435 })}</span
436 >`,
437 )}`,
426438 { tone: "danger", extra: "merge-box" },
427439 );
428440 }
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
@@ -203,6 +203,7 @@ describe("the forge over MCP", () => {
203203 "unlink",
204204 "attach_look",
205205 "hold",
206 "propose_conflict_resolution",
206207 "plan",
207208 "access",
208209 "capacity",
test/tui-workflows.test.ts +249
@@ -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";
@@ -34,6 +36,8 @@ import { local } from "../src/tui/screens/where.ts";
3436 import { listReviews } from "../src/core/reviews.ts";
3537 import { getPull } from "../src/core/pulls.ts";
3638 import type { User } from "../src/core/users.ts";
39 import { runGit } from "../src/git/env.ts";
40 import { repoDir } from "../src/git/repos.ts";
3741 import { quietLogs } from "./helpers/globals.ts";
3842 import type { App, Screen } from "../src/tui/app/app.ts";
3943 import { createForgeApp } from "../src/tui/forge.ts";
@@ -519,3 +523,248 @@ describe("reviews, threads and the merge gate", () => {
519523 }
520524 });
521525 });
526
527 // ---------------------------------------------------------------------------
528
529 describe("have the crew resolve a conflict", () => {
530 let dataDir: string;
531 let forge: Forge;
532 let alice: User;
533 let carol: User;
534 let repo: Repo;
535
536 const openThePull = async (h: Harness): Promise<void> => {
537 await h.settle();
538 await h.until("acme/lamps");
539 await h.press("enter");
540 await h.until("README");
541 await h.press("p");
542 await h.until("Both edit");
543 await h.press("enter");
544 await h.until("#1");
545 };
546
547 const queued = (): number =>
548 listRuns(forge.db, repo.id, { kind: "agent" }).filter(
549 (r) => r.reason === "conflict",
550 ).length;
551
552 beforeAll(async () => {
553 dataDir = await mkdtemp(join(tmpdir(), "forge-tuiconflict-"));
554 forge = createApp({ dataDir, port: 0 });
555 const one = await signUp(forge, {
556 username: "alice",
557 email: "[email protected]",
558 password: "a-long-passphrase",
559 });
560 const two = await signUp(forge, {
561 username: "carol",
562 email: "[email protected]",
563 password: "another-long-passphrase",
564 });
565 if (!one.ok || !two.ok) throw new Error("signup failed");
566 alice = one.value;
567 carol = two.value;
568 const org = createOrg(forge, alice, "acme");
569 if (!org.ok) throw new Error("org failed");
570 const readers = createTeam(forge, alice, org.value, "Readers", "read");
571 if (!readers.ok) throw new Error("team failed");
572 addTeamMember(forge, alice, org.value, readers.value, "carol");
573 const made = await createRepo(forge, alice, {
574 owner: "acme",
575 name: "lamps",
576 visibility: "public",
577 });
578 if (!made.ok) throw new Error("repo failed");
579 repo = made.value;
580 const agent = await createAgent(forge, alice, { username: "atlas" });
581 if (!agent.ok) throw new Error("agent failed");
582 if (!addToCrew(forge, alice, repo, "atlas").ok) throw new Error("crew");
583 const write = (branch: string, base: string | undefined, text: string) =>
584 commitToBranch(forge, alice, repo, {
585 branch,
586 ...(base === undefined ? {} : { base }),
587 message: `lamp ${text}`,
588 files: [
589 { path: "README.md", content: "# Lamps\n" },
590 { path: "lamp.txt", content: text },
591 ],
592 });
593 await write("main", undefined, "one\n");
594 await write("fix", "main", "branch\n");
595 await write("main", undefined, "main\n");
596 const pull = await openPull(forge, alice, repo, {
597 title: "Both edit",
598 baseBranch: "main",
599 headBranch: "fix",
600 });
601 if (!pull.ok) throw new Error("pull failed");
602 }, 60_000);
603
604 afterAll(async () => {
605 forge.close();
606 await rm(dataDir, { recursive: true, force: true });
607 });
608
609 test("a reader is not offered the key and queues nothing", async () => {
610 const h = boot(forge, identityFor(carol));
611 try {
612 await openThePull(h);
613 expect(h.text()).not.toContain("have the crew resolve");
614 await h.press("p");
615 expect(queued()).toBe(0);
616 } finally {
617 h.stop();
618 }
619 }, 60_000);
620
621 test("a writer queues exactly one run, and a second press queues nothing", async () => {
622 const h = boot(forge, identityFor(alice));
623 try {
624 await openThePull(h);
625 await h.press("p");
626 await h.until("atlas is resolving the conflict");
627 expect(queued()).toBe(1);
628 await h.press("p");
629 await h.settle();
630 expect(queued()).toBe(1);
631 expect(h.text()).not.toContain("is resolving the conflict");
632 } finally {
633 h.stop();
634 }
635 }, 60_000);
636 });
637
638 // ---------------------------------------------------------------------------
639
640 describe("settle a conflict by hand in the terminal", () => {
641 let dataDir: string;
642 let forge: Forge;
643 let alice: User;
644 let carol: User;
645 let repo: Repo;
646
647 const lines = (a: string, b: string): string =>
648 `one\ntwo\n${a}\nthree\nfour\nfive\nsix\nseven\n${b}\neight\n`;
649
650 const openThePull = async (h: Harness): Promise<void> => {
651 await h.settle();
652 await h.until("acme/lamps");
653 await h.press("enter");
654 await h.until("README");
655 await h.press("p");
656 await h.until("Both edit");
657 await h.press("enter");
658 await h.until("#1");
659 };
660
661 const git = async (args: string[]): Promise<string> => {
662 const out = await runGit(args, {
663 cwd: repoDir(forge.reposRoot, "acme", "lamps"),
664 });
665 if (!out.ok) throw new Error(`git ${args.join(" ")}`);
666 return out.value.trim();
667 };
668
669 const tip = async (): Promise<string> =>
670 git(["rev-parse", "refs/heads/fix"]);
671
672 beforeAll(async () => {
673 dataDir = await mkdtemp(join(tmpdir(), "forge-tuihand-"));
674 forge = createApp({ dataDir, port: 0 });
675 const one = await signUp(forge, {
676 username: "alice",
677 email: "[email protected]",
678 password: "a-long-passphrase",
679 });
680 const two = await signUp(forge, {
681 username: "carol",
682 email: "[email protected]",
683 password: "another-long-passphrase",
684 });
685 if (!one.ok || !two.ok) throw new Error("signup failed");
686 alice = one.value;
687 carol = two.value;
688 const org = createOrg(forge, alice, "acme");
689 if (!org.ok) throw new Error("org failed");
690 const readers = createTeam(forge, alice, org.value, "Readers", "read");
691 if (!readers.ok) throw new Error("team failed");
692 addTeamMember(forge, alice, org.value, readers.value, "carol");
693 const made = await createRepo(forge, alice, {
694 owner: "acme",
695 name: "lamps",
696 visibility: "public",
697 });
698 if (!made.ok) throw new Error("repo failed");
699 repo = made.value;
700 const write = (branch: string, base: string | undefined, text: string) =>
701 commitToBranch(forge, alice, repo, {
702 branch,
703 ...(base === undefined ? {} : { base }),
704 message: "lamps",
705 files: [
706 { path: "README.md", content: "# Lamps\n" },
707 { path: "list.txt", content: text },
708 ],
709 });
710 await write("main", undefined, lines("", "").replace("\n\n", "\n").replace("\nseven\n\neight", "\nseven\neight"));
711 await write("fix", "main", lines("a-fix", "b-fix"));
712 await write("main", undefined, lines("a-main", "b-main"));
713 const pull = await openPull(forge, alice, repo, {
714 title: "Both edit",
715 baseBranch: "main",
716 headBranch: "fix",
717 });
718 if (!pull.ok) throw new Error("pull failed");
719 }, 60_000);
720
721 afterAll(async () => {
722 forge.close();
723 await rm(dataDir, { recursive: true, force: true });
724 });
725
726 test("a reader is offered no key and nothing moves", async () => {
727 const h = boot(forge, identityFor(carol));
728 try {
729 await openThePull(h);
730 const before = await tip();
731 expect(h.text()).not.toContain("by hand");
732 await h.press("e");
733 await h.settle();
734 expect(h.text()).not.toContain("resolved ·");
735 expect(await tip()).toBe(before);
736 } finally {
737 h.stop();
738 }
739 }, 60_000);
740
741 test("a writer settles both blocks with b and the branch moves to a merge commit", async () => {
742 const h = boot(forge, identityFor(alice));
743 try {
744 await openThePull(h);
745 const before = await tip();
746 await h.press("e");
747 await h.until("0 of 2 resolved");
748 await h.press("enter");
749 await h.until("every block needs a choice first");
750 expect(await tip()).toBe(before);
751 await h.press("b");
752 await h.until("1 of 2 resolved");
753 await h.press("b");
754 await h.until("2 of 2 resolved");
755 await h.press("enter");
756 await h.until("merged as");
757 const after = await tip();
758 expect(after).not.toBe(before);
759 const parents = (await git(["rev-list", "--parents", "-n1", "fix"])).split(
760 " ",
761 );
762 expect(parents).toHaveLength(3);
763 const file = await git(["show", "fix:list.txt"]);
764 expect(file).toContain("a-fix\na-main");
765 expect(file).toContain("b-fix\nb-main");
766 } finally {
767 h.stop();
768 }
769 }, 60_000);
770 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs