Files
mesh-catalog/modules/gitea/mergecall.ts
T
jschoubben 40dc5fe11d FORGE-1: merge-pull is one merge call, every member judged before any is merged
merge-pull takes pulls and by, refuses a call with no proved caller,
judges each member (its head, its base a watched branch, not merged
already, no required step failed at its fingerprint) and no branch
protection, merges none when one is refused, else merges in the order
named and answers the call and each member's outcome once. The seat's
branch answers no protection. The seen-expiry test no longer depends on
today's date.

Builds: design 47 H §734, §735, §764 (the single-pull form; merge-pull's protection judgement); ADR 0682 §13; H-A-21, H-A-22, H-A-24, H-A-47

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 03:42:00 +01:00

152 lines
7.9 KiB
TypeScript

// **One merge call is a delivery's start and its group** (novox/hq design 47 H §734, §735; ADR 0682 §1, §2, §13; H-A-21,
// H-A-22, H-A-47): the seat git's `merge-pull` takes `pulls`, one or more members `{repository, number, head}`, and `by`,
// the caller as who@node, recorded beside the bus account the tool runner proved for the call. Every member is judged
// before any is merged: still the pull request's head, its base a watched branch, not merged already (refused
// `already-merged` with its commit), and no run at the head's build-input fingerprint failed a `required` step (the
// module's own `failed-steps`). No branch protection is judged (ADR 0682 §13). When one member is refused, none is merged
// and the answer names every refused member and why; else the members are merged in the order the call names them. The
// verb answers once, at the call's end: `call` and each member's outcome.
import { randomBytes } from "node:crypto";
import { UNPROVEN, callerOf } from "@novox/mesh-sdk/callers";
import type { MemberOutcome, MergePullAnswer } from "@novox/mesh-delivery-contracts-git";
import type { GiteaClient } from "./client.js";
import { Refused, checkName } from "./guard.js";
import type { Judged } from "./failedsteps.js";
/** What a merge call reaches beside the forge's API. */
export interface CallDeps {
/** Whether the first registrations were written: until then no merge is made (design 47 §95). */
registered: () => boolean;
/** The watched branches the registrations name, by their origin repository `<owner>/<name>`. */
watched: () => ReadonlyMap<string, ReadonlySet<string>>;
/** The failed `required` step that refuses a head, or null (failedsteps.ts). */
judge: (head: string) => Promise<Judged | null>;
/** A new call's id: 16 lowercase hex characters (H-A-24). */
newCall?: () => string;
}
/** The forge's API a merge call uses. */
export type CallForge = Pick<GiteaClient, "getPullRequest" | "mergePullRequest" | "commitParents">;
/** One member as the call names it, and as it was judged. */
export interface Member {
repository: string;
owner: string;
repo: string;
number: number;
head: string;
/** The pull request's base, read at judging. */
branch: string;
state: MemberOutcome["state"];
commit?: string;
why?: string;
}
const SHA = /^[0-9a-f]{40}$/;
export const CALL = /^[0-9a-f]{16}$/;
/** A new call's id. */
export const newCallId = (): string => randomBytes(8).toString("hex");
/** The members a call names, each checked, or the reason the call is refused whole. */
export function membersOf(raw: unknown): Member[] {
if (!Array.isArray(raw) || raw.length === 0) throw new Refused("pulls names one or more members {repository, number, head}");
const seen = new Set<string>();
return raw.map((p: any) => {
const parts = String(p?.repository ?? "").split("/");
if (parts.length !== 2) throw new Refused(`repository ${JSON.stringify(p?.repository)} is not <owner>/<name>`);
const owner = checkName("owner", parts[0]), repo = checkName("name", parts[1]);
const number = Number(p?.number);
if (!Number.isInteger(number) || number < 1) throw new Refused(`${JSON.stringify(p?.number)} is not a pull request's number`);
const head = String(p?.head ?? "").trim();
if (!SHA.test(head)) throw new Refused("head is a commit's full 40-hex sha");
const repository = `${owner}/${repo}`;
if (seen.has(`${repository}#${number}`)) throw new Refused(`${repository}#${number} is named twice`);
seen.add(`${repository}#${number}`);
return { repository, owner, repo, number, head, branch: "", state: "judged" as const };
});
}
/** Why a member is refused at judging, or "" when it is judged. */
async function judgeMember(forge: CallForge, deps: CallDeps, m: Member): Promise<string> {
const pull = await forge.getPullRequest(m.owner, m.repo, m.number);
m.branch = String(pull.base ?? "");
if (pull.merged) {
if (pull.merge_commit_sha) m.commit = pull.merge_commit_sha;
return `already-merged: ${m.repository}#${m.number} was merged${pull.merge_commit_sha ? ` as ${pull.merge_commit_sha}` : ""}`;
}
if (pull.state !== "open") return `${m.repository}#${m.number} is closed`;
if (pull.head_sha !== m.head) {
return `head-moved: its head is ${String(pull.head_sha).slice(0, 12)}, not the ${m.head.slice(0, 12)} the caller names`;
}
if (!deps.watched().get(m.repository)?.has(m.branch)) return `its base ${m.branch} is no watched branch`;
const failed = await deps.judge(m.head);
if (failed) {
return `the ${failed.step} step of ${failed.module} failed in run ${failed.run} at its build-input fingerprint ${failed.fingerprint}`;
}
return "";
}
/** One member merged at its head, its merge commit read back; throws when the forge refused or did not name it. */
async function mergeMember(forge: CallForge, m: Member): Promise<string> {
await forge.mergePullRequest(m.owner, m.repo, m.number, "merge", true, m.head);
const merged = await forge.getPullRequest(m.owner, m.repo, m.number);
if (!merged.merge_commit_sha) throw new Error(`${m.repository}#${m.number} WAS merged, but the forge named no merge commit`);
// The merge is done once the forge named its commit: a read-back of its parents that fails is said, never a failed act.
try {
const parents = await forge.commitParents(m.owner, m.repo, merged.merge_commit_sha);
if (parents.length === 2 && parents[1] !== m.head) {
console.error(`[gitea] ${m.repository}#${m.number} WAS merged (${merged.merge_commit_sha}), but the forge merged ` +
`${parents[1].slice(0, 12)}, not the ${m.head.slice(0, 12)} the caller names (novox/hq issue 381)`);
}
} catch (err) {
console.error(`[gitea] ${m.repository}#${m.number} was merged (${merged.merge_commit_sha}); which head it joined could not be read back — ${err instanceof Error ? err.message : err}`);
}
return merged.merge_commit_sha;
}
/** A member's outcome as the answer says it. */
export const outcomeOf = (m: Member): MemberOutcome => ({ repository: m.repository, number: m.number, state: m.state,
...(m.commit ? { commit: m.commit } : {}), ...(m.why ? { why: m.why } : {}) });
/** merge-pull: one merge call (design 47 H §734, §735). */
export async function mergeCall(forge: CallForge, args: Record<string, unknown>, deps: CallDeps): Promise<MergePullAnswer> {
const by = String(args.by ?? "").trim();
if (!/^[^\s@]+@[^\s@]+$/.test(by)) throw new Refused("by is the caller as who@node");
const account = callerOf(args);
if (account === UNPROVEN) throw new Refused("the tool runner proved no caller account for this call, so nothing is merged");
const members = membersOf(args.pulls);
// Until the first registrations are written no merge is made (design 47 §95).
if (!deps.registered()) throw new Refused("no module is registered yet: the catalog has said no registration-changed, so no merge is made until the first registrations are written");
const call = (deps.newCall ?? newCallId)();
if (!CALL.test(call)) throw new Error(`the call's id ${JSON.stringify(call)} is not 16 lowercase hex characters`);
// Every member is judged before any is merged (§735).
let refused = false;
for (const m of members) {
const why = await judgeMember(forge, deps, m);
if (why) {
m.state = "refused";
m.why = why;
refused = true;
}
}
if (refused) return { call, members: members.map(outcomeOf) };
// Then merged in the order the call names them; a member the forge refuses stops the call (§767).
for (const m of members) {
try {
m.commit = await mergeMember(forge, m);
m.state = "merged";
} catch (err) {
m.state = "refused";
m.why = `the forge refused the merge: ${err instanceof Error ? err.message : String(err)}`;
for (const rest of members.slice(members.indexOf(m) + 1)) {
rest.state = "refused";
rest.why = `not merged: ${m.repository}#${m.number} before it was refused by the forge`;
}
break;
}
}
return { call, members: members.map(outcomeOf) };
}