Artifactspublic-v0

ply

main
ply4 git calls244 ms58 KiB2 cachedprotocol v2
993 lines68 KiBRaw
1// Landing a branch, with git operations only: fast-forward, a merge commit from a three-way tree merge, branch delete.
2//
3// mergeBranch(ref ← from): ls-refs both, find the merge base (commit-only fetches, tree:0, doubling depth), then
4// - ours == base → fast-forward: push the branch head to ref, empty pack (the server has every object)
5// - theirs == base → nothing to do
6// - else → three-way merge of the two trees against the base tree, directory by directory, fetching only the
7// subtrees that differ; a commit with parents [ours, theirs]; push the commit + the new trees and
8// merged blobs. A regular file both sides changed is merged line by line with a port of git's xdiff
9// (linemerge.js: histogram diff, compaction, zealous conflict refinement) — clean exactly where git is
10// clean and byte-identical, else `merge_conflict` with the paths and a reason per path. Our conflicts
11// are a superset of git's: the rename guards below, and the rare file where git's diff falls back to
12// classic Myers, which we do not port (test/fuzz/linemerge.mjs measures it). Where we succeed, the
13// tree is what `git merge-tree --write-tree` produces (test/merge.test.js).
14// The pure parts: decidePath / threeWay (one directory), mergeMode, bestBases (git merge-base --all over known commits),
15// searchStep (the merge-base search's transition), decideMerge (what a verdict means for the branch), uniqueObjects;
16// linemerge.js. The effects: lsRefs, fetchObject, push. Every step that can fail returns a Result, the entry points
17// (mergeBranch, mergeBase, mergeTrees, attributeTree) included.
18/* oxlint-disable import/max-dependencies -- a merge drives ls-refs, fetch, push, the object codecs and the line merge */
19/* oxlint-disable eslint/require-await, typescript/promise-function-async -- each function keeps its async-ness (a sync throw stays sync); together the two rules forbid a function that forwards a promise */
20import type { ValidatedIdent } from './validate.js';
21import type { CheckedLimits } from './limits.js';
22import type { Driver, Rediff } from './linemerge.js';
23import type { ErrorOf, Extra, Miss, PlyError } from './errors.js';
24import type { Err, Ok, Option, Result } from './result.js';
25import type { Input } from './absent.js';
26import type { LsRefsResult } from './lsrefs.js';
27import type { OperationOpts, Outcome } from './operation.js';
28import { fail } from './errors.js';
29import { andThen, assertNever, err, getOrElse, isNone, isSome, map, mapOption, none, ok, some } from './result.js';
30import { at, fromNullable, fromNullish, mapGet, withDefaults } from './absent.js';
31import { lsRefs } from './lsrefs.js';
32import { fetchObject, objectAt, treeEntries } from './fetch.js';
33import { fetchPackTree0 } from './fetchpack.js';
34import { push, ZERO_OID } from './push.js';
35import { parseOid, type Oid } from './oid.js';
36import { operation, verifyRef } from './operation.js';
37import { parseTree, encodeEntries, parseCommit, encodeCommitOf, hashObject, ident, TYPE, type Mode } from './objects.js';
38import { validateRef, validatePushRef, validateMessage } from './validate.js';
39import { signCommit } from './sign.js';
40import { mergeLines } from './linemerge.js';
41import { attributeOf, attributesFor, bytesToStr, popLast, utf8ToStr } from './attributes.js';
42import { short, commitAt, commitBytesAt, isOid, givenOid, assertCommit, stamp } from './mergeio.js';
43import { checkLimit, limitError, lowered } from './limits.js';
45// A merge_conflict's payload: Detail carries `conflicts`; reasons and bases are extras (errors.ts is shared; additive
46// detail is the steward's call).
47type ConflictDetail = Extra & { readonly conflicts: readonly string[] };
49// The shapes this module reads from other modules (objects, transport, operation, push, ls-refs); their own modules
50// own the full types.
51export type TreeEntry = { readonly mode: Mode; readonly name: string; readonly oid: Oid };
52export type Commit = {
53 readonly tree: Oid;
54 readonly parents: readonly Oid[];
55 readonly author: string;
56 readonly committer: string;
57 readonly encoding: string | null;
58 readonly message: string | null;
59 readonly extra: readonly string[];
60};
61export type PackObject = { readonly type: number; readonly data: Uint8Array; readonly oid: string };
62// the transport every operation runs on (src/transport.ts); re-exported for rebase.ts
63export type { Transport } from './transport.js';
64import type { Transport } from './transport.js';
65// the span every operation records on (src/otel.js); re-exported for rebase.ts
66export type { Span } from './otel.js';
67import type { Span } from './otel.js';
68export type { Outcome } from './operation.js';
69export type OpContext = { readonly t: Transport; readonly root: Span; readonly outcome: Outcome; readonly limits: CheckedLimits };
70export type PushResult = { readonly packBytes: number };
71// a commit stamp: `time` (unix seconds) defaults to the operation's `time`, `tz` (+HHMM / -HHMM) to +0000
72export type Author = { readonly name: string; readonly email: string } & Input<{ readonly tz: string; readonly time: number }>;
73// a commit signer (src/sign.ts); re-exported for rebase.ts
74export type { Signer } from './sign.js';
75import type { Signer } from './sign.js';
76export type TreeCache = Map<string, Uint8Array>;
77export type PushObject = { readonly type: number; readonly data: Uint8Array };
80const EMPTY: readonly TreeEntry[] = [];
81const NO_PARENTS: readonly never[] = [];
82const isTreeEntry = (e: TreeEntry): boolean => e.mode === '40000';
83// An entry absent on a side is None.
84type Entry = Option<TreeEntry>;
85const same = (a: Entry, b: Entry): boolean => (a.tag === 'none' || b.tag === 'none' ? a.tag === b.tag : a.value.mode === b.value.mode && a.value.oid === b.value.oid);
86const isTree = (e: Entry): boolean => e.tag === 'some' && isTreeEntry(e.value);
87const isFile = (e: Entry): boolean => e.tag === 'some' && (e.value.mode === '100644' || e.value.mode === '100755');
88// directory vs directory, or a directory one side deleted/added: recurse so the conflict (if any) is per file,
89// and untouched files inside a directory the other side deleted go away, as git does
90const treeish = (e: Entry): boolean => e.tag === 'none' || isTree(e);
91const recurses = (O: Entry, T: Entry): boolean => treeish(O) && treeish(T) && (isTree(O) || isTree(T));
92const byName = (list: readonly TreeEntry[]): Map<string, TreeEntry> => new Map(list.map(e => [e.name, e]));
94// Pure: what a three-way merge does with one name of a directory, git's trivial-merge rules at tree level: same on both
95// sides → that; unchanged on one side → the other side's (an absent result drops the name); both trees → recurse; both
96// regular files changed differently over a regular base → content (a line merge may resolve it); otherwise → conflict.
97export type PathDecision =
98 | { readonly kind: 'take'; readonly entry: TreeEntry }
99 | { readonly kind: 'drop' }
100 | { readonly kind: 'recurse' }
101 | { readonly kind: 'content' }
102 | { readonly kind: 'conflict' };
103const DROP: PathDecision = { kind: 'drop' };
104const RECURSE: PathDecision = { kind: 'recurse' };
105const CONTENT: PathDecision = { kind: 'content' };
106const CONFLICT: PathDecision = { kind: 'conflict' };
107const taken = (e: Entry): PathDecision => (e.tag === 'some' ? { kind: 'take', entry: e.value } : DROP);
108function decidePath(B: Entry, O: Entry, T: Entry): PathDecision {
109 if (same(O, T) || same(B, T)) return taken(O);
110 if (same(B, O)) return taken(T);
111 if (recurses(O, T)) return RECURSE;
112 if (isFile(B) && isFile(O) && isFile(T)) return CONTENT;
113 return CONFLICT;
116// Pure: three-way merge of one directory's entries, as lists by decision: { entries (resolved, in no particular order),
117// recurse: [name], conflicts: [name], content: [name], deletedBoth, addedOurs, addedTheirs }. deletedBoth is the names
118// base holds and neither side does, in this one directory. The added lists feed the directory-rename guard in mergeTrees
119// (G2). The rename guard G1 does not read deletedBoth: what both sides lost is decided over the three trees (deletedOnBoth).
120export type ThreeWay = {
121 readonly entries: TreeEntry[];
122 readonly recurse: string[];
123 readonly conflicts: string[];
124 readonly content: string[];
125 readonly deletedBoth: string[];
126 readonly addedOurs: string[];
127 readonly addedTheirs: string[];
128};
129export function threeWay(base: readonly TreeEntry[], ours: readonly TreeEntry[], theirs: readonly TreeEntry[]): ThreeWay {
130 const b = byName(base);
131 const o = byName(ours);
132 const t = byName(theirs);
133 const names = new Set([...b.keys(), ...o.keys(), ...t.keys()]);
134 const entries: TreeEntry[] = [];
135 const recurse: string[] = [];
136 const conflicts: string[] = [];
137 const content: string[] = [];
138 const deletedBoth: string[] = [];
139 const addedOurs: string[] = [];
140 const addedTheirs: string[] = [];
141 for (const name of names) {
142 const B = mapGet(b, name);
143 const O = mapGet(o, name);
144 const T = mapGet(t, name);
145 if (B.tag === 'some' && O.tag === 'none' && T.tag === 'none') deletedBoth.push(name);
146 if (B.tag === 'none' && O.tag === 'some') addedOurs.push(name);
147 if (B.tag === 'none' && T.tag === 'some') addedTheirs.push(name);
148 const d = decidePath(B, O, T);
149 switch (d.kind) {
150 case 'take': entries.push(d.entry); continue;
151 case 'drop': continue;
152 case 'recurse': recurse.push(name); continue;
153 case 'content': content.push(name); continue;
154 case 'conflict': conflicts.push(name); continue;
155 }
156 // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check
157 assertNever(d);
158 }
159 return { entries, recurse, conflicts, content, deletedBoth, addedOurs, addedTheirs };
162// Pure: git's mode merge for a regular file both sides touched: equal → that; one side unchanged → the other's; null:
163// both changed it, differently (a conflict).
164export const mergeMode = <M extends string>(b: M, o: M, t: M): M | null => {
165 if (o === t || b === t) return o;
166 if (b === o) return t;
167 return null;
168};
170// Pure: git's merge bases — the best common ancestors of `a` and `b` (common ancestors that are not ancestors of another
171// common ancestor; git merge-base --all), over the commits known so far (oid → { parents }). A commit named as a parent
172// but not in the map is a cut: its ancestry is unknown. `truncated` says the answer may change once the cuts are fetched:
173// - a cut reachable from a or b outside the settled region (common ancestors and everything below them) may hide a
174// best base — any best base outside what we know is an ancestor of a or b that is not an ancestor of a known common
175// ancestor, so it lies beyond exactly such a cut;
176// - with more than one best base, a cut inside the settled region may hide that one of them is an ancestor of
177// another (through the cut), so the set would shrink: {c, z} where z is below c through a cut x is not criss-cross,
178// it is {c} (#42). Only a cut that some best base reaches and another does not can do that: z below c through a
179// cut k means k is an ancestor of c and z an ancestor of k, so k cannot also be an ancestor of z (a cycle). A cut
180// every best base reaches (deep shared history under a true criss-cross) changes nothing, and deepening for it
181// would walk to the root or the cap (limit_exceeded where git answers two bases).
182// A single best base over a graph whose only cuts are settled is final, and the rule says so without a special case:
183// every settled commit is the base or below it, so the one base reaches every settled cut.
184// The graph is over node names K: mergeBase walks Oids (K = Oid, so every base it answers is one); a caller's own graph
185// may name its nodes with any strings, since nothing here reads a name but to compare it.
186export type Parents<K extends string = string> = { readonly parents: readonly K[] };
187// a known commit's parents; a cut has none known
188const parentsIn = <K extends string>(commits: ReadonlyMap<K, Parents<K>>, c: K): readonly K[] => getOrElse(mapOption(mapGet(commits, c), x => x.parents), NO_PARENTS);
189export function bestBases<K extends string>(commits: ReadonlyMap<K, Parents<K>>, a: K, b: K): { best: K[]; truncated: boolean } {
190 // the commits reachable from `starts`, not walking into `stop` (a commit not in the map is reached, not walked)
191 const closure = (starts: readonly K[], stop: ReadonlySet<K> = new Set()): Set<K> => { const seen = new Set<K>(); const st = [...starts]; for (let c = popLast(st); c.tag === 'some'; c = popLast(st)) { if (seen.has(c.value) || stop.has(c.value)) continue; seen.add(c.value); for (const p of parentsIn(commits, c.value)) st.push(p); } return seen; };
192 const A = closure([a]);
193 const B = closure([b]);
194 const common = [...A].filter(c => B.has(c));
195 const below = closure(common.flatMap(c => parentsIn(commits, c))); // proper ancestors of common ancestors
196 const best = common.filter(c => !below.has(c)).toSorted();
197 const settled = new Set([...common, ...below]);
198 const cut = (c: K): boolean => !commits.has(c);
199 // a cut reachable from a or b outside the settled region, or a settled cut some best base reaches and another does not
200 const between = (): boolean => { const reach = best.map(c => closure([c])); return [...settled].some(k => cut(k) && reach.some(r => !r.has(k))); };
201 return { best, truncated: [...closure([a, b], settled)].some(c => cut(c)) || between() };
204// Effect: the ancestors of `head` within `depth`, via a commit-only pack (tree:0 keeps trees and blobs out).
205// The pack is held to the deepen contract (shallow-info, protocol v2): `head` is in it as a commit, every commit in it is
206// an ancestor of `head` through it, and a commit whose parent it lacks is one the server named `shallow`. Commits are
207// hash-verified, so ancestry cannot be forged, only withheld; a server that withholds it without saying so would make
208// bestBases answer over a cut graph that looks whole (#18), so that is `pack_corrupt` here. git's upload-pack keeps the
209// contract (the boundary of the depth and of a shallow server repository are both reported).
210// The answer is keyed by the ids the walk reached (head and the parents named in parsed commits), so every key is an Oid
211// parsed once (by parseOid and parseCommit), not the pack's own keys.
212export async function ancestors(t: Transport, head: Oid, depth: number): Promise<Result<Map<Oid, Commit>, PlyError>> {
213 const got = await fetchPackTree0(t, { wants: [head], filter: 'tree:0', deepen: depth });
214 if (!got.ok) return got;
215 const r = got.value;
216 const sent = new Map<string, Commit>();
217 const objects = fromNullish(r.objects);
218 if (objects.tag === 'some') for (const [oid, o] of objects.value) if (o.type === TYPE.COMMIT) { const c = parseCommit(o.data, t.limits); if (!c.ok) return c; sent.set(oid, c.value); }
219 if (!sent.has(head)) return fail('pack_corrupt', `commit ${head} not in the pack that wanted it`);
220 const commits = new Map<Oid, Commit>();
221 const seen = new Set([head]);
222 // seen grows while it is walked: every commit reachable from head through the pack
223 for (const c of seen) { const known = mapGet(sent, c); if (known.tag === 'some') { commits.set(c, known.value); for (const p of known.value.parents) seen.add(p); } }
224 const shallow = new Set(r.shallow);
225 const reached = new Set<string>(commits.keys());
226 for (const [oid, c] of sent) {
227 if (!reached.has(oid)) return fail('pack_corrupt', `commit ${oid} sent but not an ancestor of ${head}`);
228 const missing = shallow.has(oid) ? none : fromNullable(c.parents.find(p => !sent.has(p)));
229 if (missing.tag === 'some') return fail('pack_corrupt', `parent ${missing.value} of ${oid} withheld and ${oid} not reported shallow`);
230 }
231 return ok(commits);
234// The merge-base search as a machine. It starts searching a window of 8 commits a side and, while the window's graph
235// is truncated (bestBases), doubles it, the last step clamped to the cap (#79: cap 100 searches 64 and then 100, not
236// 64 alone). A graph that is not truncated is the verdict: one base, several (criss-cross), or none (unrelated). A
237// truncated graph at the cap is `capped`: limit_exceeded, never an answer over a cut graph. `searchStep` is pure; the
238// driver in mergeBase is the only part that fetches.
239export type Search<K extends string = string> =
240 | { readonly tag: 'searching'; readonly depth: number }
241 | { readonly tag: 'found'; readonly depth: number; readonly base: K; readonly bases: K[] }
242 | { readonly tag: 'criss-cross'; readonly depth: number; readonly bases: K[] }
243 | { readonly tag: 'unrelated'; readonly depth: number; readonly bases: K[] }
244 | { readonly tag: 'capped'; readonly depth: number };
245export type Verdict<K extends string = string> = Extract<Search<K>, { readonly tag: 'found' | 'criss-cross' | 'unrelated' }>;
246// `depth` is the window searched (commits a side, the tip at 1); `cap` counts whole commits (mergeBase rounds a limit
247// down); bases is git merge-base --all on every verdict. The first state is searching(min(8, cap)); a cap under 1 is
248// capped before any search.
249export function searchStep<K extends string>(depth: number, cap: number, commits: ReadonlyMap<K, Parents<K>>, a: K, b: K): Search<K> {
250 const { best, truncated } = bestBases(commits, a, b);
251 // Both sides complete and still truncated cannot happen (ancestors refuses a parent withheld without a shallow line);
252 // it used to be accepted (#18).
253 if (truncated) return depth < cap ? { tag: 'searching', depth: Math.min(depth * 2, cap) } : { tag: 'capped', depth };
254 const first = at(best, 0);
255 if (first.tag === 'none') return { tag: 'unrelated', depth, bases: best };
256 return best.length > 1 ? { tag: 'criss-cross', depth, bases: best } : { tag: 'found', depth, base: first.value, bases: best };
259// base is the verdict's one base, or null
260export type MergeBase = { readonly base: Oid | null; readonly bases: Oid[]; readonly depth: number; readonly commits: Map<Oid, Commit>; readonly verdict: Verdict<Oid> };
261// maxDepth: the search cap in commits a side; null (the default) reads the transport's limits.maxMergeDepth.
262export type MergeBaseConfig = { readonly maxDepth: number | null };
263export type MergeBaseOptions = Input<MergeBaseConfig>;
264// mergeBase of parsed ids: mergeBranch and rebaseBranch, which hold Oids, start here.
265export async function mergeBaseOf(t: Transport, a: Oid, b: Oid, options: MergeBaseOptions = {}): Promise<Result<MergeBase, PlyError>> {
266 const { maxDepth } = withDefaults<MergeBaseConfig>(options, { maxDepth: null });
267 const capped = maxDepth === null ? ok(t.limits.maxMergeDepth) : checkLimit(maxDepth, 'maxMergeDepth');
268 if (!capped.ok) return capped;
269 const cap = capped.value;
270 const top = Math.floor(cap);
271 let s: Search<Oid> = top < 1 ? { tag: 'capped', depth: 0 } : { tag: 'searching', depth: Math.min(8, top) };
272 let commits = new Map<Oid, Commit>();
273 while (s.tag === 'searching') {
274 const depth: number = s.depth;
275 // oxlint-disable-next-line eslint/no-await-in-loop -- each round deepens from what the last one found
276 const [A, B] = await Promise.all([ancestors(t, a, depth), ancestors(t, b, depth)]);
277 if (!A.ok) return A;
278 if (!B.ok) return B;
279 commits = new Map([...B.value, ...A.value]);
280 s = searchStep(depth, top, commits, a, b);
281 }
282 switch (s.tag) {
283 case 'capped': {
284 const attempted = s.depth === 0 ? 1 : s.depth * 2;
285 return err(limitError('merge-base search depth', attempted, cap));
286 }
287 case 'found': return ok({ base: s.base, bases: s.bases, depth: s.depth, commits, verdict: s });
288 case 'criss-cross':
289 case 'unrelated': return ok({ base: null, bases: s.bases, depth: s.depth, commits, verdict: s });
290 }
291 // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check
292 return assertNever(s);
295// The caller's two ids are parsed once, here (parseOid: bad_request, what `oid`), before any fetch.
296export async function mergeBase(t: Transport, a: string, b: string, options: MergeBaseOptions = {}): Promise<Result<MergeBase, PlyError>> {
297 const ia = parseOid(a);
298 if (!ia.ok) return ia;
299 const ib = parseOid(b);
300 if (!ib.ok) return ib;
301 return mergeBaseOf(t, ia.value, ib.value, options);
304// Effect: a tree's entries, from the oid → bytes cache or fetched into it (`onFetch` counts a fetch)
305const NO_COUNT = (): void => { /* not counted */ };
306// oxlint-disable-next-line eslint/max-params -- the transport, the cache, the oid and the counter
307const cachedTree = async (t: Transport, cache: TreeCache, oid: string, onFetch: () => void = NO_COUNT): Promise<Result<TreeEntry[], PlyError>> => {
308 const held = mapGet(cache, oid);
309 if (held.tag === 'some') return parseTree(held.value, t.limits);
310 const got = await fetchObject(t, { oid, expectType: TYPE.TREE });
311 if (!got.ok) return got;
312 cache.set(oid, got.value.data); onFetch();
313 // the fetch's check parsed it (#208)
314 return treeEntries(got.value, t.limits);
315};
316const subtree = (e: Entry): Oid | null => (e.tag === 'some' && isTreeEntry(e.value) ? e.value.oid : null);
317// a tree by oid; null is the empty tree
318type ReadTree = (oid: Oid | null) => Promise<Result<readonly TreeEntry[], PlyError>>;
319// Effect: what `side` adds relative to `base` (both tree oids), recursing only into differing subtrees; a directory new
320// on `side` is one entry, 'dir/', standing for everything inside it, so it carries the directory's tree id: two sides
321// added the same things there only if they added the same tree.
322type Added = { readonly path: string; readonly oid: Oid };
323async function addedPaths(read: ReadTree, base: Oid | null, side: Oid | null, prefix = ''): Promise<Result<Added[], PlyError>> {
324 if (base === side) return ok([]);
325 const [B, S] = await Promise.all([read(base), read(side)]);
326 if (!B.ok) return B;
327 if (!S.ok) return S;
328 const b = byName(B.value); const out: Added[] = [];
329 for (const e of S.value) {
330 const was = mapGet(b, e.name);
331 // new, or a file where a directory was (or the reverse): added
332 if (was.tag === 'none' || isTreeEntry(e) !== isTreeEntry(was.value)) out.push({ path: prefix + e.name + (isTreeEntry(e) ? '/' : ''), oid: e.oid });
333 else if (isTreeEntry(e) && was.value.oid !== e.oid) {
334 // oxlint-disable-next-line eslint/no-await-in-loop -- one subtree at a time, as before
335 const inner = await addedPaths(read, was.value.oid, e.oid, `${prefix}${e.name}/`);
336 if (!inner.ok) return inner;
337 out.push(...inner.value);
338 }
339 }
340 return ok(out);
343// a list of additions as one comparable value: each path with what was put there (paths hold no NUL)
344const changeSet = (l: readonly Added[]): string => l.map(a => `${a.path}\0${a.oid}`).toSorted().join('\0');
345// a side still holds a base file as a file (a file replaced by a directory of its name is deleted there: the rename
346// detection ply stands in for counts anything but a tree as the file)
347const holdsFile = (e: Entry): boolean => e.tag === 'some' && !isTreeEntry(e.value);
348// Effect: the base paths neither side holds any more: every rename source both sides lost, which is what arms G1. It is
349// read off the three trees, not off the merge walk, because the walk does not visit every place a file can be lost on
350// both sides: a subtree that is the same tree on ours and theirs is taken whole, and a base file under a name where a
351// side now has a directory is merged as if the base were empty. Descends only where base differs from both sides (a
352// subtree one side left alone has no deletion on that side); a directory gone from both sides (absent, or a file now)
353// is one path. Where the sides differ the walk has been, so those reads are the tree cache's. A subtree ours and theirs
354// agree on and base does not is the only place this reads what the walk did not: base's copy and the sides' one copy,
355// each once. With `gate` given such a subtree is not entered but listed there, for the caller to enter only if the
356// merge can have a rename hazard (see mergeDir), and the directories exactly one side changed are counted (`lone`):
357// the two numbers say which of the gate's questions has fewer directories to read.
358type Shared = { readonly base: Oid; readonly side: Oid; readonly prefix: string };
359type Gate = { readonly shared: Shared[]; lone: number };
360// The gate reads sibling directories this many at a time, each up to two trees the walk did not read.
361const GATE_WIDTH = 8;
362// a base directory still a directory on both sides, changed by exactly one of them
363// oxlint-disable-next-line eslint/max-params -- base's tree and the two sides'
364const loneChange = (was: Oid, so: Oid | null, st: Oid | null): boolean => so !== null && st !== null && (so === was) !== (st === was);
365// oxlint-disable-next-line eslint/max-params -- the reader, the trees, where they are, the list filled and the gate's
366async function deletedOnBoth(read: ReadTree, { base, ours, theirs }: Trees, prefix: string, out: string[], gate: Gate | null): Promise<Result<true, PlyError>> {
367 if (base === null || base === ours || base === theirs) return ok(true);
368 const [B, O, T] = await Promise.all([read(base), read(ours), read(theirs)]);
369 if (!B.ok) return B;
370 if (!O.ok) return O;
371 if (!T.ok) return T;
372 const o = byName(O.value); const t = byName(T.value);
373 for (const e of B.value) {
374 const eo = mapGet(o, e.name); const et = mapGet(t, e.name);
375 if (!isTreeEntry(e)) { if (!holdsFile(eo) && !holdsFile(et)) out.push(prefix + e.name); continue; }
376 const so = subtree(eo); const st = subtree(et);
377 if (so === null && st === null) { out.push(prefix + e.name); continue; }
378 if (gate !== null && so !== null && so === st && so !== e.oid) { gate.shared.push({ base: e.oid, side: so, prefix: `${prefix}${e.name}/` }); continue; }
379 if (gate !== null && loneChange(e.oid, so, st)) gate.lone++;
380 // oxlint-disable-next-line eslint/no-await-in-loop -- one subtree at a time, as addedPaths
381 const inner = await deletedOnBoth(read, { base: e.oid, ours: so, theirs: st }, `${prefix}${e.name}/`, out, gate);
382 if (!inner.ok) return inner;
383 }
384 return ok(true);
386// One directory of oneSided: true when `side` added or removed a name here (a file where a directory was, or the
387// reverse, is both), else the subdirectories `side` changed, still to be looked at.
388type Level = { readonly base: Oid | null; readonly side: Oid | null; readonly other: Oid | null };
389async function oneSidedAt(read: ReadTree, { base, side, other }: Level): Promise<Result<true | Level[], PlyError>> {
390 if (base === side || side === other) return ok([]);
391 const [B, S, X] = await Promise.all([read(base), read(side), read(other)]);
392 if (!B.ok) return B;
393 if (!S.ok) return S;
394 if (!X.ok) return X;
395 const b = byName(B.value); const s = byName(S.value); const x = byName(X.value);
396 for (const e of B.value) { const now = mapGet(s, e.name); if (now.tag === 'none' || isTreeEntry(now.value) !== isTreeEntry(e)) return ok(true); }
397 const below: Level[] = [];
398 for (const e of S.value) {
399 const was = mapGet(b, e.name);
400 if (was.tag === 'none') return ok(true);
401 if (isTreeEntry(e) && was.value.oid !== e.oid) below.push({ base: was.value.oid, side: e.oid, other: subtree(mapGet(x, e.name)) });
402 }
403 return ok(below);
405// Effect: whether `side` added or removed a path relative to `base` anywhere outside the subtrees it shares with `other`.
406// Reads what the walk read, plus base's and the side's copy of each directory only that side changed: one depth at a
407// time, GATE_WIDTH sibling directories at once, stopping after the batch that holds an add or a removal. Inside a shared
408// subtree both sides added and removed the same things; if neither side added or removed anything outside them, the
409// two sides give rename detection the same sources and the same targets, so it pairs the same renames on both and
410// there is nothing for G1 to guard.
411// oxlint-disable-next-line eslint/max-params -- the reader and the three trees
412async function oneSided(read: ReadTree, base: Oid | null, side: Oid | null, other: Oid | null): Promise<Result<boolean, PlyError>> {
413 let level: Level[] = [{ base, side, other }];
414 while (level.length > 0) {
415 const below: Level[] = [];
416 for (let i = 0; i < level.length; i += GATE_WIDTH) {
417 // oxlint-disable-next-line eslint/no-await-in-loop -- GATE_WIDTH directories at a time
418 const found = await Promise.all(level.slice(i, i + GATE_WIDTH).map(async d => oneSidedAt(read, d)));
419 for (const f of found) {
420 if (!f.ok) return f;
421 if (f.value === true) return ok(true);
422 for (const d of f.value) below.push(d);
423 }
424 }
425 level = below;
426 }
427 return ok(false);
429export type DriverFor = (path: string) => Promise<Result<Driver, PlyError>>;
430// Why a path conflicts. The text is the reason a caller reads in merge_conflict's `reasons`.
431export type ContentReason =
432 | 'binary (merge attribute)' | 'too large to merge' | 'binary'
433 | 'content (both sides changed the same lines)'
434 | 'content (git would decide this with a classic-diff fallback ply does not implement)';
435export type ConflictReason =
436 | ContentReason
437 | 'tree' // the sides disagree on what the path is (modify/delete, file/directory, add/add of different kinds, …)
438 | 'mode' // both sides changed a file's mode, differently
439 | 'content' // both sides changed a file and no line merge was given
440 | 'possible directory rename (added inside a directory the other side removed)'
441 | 'possible rename source (deleted on both sides while paths were added; ply does not detect renames)'
442 | 'possible rename target (added while the merge has a deletion conflict)';
443export type BlobSpec = { readonly base: Oid; readonly ours: Oid; readonly theirs: Oid; readonly path: string; readonly driverFor: DriverFor | null };
444// A both-sides-changed file's content: one side's blob as it is (already on the server), a new merged blob (to push),
445// or a conflict with its reason.
446export type BlobMerge =
447 | { readonly kind: 'existing'; readonly oid: Oid }
448 | { readonly kind: 'merged'; readonly oid: Oid; readonly data: Uint8Array }
449 | { readonly kind: 'conflict'; readonly reason: ContentReason };
450export type MergeStats = { merged: number; undecided: number; unioned: number; attrBinary: number };
451export type MergeBlob = ((spec: BlobSpec) => Promise<Result<BlobMerge, PlyError>>) & { stats: MergeStats };
452export type Removed = 'ours' | 'theirs' | null;
453// The three trees by oid (null: the empty tree), the path prefix of this directory, which side removed the directory
454// being merged (null: neither), the line merge for a both-sides-changed file (null: such a file conflicts), and the
455// .gitattributes merge driver per path (null: text).
456export type MergeTreesConfig = {
457 readonly base: string | null;
458 readonly ours: string | null;
459 readonly theirs: string | null;
460 readonly prefix: string;
461 readonly removed: Removed;
462 readonly mergeBlob: MergeBlob | null;
463 readonly driverFor: DriverFor | null;
464};
465export type MergeTreesSpec = Input<MergeTreesConfig>;
466// The same, the three tree ids parsed (mergeTrees' edge, or an Oid the caller already holds).
467type MergeDirConfig = Omit<MergeTreesConfig, 'base' | 'ours' | 'theirs'> & Trees;
468// A reasons record with no prototype (Object.create's result is `any`). It has no keys, so it is any such record.
469// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- an empty null-prototype object: no key, no inherited key
470const noProtoReasons = (): Record<string, ConflictReason> => Object.create(null) as Record<string, ConflictReason>;
472// The accumulator one merge shares across its recursion. reasons is keyed by path and has no prototype. deletedOne: a
473// modify/delete conflict was seen.
474export type MergeAcc = {
475 objects: PackObject[];
476 conflicts: string[];
477 fetched: number;
478 deletedBoth: string[];
479 dirAdds: string[];
480 reasons: Record<string, ConflictReason>;
481 contentMerged: number;
482 deletedOne: boolean;
483};
484// oid: the merged tree, or null when the merge conflicts or the tree is empty
485export type MergeTreesResult = MergeAcc & { readonly oid: Oid | null };
486const mergeTreesDefaults = (): MergeTreesConfig => ({ base: null, ours: null, theirs: null, prefix: '', removed: null, mergeBlob: null, driverFor: null });
488// Effect: merge three trees (by oid, any may be null = empty) into a new tree, returning its oid, the new objects to push
489// and conflicts as paths. Fetches only directories where the sides differ; `cache` is the oid → bytes tree cache.
490// `mergeBlob(base, ours, theirs, path)` resolves a path both sides changed (line merge); without it such paths conflict.
491//
492// Rename guards. merge-ort detects renames (and directory renames, as conflicts); we do not. Two shapes are where a
493// rename could make git conflict while a rename-blind merge is clean, so they are conflicts here (superset of git's):
494// G1 a path deleted on both sides while either side adds a path (rename/rename(1to2), rename/delete) — the deleted
495// paths and the added ones are reported, since git names the conflict at the rename target. "Deleted on both
496// sides" is decided over the whole of the three trees (deletedOnBoth), wherever the walk went
497// (G2's target is a path git computes from the directory rename; we report the added path and the reason.)
498// G2 a directory one side removed entirely, the other side adds inside it (directory rename + add)
499// A rename on one side with the other side untouched merges exactly as git does.
500/* oxlint-disable eslint/no-await-in-loop, eslint/complexity, eslint/max-params -- one path at a time (the merges share `out`, the cache and the fetch budget); the rename guards run once, at the top */
501async function mergeDir(t: Transport, cache: TreeCache, { base, ours, theirs, prefix, removed, mergeBlob, driverFor }: MergeDirConfig, out: MergeAcc, top: boolean): Promise<Result<MergeTreesResult, PlyError>> {
502 const conflict = (path: string, why: ConflictReason): void => { out.conflicts.push(path); out.reasons[path] = why; };
503 // A tree asked for again while its fetch is in flight is that fetch: two of the three trees can be one tree (a
504 // subtree ours and theirs share), and no tree is fetched twice.
505 const flying = new Map<Oid, Promise<Result<readonly TreeEntry[], PlyError>>>();
506 const read: ReadTree = async oid => {
507 if (oid === null) return ok(EMPTY);
508 const held = mapGet(flying, oid);
509 if (held.tag === 'some') return held.value;
510 const p = cachedTree(t, cache, oid, () => { out.fetched++; });
511 flying.set(oid, p);
512 const got = await p;
513 flying.delete(oid);
514 return got;
515 };
516 const [readB, readO, readT] = await Promise.all([read(base), read(ours), read(theirs)]);
517 if (!readB.ok) return readB;
518 if (!readO.ok) return readO;
519 if (!readT.ok) return readT;
520 const [B, O, T] = [readB.value, readO.value, readT.value];
521 const r = threeWay(B, O, T);
522 const { entries } = r;
523 // Names are the repository's: a Map, so a directory called `constructor` or `__proto__` is not Object.prototype's
524 const b = byName(B);
525 const o = byName(O);
526 const th = byName(T);
527 for (const name of r.conflicts) conflict(prefix + name, 'tree');
528 if (r.conflicts.some(name => b.has(name) && !(o.has(name) && th.has(name)))) out.deletedOne = true; // modify/delete
529 if (removed === 'ours') for (const name of r.addedTheirs) out.dirAdds.push(prefix + name);
530 if (removed === 'theirs') for (const name of r.addedOurs) out.dirAdds.push(prefix + name);
531 for (const name of r.content) {
532 // content names are files on all three sides (threeWay)
533 const eb = mapGet(b, name);
534 const eo = mapGet(o, name);
535 const et = mapGet(th, name);
536 if (eb.tag === 'none' || eo.tag === 'none' || et.tag === 'none') continue;
537 const mode = mergeMode(eb.value.mode, eo.value.mode, et.value.mode);
538 if (mode === null) { conflict(prefix + name, 'mode'); continue; }
539 if (mergeBlob === null) { conflict(prefix + name, 'content'); continue; }
540 const blobMerged = await mergeBlob({ base: eb.value.oid, ours: eo.value.oid, theirs: et.value.oid, path: prefix + name, driverFor });
541 if (!blobMerged.ok) return blobMerged;
542 const blob = blobMerged.value;
543 switch (blob.kind) {
544 case 'conflict': conflict(prefix + name, blob.reason); continue;
545 case 'existing': entries.push({ mode, name, oid: blob.oid }); out.contentMerged++; continue;
546 case 'merged': entries.push({ mode, name, oid: blob.oid }); out.objects.push({ type: TYPE.BLOB, data: blob.data, oid: blob.oid }); out.contentMerged++; continue;
547 }
548 // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check
549 assertNever(blob);
550 }
551 for (const name of r.recurse) {
552 const eb = mapGet(b, name);
553 let sideRemoved = removed;
554 if (sideRemoved === null && isTree(eb)) { if (!o.has(name)) sideRemoved = 'ours'; else if (!th.has(name)) sideRemoved = 'theirs'; }
555 const sub = await mergeDir(t, cache, { base: subtree(eb), ours: subtree(mapGet(o, name)), theirs: subtree(mapGet(th, name)), prefix: `${prefix}${name}/`, removed: sideRemoved, mergeBlob, driverFor }, out, false);
556 if (!sub.ok) return sub;
557 if (sub.value.oid !== null) entries.push({ mode: '40000', name, oid: sub.value.oid }); // an empty merged subtree drops the directory, as git does
558 }
559 if (top) for (const p of out.dirAdds) if (!(p in out.reasons)) conflict(p, 'possible directory rename (added inside a directory the other side removed)');
560 const encoded = encodeEntries(entries);
561 if (!encoded.ok) return encoded;
562 const data: Uint8Array = encoded.value;
563 const oid: Oid = hashObject('tree', data);
564 // What both sides lost. Where the walk went this reads nothing new, and a merge with no shared subtree (one ours and
565 // theirs changed identically) reads nothing here at all. With shared subtrees and no loss seen by the walk, G1 can
566 // only fire if both hold: a path lost on both sides inside a shared subtree, and a path one side alone added or
567 // removed (without one there is no rename for git to pair differently on the two sides). One "no" settles it, so the
568 // question with fewer directories to read is asked first: the shared subtrees when they are fewer than the
569 // directories one side alone changed, those directories otherwise. A "yes" asks the other question too, so what is
570 // decided never depends on the order: the shared subtrees' losses arm G1 only when a side added or removed a path
571 // of its own.
572 const gate: Gate = { shared: [], lone: 0 };
573 // the paths both sides lost inside the shared subtrees, in the subtrees' order; each is entered once, GATE_WIDTH at a time
574 const enter = async (): Promise<Result<string[], PlyError>> => {
575 const subtrees = gate.shared.splice(0); const lost: string[] = [];
576 for (let i = 0; i < subtrees.length; i += GATE_WIDTH) {
577 const found = await Promise.all(subtrees.slice(i, i + GATE_WIDTH).map(async (s): Promise<Result<string[], PlyError>> => {
578 const paths: string[] = [];
579 const inner = await deletedOnBoth(read, { base: s.base, ours: s.side, theirs: s.side }, s.prefix, paths, null);
580 return inner.ok ? ok(paths) : inner;
581 }));
582 for (const f of found) { if (!f.ok) return f; for (const p of f.value) lost.push(p); }
583 }
584 return ok(lost);
585 };
586 // the shared subtrees' losses that arm G1: none unless a side added or removed a path of its own
587 const armed = async (): Promise<Result<string[], PlyError>> => {
588 const first = gate.shared.length < gate.lone ? await enter() : null; // null: the shared subtrees are not read yet
589 if (first !== null && (!first.ok || first.value.length === 0)) return first;
590 const mine = await oneSided(read, base, ours, theirs);
591 if (!mine.ok) return mine;
592 const yours = mine.value ? mine : await oneSided(read, base, theirs, ours);
593 if (!yours.ok) return yours;
594 if (!yours.value) return ok([]);
595 return first === null ? enter() : first;
596 };
597 if (top) {
598 const lost = await deletedOnBoth(read, { base, ours, theirs }, prefix, out.deletedBoth, gate);
599 if (!lost.ok) return lost;
600 if (out.deletedBoth.length === 0 && !out.deletedOne && gate.shared.length > 0) {
601 const hidden = await armed();
602 if (!hidden.ok) return hidden;
603 for (const p of hidden.value) out.deletedBoth.push(p);
604 }
605 }
606 // deletedOne is set only beside a conflict
607 if (top && (out.deletedBoth.length > 0 || out.deletedOne)) {
608 // Every path either side added, across the whole tree — the walk above skips directories only one side changed, and a
609 // rename target can be anywhere. Fetched only when a deletion is in play.
610 const addedOursR = await addedPaths(read, base, ours);
611 if (!addedOursR.ok) return addedOursR;
612 const addedTheirsR = await addedPaths(read, base, theirs);
613 if (!addedTheirsR.ok) return addedTheirsR;
614 const addedOurs = addedOursR.value;
615 const addedTheirs = addedTheirsR.value;
616 const added = [...new Set([...addedOurs, ...addedTheirs].map(a => a.path))];
617 // G1 stands down when the rename is already applied (#103): the rename-blind merge is ours' tree (every change theirs
618 // made is in ours) and both sides added and deleted exactly the same things (a directory new on both sides is one
619 // name, and the same addition only as the same tree), so git pairs the same renames on both
620 // sides and finds nothing to conflict (a cherry-pick of it is empty). An add or delete on ours alone could let git
621 // pair a different source or target there (rename/rename, rename/delete), so the guard stays.
622 const sameChanges = async (): Promise<Result<boolean, PlyError>> => {
623 if (changeSet(addedOurs) !== changeSet(addedTheirs)) return ok(false);
624 const removedOurs = await addedPaths(read, ours, base);
625 if (!removedOurs.ok) return removedOurs;
626 return map(await addedPaths(read, theirs, base), removedTheirs => changeSet(removedOurs.value) === changeSet(removedTheirs));
627 };
628 const unchanged = out.conflicts.length === 0 && oid === ours ? await sameChanges() : ok(false);
629 if (!unchanged.ok) return unchanged;
630 const applied = unchanged.value;
631 // the refusal names every path both sides lost, the shared subtrees' too; a path the walk already conflicts on is
632 // listed once and keeps the walk's reason
633 if (added.length > 0 && !applied) { const entered = await enter(); if (!entered.ok) return entered; for (const p of entered.value) out.deletedBoth.push(p); }
634 if (added.length > 0 && !applied) for (const p of out.deletedBoth) if (!(p in out.reasons)) conflict(p, 'possible rename source (deleted on both sides while paths were added; ply does not detect renames)');
635 // Naming: git reports a rename's conflict at the rename target (rename/delete, rename/rename, or a content conflict
636 // after following a rename onto a modify/delete). When this merge conflicts with a deletion in play, every added path
637 // is a possible target, so it is listed too. This adds names to a conflicting merge; it never makes one conflict.
638 if (out.conflicts.length > 0) for (const p of added) if (!(p in out.reasons)) conflict(p, 'possible rename target (added while the merge has a deletion conflict)');
639 }
640 if (out.conflicts.length > 0 || entries.length === 0) return ok({ oid: null, ...out });
641 if (oid !== ours && oid !== theirs && oid !== base) out.objects.push({ type: TYPE.TREE, data, oid });
642 cache.set(oid, data);
643 return ok({ oid, ...out });
645/* oxlint-enable eslint/no-await-in-loop, eslint/complexity, eslint/max-params */
647// A tree id as mergeTrees takes it: null is the empty tree; anything else is parsed once (parseOid: 40 lowercase hex,
648// what: 'oid') before any tree is read.
649const treeIdOf = (id: string | null): Result<Oid | null, ErrorOf<'bad_request'>> => (id === null ? ok(null) : parseOid(id));
650// The three trees parsed once, at the edge: base, then ours, then theirs.
651function parseTrees({ base, ours, theirs }: Pick<MergeTreesConfig, 'base' | 'ours' | 'theirs'>): Result<Trees, ErrorOf<'bad_request'>> {
652 const b = treeIdOf(base); if (!b.ok) return b;
653 const o = treeIdOf(ours); if (!o.ok) return o;
654 const th = treeIdOf(theirs); if (!th.ok) return th;
655 return ok({ base: b.value, ours: o.value, theirs: th.value });
657// mergeTrees of parsed tree ids: the merge and rebase entries, which hold Oids, start here.
658export async function mergeTreesOf(t: Transport, cache: TreeCache, spec: MergeDirConfig, into: MergeAcc | null = null): Promise<Result<MergeTreesResult, PlyError>> {
659 const top = into === null;
660 // reasons is keyed by path, so it has no prototype: a path named `__proto__` or `constructor` is recorded like any other
661 const out: MergeAcc = into === null ? { objects: [], conflicts: [], fetched: 0, deletedBoth: [], dirAdds: [], reasons: noProtoReasons(), contentMerged: 0, deletedOne: false } : into;
662 return mergeDir(t, cache, spec, out, top);
664export async function mergeTrees(t: Transport, cache: TreeCache, spec: MergeTreesSpec, into: MergeAcc | null = null): Promise<Result<MergeTreesResult, PlyError>> {
665 const config = withDefaults(spec, mergeTreesDefaults());
666 const trees = parseTrees(config);
667 if (!trees.ok) return trees;
668 // the parsed ids, and none of the caller's: past this line no tree id is a raw string
669 const { prefix, removed, mergeBlob, driverFor } = config;
670 return mergeTreesOf(t, cache, { prefix, removed, mergeBlob, driverFor, ...trees.value }, into);
672// Effect: the merge driver for a path from the .gitattributes files of one tree (git's attr.tree / --attr-source, or the
673// worktree's — which is ours — for a non-bare `git merge`). Reads only the directories on the path, each once; returns
674// 'text' | 'union' | 'binary' as find_ll_merge_driver picks: merge set → text, -merge → binary, merge=binary|union|text
675// → that, any other name → text (a custom driver is server configuration we cannot see), unspecified → text.
676export function attributeDrivers(t: Transport, cache: TreeCache, treeOid: string): DriverFor {
677 // Each directory's tree and .gitattributes text is looked up once and shared, while it is pending or once it has
678 // succeeded. A lookup that fails (an Err, or a rejection) is forgotten as it fails, so the next path asks again (#79:
679 // one transient failure poisoned every later lookup of that directory).
680 type Look = Promise<Result<Option<string>, PlyError>>;
681 const memo = new Map<string, Look>([['/', Promise.resolve(ok(some(treeOid)))]]);
682 const once = (key: string, look: () => Look): Look => {
683 const known = mapGet(memo, key);
684 if (known.tag === 'some') return known.value;
685 const p = look(); memo.set(key, p); p.then(r => r.ok || memo.delete(key), () => memo.delete(key)).catch(() => false);
686 return p;
687 };
688 // the first entry of the tree `oid` that `keep` accepts
689 const entryIn = async (oid: string, keep: (e: TreeEntry) => boolean): Promise<Result<Option<TreeEntry>, PlyError>> => map(await cachedTree(t, cache, oid), l => fromNullable(l.find(e => keep(e))));
690 // keys: '/' + dir for a directory's tree oid, dir alone for its .gitattributes text (a dir never starts with '/')
691 const treeOf = (dir: string): Look => once(`/${dir}`, async () => {
692 const cut = dir.lastIndexOf('/');
693 const p = await treeOf(cut < 0 ? '' : dir.slice(0, cut));
694 if (!p.ok || p.value.tag === 'none') return p;
695 return map(await entryIn(p.value.value, e => e.name === dir.slice(cut + 1) && e.mode === '40000'), found => mapOption(found, e => e.oid));
696 });
697 // a .gitattributes entry's text
698 const textOf = async (e: Option<TreeEntry>): Promise<Result<Option<string>, PlyError>> => {
699 if (e.tag === 'none') return ok(none);
700 return map(await objectAt(t, e.value.oid, { expectType: TYPE.BLOB }), b => some(bytesToStr(b.data)));
701 };
702 const fileOf = (dir: string): Look => once(dir, async () => {
703 const oid = await treeOf(dir);
704 if (!oid.ok || oid.value.tag === 'none') return oid;
705 const e = await entryIn(oid.value.value, x => x.name === '.gitattributes' && x.mode !== '40000' && x.mode !== '160000');
706 if (!e.ok) return e;
707 return textOf(e.value);
708 });
709 return async path => {
710 const dirs = ['']; for (let i = path.indexOf('/'); i >= 0; i = path.indexOf('/', i + 1)) dirs.push(path.slice(0, i));
711 const texts = await Promise.all(dirs.map(d => fileOf(d)));
712 for (const r of texts) if (!r.ok) return r;
713 const byDir = new Map<string, string>();
714 for (const [i, d] of dirs.entries()) {
715 const text = at(texts, i);
716 if (text.tag === 'none' || !text.value.ok || text.value.value.tag === 'none') continue;
717 const dir = utf8ToStr(d);
718 if (!dir.ok) return dir;
719 byDir.set(dir.value, text.value.value.value);
720 }
721 const file = utf8ToStr(path);
722 if (!file.ok) return file;
723 const v = attributeOf(attributesFor(file.value, byDir), 'merge');
724 if (v.tag === 'none') return ok<Driver>('text');
725 if (v.value === false) return ok<Driver>('binary');
726 if (v.value === 'binary' || v.value === 'union') return ok<Driver>(v.value);
727 return ok<Driver>('text');
728 };
731const refused = (reason: ContentReason): Ok<BlobMerge> => ok({ kind: 'conflict', reason });
732// A blob that could not be read: too large is a refusal (the merge goes on), anything else fails it.
733const lost = (r: Err<PlyError>): Result<BlobMerge, PlyError> => (r.error.code === 'limit_exceeded' ? refused('too large to merge') : r);
735// Effect: the content half of a both-sides-changed file — git's shortcuts first (one side equal to base or both equal),
736// then the three blobs (bounded by maxMergeBlobBytes, their diff steps by maxMergeWork) through the ported xdiff merge. Shared by merge, rebase,
737// cherry-pick and revert. Refused (bad_request) before any merge: a rediff that is not one of the three, or a blob cap
738// that bounds nothing (the transport's object cap was checked where the transport was made). Blobs are read under the
739// lower of the two caps.
740export function blobMerger(t: Transport, maxMergeBlobBytes: unknown, rediff: Rediff): Result<MergeBlob, ErrorOf<'bad_request'>> {
741 if (!['undecided', 'skip', 'myers'].includes(rediff)) return fail('bad_request', `rediff must be 'undecided', 'skip' or 'myers', not ${JSON.stringify(rediff)}`);
742 const blobCapped = checkLimit(maxMergeBlobBytes, 'maxMergeBlobBytes');
743 if (!blobCapped.ok) return blobCapped;
744 const stats: MergeStats = { merged: 0, undecided: 0, unioned: 0, attrBinary: 0 };
745 // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Object.create returns any; the view is `t` with limits shadowed (as transport.ts withParent)
746 const bounded = Object.create(t, { limits: { value: lowered(t.limits, 'maxObjectSize', blobCapped.value) } }) as Transport;
747 // Blobs this merger produced exist only in the pending push (a rebase replays commit 2 onto commit 1's merged blob), so
748 // they are served from here; the bytes are already held for the push, so this costs no extra memory.
749 const made = new Map<string, Uint8Array>();
750 const get = async (oid: Oid): Promise<Result<Uint8Array, PlyError>> => { const held = mapGet(made, oid); return held.tag === 'some' ? ok(held.value) : map(await objectAt(bounded, oid, { expectType: TYPE.BLOB }), b => b.data); };
751 const f = async ({ base, ours, theirs, path, driverFor }: BlobSpec): Promise<Result<BlobMerge, PlyError>> => {
752 if (ours === theirs || theirs === base) return ok({ kind: 'existing', oid: ours });
753 if (ours === base) return ok({ kind: 'existing', oid: theirs });
754 // the merge attribute (when an attribute source was given): binary/-merge conflicts without reading the blobs
755 const driven = driverFor === null ? ok<Driver>('text') : await driverFor(path);
756 if (!driven.ok) return driven;
757 const driver = driven.value;
758 if (driver === 'binary') { stats.attrBinary++; return refused('binary (merge attribute)'); }
759 const [rB, rO, rT] = await Promise.all([get(base), get(ours), get(theirs)]);
760 if (!rB.ok) return lost(rB);
761 if (!rO.ok) return lost(rO);
762 if (!rT.ok) return lost(rT);
763 const [B, O, T] = [rB.value, rO.value, rT.value];
764 const m = mergeLines(B, O, T, { maxBytes: blobCapped.value, maxWork: t.limits.maxMergeWork, rediff, driver });
765 if (!m.clean) {
766 if (m.reason === 'undecided') { stats.undecided++; return refused('content (git would decide this with a classic-diff fallback ply does not implement)'); }
767 return refused(m.reason === 'content' ? 'content (both sides changed the same lines)' : m.reason);
768 }
769 stats.merged++; if ('unioned' in m) stats.unioned++;
770 const oid: Oid = hashObject('blob', m.data); made.set(oid, m.data);
771 return ok({ kind: 'merged', oid, data: m.data });
772 };
773 return ok(Object.assign(f, { stats }));
776// Pure: one entry per oid, first wins. git's unpack-objects/index-pack refuse a pack that carries an object twice
777// ("tried to add buffer twice"), and a merge produces the same blob or tree at two paths, or in two replayed commits.
778// the set grows exactly when the oid is new
779export const uniqueObjects = <O extends { readonly oid: string }>(objects: readonly O[]): O[] => { const seen = new Set<string>(); return objects.filter(o => seen.size < seen.add(o.oid).size); };
781// Effect: the tree whose .gitattributes govern a merge. null → none (git ≥ 2.46 in a bare repository, unless attr.tree
782// is set); 'ours' | 'theirs' | 'base' → that side's tree ('ours' is what `git merge` in a worktree reads, and git
783// 2.43–2.45 in a bare repository whose HEAD is the target branch); a ref name or commit oid → its tree (attr.tree=<rev>).
784// 'ours' | 'theirs' | 'base', a ref name or a commit oid, or null
785export type AttributeSource = string | null;
786// A caller's attributes option, checked (a JS caller's missing value is null).
787export const validateAttributes = (a: unknown): Result<AttributeSource, ErrorOf<'bad_request'>> => {
788 const given = fromNullish(a);
789 if (given.tag === 'none') return ok(null);
790 const v = given.value;
791 if (typeof v !== 'string') return fail('bad_request', 'attributes must be null, ours, theirs, base, a ref or a commit oid');
792 if (v === 'ours' || v === 'theirs' || v === 'base' || isOid(v)) return ok(v);
793 return map(validateRef(v), () => v);
794};
795// The three sides' trees (null: the empty tree, or a side not in play).
796// The three trees of a merge, parsed (null: the empty tree).
797export type Trees = { readonly base: Oid | null; readonly ours: Oid | null; readonly theirs: Oid | null };
798export const NO_TREES: Trees = { base: null, ours: null, theirs: null };
799const refMiss = (ref: string): Miss => ({ kind: 'ref', ref, candidates: [ref] });
800// a ref's oid in an ls-refs answer
801export const refOid = (refs: LsRefsResult['refs'], ref: string): Option<Oid> => mapOption(mapGet(refs, ref), r => r.oid);
802// The tree whose .gitattributes apply; a JS caller's missing tree is null.
803export async function attributeTree(t: Transport, attributes: AttributeSource, given: Input<Trees>): Promise<Result<string | null, PlyError>> {
804 const trees = withDefaults(given, { ...NO_TREES });
805 if (attributes === null) return ok(null);
806 if (attributes === 'ours' || attributes === 'theirs' || attributes === 'base') return ok(trees[attributes]);
807 // validateAttributes ran first (mergeBranch, rebaseBranch, pickCommit): a ref name or an oid, parsed once here
808 const id = parseOid(attributes);
809 let oid: Oid;
810 if (id.ok) oid = id.value;
811 else {
812 const named = validateRef(attributes);
813 if (!named.ok) return named;
814 const listed = await lsRefs(t, [attributes]); if (!listed.ok) return listed;
815 const found = refOid(listed.value.refs, attributes);
816 if (found.tag === 'none') return fail('not_found', `attributes ref ${attributes} not found`, { miss: { kind: 'ref', ref: attributes, candidates: [attributes] } });
817 oid = found.value;
818 }
819 return map(await commitAt(t, oid), c => c.tree);
822// Fast-forward `ref` to `to`, expecting it to be at `from` (CAS). Empty pack: the server already has the objects.
823export async function fastForward(t: Transport, { ref, from, to }: { readonly ref: string; readonly from: string; readonly to: string }): Promise<Result<PushResult, PlyError>> {
824 return push(t, { ref, oldOid: from, newOid: to, objects: [] });
827// Delete `ref` on a transport the caller holds, expecting it at `oid` (CAS). By URL, with the tip read for you:
828// refops.ts deleteBranch.
829export async function deleteRef(t: Transport, { ref, oid }: { readonly ref: string; readonly oid: string }): Promise<Result<PushResult, PlyError>> {
830 return push(t, { ref, oldOid: oid, newOid: ZERO_OID, objects: [] });
833// What a merge-base verdict means for landing `theirs` on `ours`, before any tree is read: nothing to do, a
834// fast-forward, or a three-way merge over the one base. Criss-cross history is refused (git merges the bases into a
835// virtual one, recursively; a single base can give a clean result that differs from git's, so we refuse rather than
836// guess), as are unrelated histories and, when only a fast-forward is allowed, a merge commit.
837type Landing =
838 | { readonly kind: 'up_to_date'; readonly base: Oid }
839 | { readonly kind: 'fast_forward'; readonly base: Oid }
840 | { readonly kind: 'three_way'; readonly base: Oid };
841type LandingFlags = { readonly ref: string; readonly from: string; readonly fastForwardOnly: boolean; readonly noFastForward: boolean };
842function decideMerge(verdict: Verdict<Oid>, ours: Oid, theirs: Oid, { ref, from, fastForwardOnly, noFastForward }: LandingFlags): Result<Landing, PlyError> {
843 switch (verdict.tag) {
844 case 'criss-cross': return fail('merge_conflict', `${ref} and ${from} have ${verdict.bases.length} merge bases (criss-cross history); ply does not build git's virtual merge base`, { conflicts: [], reasons: noProtoReasons(), bases: verdict.bases } as ConflictDetail);
845 case 'unrelated': return fail('unrelated_histories', `${ref} and ${from} share no common ancestor within the search depth`);
846 case 'found': {
847 const { base } = verdict;
848 if (base === theirs) return ok({ kind: 'up_to_date', base });
849 if (base === ours && !noFastForward) return ok({ kind: 'fast_forward', base });
850 if (fastForwardOnly) return fail('not_fast_forward', `${ref} has moved past the merge base; a merge commit would be needed`);
851 return ok({ kind: 'three_way', base });
852 }
853 }
854 // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check
855 return assertNever(verdict);
858export type MergeSpecConfig = {
859 readonly ref: string;
860 readonly author: Author | null;
861 // null: the author (one identity, one time, as before)
862 readonly committer: Author | null;
863 readonly message: string | null;
864 readonly time: number;
865 readonly fastForwardOnly: boolean;
866 readonly noFastForward: boolean;
867};
868export type MergeSpec = Input<MergeSpecConfig> & { readonly from: string };
869const mergeSpecDefaults = (): MergeSpecConfig => ({ ref: 'refs/heads/main', author: null, committer: null, message: null, time: Math.floor(Date.now() / 1000), fastForwardOnly: false, noFastForward: false });
870// The operation options (auth, tracer, limits, …) pass through to operation(); these are the ones merge reads.
871export type MergeConfig = {
872 readonly cache: TreeCache;
873 readonly signer: Signer | null;
874 readonly verify: boolean;
875 readonly rediff: Rediff;
876 readonly attributes: AttributeSource;
877};
878export type MergeOptions = Input<MergeConfig> & Readonly<Record<string, unknown>>;
879const mergeDefaults = (): MergeConfig => ({ cache: new Map(), signer: null, verify: false, rediff: 'myers', attributes: null });
880type Sides = { readonly ref: string; readonly oid: string; readonly ours: string; readonly theirs: string };
881export type MergeOutcome =
882 | Sides & { readonly outcome: 'up_to_date' | 'fast_forward'; readonly base: string }
883 | Sides & { readonly outcome: 'merge'; readonly tree: string; readonly base: string; readonly pushBytes: number; readonly newTrees: number; readonly contentMerged: number };
885// The entry options as operation() takes them, with the operation's attributes. The tracer is the caller's, required at
886// run time (operation starts the root span on it), as for every entry (boundary.ts EntryOptions).
887export const operationOpts = (options: Readonly<Record<string, unknown>>, attrs: Readonly<Record<string, unknown>>): OperationOpts =>
888 ({ ...options, attrs });
890// an annotated tag's peeled commit, as ls-refs reports it
891const peeledOf = (refs: LsRefsResult['refs'], ref: string): Option<string> => {
892 const r = mapGet(refs, ref);
893 return r.tag === 'none' ? none : fromNullish(r.value.peeled);
894};
896// Effect: a landing that writes no merge commit: nothing to do, or the fast-forward push.
897type Quick = Exclude<Landing, { readonly kind: 'three_way' }>;
898async function landWithoutMerge(t: Transport, outcome: Outcome, land: Quick, { ref, ours, theirs }: { readonly ref: string; readonly ours: string; readonly theirs: string }): Promise<Result<MergeOutcome, PlyError>> {
899 switch (land.kind) {
900 case 'up_to_date': return outcome('up_to_date', { outcome: 'up_to_date', ref, oid: ours, ours, theirs, base: land.base });
901 case 'fast_forward': {
902 const r = await fastForward(t, { ref, from: ours, to: theirs });
903 if (!r.ok) return r;
904 return outcome('fast_forward', { outcome: 'fast_forward', ref, oid: theirs, ours, theirs, base: land.base }, { 'git.merge.push.bytes': r.value.packBytes });
905 }
906 }
907 // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check
908 return assertNever(land);
911// A stamp, or None when none was given.
912const stampOf = (p: Author | null, time: number): Result<Option<ValidatedIdent>, PlyError> => (p === null ? ok(none) : map(stamp(p, time), some));
914// The inputs are checked before any I/O; a refusal returns before the operation starts. The body's refusals keep the
915// names the decision inventory knows them by (mergeBranch#…), and the operation records an Err's code on the root span.
916/* oxlint-disable eslint/complexity -- one operation's steps in order: refs, merge base, landing, tree merge, commit, push */
917export async function mergeBranch(url: string, spec: MergeSpec, options: MergeOptions = {}): Promise<Result<MergeOutcome, PlyError>> {
918 const { ref, author, committer, message, time, fastForwardOnly, noFastForward } = withDefaults(spec, mergeSpecDefaults());
919 const { from } = spec;
920 const { cache, signer, verify, rediff, attributes: attributesGiven } = withDefaults(options, mergeDefaults());
921 const pushRef = validatePushRef(ref, false); if (!pushRef.ok) return pushRef;
922 const given = givenOid(from, 'from'); if (!given.ok) return given;
923 const fromOid = given.value;
924 const authorStamp = stampOf(author, time); if (!authorStamp.ok) return authorStamp;
925 const committerStamp = committer === null ? authorStamp : stampOf(committer, time); if (!committerStamp.ok) return committerStamp;
926 const person = authorStamp.value;
927 const committerPerson = committerStamp.value;
928 if (message !== null && message !== '') { const checked = validateMessage(message); if (!checked.ok) return checked; }
929 const attributesChecked = validateAttributes(attributesGiven); if (!attributesChecked.ok) return attributesChecked;
930 const attributes = attributesChecked.value;
931 return operation('merge', url, operationOpts(options, { 'git.merge.ref': ref, 'git.merge.from': from, 'git.merge.ff_only': fastForwardOnly, 'git.merge.no_ff': noFastForward }), async ({ t, root, outcome }: OpContext): Promise<Result<MergeOutcome, PlyError>> => {
932 const listed = await lsRefs(t, isNone(fromOid) ? [ref, from] : [ref]); if (!listed.ok) return listed;
933 const { refs } = listed.value;
934 const oursAt = refOid(refs, ref);
935 const theirsAt = isSome(fromOid) ? fromOid : refOid(refs, from);
936 if (oursAt.tag === 'none') return fail('not_found', `ref ${ref} not found`, { miss: refMiss(ref) });
937 if (theirsAt.tag === 'none') return fail('not_found', `ref ${from} not found`, { miss: refMiss(from) });
938 const ours = oursAt.value;
939 const theirs = theirsAt.value;
940 // ls-refs names an annotated tag's object, not a commit; `git merge <tag>` records the tag in a mergetag header, which
941 // ply does not write. Refused by name (it read as a missing commit, pack_corrupt, before #43's matrix ran it).
942 for (const r of [ref, from]) { const peeled = peeledOf(refs, r); if (peeled.tag === 'some') return fail('unsupported', `${r} is an annotated tag (git merge writes a mergetag header ply does not); merge its commit ${peeled.value}`, { what: r === ref ? 'ref' : 'from' }); }
943 if (fromOid.tag === 'some') { const c = await assertCommit(t, fromOid.value, 'from'); if (!c.ok) return c; }
944 root.set({ 'git.merge.ours': ours, 'git.merge.theirs': theirs });
945 const upToDate = (base: string): Ok<MergeOutcome> => outcome('up_to_date', { outcome: 'up_to_date', ref, oid: ours, ours, theirs, base });
946 if (ours === theirs) return upToDate(ours);
947 const found = await mergeBaseOf(t, ours, theirs);
948 if (!found.ok) return found;
949 const { base: one, bases, depth, verdict } = found.value;
950 root.set({ 'git.merge.base': one === null ? '' : one, 'git.merge.bases': bases.length, 'git.merge.base.depth': depth });
951 const landing = decideMerge(verdict, ours, theirs, { ref, from, fastForwardOnly, noFastForward });
952 if (!landing.ok) return landing;
953 const land = landing.value;
954 if (land.kind !== 'three_way') return landWithoutMerge(t, outcome, land, { ref, ours, theirs });
955 const { base } = land;
956 // three-way: commits for the three trees (the commit-only packs from mergeBase did not carry trees)
957 const [cB, cO, cT] = await Promise.all([commitBytesAt(t, base), commitBytesAt(t, ours), commitBytesAt(t, theirs)]);
958 const tree = (c: Result<{ readonly data: Uint8Array }, PlyError>): Result<Oid, PlyError> => andThen(c, b => map(parseCommit(b.data, t.limits), x => x.tree));
959 const tB = tree(cB); if (!tB.ok) return tB;
960 const tO = tree(cO); if (!tO.ok) return tO;
961 const tT = tree(cT); if (!tT.ok) return tT;
962 const trees: Trees = { base: tB.value, ours: tO.value, theirs: tT.value };
963 const merger = blobMerger(t, t.limits.maxMergeBlobBytes, rediff);
964 if (!merger.ok) return merger;
965 const mergeBlob = merger.value;
966 const attrTree = await attributeTree(t, attributes, trees);
967 if (!attrTree.ok) return attrTree;
968 root.set({ 'git.merge.attributes': attributes === null ? '' : attributes });
969 const treesMerged = await mergeTreesOf(t, cache, { ...trees, prefix: '', removed: null, mergeBlob, driverFor: attrTree.value === null ? null : attributeDrivers(t, cache, attrTree.value) });
970 if (!treesMerged.ok) return treesMerged;
971 const merged = treesMerged.value;
972 const newTrees = merged.objects.filter(o => o.type === TYPE.TREE).length;
973 root.set({ 'git.merge.content.merged': merged.contentMerged, 'git.merge.content.undecided': mergeBlob.stats.undecided, 'git.merge.content.unioned': mergeBlob.stats.unioned, 'git.merge.content.attr_binary': mergeBlob.stats.attrBinary, 'git.merge.trees.fetched': merged.fetched, 'git.merge.trees.new': newTrees, 'git.merge.conflicts': merged.conflicts.slice(0, 64), 'git.merge.conflicts.count': merged.conflicts.length });
974 if (merged.conflicts.length > 0) return fail('merge_conflict', `conflicts: ${merged.conflicts.slice(0, 8).map(p => `${p} (${merged.reasons[p]})`).join(', ')}${merged.conflicts.length > 8 ? '…' : ''}`, { conflicts: merged.conflicts, reasons: merged.reasons } as ConflictDetail);
975 const emptyTree = encodeEntries([]); if (!emptyTree.ok) return emptyTree;
976 const treeOid: Oid = merged.oid === null ? hashObject('tree', emptyTree.value) : merged.oid;
977 if (person.tag === 'none' || committerPerson.tag === 'none') return fail('bad_request', 'author is required for a merge commit');
978 const authorLine = ident(person.value); if (!authorLine.ok) return authorLine;
979 const committerLine = ident(committerPerson.value); if (!committerLine.ok) return committerLine;
980 const encoded = encodeCommitOf({ tree: treeOid, parents: [ours, theirs], author: authorLine.value, committer: committerLine.value, message: (message === null ? `Merge ${short(from)} into ${short(ref)}` : message).replace(/\n?$/u, '\n') });
981 if (!encoded.ok) return encoded;
982 let commitData = encoded.value;
983 if (signer) { const signed = await signCommit(commitData, signer); if (!signed.ok) return signed; commitData = signed.value; }
984 const oid: string = hashObject('commit', commitData);
985 const objects = uniqueObjects([{ type: TYPE.COMMIT, data: commitData, oid }, ...(merged.oid === null ? [{ type: TYPE.TREE, data: emptyTree.value, oid: treeOid }] : []), ...merged.objects]).map(o => ({ type: o.type, data: o.data }));
986 const pushed = await push(t, { ref, oldOid: ours, newOid: oid, objects });
987 if (!pushed.ok) return pushed;
988 const r = pushed.value;
989 if (verify) { const seen = await verifyRef(t, root, 'git.merge', ref, oid); if (!seen.ok) return seen; }
990 return outcome('merge', { outcome: 'merge', ref, oid, tree: treeOid, ours, theirs, base, pushBytes: r.packBytes, newTrees, contentMerged: merged.contentMerged }, { 'git.merge.commit': oid, 'git.merge.tree': treeOid, 'git.merge.push.bytes': r.packBytes });
991 });
993/* oxlint-enable eslint/complexity */
Diagnostics4 git calls · 244 ms
CallStatusSizeTime0244 ms
discover200152 B3 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=152
git.server.agent=gitty/1.0
git.server.object_format=sha1
git.server.caps=agent ls-refs fetch object-format
git.server.fetch=shallow filter sideband-all
git.protocol.version=2
git.pkt.frames=8
git.pkt.data=6
git.pkt.flush=2
git.pkt.delim=0
git.pkt.bytes=152
git.pkt.payload.max=34
ls-refs200145 B · hit3 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=145
git.response.cache=HIT
git.response.duration_ms=3
git.protocol.version=2
git.pkt.frames=3
git.pkt.data=2
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=145
git.pkt.payload.max=76
git.ls_refs.count=2
git.ls_refs.head=refs/heads/main
fetchblob:none · deepen 1020038 KiB · hit7 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=234
git.response.bytes=38434
git.response.cache=HIT
git.response.duration_ms=7
git.fetch.filter=blob:none
git.fetch.filter.requested=tree:0
git.fetch.filter.fallback=blob:none
git.fetch.filter.learned=false
git.fetch.wants=19912563f540228593df0c489082e5e2508e21e4
git.fetch.haves.count=0
git.fetch.deepen=10
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=6
git.pkt.data=4
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=38434
git.pkt.payload.max=38339
git.sideband.band1.bytes=38338
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=63
git.pack.bytes=38338
git.pack.ofs_delta=0
git.pack.ref_delta=8
git.pack.chain.max=8
git.pack.trailer=0bc36ab7adf82d3109177f11f1ea93f1ce071f77
git.pack.full=55
Open pack map
fetch20020 KiB234 ms
git.upload-pack fetch
http.response.status_code=200
git.response.bytes=20944
git.response.cache=MISS
git.response.duration_ms=234
git.fetch.wants=0b7fe66578b2483704ab8120e2d5acd1c5915216
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=3
git.pkt.data=2
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=20944
git.pkt.payload.max=20923
git.sideband.band1.bytes=20922
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0

Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.

Remote
https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/ply.git
Ref
refs/heads/main
Commit
19912563f540228593df0c489082e5e2508e21e4
cf-ray
a5e3008ebd79f3c9
Request
5f6eb6ec…
Protocol
v2 · sha1
Agent
gitty/1.0
Filter
advertised
Fetch
shallow filter sideband-all
Capabilities
agent ls-refs fetch object-format