Files
mesh-catalog/modules/gitea/mergecall.ts
T
jschoubben 3ba309c5e4 FORGE-4: a member the forge refuses after judging raises merge-partial
The call stops merging, says merge-called with what landed and refused,
and raises merge-partial (scope delivery, id the call, urgent, resolver
operator) in the module's findings; a later call landing every refused
member clears it, and forge_partial_clear clears one by hand after the
hand-act log took it.

Builds: design 47 H §767; H-A-1, H-A-18, H-A-81

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

190 lines
10 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 { Call, 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";
import { keptMember, sayCall, type Calls, type Say } from "./calls.js";
import type { Partials } from "./partials.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 state calls (calls.ts): the call is written before its first merge and as each member merges (§766). */
calls?: Calls;
now?: () => Date;
/** Says a seat event on its subject under an id the bus keeps once (mesh-sdk runtime.seatPublish): merge-called (§736). */
say?: Say;
/** The findings merge-partial (partials.ts; §767). */
partials?: Partials;
}
/** 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;
}
}
const now = deps.now ?? (() => new Date());
// The call as kept (§766), its `at` the time of its write, then of its last merge (the event's `at`, §736).
let at = now().toISOString();
const value = (said: boolean): Call => ({ by, account, at, members: members.map(keptMember), said });
const keep = async (said: boolean) => { await deps.calls?.put(call, value(said), now()); };
// A call refused at judging merged nothing and has nothing to say.
if (refused) {
await keep(true);
return { call, members: members.map(outcomeOf) };
}
// Written before the first merge, and again as each member merges.
await keep(false);
// 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";
at = now().toISOString();
await keep(false);
} 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`;
}
await keep(false);
// Raised for the refused members, the landed ones delivered as any call's (§767).
await deps.partials?.raise({ ...value(false), call });
break;
}
}
// Once its members are merged or refused, the call says merge-called, then is kept said (§736, §766).
if (deps.say) {
try {
await sayCall({ ...value(false), call }, deps.say);
await keep(true);
} catch (err) {
console.error(`[gitea] the merge call ${call} landed and its merge-called is not said yet; it is said at the next start — ${err instanceof Error ? err.message : err}`);
}
}
// A call that landed members clears every merge-partial whose refused members are now all landed (§767).
if (members.some((m) => m.state === "merged")) {
await deps.partials?.landed().catch((err) => console.error(`[gitea] the merge-partial findings could not be judged after the call ${call} — ${err instanceof Error ? err.message : err}`));
}
return { call, members: members.map(outcomeOf) };
}