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
This commit is contained in:
2026-11-20 03:42:00 +01:00
parent 82d5688477
commit 40dc5fe11d
6 changed files with 279 additions and 122 deletions
+2 -1
View File
@@ -410,7 +410,8 @@ void failedSteps.expireSeen().catch((err) => console.log(`[gitea] the seen keys
// announcement's pending and a trunk's move, so a recheck's pending never lands over a later verdict (issue 456).
registerModuleTools("gitea", () => [eventsTool(pace), ...readAllTools(readAll), ...writeTools(writes), ...statusTools("gitea", "gitea_first_views", "gitea_first_view_again", followers, firstViews,
async (act) => { await broker().request("seat:mesh-hand-acts.hand-act", act); }),
...(gitea ? seatTools(gitea, { run, container: FORGE_CONTAINER, statuses: gates, registered: () => registrations.written, judge: (head) => failedSteps.judge(head) }) : []),
...(gitea ? seatTools(gitea, { run, container: FORGE_CONTAINER, statuses: gates, registered: () => registrations.written, judge: (head) => failedSteps.judge(head),
watched: () => registrations.watched }) : []),
...failedStepsTools(failedSteps, async (act) => { await broker().request("seat:mesh-hand-acts.hand-act", act); })]);
/** What the forge's event asks of the announcer at once (issue 729, 1422): see watch.ts. */
+151
View File
@@ -0,0 +1,151 @@
// **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) };
}
+10 -69
View File
@@ -9,9 +9,9 @@
// 4xx, or a refusal of this holder) the kind `refused`, a forge that failed or did not answer the kind `failed`; an empty list or an absent file is answered
// only when the forge said so.
//
// **The acts carry the caller's id** (status, comment, view, note, merge-pull): an id the pull request or the note already
// holds is answered `held` and nothing is done again; `merge-pull` merges the head the caller names, only into a base
// whose protection refuses a push, and refuses a head at whose fingerprint a run failed a `required` step (design 47 §39, §314).
// **The acts carry the caller's id** (status, comment, view, note): an id the pull request or the note already holds is
// answered `held` and nothing is done again. `merge-pull` is one merge call of one or more pull requests, every member
// judged before any is merged, no branch protection judged (mergecall.ts; design 47 H §734, §735; ADR 0682 §13).
import type { ToolDefinition } from "@novox/mesh-sdk/tools";
import {
@@ -26,6 +26,7 @@ import { containedFrom, newestByContext } from "./checks.js";
import { Refused, checkName } from "./guard.js";
import { appendNote, viewBody, viewComment, type Runner } from "./delivery.js";
import type { Judged } from "./failedsteps.js";
import { mergeCall } from "./mergecall.js";
/** The verbs of the seat, in its definition's order. */
export const VERBS: readonly string[] = Object.values(GIT_VERBS);
@@ -53,6 +54,8 @@ export interface SeatDeps {
registered: () => boolean;
/** The failed `required` step that refuses a head, judged from the module's own state `failed-steps` (failedsteps.ts), or null. */
judge: (head: string) => Promise<Judged | null>;
/** The watched branches the registrations name, by their origin repository (registrations.ts): a member's base is one. */
watched: () => ReadonlyMap<string, ReadonlySet<string>>;
}
/** A failure as the contract says it: the forge's or this holder's refusal, or a forge that failed. */
@@ -149,7 +152,7 @@ export function seatTools(gitea: GiteaClient, deps: SeatDeps): ToolDefinition[]
const pull = pullOf(full, p);
return pull.state === "open" ? { pull, merging: await mergingOf(gitea, owner, repo, p) } : { pull };
}),
verb(GIT_VERBS.branch, "The seat git's branch: a branch's head, and whether a protection rule refuses a direct push and admits only merges.",
verb(GIT_VERBS.branch, "The seat git's branch: a branch's head.",
async (args): Promise<BranchAnswer> => {
const { owner, repo, full } = repositoryOf(args.repository);
// No branch named is the repository's default branch, read from the forge, as the verb file reads it (A-399).
@@ -158,7 +161,7 @@ export function seatTools(gitea: GiteaClient, deps: SeatDeps): ToolDefinition[]
if (branch === "") throw new Error(`the forge names no default branch of ${full}`);
// The head first: a branch the forge does not hold is its 404, the kind not-found, never an unprotected branch.
const head = await gitea.branchHead(owner, repo, branch);
return { repository: full, branch, head, protected: pushRefused(await gitea.appliedProtection(owner, repo, branch)) };
return { repository: full, branch, head };
}),
verb(GIT_VERBS.openPulls, "The seat git's open-pulls: every open pull request of every repository, with the statuses its base requires and those its head has.",
async (): Promise<OpenPullsAnswer> => {
@@ -258,8 +261,8 @@ export function seatTools(gitea: GiteaClient, deps: SeatDeps): ToolDefinition[]
const said = await appendNote(deps.run, deps.container, owner, repo, commit, "mesh-plan", `${String(args.line ?? "")} [${id}]`, id);
return said.added ? { id, performed: true } : { id, held: true, performed: true };
}),
verb(GIT_VERBS.mergePull, "The seat git's merge-pull: an act of the forge bridge, a pull request merged at the head the caller names; it refuses a head at whose fingerprint a required step failed.",
async (args): Promise<MergePullAnswer> => mergePull(gitea, args, deps.registered, deps.judge)),
verb(GIT_VERBS.mergePull, "The seat git's merge-pull: one merge call, a delivery's start and its group: the pull requests named (pulls, each {repository, number, head}) and by (who@node); every member is judged before any is merged (still its head, its base a watched branch, no required step failed at its fingerprint), none merged when one is refused, then each merged in the order named; it answers the call and each member's outcome.",
async (args): Promise<MergePullAnswer> => mergeCall(gitea, args, deps)),
verb(GIT_VERBS.tag, "The seat git's tag: the git tag go/vMAJOR.MINOR.PATCH of a released version, written at the commit its build was made from; a tag that is at that commit is performed.",
async (args): Promise<TagAnswer> => {
const { owner, repo } = repositoryOf(args.repository);
@@ -275,68 +278,6 @@ export function seatTools(gitea: GiteaClient, deps: SeatDeps): ToolDefinition[]
];
}
/** Whether a protection rule refuses a direct push and admits only merges: the rule exists and takes no push. */
export function pushRefused(rule: { enable_push?: boolean } | null): boolean {
return !!rule && rule.enable_push === false;
}
function holds(comments: GiteaComment[], id: string): boolean {
return comments.some((c) => String(c.body ?? "").includes(actMarker(id)));
}
/** merge-pull (design 47 §314): only the head the caller names, only into a base that takes no push, no check judged. */
export async function mergePull(gitea: GiteaClient, args: Record<string, unknown>, registered: () => boolean,
judge: (head: string) => Promise<Judged | null>): Promise<MergePullAnswer> {
const id = idOf(args.id);
const { owner, repo, full } = repositoryOf(args.repository);
const number = numberOf(args.number);
const head = commitOf("head", args.head);
const no = (why: string, kind: NonNullable<MergePullAnswer["refused-kind"]>): MergePullAnswer =>
({ id, refused: `${full}#${number} is not merged: ${why}`, "refused-kind": kind });
// Until the first registrations are written no merge is made: the old assigner would write a want from the trunk with no
// pipeline (design 47 §95). It names what is missing.
if (!registered()) return no("no module is registered yet: the catalog has said no registration-changed, so no merge is made until the first registrations are written", "no-registrations");
const pull = await gitea.getPullRequest(owner, repo, number);
if (pull.merged) {
// Already merged at that head: performed (the act said again after its answer was lost); at another, refused.
return pull.head_sha === head ? { id, performed: true, held: true, ...(pull.merge_commit_sha ? { "merge-commit": pull.merge_commit_sha } : {}) }
: no(`it was merged at ${String(pull.head_sha).slice(0, 12)}, not the ${head.slice(0, 12)} the caller names`, "head-moved");
}
if (pull.state !== "open") return no("it is closed", "git-refused");
if (pull.head_sha !== head) {
return no(`its head is ${String(pull.head_sha).slice(0, 12)}, not the ${head.slice(0, 12)} the caller names`, "head-moved");
}
const rule = await gitea.appliedProtection(owner, repo, String(pull.base ?? ""));
if (!pushRefused(rule)) {
return no(`its base ${pull.base} is guarded by no protection rule that refuses a push`, "unprotected");
}
// The head's runs, judged from the module's own state (design 47 §39): a step that failed at its fingerprint in any run refuses it,
// naming the run, the module and the step; a head no run named merges, and the runner being down changes nothing.
const failed = await judge(head);
if (failed) {
return { id, refused: `${full}#${number} is not merged: the ${failed.step} step of ${failed.module} failed in run ${failed.run} at its build-input fingerprint ${failed.fingerprint}`,
"refused-kind": "policy-failed", run: failed.run, module: failed.module, step: failed.step };
}
try {
await gitea.mergePullRequest(owner, repo, number, "merge", true, head);
} catch (err) {
const f = failure(err);
if (f["error-kind"] === "refused") return no(`the forge refused the merge: ${f.error}`, "git-refused");
throw err;
}
const merged = await gitea.getPullRequest(owner, repo, number);
if (!merged.merge_commit_sha) throw new Error(`${full}#${number} WAS merged, but the forge named no merge commit`);
// The merge is done once the forge named its commit: a read-back that fails is said, never answered as a failed act.
let parents: string[];
try {
parents = await gitea.commitParents(owner, repo, merged.merge_commit_sha);
} catch (err) {
console.error(`[gitea] ${full}#${number} was merged (${merged.merge_commit_sha}); which head it joined could not be read back — ${err instanceof Error ? err.message : err}`);
return { id, performed: true, "merge-commit": merged.merge_commit_sha };
}
if (parents.length === 2 && parents[1] !== head) {
throw new Error(`${full}#${number} WAS merged (${merged.merge_commit_sha}), but the forge merged ${parents[1].slice(0, 12)}, ` +
`not the ${head.slice(0, 12)} the caller names (novox/hq issue 381)`);
}
return { id, performed: true, "merge-commit": merged.merge_commit_sha };
}
+2 -1
View File
@@ -109,7 +109,8 @@ test("a seen key past 30 days is deleted at the next step-ended, a younger one k
const now = new Date("2026-11-11T12:00:00Z");
const old = (n: number) => new Date(Date.parse("2026-10-01T00:00:00Z") - n * 60000).toISOString();
await st.put(seenKey(C1, "old"), { v: 1, commit: C1, module: "old", fingerprints: ["x"], at: old(0) });
await st.put(seenKey(C2, "young"), { v: 1, commit: C2, module: "young", fingerprints: ["x"], at: "2026-10-20T00:00:00Z" });
// Younger than 30 days both before the step-ended and before the tool's own clock, today's: kept by both.
await st.put(seenKey(C2, "young"), { v: 1, commit: C2, module: "young", fingerprints: ["x"], at: new Date(Date.now() - 86_400_000).toISOString() });
await f.stepEnded(ended(C3, "passed"));
assert.equal(kv.has(seenKey(C1, "old")), false, "past 30 days: deleted at the next step-ended");
assert.equal(kv.has(seenKey(C2, "young")), true, "younger: kept");
+8 -51
View File
@@ -431,15 +431,12 @@ test("the two new tools are named for what mesh_search is asked, and gitea_api s
assert.ok("refused" in judgeApiCall("PATCH", "/repos/a/b/pulls/7", { base: "x" }));
});
// **merge-pull judges the head it is asked at and no check** (design 47 *The seat git*, §314): merge-pull merges the
// head it is named into a base that takes no push, whatever its statuses say, and an id said again after the merge is
// answered performed.
test("merge-pull merges the head the caller names, and refuses one at whose fingerprint a required step failed", async () => {
// The seat git's pull and status (design 47 *The seat git*): an open pull request answers what the forge would merge now,
// and two writes of one head's status land in order. merge-pull is the merge call's (merge-call.test.ts).
test("the seat's pull answers what the forge would merge now, and a head's statuses land in order", async () => {
const { seatTools } = await import("../dist/seat.js");
const { runAs } = await import("@novox/mesh-sdk/callers");
const bridge = "ace.mesh-delivery-forge-bridge";
let registered = true;
let failedStep: { run: string; module: string; step: string; fingerprint: string } | null = null;
// The head's one writer of its statuses (gate.ts), over a forge whose first write is still in flight when the next is asked.
const { GateWriter } = await import("../dist/gate.js");
const landed: string[] = [];
@@ -453,48 +450,10 @@ test("merge-pull merges the head the caller names, and refuses one at whose fing
};
const gates = new GateWriter(slow);
const seat = seatTools(Object.assign(Object.create(client), { setCommitStatus: slow.setCommitStatus }),
{ run: async () => ({ stdout: "", code: 0 }), container: "gitea", statuses: gates, registered: () => registered, judge: async () => failedStep });
{ run: async () => ({ stdout: "", code: 0 }), container: "gitea", statuses: gates, registered: () => true, judge: async () => null,
watched: () => new Map() });
const call = (verb: string, args: Record<string, unknown>, caller = bridge) =>
runAs({ "mesh/caller": caller }, args, () => seat.find((t: any) => t.name === `git.${verb}`)!.run(args)) as Promise<any>;
const merge = (extra: Record<string, unknown> = {}, caller?: string) =>
call("merge-pull", { id: "act-1", repository: "novox/mesh-catalog", number: 7, head: REVIEWED, ...extra }, caller);
const rows: { name: string; set: () => void; caller?: string; extra?: Record<string, unknown>; want: RegExp | "merged" | "held"; loud?: boolean; kind?: string }[] = [
{ name: "no registration written yet", set: () => { registered = false; }, want: /no module is registered yet/, kind: "no-registrations" },
{ name: "a head that moved", set: () => { state.head = MOVED; }, want: /its head is 3c4d5e6f7a8b, not the abc1234def56/, kind: "head-moved" },
{ name: "a base no rule guards", set: () => { state.rules = []; }, want: /guarded by no protection rule/, kind: "unprotected" },
{ name: "a base whose protection was removed after the last branch-moved", set: () => { state.rules = [protectedMain()]; state.rules = []; }, want: /guarded by no protection rule/, kind: "unprotected" },
{ name: "a base that takes a push", set: () => { state.rules = [{ rule_name: "main", enable_push: true }]; }, want: /guarded by no protection rule/, kind: "unprotected" },
{ name: "a required step failed at the head's fingerprint", set: () => { failedStep = { run: "main.7.nats", module: "nats", step: "unit", fingerprint: "fp-1" }; },
want: /the unit step of nats failed in run main\.7\.nats/, kind: "policy-failed" },
{ name: "a failed check", set: () => { state.statuses = [{ context: "mesh/check", state: "failure", description: "fail" }]; }, want: "merged" },
{ name: "no status at all", set: () => { state.statuses = []; }, want: "merged" },
{ name: "a check of another trunk", set: () => { state.statuses = judgedAt(MOVED); }, want: "merged" },
{ name: "the id said again after the merge", set: () => { state.merged = true; }, want: "held" },
{ name: "a pull request merged at another head", set: () => { state.merged = true; state.head = MOVED; }, want: /merged at 3c4d5e6f7a8b, not the abc1234def56/ },
{ name: "a closed pull request", set: () => { state.prState = "closed"; }, want: /it is closed/, kind: "git-refused" },
{ name: "a fast-forward", set: () => { state.parents = [REVIEWED]; }, want: "merged" },
{ name: "the merge read back fails", set: () => { state.commitsFail = 502; }, want: "merged" },
{ name: "the forge merged another head", set: () => { state.landed = MOVED; }, want: /WAS merged .*the forge merged 3c4d5e6f7a8b, not the abc1234def56/, loud: true },
];
for (const r of rows) {
registered = true; failedStep = null; state.merged = false; state.head = REVIEWED; state.statuses = judgedAt(TRUNK); state.sent = [];
state.rules = [protectedMain()]; state.prState = "open"; state.parents = null; state.commitsFail = 0; state.landed = "";
r.set();
const got = await merge(r.extra, r.caller);
if (r.want === "merged") {
assert.equal(got.performed, true, `${r.name}: ${JSON.stringify(got)}`);
assert.equal(got["merge-commit"], state.mergeCommit, r.name);
assert.equal(state.sent.find((s) => s.path.endsWith("/pulls/7/merge"))?.body.head_commit_id, REVIEWED, r.name);
} else if (r.want === "held") {
assert.deepEqual([got.performed, got.held], [true, true], r.name);
assert.deepEqual(writes(), [], `${r.name}: nothing merged again`);
} else {
assert.match(String(got.refused ?? got.error), r.want, r.name);
if (r.kind) assert.equal(got["refused-kind"], r.kind, r.name);
if (r.kind === "policy-failed") assert.deepEqual([got.run, got.module, got.step], ["main.7.nats", "nats", "unit"], r.name);
assert.deepEqual(writes(), r.loud ? ["POST /repos/novox/mesh-catalog/pulls/7/merge"] : [], `${r.name}: what was merged`);
}
}
// A read: an open pull request answers what the forge would merge now; a forge that fails is the kind failed.
state.merged = false; state.head = REVIEWED; state.rules = [protectedMain()];
const pull = await call("pull", { repository: "novox/mesh-catalog", number: 7 });
@@ -552,10 +511,10 @@ test("every read and act of the seat git answers its contract, and an error is a
};
const run = async (_f: string, args: string[]) => args.includes("show") || args.includes("--ref") && !args.includes("append")
? { stdout: noteShown, code: noteShown ? 0 : 1 } : (noteWritten++, { stdout: "", code: 0 });
const seat = seatTools(forge as any, { run: run as any, container: "gitea", statuses: { status: async () => {} }, registered: () => true, judge: async () => null });
const seat = seatTools(forge as any, { run: run as any, container: "gitea", statuses: { status: async () => {} }, registered: () => true, judge: async () => null, watched: () => new Map() });
const call = (verb: string, args: Record<string, unknown>, over: Record<string, unknown> = {}) => {
const t = seat.find((x: any) => x.name === `git.${verb}`)!;
const wrapped = seatTools(Object.assign(Object.create(forge), over) as any, { run: run as any, container: "gitea", statuses: { status: async () => {} }, registered: () => true, judge: async () => null });
const wrapped = seatTools(Object.assign(Object.create(forge), over) as any, { run: run as any, container: "gitea", statuses: { status: async () => {} }, registered: () => true, judge: async () => null, watched: () => new Map() });
return runAs({ "mesh/caller": "ace.x" }, args, () => wrapped.find((x: any) => x.name === t.name)!.run(args)) as Promise<any>;
};
const rows: [string, string, Record<string, unknown>, Record<string, unknown>, (a: any) => unknown, unknown][] = [
@@ -563,9 +522,7 @@ test("every read and act of the seat git answers its contract, and an error is a
["pull", "by merge commit", { repository: "novox/app", "merge-commit": OTHER }, {}, (a) => [a.pull.state, a.pull["merge-commit"], a.merging], ["merged", OTHER, undefined]],
["pull", "unknown", { repository: "novox/app", number: 404 }, {}, (a) => [a.pull, a["error-kind"]], [undefined, "not-found"]],
["pull", "forge down", { repository: "novox/app", number: 9 }, { getPullRequest: down }, (a) => [a.pull, a["error-kind"]], [undefined, "failed"]],
["branch", "a branch a rule guards", { repository: "novox/app", branch: "main" }, { branchHead: async () => SHA, appliedProtection: async () => ({ rule_name: "main", enable_push: false }) }, (a) => [a.head, a.protected], [SHA, true]],
["branch", "a branch no rule guards", { repository: "novox/app", branch: "scratch" }, { branchHead: async () => SHA, appliedProtection: async () => null }, (a) => [a.head, a.protected], [SHA, false]],
["branch", "a rule that takes a push", { repository: "novox/app", branch: "main" }, { branchHead: async () => SHA, appliedProtection: async () => ({ rule_name: "main", enable_push: true }) }, (a) => [a.protected], [false]],
["branch", "a branch's head, no protection read (ADR 0682 §13)", { repository: "novox/app", branch: "main" }, { branchHead: async () => SHA, appliedProtection: async () => { throw new Error("read"); } }, (a) => [a.head, a.protected, a.error], [SHA, undefined, undefined]],
["branch", "no such branch", { repository: "novox/app", branch: "nope" }, { branchHead: gone }, (a) => [a.head, a["error-kind"]], [undefined, "not-found"]],
["open-pulls", "one", {}, {}, (a) => [a.pulls.length, a.pulls[0].required], [1, ["mesh/check"]]],
["open-pulls", "forge down", {}, { openPulls: down }, (a) => [a.pulls, a["error-kind"]], [undefined, "failed"]],
+106
View File
@@ -0,0 +1,106 @@
import assert from "node:assert/strict";
import { test } from "node:test";
// **One merge call, every member judged before any is merged** (novox/hq design 47 H §734, §735; ADR 0682 §13; H-A-21,
// H-A-22, H-A-47): the seat git's merge-pull takes pulls and by, 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 them in the order named, and answers the call and each member's outcome once.
const A = "a".repeat(40), B = "b".repeat(40), MOVED = "c".repeat(40);
const CALL = "0123456789abcdef";
interface FakePull { base: string; head: string; state: string; merged: boolean; merge?: string; refuse?: string }
/** A forge of pull requests by `<repository>#<number>`, recording each merge asked. It has no protection API: a call that
* read a branch's protection would throw. */
function forge(pulls: Record<string, FakePull>) {
const merges: string[] = [];
const key = (o: string, r: string, n: number) => `${o}/${r}#${n}`;
return {
merges,
getPullRequest: async (o: string, r: string, n: number) => {
const p = pulls[key(o, r, n)];
if (!p) throw new Error(`Gitea API GET /repos/${o}/${r}/pulls/${n}: 404 {}`);
return { number: n, title: "", state: p.state, merged: p.merged, base: p.base, head: "b", head_sha: p.head,
...(p.merged ? { merge_commit_sha: p.merge ?? "m".repeat(40) } : {}) } as any;
},
mergePullRequest: async (o: string, r: string, n: number, _m: string, _d: boolean, head: string) => {
const p = pulls[key(o, r, n)];
merges.push(key(o, r, n));
if (p.refuse) throw new Error(`Gitea API POST /repos/${o}/${r}/pulls/${n}/merge: 409 ${p.refuse}`);
assert.equal(head, p.head);
p.merged = true;
p.merge = `${n}`.repeat(40).slice(0, 40);
},
commitParents: async (_o: string, _r: string, sha: string) => [sha, "x"],
};
}
const watched = new Map([["novox/app", new Set(["main"])], ["novox/lib", new Set(["main"])]]);
async function call(f: ReturnType<typeof forge>, args: Record<string, unknown>, over: Record<string, unknown> = {}, caller = "person.jochen") {
const { mergeCall } = await import("../dist/mergecall.js");
const { runAs } = await import("@novox/mesh-sdk/callers");
const deps = { registered: () => true, watched: () => watched, judge: async () => null, newCall: () => CALL, ...over };
return runAs({ "mesh/caller": caller }, args, () => mergeCall(f as any, args, deps as any)) as Promise<any>;
}
const two = { by: "lead@shanks", pulls: [{ repository: "novox/app", number: 5, head: A }, { repository: "novox/lib", number: 9, head: B }] };
const open = (): Record<string, FakePull> => ({ "novox/app#5": { base: "main", head: A, state: "open", merged: false },
"novox/lib#9": { base: "main", head: B, state: "open", merged: false } });
test("a merge call merges its members in the order named and answers each with its merge commit; one pull request is a list of one", async () => {
const f = forge(open());
const got = await call(f, two);
assert.equal(got.call, CALL);
assert.deepEqual(f.merges, ["novox/app#5", "novox/lib#9"]);
assert.deepEqual(got.members.map((m: any) => [m.repository, m.number, m.state, m.commit]),
[["novox/app", 5, "merged", "5".repeat(40)], ["novox/lib", 9, "merged", "9".repeat(40)]]);
const one = forge(open());
const single = await call(one, { by: "lead@shanks", pulls: [two.pulls[0]] });
assert.deepEqual([one.merges, single.members.length, single.members[0].state], [["novox/app#5"], 1, "merged"]);
});
test("a member refused at judging merges none and names every refused member and why", async () => {
const rows: { name: string; set: (p: Record<string, FakePull>) => void; over?: Record<string, unknown>; why: RegExp }[] = [
{ name: "the second member's head moved", set: (p) => { p["novox/lib#9"].head = MOVED; }, why: /head-moved: its head is cccccccccccc, not the bbbbbbbbbbbb/ },
{ name: "already merged", set: (p) => { Object.assign(p["novox/lib#9"], { merged: true, merge: "e".repeat(40) }); }, why: /already-merged: .* as e{40}/ },
{ name: "closed", set: (p) => { p["novox/lib#9"].state = "closed"; }, why: /is closed/ },
{ name: "a base no registration watches", set: (p) => { p["novox/lib#9"].base = "feat/x"; }, why: /its base feat\/x is no watched branch/ },
{ name: "a required step failed at its head's fingerprint",
set: () => {}, over: { judge: async (h: string) => (h === B ? { run: "main.7", module: "lib", step: "unit", fingerprint: "fp" } : null) },
why: /the unit step of lib failed in run main\.7 at its build-input fingerprint fp/ },
];
for (const r of rows) {
const pulls = open();
r.set(pulls);
const f = forge(pulls);
const got = await call(f, two, r.over);
assert.deepEqual(f.merges, [], `${r.name}: nothing merged`);
assert.equal(got.members[0].state, "judged", r.name);
assert.equal(got.members[1].state, "refused", r.name);
assert.match(got.members[1].why, r.why, r.name);
}
});
test("a call is refused whole with no proved caller, no by, no registration or no pull request", async () => {
const f = forge(open());
await assert.rejects(call(f, two, {}, ""), /proved no caller account/);
await assert.rejects(call(f, { pulls: two.pulls }), /by is the caller as who@node/);
await assert.rejects(call(f, two, { registered: () => false }), /no module is registered yet/);
await assert.rejects(call(f, { by: "lead@shanks", pulls: [] }), /one or more members/);
await assert.rejects(call(f, { by: "lead@shanks", pulls: [two.pulls[0], two.pulls[0]] }), /named twice/);
assert.deepEqual(f.merges, []);
});
test("the forge refusing a member after every member was judged stops the call: the landed member merged, the rest refused", async () => {
const pulls = open();
pulls["novox/lib#9"].refuse = "merge conflict";
const three = { by: "lead@shanks", pulls: [...two.pulls, { repository: "novox/app", number: 6, head: A }] };
pulls["novox/app#6"] = { base: "main", head: A, state: "open", merged: false };
const f = forge(pulls);
const got = await call(f, three);
assert.deepEqual(f.merges, ["novox/app#5", "novox/lib#9"], "the third is never asked");
assert.deepEqual(got.members.map((m: any) => m.state), ["merged", "refused", "refused"]);
assert.match(got.members[1].why, /the forge refused the merge: .*merge conflict/);
});