From 815be6bdcebc2f61ddec1b24d9fc39c8fdd4fca1 Mon Sep 17 00:00:00 2001 From: jochen Date: Fri, 20 Nov 2026 03:54:09 +0100 Subject: [PATCH] FORGE-6: the forge module's merge-check machinery and its polls go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit announceHead with its mesh/merge-gate pending, the weighing of trunk and sibling moves (passPulls, trunksMoved, siblingMoves, GateWriter) and their files on disk, the pass's pull-passing half with its 60 s retry, and the 10-minute keep-main-rules step go. A pull request's new head is said as pull.updated from the forge's event alone; the seat's status writes through the client; pollRepos, pollMerged and readAllAtStart stay. Builds: design 47 H §764 (the forge module: the merge-check machinery, its poll and timer), §762; H-A-28, H-A-100 Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy --- modules/gitea/gate.ts | 103 -------- modules/gitea/index.ts | 159 ++---------- modules/gitea/mainrules.ts | 18 -- modules/gitea/pulls.ts | 94 +------ modules/gitea/seat.ts | 15 +- modules/gitea/siblings.ts | 298 ----------------------- modules/gitea/test/announcing.test.ts | 16 -- modules/gitea/test/gate.test.ts | 69 ------ modules/gitea/test/guard.test.ts | 39 +-- modules/gitea/test/mainrules.test.ts | 21 +- modules/gitea/test/paging.test.ts | 27 -- modules/gitea/test/pulls.test.ts | 59 +---- modules/gitea/test/siblings.test.ts | 273 --------------------- modules/gitea/test/tools-account.test.ts | 6 +- modules/gitea/test/trunk.test.ts | 167 ------------- modules/gitea/test/watch.test.ts | 49 +--- modules/gitea/trunk.ts | 211 ---------------- modules/gitea/updated.ts | 42 ++++ modules/gitea/watch.ts | 60 +---- 19 files changed, 92 insertions(+), 1634 deletions(-) delete mode 100644 modules/gitea/gate.ts delete mode 100644 modules/gitea/siblings.ts delete mode 100644 modules/gitea/test/gate.test.ts delete mode 100644 modules/gitea/test/siblings.test.ts delete mode 100644 modules/gitea/test/trunk.test.ts delete mode 100644 modules/gitea/trunk.ts create mode 100644 modules/gitea/updated.ts diff --git a/modules/gitea/gate.ts b/modules/gitea/gate.ts deleted file mode 100644 index e738bc70e..000000000 --- a/modules/gitea/gate.ts +++ /dev/null @@ -1,103 +0,0 @@ -// **One writer of a head's mesh/merge-gate** (novox/hq issue 446). -// -// A pending check says where it is: "waiting in the build queue since …" when the head is announced. The forge keeps only -// the newest status of a context, so two writers cannot order their writes; this module is the one writer of -// mesh/merge-gate, and every write of one head's gate goes through one chain, in the order it was asked. A recheck's -// pending (novox/hq issue 456) and a trunk's move (ADR 0323 §4) take their turns on the same chain. No verdict is written -// here any more: the controller's `checked` is no event (ADR 0571 clause 13), and main requires the checker's mesh/check. - -import { CHECK_CONTEXT, pendingWords } from "./pulls.js"; -import type { CommitStatus, HeadCheck } from "./client.js"; - -/** What the gate writer needs of the forge: a status set, and a head's statuses as the forge holds them. */ -export interface GateForge { - setCommitStatus(owner: string, repo: string, sha: string, status: CommitStatus): Promise; - /** The head's statuses by context, the newest of each, with their words (novox/hq ADR 0323). */ - headChecks(owner: string, repo: string, sha: string): Promise>; -} - -/** Whether a repository as the mesh clones it (`http://forge/novox/hq.git`) is owner/repo. */ -export function clonedAs(url: string | undefined, owner: string, repo: string): boolean { - const u = (url ?? "").trim().toLowerCase().replace(/\.git$/, ""); - const full = `${owner}/${repo}`.toLowerCase(); - return u === full || u.endsWith("/" + full); -} - -interface Head { - /** The chain the head's writes take their turns on. */ - chain: Promise; -} - -export class GateWriter { - private heads = new Map(); - private forge: GateForge; - private now: () => Date; - - constructor(forge: GateForge, now: () => Date = () => new Date()) { - this.forge = forge; - this.now = now; - } - - private head(owner: string, repo: string, sha: string): Head { - const key = `${owner}/${repo}@${sha}`.toLowerCase(); - let h = this.heads.get(key); - if (!h) { - h = { chain: Promise.resolve() }; - this.heads.set(key, h); - // Kept for the heads still in play; the oldest go first, past what any forge holds open at once. - if (this.heads.size > 2000) this.heads.delete(this.heads.keys().next().value as string); - } - return h; - } - - /** One turn on the head's chain; a turn that fails never stops the next. Its failure is the caller's. */ - private turn(h: Head, fn: () => Promise): Promise { - const run = h.chain.then(fn); - h.chain = run.catch(() => {}); - return run; - } - - /** A turn whose failure is said here: a pending word not written is not worth the event again. */ - private said(h: Head, what: string, fn: () => Promise): Promise { - return this.turn(h, fn).catch((err) => { - console.error(`[gitea] ${what} — ${err instanceof Error ? err.message : err}`); - }); - } - - /** The head announced: it waits in the build queue from now. A new check of the head, so no verdict yet. */ - pending(owner: string, repo: string, sha: string): Promise { - const h = this.head(owner, repo, sha); - const at = this.now(); - return this.said(h, `${owner}/${repo}@${sha.slice(0, 8)}: could not say a check is pending`, () => - this.forge.setCommitStatus(owner, repo, sha, { state: "pending", context: CHECK_CONTEXT, description: pendingWords(at) })); - } - - /** - * A status the seat git's `status` verb sets (seat.ts), a recheck's pending among them (novox/hq issue 456): it takes - * its turn after every write of the head already asked for, so it lands over them, and a later write lands over it. A - * write that fails fails the caller. - */ - status(owner: string, repo: string, sha: string, status: CommitStatus): Promise { - return this.turn(this.head(owner, repo, sha), () => this.forge.setCommitStatus(owner, repo, sha, status)); - } - - /** - * **A trunk's move puts the head's verdict out of date** (novox/hq ADR 0323 §4): its merge check statuses are put back - * to pending, with the reason, in their turn after every write of the head already asked for — a verdict in flight - * lands first. What is written is decided in the turn, from the statuses the forge holds then (`decide`, trunk.ts's - * outOfDateStatuses): a check on its way, or a verdict already judged against the trunk's head, is left as it is. It - * opens no check — nothing is asked — so a verdict of a check asked before it keeps its weight. Answers what it wrote; - * a write that fails fails the caller, and the move is weighed again on the next pass. - */ - outOfDate(owner: string, repo: string, sha: string, - decide: (checks: Record) => CommitStatus[] | Promise, target?: string): Promise { - const h = this.head(owner, repo, sha); - const written: CommitStatus[] = []; - return this.turn(h, async () => { - for (const s of await decide(await this.forge.headChecks(owner, repo, sha))) { - await this.forge.setCommitStatus(owner, repo, sha, target ? { ...s, target_url: target } : s); - written.push(s); - } - }).then(() => written); - } -} diff --git a/modules/gitea/index.ts b/modules/gitea/index.ts index 793738a33..4e52c8c3b 100644 --- a/modules/gitea/index.ts +++ b/modules/gitea/index.ts @@ -4,8 +4,7 @@ // Emits (novox/hq ADR 0041/0042): // module.gitea.repo.created — a repository appeared, however it was made (push, web UI, or tool) // module.gitea.pull.merged — a pull request was merged, however it was merged (web UI, API, or tool) -// module.gitea.pull.updated — an open pull request's head moved, opened or pushed to: the mesh checks it -// before it merges (novox/hq to-be 45 §9) +// module.gitea.pull.updated — an open pull request's head moved, opened or pushed to, said from the forge's event alone // // module.gitea.pull.closed — a pull request closed unmerged: the delivery it was is stopped (novox/hq ADR 0239) // @@ -16,13 +15,8 @@ // It reads no other module's state: mesh/check, and every act of a delivery part on the forge, arrive as verbs of the seat // git (seat.ts), asked by the forge bridge (novox/hq design 47 *The seat git*). // -// This module is the one writer of mesh/merge-gate. It hears no build seat's event: since R4g a check's steps are asks -// on the build seats' streams, whose backlog the delivery view shows (novox/hq ADR 0525 §9; issue 1887). -// -// **A trunk's move puts every open verdict into it out of date** (novox/hq ADR 0323 §4, trunk.ts): each pass reads the -// head of every trunk an open pull request merges into, and when one moved, the merge check statuses of every open pull -// request into it go back to pending with the reason. Nothing is run for it. A verdict that lands judged against a trunk -// commit that is no longer the trunk's head is said out of date in place of its pass or failure. +// No merge check is asked, weighed or written here (design 47 H §764; H-A-28, H-A-100): a merge is one merge call of the +// seat git (mergecall.ts), its members judged by their heads and failed steps alone. // // Every pull request the forge holds is announced, whatever its repository: the controller holds the // module graph and decides what is checked — a repository is never asked to opt in. @@ -58,14 +52,10 @@ import { seat as GIT, events as GIT_EVENTS, type BranchMovedEvent, type PullClos import { seat as RUNNER, events as RUNNER_EVENTS, type StepEndedEvent } from "@novox/mesh-delivery-contracts-mesh-pipeline-runner"; import { run } from "./delivery.js"; import { GiteaAdmin, GiteaClient, movedSince } from "./client.js"; -import { keepMainRules, mainRulesStep } from "./mainrules.js"; -import { CHECK_CONTEXT, CHECK_STATUS, REPO_CHECK_CONTEXT, headKey, requiredOf, writesGate, type Announced } from "./pulls.js"; -import { actOn, announceNewHeads, startPass } from "./watch.js"; -import { GateWriter } from "./gate.js"; -import { HOOK_PATH, HOOK_PORT, Pace, claimHead, ensureSystemHook, eventsTool, keptSecret, receiver, type ForgeEvent } from "./webhook.js"; -import { keepSiblings, readSiblings, siblingsFile, weighSiblings } from "./siblings.js"; +import { actOn } from "./watch.js"; +import { HOOK_PATH, HOOK_PORT, Pace, ensureSystemHook, eventsTool, keptSecret, receiver, type ForgeEvent } from "./webhook.js"; import { bindInBackground, bindUntilHeld } from "./bind.js"; -import { announcementOf, weighTrunks } from "./trunk.js"; +import { announcementOf } from "./updated.js"; import { ReadAll, readAllTools } from "./readall.js"; import { DeliveredWrites, writeTools } from "./writes.js"; import { TOOLS_ACCOUNT, TOOLS_ORG, meshAccounts } from "./tools-account.js"; @@ -111,7 +101,7 @@ async function pollRepos(client: GiteaClient): Promise { // What has been announced is kept beside the module's state, so a restart does not announce the // whole history again — and the first tick on a machine with no record announces nothing, because // everything it sees then predates the watching. -import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; + import { join } from "node:path"; // What has been announced is no longer kept in a file (novox/hq ADR 0406 §6, §7, issue 976): an announcement carries a // message id (announce.ts), so the same merge announced by the poll and by the forge's event, or again after a restart, @@ -183,7 +173,6 @@ async function announceClosed(client: GiteaClient, repo: RepoOf, pull: PullOf): throw err; } console.log(`[gitea] announced ${repo.full_name}#${pull.number} closed unmerged`); - await siblingMoves(client, repo.full_name, pull.number); return true; } @@ -243,8 +232,6 @@ async function announceMerge(client: GiteaClient, repo: RepoOf, pull: PullOf): P // Said, because a trigger that fires silently is indistinguishable from one that did not // fire (novox/hq 04-ISSUES/131) — this line is how an operator knows the mesh was told. console.log(`[gitea] announced merge ${repo.full_name}#${pull.number} (${pull.merge_commit_sha.slice(0, 8)}) into ${pull.base}`); - // Its own merge of the head that was read is no sibling's move; any other is (ADR 0382 §5). - await siblingMoves(client, repo.full_name, pull.number); } catch (err) { announced.delete(pull.merge_commit_sha); throw err; @@ -252,123 +239,12 @@ async function announceMerge(client: GiteaClient, repo: RepoOf, pull: PullOf): P return true; } -// **Every new head of an open pull request is announced** (novox/hq to-be 45 §9): the mesh checks it against every -// machine of its facts before it merges. What this process announced is remembered in memory only (novox/hq ADR 0406 -// §6, §7, issue 976): the announcement carries a message id (announce.ts), so the poll's, the forge event's and the -// merge tool's are one to the bus. After a start, the first look announces a head only if the forge shows no merge check -// of it yet — a head with one was announced — and only what moved in the last day, so a forge's whole backlog is not -// checked at once and a restart asks no check again against a trunk that moved. -let heads: Announced = {}; -let primedPulls = false; -/** **A head, announced once, whichever path saw it first** (novox/hq issue 729): the poll or the forge's event. */ -async function announceHead(client: GiteaClient, repo: RepoOf, pull: OpenOf): Promise { - const key = headKey(repo.full_name, pull.number, pull.base); - const sha = String(pull.head_sha ?? ""); - const before = heads[key]; - // Claimed before the first wait, so the other path finds it taken while this one is still announcing. - if (!claimHead(heads, key, sha)) return false; - try { - // The announcement the merge tool makes too when it asks a check (trunk.ts, novox/hq ADR 0323 §5). - await announce("pull.updated", await announcementOf(client, repo.owner, repo.name, repo.clone_url ?? "", pull)); - } catch (err) { - if (before === undefined) delete heads[key]; - else heads[key] = before; - throw err; - } - // A sibling's new head puts out of date every verdict that read the sibling at another head (ADR 0382 §5). - await siblingMoves(client, repo.full_name, pull.number); - // Said, so an operator knows the mesh was asked to check it. - console.log(`[gitea] announced ${key} at ${sha.slice(0, 8)} to be checked before it merges`); - // Pending until the verdict comes, so the pull request says a check is running rather than nothing — and - // where it is: in the build queue from now, until a build machine takes it (novox/hq issue 446). Only where the base - // still requires mesh/merge-gate (issue 1301): a main that requires mesh/check is the checker's; - // a rule that cannot be read is said pending, as before. - const rule = pull.base ? await client.appliedProtection(repo.owner, repo.name, String(pull.base)).catch(() => undefined) : undefined; - if (writesGate(requiredOf(rule))) await gates.pending(repo.owner, repo.name, sha); - return true; +/** **A pull request's new head, said as pull.updated from the forge's event alone** (design 47 H §764; H-A-100): no + * poll, no pending status and no sibling's weighing. */ +async function announceUpdated(client: GiteaClient, repo: RepoOf, pull: PullOf): Promise { + await announce("pull.updated", await announcementOf(client, repo.owner, repo.name, repo.clone_url ?? "", pull)); + console.log(`[gitea] said ${repo.full_name}#${pull.number} at ${String(pull.head_sha ?? "").slice(0, 8)} updated`); } -type OpenOf = Awaited>[number]; - -/** Whether the forge shows a merge check of the head, in any state: only an announced head has one. */ -async function alreadyChecked(client: GiteaClient, repo: RepoOf, pull: OpenOf): Promise { - try { - const checks = await client.headChecks(repo.owner, repo.name, String(pull.head_sha)); - return CHECK_CONTEXT in checks || REPO_CHECK_CONTEXT in checks || CHECK_STATUS in checks; - } catch { - return false; // the forge cannot say: announced, and the bus's message id collapses it if it was - } -} - -let lastPullLook = ""; -/** The pass over every open pull request: run at the start and when the receiver listens, never on a timer (issue 1422). */ -async function passPulls(client: GiteaClient): Promise { - const began = new Date().toISOString(); - const dayAgo = new Date(Date.now() - 24 * 3600_000).toISOString(); - for (const repo of await client.listAllRepos()) { - // Every open pull request, paged (novox/hq issue 579). - const open = await client.listOpenPullsSince(repo.owner, repo.name, ""); - await announceNewHeads(repo.full_name, open, heads, primedPulls, dayAgo, { - alreadyChecked: (pull) => alreadyChecked(client, repo, pull), - announceHead: (pull) => announceHead(client, repo, pull), - missed: (what) => pace.miss(what), - }); - if (await trunksMoved(client, repo.owner, repo.name)) changedTrunks = true; - } - if (changedTrunks) keepTrunks(); - changedTrunks = false; - primedPulls = true; - lastPullLook = began; -} - -// **The trunks' heads, as this module last read them** (novox/hq ADR 0323 §4), by `owner/repo:branch`: kept beside the -// other records, so a move made while this module was away is weighed on its first pass back. With no record — the -// first pass after this rolls out — a trunk's head is taken as it is and nothing is put out of date: the verdicts -// then standing are weighed on the trunk's next move, and the merge tool compares commits whatever this holds. -const trunksRecord = process.env.MESH_GITEA_STATE_DIR ? join(process.env.MESH_GITEA_STATE_DIR, "trunks-seen.json") : null; -let trunks: Record = {}; -let changedTrunks = false; -if (trunksRecord && existsSync(trunksRecord)) { - try { - trunks = (JSON.parse(readFileSync(trunksRecord, "utf8")) as { trunks: Record }).trunks ?? {}; - } catch { - // An unreadable record is no record: the next pass takes each trunk's head as it is. - } -} -function keepTrunks(): void { - if (!trunksRecord) return; - mkdirSync(join(trunksRecord, ".."), { recursive: true }); - const tmp = trunksRecord + ".tmp"; - writeFileSync(tmp, JSON.stringify({ trunks })); - renameSync(tmp, trunksRecord); -} - -/** Whether a trunk of one repository moved, weighed with this module's forge and its one writer (trunk.ts). */ -function trunksMoved(client: GiteaClient, owner: string, name: string): Promise { - return weighTrunks(client, gates, trunks, owner, name, () => siblingMoves(client, `${owner}/${name}`)); -} - -// **The siblings each open pull request's latest verdict names** (novox/hq ADR 0382 §5, siblings.ts), by member, kept beside -// the other records. A sibling's new head, close unmerged, merge, or a move of its base puts the merge check of every -// member whose verdict names it back to pending, with the reason; nothing is run for it. -const siblingsRecord = siblingsFile(process.env.MESH_GITEA_STATE_DIR); -const siblingNamed = readSiblings(siblingsRecord); - -/** A sibling moved, weighed (ADR 0382 §5): never fatal to what heard it. */ -async function siblingMoves(client: GiteaClient, repository: string, number?: number): Promise { - try { - if (await weighSiblings(client, gates, siblingNamed, repository, number)) keepSiblings(siblingsRecord, siblingNamed); - } catch (err) { - console.error(`[gitea] whether a sibling of ${repository}${number ? "#" + number : ""} moved could not be weighed — ${err instanceof Error ? err.message : err}`); - } -} - -// **This module is the one writer of a head's mesh/merge-gate** (novox/hq issue 446): the announcement's pending words, -// where the check is when a build machine takes it, and the verdict — each head's writes in one chain, the verdict last -// (gate.ts). A second writer elsewhere raced the verdict and could leave a pass reading pending. -const gates = new GateWriter({ - setCommitStatus: (owner, repo, sha, status) => (gitea as GiteaClient).setCommitStatus(owner, repo, sha, status), - headChecks: (owner, repo, sha) => (gitea as GiteaClient).headChecks(owner, repo, sha), -}); /** How fast the polls look: 30 s until the forge's events are heard, five minutes while they are; and what * gitea_events says of them (webhook.ts). */ @@ -417,11 +293,10 @@ const failedSteps = new FailedSteps(state("failed-steps"), (line) => co void failedSteps.expireSeen().catch((err) => console.log(`[gitea] the seen keys past 30 days could not be deleted at the start: ${err instanceof Error ? err.message : String(err)}`)); // gitea_events is served whether or not the forge is watched: it says so (novox/hq issue 729). The seat git's verbs are -// served here, beside the one writer of a head's statuses: the seat's status takes its turn on the head's chain, after the -// announcement's pending and a trunk's move, so a recheck's pending never lands over a later verdict (issue 456). +// served here. 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, registered: () => registrations.written, judge: (head) => failedSteps.judge(head), watched: () => registrations.watched, calls, say: seatPublish, partials }) : []), ...callTools(calls, partials, seatPublish, async (act) => { await broker().request("seat:mesh-hand-acts.hand-act", act); }), ...failedStepsTools(failedSteps, async (act) => { await broker().request("seat:mesh-hand-acts.hand-act", act); })]); @@ -430,10 +305,9 @@ registerModuleTools("gitea", () => [eventsTool(pace), ...readAllTools(readAll), const actOnEvent = (client: GiteaClient, event: ForgeEvent): Promise => actOn(event, { getRepo: (o, r) => client.getRepo(o, r), getPull: (o, r, n) => client.getPullRequest(o, r, n) as Promise, - announceHead: (repo, pull) => announceHead(client, repo, pull as OpenOf), + announceUpdated: (repo, pull) => announceUpdated(client, repo, pull), announceMerge: (repo, pull) => announceMerge(client, repo, pull), announceClosed: (repo, pull) => announceClosed(client, repo, pull), - siblingMoves: (full, n) => siblingMoves(client, full, n), }); /** @@ -610,14 +484,13 @@ if (gitea) { } catch (err) { console.error(`[gitea] the package seats cannot write — ${err instanceof Error ? err.message : err}`); } - tick(mainRulesStep(keepMainRules(), () => GiteaAdmin.fromEnv().ensureMainMerges("novox"), (line) => console.log(line)), 600_000); tick(() => pollRepos(client), 60_000); // **No timer asks the forge for pull requests or merges** (issue 1422): the forge's events announce them. One pass over // every repository runs at the start and again once the receiver listens, so what happened while the module was away or // not yet listening is announced; passes run one at a time, a failed one is asked again a minute later. let passes: Promise = Promise.resolve(); const pass = (): Promise => (passes = passes.catch(() => {}).then(() => - startPass(async () => { await pollMerged(client); await passPulls(client); }, { retryMs: 60_000 }))); + pollMerged(client).catch((err) => console.error(`[gitea] the pass over every repository's merges failed — ${err instanceof Error ? err.message : err}`)))); void pass(); let catchUpAsked = false; catchUp = () => { diff --git a/modules/gitea/mainrules.ts b/modules/gitea/mainrules.ts index e8ac249f7..7e51bcab8 100644 --- a/modules/gitea/mainrules.ts +++ b/modules/gitea/mainrules.ts @@ -3,8 +3,6 @@ // False, the default, leaves every repository's branch protection as people set it at the forge. import { readFileSync } from "node:fs"; -export const LEFT_AS_SET = "[gitea] main's rules are left as set at the forge (keep-main-rules is false)"; - /** The setting from the settings-merged config file the mesh delivers; absent, unreadable or not true is false. */ export function keepMainRules(env: NodeJS.ProcessEnv = process.env): boolean { const file = env.MESH_GITEA_CONFIG_FILE; @@ -14,19 +12,3 @@ export function keepMainRules(env: NodeJS.ProcessEnv = process.env): boolean { return v === true || v === "true"; } catch { return false; } } - -/** The 10-minute step: puts the rules right only when kept; else says once that they are left and writes nothing. */ -export function mainRulesStep(keep: boolean, put: () => Promise, say: (line: string) => void): () => Promise { - let said = false; - let touched = -1; - return async () => { - if (!keep) { - if (!said) say(LEFT_AS_SET); - said = true; - return; - } - const repos = await put(); - if (repos.length !== touched) say(`[gitea] main's rule is right in ${repos.length} repositories`); - touched = repos.length; - }; -} diff --git a/modules/gitea/pulls.ts b/modules/gitea/pulls.ts index 16a011834..364173ac8 100644 --- a/modules/gitea/pulls.ts +++ b/modules/gitea/pulls.ts @@ -1,15 +1,5 @@ -// A pull request's merge check (novox/hq to-be 45 §9): what the forge's announcer says when a pull -// request's head moves, and the status contexts the check is kept under. -// -// **Before merge, never after.** Each new head of an open pull request is announced as `pull.updated`, and the mesh -// checks it against every machine of its facts before it merges. The verdict is the checker's `mesh/check`, which this -// module writes from the checker's owed state (check.ts); the controller's `checked`, which once set the two older -// statuses, is no event any more (ADR 0571 clause 13). -// -// Pure functions here, so they are tested without a forge. - -import type { GiteaPull, GiteaRepo } from "./client.js"; -import { movedSince } from "./client.js"; +// The status contexts the forge's protections named for a merge check, read by the account's writes (writes.ts) to take +// them off a protection: no merge check is asked, weighed or written any more (design 47 H §764; H-A-28, H-A-100). /** The status context a merge check's gate is kept under: one per commit, the newest replacing the last. */ export const CHECK_CONTEXT = "mesh/merge-gate"; @@ -20,83 +10,3 @@ export const REPO_CHECK_CONTEXT = "mesh/repo-check"; /** The one status main requires (novox/hq ADR 0447 §1, issue 1301): the checker's verdict, written by this module from the * checker's owed state (check.ts, ADR 0521). Its line names the head and the trunk commit it judged: "pass on …". */ export const CHECK_STATUS = "mesh/check"; - -/** The statuses a branch's rule requires, from the rule the forge applies to it: none when it is unprotected or checks - * no status; undefined when the rule could not be read. */ -export function requiredOf(rule: { enable_status_check?: boolean; status_check_contexts?: string[] | null } | null | undefined): string[] | undefined { - if (rule === undefined) return undefined; - if (!rule || !rule.enable_status_check) return []; - return (rule.status_check_contexts ?? []).filter(Boolean); -} - -/** - * **The controller's statuses are written only where a base still requires them** (issue 1301; ADR 0503 §3, §5): of - * mesh/merge-gate and mesh/repo-check, those the base requires — hq's mesh/repo-check alone once the forge requires - * mesh/check everywhere else, so no mesh/merge-gate stands on a head that nothing will set. A base whose rule could not - * be read keeps both, as before: a status nothing requires blocks nothing, and one that is required is never left out. - */ -export function maintained(required: string[] | undefined): string[] { - const both = [CHECK_CONTEXT, REPO_CHECK_CONTEXT]; - return required === undefined ? both : both.filter((c) => required.includes(c)); -} - -/** Whether mesh/merge-gate is written on a head of this base (maintained). */ -export function writesGate(required: string[] | undefined): boolean { - return maintained(required).includes(CHECK_CONTEXT); -} - -/** - * The pending words a head's merge check is announced with (novox/hq issue 446): where the check is, and since when, - * in the time the operator reads. They stood as "the mesh is mapping this head onto its module graph" for the whole - * check — the few seconds the controller maps the head and then the queue wait and the build — and readers took the - * forge for lagging (issue 423). The controller maps and queues the check in seconds, so from the announcement it waits - * in the build queue; mesh-delivery says "building on since …" when a build machine takes it. - */ -export function pendingWords(announced: Date): string { - const two = (n: number) => String(n).padStart(2, "0"); - return `waiting in the build queue since ${two(announced.getHours())}:${two(announced.getMinutes())}`; -} - -/** The heads already announced, keyed by `headKey`, so a restart announces nothing twice. */ -export type Announced = Record; - -/** The key a pull request's announced head is kept under: `owner/repo#number@base`. The base is in it because a pull - * request retargeted keeps its head, and a head judged into one base is not judged into another (issue 1422, de-spiegel #6). */ -export function headKey(full: string, number: number, base?: string): string { - return `${full}#${number}@${base ?? ""}`; -} - -/** Which open pull requests have a head not yet announced. A pull request merged or closed is not - * open and is never asked about. */ -export function headsToAnnounce(full: string, pulls: GiteaPull[], announced: Announced): GiteaPull[] { - return pulls.filter((p) => p.state === "open" && !!p.head_sha && announced[headKey(full, p.number, p.base)] !== p.head_sha); -} - -/** A pull request the forge found updated, by its repository: what `searchOpenPulls` answers. */ -export interface PullSeen { - owner: string; - name: string; - updated_at?: string; -} - -/** **The repositories a pass looks at** (novox/hq issue 347): every one that moved since the floor, every one - * holding a pull request updated since the floor — opening, reopening or retargeting a pull request moves its own - * update time and not its repository's — and every one on a sweep or the first pass. */ -export function reposToLook(repos: GiteaRepo[], floor: string, pulls: PullSeen[], sweep: boolean): GiteaRepo[] { - if (sweep || !floor) return repos; - const moved = new Set(movedSince(repos, floor).map((r) => r.full_name)); - const at = Date.parse(floor); - for (const p of pulls) { - if (!p.updated_at || !(Date.parse(p.updated_at) < at)) moved.add(`${p.owner}/${p.name}`); - } - return repos.filter((r) => moved.has(r.full_name)); -} - -export function clipped(d: string): string { - d = d.replace(/\s+/g, " ").trim(); - return d.length > 140 ? d.slice(0, 139) + "…" : d; -} - -/** What a group member's gate says while the group's composed check is the one that judges it: the member's own check can say - * nothing more of it, so asking that check again brings no verdict that names a trunk (novox/hq issue 1106). */ -export const WAITS_FOR_COMPOSED = "waits for its group's composed check"; diff --git a/modules/gitea/seat.ts b/modules/gitea/seat.ts index 2e9cda399..dee5185b3 100644 --- a/modules/gitea/seat.ts +++ b/modules/gitea/seat.ts @@ -40,18 +40,11 @@ export const TAGS_PAGE = 50; * is the manifest's container's; no variable names it (a MESH_* word nothing sets is refused, checks/environment). */ export const FORGE_CONTAINER = "gitea"; -/** The writer every status of a head takes its turn on (gate.ts): the seat's status lands after every write of the head - * already asked for, so a recheck's pending never lands over a later verdict (novox/hq issue 456). */ -export interface HeadStatuses { - status(owner: string, repo: string, sha: string, status: CommitStatus): Promise; -} - -/** What the holder reaches beside the forge's API: git in the forge's container (the note), the head's one writer of its - * statuses, and whether the first registrations are written. */ +/** What the holder reaches beside the forge's API: git in the forge's container (the note), and whether the first + * registrations are written. */ export interface SeatDeps { run: Runner; container: string; - statuses: HeadStatuses; /** Whether the first registrations were written (registrations.ts): until then merge-pull refuses every merge (design 47 §95). */ registered: () => boolean; /** The failed `required` step that refuses a head, judged from the module's own state `failed-steps` (failedsteps.ts), or null. */ @@ -229,14 +222,14 @@ export function seatTools(gitea: GiteaClient, deps: SeatDeps): ToolDefinition[] const combined = await gitea.combinedStatus(owner, repo, commit); return { commit, combined: combined.state, statuses: newestByContext(combined.statuses).map(statusOf) }; }), - verb(GIT_VERBS.status, "The seat git's status: an act of the forge bridge, a commit status set in its turn after every write of the head already asked for; the same id said again sets it again to the same.", + verb(GIT_VERBS.status, "The seat git's status: an act of the forge bridge, a commit status set on a commit; the same id said again sets it again to the same.", async (args): Promise => { const id = idOf(args.id); const { owner, repo } = repositoryOf(args.repository); const commit = commitOf("commit", args.commit); const state = String(args.state ?? ""); if (!STATES.has(state)) throw new Refused(`state ${JSON.stringify(state)} is none of ${[...STATES].join(", ")}`); - await deps.statuses.status(owner, repo, commit, { state: state as CommitStatus["state"], context: String(args.context ?? ""), + await gitea.setCommitStatus(owner, repo, commit, { state: state as CommitStatus["state"], context: String(args.context ?? ""), description: String(args.description ?? ""), ...(args.target ? { target_url: String(args.target) } : {}) }); return { id, performed: true }; }), diff --git a/modules/gitea/siblings.ts b/modules/gitea/siblings.ts deleted file mode 100644 index 5dcff478a..000000000 --- a/modules/gitea/siblings.ts +++ /dev/null @@ -1,298 +0,0 @@ -// **A delivery group's member is checked beside the other members' heads, and a sibling's move puts that verdict out of -// date** (novox/hq ADR 0382 §5, §6; issue 867). -// -// The controller's verdict (`checked`) names the siblings its check read: each as the sibling's repository, pull -// request, head, base branch and the base commit the sibling's head was merged onto. This module, the forge's holder, -// keeps them per open pull request, beside its other records, and: -// -// - on its own hearing of a sibling's new head, of its close unmerged, or of a move of its base, sets -// mesh/merge-gate and mesh/repo-check of every member whose verdict names that sibling back to pending, with the -// reason. Nothing is run for it. The one move that does not count is the sibling's own merge of the head that was -// read onto the base commit that was read (in either order of the two merges); -// - lets the merge tool refuse a verdict that read siblings unless mesh/delivery-group passed at the very heads it -// read, and every sibling head it read carries an approving review at that head (merge.ts). -// -// A verdict without siblings (a controller from before ADR 0382) is none of this: nothing is kept and nothing changes. -// Pure functions and one small file of the module's own state, so this is tested without a forge. - -import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; -import { dirname } from "node:path"; -import type { CommitStatus, GiteaPull, HeadCheck } from "./client.js"; -import { Refused } from "./guard.js"; -import { CHECK_CONTEXT, REPO_CHECK_CONTEXT, clipped } from "./pulls.js"; -import { sameCommit, twelve, type OutOfDateWriter } from "./trunk.js"; - -/** The status the delivery group's owner sets on each member's head (novox/hq ADR 0239). */ -export const GROUP_CONTEXT = "mesh/delivery-group"; - -/** One sibling a verdict read, as the controller names it (contract of ADR 0382 §4). */ -export interface SiblingNamed { - repository: string; - number: number; - head: string; - base: string; - base_commit: string; - /** Set here, never by the controller: the sibling merged its head onto its base commit read, so it is no sibling's - * move any more. */ - merged?: boolean; -} - -/** What is kept of one member's latest verdict that read siblings: the head it was of and the siblings it named. */ -export interface SiblingEntry { - head: string; - siblings: SiblingNamed[]; -} - -/** The records, by `owner/repo#number` of the member. */ -export type SiblingRecord = Record; - -/** The member's key. */ -export function memberKey(owner: string, repo: string, number: number): string { - return `${owner}/${repo}#${number}`.toLowerCase(); -} - -/** The siblings a verdict names, trimmed to what is kept; none when it names none or names one badly. */ -export function siblingsOf(named: unknown): SiblingNamed[] { - if (!Array.isArray(named)) return []; - const out: SiblingNamed[] = []; - for (const s of named) { - const r = s as Record; - const repository = String(r?.repository ?? ""), head = String(r?.head ?? ""), base = String(r?.base ?? ""); - const number = Number(r?.number); - if (!repository || !head || !base || !Number.isInteger(number) || number <= 0) continue; - out.push({ repository, number, head, base, base_commit: String(r?.base_commit ?? "") }); - } - return out; -} - -/** The siblings as a status names them: "mesh-host#114@abcdef123456, …". */ -export function siblingWords(siblings: SiblingNamed[]): string { - return siblings.map((s) => `${s.repository.split("/").pop()}#${s.number}@${twelve(s.head)}`).join(", "); -} - -/** What a status of a verdict that read siblings carries, after the commits it judged. */ -export function besideWords(siblings: SiblingNamed[]): string { - // Short, so that the verdict word and the start of its reason survive the forge's 140 characters: the first sibling - // by its pull request and 8 characters of its head, and how many more. The whole list is the holder's record and the comment's. - const first = siblings[0]; - const more = siblings.length > 1 ? ` +${siblings.length - 1} more` : ""; - return `beside ${first.repository.split("/").pop()}#${first.number}@${twelve(first.head).slice(0, 8)}${more}`; -} - -/** The mark a status carries when the siblings could not be learned (ADR 0382 §1): said, never silent. */ -export const UNKNOWN_MARK = "siblings unknown"; - -/** Whether a status names that its verdict read siblings (so that a record lost does not read as none). */ -export function namesSiblings(description: string | undefined): boolean { - return / beside [\w.-]+#\d+@[0-9a-f]{8}\b/.test(description ?? ""); -} - -/** Whether a status is a verdict put out of date by a sibling's move. */ -export function siblingOutOfDate(description: string | undefined): boolean { - return /^out of date: judged beside /.test(description ?? ""); -} - -// --- the record on disk ---------------------------------------------------------------------------------------- - -/** The file the holder keeps the siblings its verdicts name in, beside its other records. */ -export function siblingsFile(stateDir: string | undefined): string | null { - return stateDir ? `${stateDir.replace(/\/+$/, "")}/siblings-named.json` : null; -} - -export function readSiblings(file: string | null): SiblingRecord { - if (!file || !existsSync(file)) return {}; - try { - return (JSON.parse(readFileSync(file, "utf8")) as { members?: SiblingRecord }).members ?? {}; - } catch { - return {}; - } -} - -export function keepSiblings(file: string | null, record: SiblingRecord): void { - if (!file) return; - try { - mkdirSync(dirname(file), { recursive: true }); - writeFileSync(file + ".tmp", JSON.stringify({ members: record })); - renameSync(file + ".tmp", file); - } catch (err) { - console.error(`[gitea] the siblings a verdict named could not be kept — ${err instanceof Error ? err.message : err}`); - } -} - -// --- what a sibling's move is --------------------------------------------------------------------------------- - -/** What weighing a sibling reads of the forge. */ -export interface SiblingForge { - getPullRequest(owner: string, repo: string, index: number): Promise; - branchHead(owner: string, repo: string, branch: string): Promise; - commitParents(owner: string, repo: string, sha: string): Promise; -} - -/** The reason a verdict that named this sibling is out of date, from what the forge holds now, or nothing; and whether - * the sibling has merged its head read onto the base commit read, which ends it as a sibling. */ -export async function siblingMoved(forge: SiblingForge, s: SiblingNamed): Promise<{ reason?: string; merged?: boolean }> { - const [owner, repo] = s.repository.split("/"); - const who = `${repo}#${s.number}`; - const pull = await forge.getPullRequest(owner, repo, s.number); - if (pull.merged) { - // Its own merge of the head that was read onto the base commit that was read: the head the merge joined is the head - // read, and the commit it was made onto is the base commit read. Any other merge is a move of the base. - const parents = pull.merge_commit_sha ? await forge.commitParents(owner, repo, pull.merge_commit_sha).catch(() => []) : []; - const own = sameCommit(pull.head_sha, s.head) && parents.length >= 1 && sameCommit(parents[0], s.base_commit) && - (parents.length === 1 || sameCommit(parents[1], s.head)); - if (own) return { merged: true }; - return { reason: `${who} was merged otherwise than its head ${twelve(s.head)} onto ${twelve(s.base_commit)}` }; - } - if (pull.state !== "open") return { reason: `${who} was closed unmerged` }; - if (!sameCommit(pull.head_sha, s.head)) { - return { reason: `${who} at ${twelve(s.head)}, it is now at ${twelve(pull.head_sha)}` }; - } - const base = await forge.branchHead(owner, repo, s.base); - if (!sameCommit(base, s.base_commit)) { - return { reason: `${who} merged onto ${twelve(s.base_commit)}, its ${s.base} is now ${twelve(base)}` }; - } - return {}; -} - -/** A verdict out of date because a sibling moved, as its statuses say it (ADR 0382 §5; the wording of ADR 0323 §4). */ -export function siblingOutOfDateWords(reason: string): string { - return clipped(`out of date: judged beside ${reason}; judged again on a recheck or when it is merged`); -} - -/** The statuses a sibling's move puts back to pending on one member's head, from what the forge holds on it now: none - * when it has no merge check, or its gate is pending (a check on its way, or already out of date). */ -export function siblingStatuses(checks: Record, reason: string): CommitStatus[] { - const gate = checks[CHECK_CONTEXT]; - if (!gate || gate.state === "pending") return []; - const description = siblingOutOfDateWords(reason); - const out: CommitStatus[] = [{ state: "pending", context: CHECK_CONTEXT, description }]; - if (checks[REPO_CHECK_CONTEXT]) out.push({ state: "pending", context: REPO_CHECK_CONTEXT, description }); - return out; -} - -/** What weighing a sibling's move writes with, beside the forge's reads. */ -export interface SiblingWeighing extends SiblingForge {} - -/** - * A sibling moved (a new head, a close, a base move, a merge): every member whose latest verdict names it has its - * merge check put back to pending with the reason. `repository` and, when the event names one, `number` say which - * sibling. A member whose head is no longer the one its verdict was of is dropped from the record: its new head is - * checked afresh. Nothing is run. Answers whether the record changed. A read that fails leaves that member for the next - * move to weigh, and is said. - */ -export async function weighSiblings(forge: SiblingWeighing, gates: OutOfDateWriter, record: SiblingRecord, - repository: string, number?: number): Promise { - let changed = false; - const repo = repository.toLowerCase(); - for (const [key, entry] of Object.entries(record)) { - const [path] = key.split("#"); - const [owner, name] = path.split("/"); - const memberNumber = Number(key.split("#")[1]); - // A member that is merged or no longer open has no verdict to put out of date: its entry goes (the record must not - // grow without bound, and a merged head is never re-pended by a sibling's later push). Weighed when the event is the - // member's own, or names one of its siblings. - const own = path === repo && (number === undefined || number === memberNumber); - if (own || entry.siblings.some((s) => !s.merged && s.repository.toLowerCase() === repo && (number === undefined || s.number === number))) { - try { - const member = await forge.getPullRequest(owner, name, memberNumber); - if (member.merged || member.state !== "open") { - delete record[key]; - changed = true; - continue; - } - } catch (err) { - console.error(`[gitea] ${key}: whether it is still open could not be read — ${err instanceof Error ? err.message : err}`); - } - } - for (const s of entry.siblings) { - if (s.merged || s.repository.toLowerCase() !== repo || (number !== undefined && s.number !== number)) continue; - try { - const moved = await siblingMoved(forge, s); - if (moved.merged) { - s.merged = true; - changed = true; - continue; - } - if (!moved.reason) continue; - const member = await forge.getPullRequest(owner, name, memberNumber); - if (!sameCommit(member.head_sha, entry.head)) { - delete record[key]; - changed = true; - break; - } - const written = await gates.outOfDate(owner, name, entry.head, (checks) => siblingStatuses(checks, moved.reason!), - member.html_url || undefined); - if (written.length) { - console.log(`[gitea] ${key}: its verdict was judged beside ${moved.reason}: out of date, nothing run (novox/hq ADR 0382)`); - } - break; - } catch (err) { - console.error(`[gitea] ${key}: whether ${s.repository}#${s.number} moved could not be weighed, so it is weighed again ` + - `on its next move — ${err instanceof Error ? err.message : err}`); - } - } - } - return changed; -} - -// --- the merge tool's rule (ADR 0382 §6) ---------------------------------------------------------------------- - -/** What the rule reads beside the pull request being merged. */ -export interface GroupForge { - headChecks(owner: string, repo: string, sha: string): Promise>; -} - -/** The heads the operator's Approve covers (novox/hq ADR 0421 §9, issue 1022), as mesh-delivery hands them to the merge - * tool: `owner/repo@`, one per member, by repository. A malformed entry is refused, never skipped. */ -export function approvedHeadsOf(given: unknown): Map | undefined { - if (given === undefined || given === null) return undefined; - if (!Array.isArray(given)) throw new Refused("approved_heads must be a list of owner/repo@. Nothing was merged"); - const out = new Map(); - for (const entry of given) { - const m = /^([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)@([0-9a-f]{40}|[0-9a-f]{64})$/i.exec(String(entry)); - if (!m) throw new Refused(`approved_heads holds ${JSON.stringify(entry)}, which is not owner/repo@. Nothing was merged`); - out.set(m[1].toLowerCase(), m[2].toLowerCase()); - } - return out; -} - -/** Why a pull request's head is not one the Approve covers, in words, or nothing: its repository is not named, or names - * another head. */ -export function notApproved(approved: Map, repository: string, number: number, head: string): string | undefined { - const covered = approved.get(repository.toLowerCase()); - const at = `${repository.split("/")[1]}#${number}@${twelve(head)}`; - if (covered === undefined) return `${at} is not among the heads the Approve covers`; - if (covered !== head.toLowerCase()) return `${at} is not the head the Approve covers (${twelve(covered)})`; - return undefined; -} - -/** - * What stops a pull request whose verdict read siblings from merging, in words, or nothing: mesh/delivery-group must be - * a success at its own head and at every sibling head the verdict read, and every head read must be one the operator's - * Approve covers (ADR 0421 §9: the Approve is the review; the merge tool takes the approved heads from mesh-delivery). - * Every missing thing is named. - */ -export async function groupRefusal(forge: GroupForge, self: { owner: string; repo: string; number: number; head: string }, - siblings: SiblingNamed[], approved: Map | undefined): Promise { - const missing: string[] = []; - const members = [{ repository: `${self.owner}/${self.repo}`, number: self.number, head: self.head }, - ...siblings.map((s) => ({ repository: s.repository, number: s.number, head: s.head }))]; - for (const m of members) { - const [owner, repo] = m.repository.split("/"); - const at = `${repo}#${m.number}@${twelve(m.head)}`; - let group: HeadCheck | undefined; - try { - group = (await forge.headChecks(owner, repo, m.head))[GROUP_CONTEXT]; - } catch (err) { - missing.push(`${GROUP_CONTEXT} at ${at} could not be read (${err instanceof Error ? err.message : err})`); - continue; - } - if (group?.state !== "success") missing.push(`${GROUP_CONTEXT} is ${group?.state ?? "missing"} at ${at}`); - if (!approved) missing.push(`${at} is covered by no Approve: the merge was handed no approved heads`); - else { - const why = notApproved(approved, m.repository, m.number, m.head); - if (why) missing.push(why); - } - } - return missing.length ? missing.join("; ") : undefined; -} diff --git a/modules/gitea/test/announcing.test.ts b/modules/gitea/test/announcing.test.ts index 375124d71..d47881a12 100644 --- a/modules/gitea/test/announcing.test.ts +++ b/modules/gitea/test/announcing.test.ts @@ -12,22 +12,6 @@ const repo = (full: string, updated: string) => { return { full_name: full, owner, name, private: false, html_url: "", updated_at: updated }; }; -test("a pull request opened after the margin is looked at, by its own update time", async () => { - const { reposToLook } = await import("../pulls.ts"); - const pushed = "2026-10-09T10:00:00Z"; // the branch pushed: the repository's update time - // The pull request opened two minutes later; the last pass was at 10:02:30, so the floor is 10:01:30. - const floor = "2026-10-09T10:01:30Z"; - const repos = [repo("novox/mesh-sdk", pushed), repo("novox/hq", "2026-10-09T09:00:00Z")]; - const opened = [{ owner: "novox", name: "mesh-sdk", updated_at: "2026-10-09T10:02:00Z" }]; - assert.deepEqual(reposToLook(repos, floor, opened, false).map((r) => r.full_name), ["novox/mesh-sdk"], - "the repository of a pull request updated since the floor, though the repository itself did not move"); - assert.deepEqual(reposToLook(repos, floor, [], false).map((r) => r.full_name), [], - "without the pull request's own time nothing is looked at — the fault"); - assert.deepEqual(reposToLook(repos, floor, [], true).map((r) => r.full_name).sort(), ["novox/hq", "novox/mesh-sdk"], - "a sweep looks at every repository"); - assert.deepEqual(reposToLook(repos, "", [], false).length, 2, "the first pass looks at every repository"); -}); - test("every open pull request is read with what its base requires and what its head has (gitea_open_pulls)", async () => { const { GiteaClient } = await import("../client.ts"); const asked: string[] = []; diff --git a/modules/gitea/test/gate.test.ts b/modules/gitea/test/gate.test.ts deleted file mode 100644 index 404452c84..000000000 --- a/modules/gitea/test/gate.test.ts +++ /dev/null @@ -1,69 +0,0 @@ -import assert from "node:assert/strict"; -import { test } from "node:test"; - -// **One writer of a head's mesh/merge-gate** (novox/hq issue 446): the announcement's pending words, a recheck's pending and -// a trunk's move, each write of a head in the order it was asked. - -const SHA = "a6b08de8507c1703528277e5cefc80548dbc9bb3"; - -/** A forge that keeps the newest status per context, as gitea does, and whose writes take as long as a test says. */ -function aForge() { - const kept: Record = {}; - const written: string[] = []; - let failNext = 0; - let hold: Promise | null = null; - let release = () => {}; - return { - kept, written, - /** The next writes fail: a request the forge did not take. */ - failWrites(n = 1) { - failNext = n; - }, - /** The next writes wait until released: a request in flight. */ - holdWrites() { - hold = new Promise((r) => (release = r)); - }, - release() { - hold = null; - release(); - }, - async headChecks() { - return {}; - }, - async setCommitStatus(_o: string, _r: string, _sha: string, s: { state: string; context: string; description: string }) { - if (hold) await hold; - if (failNext > 0) { - failNext--; - throw new Error("the forge answered 502"); - } - kept[s.context] = { state: s.state, description: s.description, updated_at: new Date().toISOString() }; - written.push(`${s.state} ${s.description}`); - }, - }; -} - -// **A recheck's pending goes through the one writer** (novox/hq issue 456). - -const recheckAt = new Date("2026-10-11T01:30:00Z"); -const checkingAgain = { state: "pending" as const, context: "mesh/merge-gate", description: "checking again: main moved on" }; -const gateOf = (forge: ReturnType) => - `${forge.kept["mesh/merge-gate"].state} ${forge.kept["mesh/merge-gate"].description}`; - -test("a repository as the mesh clones it is told from another", async () => { - const { clonedAs } = await import("../gate.ts"); - assert.equal(clonedAs("http://127.0.0.1:20000/novox/hq.git", "novox", "hq"), true); - assert.equal(clonedAs("http://127.0.0.1:20000/novox/mesh-hq.git", "novox", "hq"), false); - assert.equal(clonedAs("http://127.0.0.1:20000/novox/mesh-controller.git", "novox", "hq"), false); -}); - -test("a recheck the forge does not take fails its caller, and the next write still takes its turn", async () => { - const { GateWriter } = await import("../gate.ts"); - const forge = aForge(); - const gates = new GateWriter(forge, () => recheckAt); - await gates.pending("novox", "hq", SHA); - forge.failWrites(); - await assert.rejects(gates.status("novox", "hq", SHA, checkingAgain)); - await gates.status("novox", "hq", SHA, checkingAgain); - assert.equal(gateOf(forge), "pending checking again: main moved on"); -}); - diff --git a/modules/gitea/test/guard.test.ts b/modules/gitea/test/guard.test.ts index 424b5076e..ae7348ab7 100644 --- a/modules/gitea/test/guard.test.ts +++ b/modules/gitea/test/guard.test.ts @@ -433,25 +433,16 @@ test("the two new tools are named for what mesh_search is asked, and gitea_api s // 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 () => { +test("the seat's pull answers what the forge would merge now, and its status is set on the commit", async () => { const { seatTools } = await import("../dist/seat.js"); const { runAs } = await import("@novox/mesh-sdk/callers"); const bridge = "ace.mesh-delivery-forge-bridge"; - // 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"); + // The seat's status is set through the forge's client directly (design 47 H §764; H-A-100): no chain of a head's writes. const landed: string[] = []; - let inFlight: Promise | null = null, land = () => {}; - const slow = { - headChecks: async () => ({}), - setCommitStatus: async (_o: string, _r: string, _sha: string, s: { state: string; description: string }) => { - if (inFlight) { const w = inFlight; inFlight = null; await w; } - landed.push(`${s.state} ${s.description}`); - }, - }; - 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: () => true, judge: async () => null, - watched: () => new Map() }); + const seat = seatTools(Object.assign(Object.create(client), { + setCommitStatus: async (_o: string, _r: string, _sha: string, s: { state: string; description: string }) => { landed.push(`${s.state} ${s.description}`); }, + }), { run: async () => ({ stdout: "", code: 0 }), container: "gitea", registered: () => true, judge: async () => null, + watched: () => new Map() }); const call = (verb: string, args: Record, caller = bridge) => runAs({ "mesh/caller": caller }, args, () => seat.find((t: any) => t.name === `git.${verb}`)!.run(args)) as Promise; // A read: an open pull request answers what the forge would merge now; a forge that fails is the kind failed. @@ -466,17 +457,9 @@ test("the seat's pull answers what the forge would merge now, and a head's statu assert.deepEqual([open.pull?.head, open.pull?.state, open.merging?.protected, open.merging?.required], [REVIEWED, "open", true, ["mesh/merge-gate", "mesh/repo-check"]], JSON.stringify(open)); assert.equal("body" in (open.pull ?? {}), false, "never its description"); - // Two writes of one head out of order (issue 456): a recheck's pending still in flight when the verdict is set through the - // seat; the verdict takes its turn after it and is what the head carries. - inFlight = new Promise((r) => (land = r)); - const recheck = gates.pending("novox", "mesh-catalog", REVIEWED); - const verdict = call("status", { id: "act-s", repository: "novox/mesh-catalog", commit: REVIEWED, state: "success", - context: "mesh/merge-gate", description: "passed" }); - await new Promise((r) => setImmediate(r)); - land(); - await recheck; - assert.equal((await verdict).performed, true); - assert.equal(landed.at(-1), "success passed", `the verdict lands last: ${JSON.stringify(landed)}`); + const verdict = await call("status", { id: "act-s", repository: "novox/mesh-catalog", commit: REVIEWED, state: "success", + context: "mesh/check", description: "passed" }); + assert.deepEqual([verdict.performed, landed], [true, ["success passed"]]); // A pull request the forge does not have is the kind not-found, so a caller never reads it out of the words. const gone = await call("pull", { repository: "novox/mesh-catalog", number: 404 }); assert.deepEqual([gone.pull, gone["error-kind"]], [undefined, "not-found"], JSON.stringify(gone)); @@ -511,10 +494,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, watched: () => new Map() }); + const seat = seatTools(forge as any, { run: run as any, container: "gitea", registered: () => true, judge: async () => null, watched: () => new Map() }); const call = (verb: string, args: Record, over: Record = {}) => { 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, watched: () => new Map() }); + const wrapped = seatTools(Object.assign(Object.create(forge), over) as any, { run: run as any, container: "gitea", 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; }; const rows: [string, string, Record, Record, (a: any) => unknown, unknown][] = [ diff --git a/modules/gitea/test/mainrules.test.ts b/modules/gitea/test/mainrules.test.ts index 37916cd70..9575b4361 100644 --- a/modules/gitea/test/mainrules.test.ts +++ b/modules/gitea/test/mainrules.test.ts @@ -6,7 +6,7 @@ import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { keepMainRules, mainRulesStep, LEFT_AS_SET } from "../dist/mainrules.js"; +import { keepMainRules } from "../dist/mainrules.js"; function env(body?: string): NodeJS.ProcessEnv { if (body === undefined) return {}; @@ -23,25 +23,6 @@ test("the setting is false unless the config says true", () => { assert.equal(keepMainRules(env('{"keep-main-rules":true}')), true); }); -test("false: the step never writes and says once that the rules are left", async () => { - let writes = 0; - const said: string[] = []; - const step = mainRulesStep(false, async () => { writes++; return ["a"]; }, (l) => said.push(l)); - await step(); await step(); await step(); - assert.equal(writes, 0); - assert.deepEqual(said, [LEFT_AS_SET]); - assert.match(LEFT_AS_SET, /main's rules are left as set at the forge \(keep-main-rules is false\)/); -}); - -test("true: every step puts the rules right", async () => { - let writes = 0; - const said: string[] = []; - const step = mainRulesStep(true, async () => { writes++; return ["a", "b"]; }, (l) => said.push(l)); - await step(); await step(); - assert.equal(writes, 2); - assert.deepEqual(said, ["[gitea] main's rule is right in 2 repositories"]); -}); - test("a token mint's account setup writes no protection while keep-main-rules is false, and does when true", async () => { const { setUpToolsAccount } = await import("../dist/tools-account.js"); for (const [keep, want] of [[false, 0], [true, 1]] as const) { diff --git a/modules/gitea/test/paging.test.ts b/modules/gitea/test/paging.test.ts index aefda7dee..8bf0bcca9 100644 --- a/modules/gitea/test/paging.test.ts +++ b/modules/gitea/test/paging.test.ts @@ -41,33 +41,6 @@ async function serve(count: number, heads: Record) { return { client, ...f }; } -test("a new head beyond the newest 20 open pull requests is announced, exactly once", async () => { - const { headsToAnnounce } = await import("../pulls.ts"); - // 25 open, every head announced before; #3 — the 23rd most recently updated — got a new head. - const announced: Record = {}; - for (let n = 1; n <= 25; n++) announced[`novox/hq#${n}@main`] = sha(n, "a"); - const { client, server, asked } = await serve(25, { 3: sha(3, "b") }); - try { - // The fault: the newest 20 alone do not hold it. - const newest = await client.listPullRequests("novox", "hq", { state: "open", sort: "recentupdate", limit: "20" }); - assert.deepEqual(headsToAnnounce("novox/hq", newest, announced), [], "the newest 20 miss #3's new head"); - asked.length = 0; - const said: string[] = []; - for (let pass = 0; pass < 2; pass++) { - // The sweep, as index.ts's pollPulls asks: no floor, every page. - const open = await client.listOpenPullsSince("novox", "hq", ""); - for (const p of headsToAnnounce("novox/hq", open, announced)) { - said.push(`#${p.number}@${p.head_sha}`); - announced[`novox/hq#${p.number}@${p.base}`] = String(p.head_sha); - } - } - assert.deepEqual(said, [`#3@${sha(3, "b")}`], "the new head past the newest 20, announced once over two passes"); - assert.ok(asked.every((q) => q.get("state") === "open" && q.get("sort") === "recentupdate"), "asked newest first"); - } finally { - server.close(); - } -}); - test("a pass pages until it reaches back past its floor, and no further", async () => { // 130 open pull requests, #n updated n hours after T0: page 1 holds #130–#81, page 2 #80–#31, page 3 #30–#1. const { client, server, asked } = await serve(130, {}); diff --git a/modules/gitea/test/pulls.test.ts b/modules/gitea/test/pulls.test.ts index bbc0daf13..3e62b2581 100644 --- a/modules/gitea/test/pulls.test.ts +++ b/modules/gitea/test/pulls.test.ts @@ -2,32 +2,7 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { createServer } from "node:http"; -// A pull request's merge check (novox/hq to-be 45 §9): each new head announced once, and the verdict set -// where the pull request shows it — an error never as a success. - -test("each open pull request's new head is announced once, and nothing closed or merged", async () => { - const { headsToAnnounce } = await import("../pulls.ts"); - const pulls = [ - { number: 1, title: "a", state: "open", merged: false, head_sha: "aaa", base: "main", html_url: "" }, - { number: 2, title: "b", state: "open", merged: false, head_sha: "bbb", html_url: "" }, - { number: 3, title: "c", state: "closed", merged: true, head_sha: "ccc", html_url: "" }, - { number: 4, title: "d", state: "open", merged: false, html_url: "" }, - ]; - const announced = { "novox/mesh-catalog#1@main": "aaa", "novox/mesh-catalog#2@": "old" }; - assert.deepEqual(headsToAnnounce("novox/mesh-catalog", pulls, announced).map((p) => p.number), [2], - "only a head not announced, of a pull request that is open"); -}); - -test("a pull request retargeted keeps its head and is announced again, into its new base (de-spiegel #6)", async () => { - const { headsToAnnounce, headKey } = await import("../pulls.ts"); - const was = { number: 6, title: "a", state: "open", merged: false, head_sha: "aaa", base: "old-trunk", html_url: "" }; - const announced: Record = { [headKey("novox/de-spiegel", 6, "old-trunk")]: "aaa" }; - assert.deepEqual(headsToAnnounce("novox/de-spiegel", [was], announced), [], "the same head into the same base is announced once"); - const retargeted = { ...was, base: "main" }; - assert.deepEqual(headsToAnnounce("novox/de-spiegel", [retargeted], announced).map((p) => p.number), [6], - "the same head into a new base is judged afresh"); - assert.notEqual(headKey("novox/de-spiegel", 6, "main"), headKey("novox/de-spiegel", 6, "old-trunk")); -}); +// A commit status, set where the pull request shows it (the seat git's status). test("a commit status is set on the commit, under the merge check's context", async () => { const { GiteaClient } = await import("../client.ts"); @@ -53,35 +28,3 @@ test("a commit status is set on the commit, under the merge check's context", as assert.equal(seen!.body.state, "failure"); assert.equal(seen!.body.context, "mesh/merge-gate"); }); - -// **A pending check says where it is** (novox/hq issue 446): announced, it waits in the build queue, since the time the -// operator reads — not "mapping this head onto its module graph" for the ten minutes of a controller check. -test("a head announced is pending in the build queue, since the local time it was announced", async () => { - const { pendingWords } = await import("../pulls.ts"); - assert.equal(pendingWords(new Date(2026, 9, 11, 3, 8, 50)), "waiting in the build queue since 03:08"); - assert.equal(pendingWords(new Date(2026, 9, 11, 14, 0, 0)), "waiting in the build queue since 14:00"); -}); - -// Issue 1301 (ADR 0503 §3, §5): gitea writes the controller's statuses only where the base still requires them. hq's main -// requires mesh/repo-check alone, so no mesh/merge-gate is written on its heads. -test("a base's required statuses decide which of the controller's statuses are written", async () => { - const { maintained, writesGate, CHECK_STATUS } = await import("../pulls.ts"); - assert.equal(CHECK_STATUS, "mesh/check"); - assert.deepEqual(maintained(undefined), ["mesh/merge-gate", "mesh/repo-check"], "a rule not read: as before"); - assert.deepEqual(maintained(["mesh/repo-check"]), ["mesh/repo-check"]); - assert.deepEqual(maintained(["mesh/check", "other/x"]), []); - assert.deepEqual(maintained([]), []); - assert.equal(writesGate(undefined), true); - assert.equal(writesGate(["mesh/repo-check"]), false); - assert.equal(writesGate(["mesh/check"]), false); - assert.equal(writesGate(["mesh/merge-gate", "mesh/repo-check"]), true); -}); - -test("a rule the forge gives with no contexts (null) requires nothing, and an unread rule is unknown", async () => { - const { requiredOf } = await import("../pulls.ts"); - // The forge's BranchProtection says status_check_contexts may be null (protection.ts); requiredOf takes it as it comes. - assert.deepEqual(requiredOf({ enable_status_check: true, status_check_contexts: null }), []); - assert.deepEqual(requiredOf({ enable_status_check: true, status_check_contexts: ["mesh/check", ""] }), ["mesh/check"]); - assert.deepEqual(requiredOf(null), []); - assert.equal(requiredOf(undefined), undefined); -}); diff --git a/modules/gitea/test/siblings.test.ts b/modules/gitea/test/siblings.test.ts deleted file mode 100644 index 0562b6351..000000000 --- a/modules/gitea/test/siblings.test.ts +++ /dev/null @@ -1,273 +0,0 @@ -// **A delivery group's member is judged beside its siblings, and a sibling's move puts that verdict out of date** -// (novox/hq ADR 0382 §4-§6, issue 867): the holder keeps the siblings each verdict names; a sibling's new head, close -// unmerged or base move (other than its own merge of the head that was read) sets both statuses of every member whose -// verdict names it back to pending, and runs nothing; a member merges only with its group passed and every sibling head -// read approved. - -import { test } from "node:test"; -import assert from "node:assert/strict"; -import { mkdtempSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; - -import { approvedHeadsOf, besideWords, groupRefusal, keepSiblings, namesSiblings, readSiblings, siblingOutOfDate, siblingsFile, - siblingsOf, siblingStatuses, weighSiblings, type SiblingRecord } from "../dist/siblings.js"; -import { weighTrunks } from "../dist/trunk.js"; - -const h = (c: string) => c.repeat(40); -const MEMBER_HEAD = h("a"), HOST_HEAD = h("b"), HOST_BASE = h("c"), HOST_NEW = h("d"), HOST_MOVED = h("e"), MERGE = h("f"); -const sibling = { repository: "novox/mesh-host", number: 114, head: HOST_HEAD, base: "main", base_commit: HOST_BASE }; -const verdict = { owner: "novox", repo: "mesh-controller", number: 346, commit: MEMBER_HEAD, verdict: "pass", summary: "x", id: "build-1", - trunk: h("1").slice(0, 12), siblings: [sibling], judge_from: "sibling novox/mesh-controller#346 merge 123456789abc", - gate: { verdict: "pass", summary: "every machine composes ".repeat(10) }, "repo-check": { verdict: "pass", summary: "ok" } }; - -test("the siblings a verdict names are kept per member, and read back from where the holder keeps its state", () => { - const file = siblingsFile(mkdtempSync(join(tmpdir(), "gitea-siblings-"))); - const record: SiblingRecord = { "novox/mesh-controller#346": { head: MEMBER_HEAD, siblings: siblingsOf([sibling]) } }; - keepSiblings(file, record); - assert.deepEqual(readSiblings(file), record, "kept where the holder keeps its state"); - assert.deepEqual(readSiblings(null), {}); -}); - -// --- a sibling's move ----------------------------------------------------------------------------------------- - -interface World { - host: { merged: boolean; state: string; head_sha: string; merge_commit_sha?: string }; - hostBase: string; - parents: string[]; - member: { head_sha: string; state: string; merged: boolean }; - checks: Record; - written: { sha: string; context: string; state: string; description: string }[]; - reads: string[]; -} -const world = (): World => ({ host: { merged: false, state: "open", head_sha: HOST_HEAD }, hostBase: HOST_BASE, parents: [], - member: { head_sha: MEMBER_HEAD, state: "open", merged: false }, - checks: { "mesh/merge-gate": { state: "success", description: "head aaaaaaaaaaaa merged into trunk 111111111111 beside mesh-host#114@bbbbbbbb — pass: x" }, - "mesh/repo-check": { state: "success", description: "pass: y" } }, - written: [], reads: [] }); -const forgeOf = (w: World) => ({ - async getPullRequest(owner: string, repo: string, n: number) { - w.reads.push(`${owner}/${repo}#${n}`); - return repo === "mesh-host" ? { number: n, title: "", html_url: "", ...w.host } : { number: n, title: "", html_url: "", merged: false, ...w.member }; - }, - async branchHead(_o: string, _r: string, _b: string) { return w.hostBase; }, - async commitParents() { return w.parents; }, -}); -const gatesOf = (w: World) => ({ - async outOfDate(_o: string, _r: string, sha: string, decide: (c: any) => any[] | Promise) { - const put = await decide(w.checks); - for (const s of put) { w.written.push({ sha, ...s }); w.checks[s.context] = { state: s.state, description: s.description }; } - return put; - }, -}); -const recordOf = (): SiblingRecord => ({ "novox/mesh-controller#346": { head: MEMBER_HEAD, siblings: siblingsOf([sibling]) } }); -const weigh = (w: World, record: SiblingRecord, repository = "novox/mesh-host", number?: number) => - weighSiblings(forgeOf(w) as any, gatesOf(w) as any, record, repository, number); - -test("a sibling's new head puts both statuses of the member back to pending, with the reason, and runs nothing", async () => { - const w = world(); - w.host.head_sha = HOST_NEW; - await weigh(w, recordOf(), "novox/mesh-host", 114); - assert.deepEqual(w.written.map((s) => [s.sha, s.context, s.state]), - [[MEMBER_HEAD, "mesh/merge-gate", "pending"], [MEMBER_HEAD, "mesh/repo-check", "pending"]]); - assert.equal(w.written[0].description, - "out of date: judged beside mesh-host#114 at bbbbbbbbbbbb, it is now at dddddddddddd; judged again on a recheck or when it is merged"); - assert.ok(siblingOutOfDate(w.written[0].description)); - // Already pending (out of date, or a check on its way): not written again. - w.written.length = 0; - await weigh(w, recordOf(), "novox/mesh-host", 114); - assert.deepEqual(w.written, []); -}); - -test("a sibling closed unmerged puts the member's verdict out of date", async () => { - const w = world(); - w.host.state = "closed"; - await weigh(w, recordOf(), "novox/mesh-host", 114); - assert.equal(w.written.length, 2); - assert.match(w.written[0].description, /^out of date: judged beside mesh-host#114 was closed unmerged/); -}); - -test("a move of the sibling's base puts it out of date, naming both commits", async () => { - const w = world(); - w.hostBase = HOST_MOVED; - await weigh(w, recordOf()); - assert.equal(w.written.length, 2); - assert.match(w.written[0].description, /mesh-host#114 merged onto cccccccccccc, its main is now eeeeeeeeeeee/); -}); - -test("the sibling's own merge of the head read onto the base read does not, in either order of the two merges", async () => { - // The sibling merges first (a merge commit of the base commit read and the head read). - const w = world(); - Object.assign(w.host, { merged: true, state: "closed", merge_commit_sha: MERGE }); - w.hostBase = MERGE; - w.parents = [HOST_BASE, HOST_HEAD]; - const record = recordOf(); - assert.equal(await weigh(w, record), true, "the record changes: the sibling is marked merged"); - assert.deepEqual(w.written, []); - assert.equal(record["novox/mesh-controller#346"].siblings[0].merged, true); - // A move of that base afterwards is no sibling's move: the sibling is merged. - w.hostBase = HOST_MOVED; - await weigh(w, record); - assert.deepEqual(w.written, []); - - // The member merges first: its own repository moves, which no member's verdict names as a sibling. - const m = world(); - m.member.merged = true; - await weigh(m, recordOf(), "novox/mesh-controller"); - assert.deepEqual(m.written, []); - // And the sibling then merges: still not a move. - Object.assign(m.host, { merged: true, state: "closed", merge_commit_sha: MERGE }); - m.parents = [HOST_BASE, HOST_HEAD]; - await weigh(m, recordOf()); - assert.deepEqual(m.written, []); - - // A squash is one parent: the base commit read. - const q = world(); - Object.assign(q.host, { merged: true, state: "closed", merge_commit_sha: MERGE }); - q.parents = [HOST_BASE]; - await weigh(q, recordOf()); - assert.deepEqual(q.written, []); -}); - -test("a merge of another head, or onto another base, is a move", async () => { - const other = world(); - Object.assign(other.host, { merged: true, state: "closed", merge_commit_sha: MERGE, head_sha: HOST_NEW }); - other.parents = [HOST_BASE, HOST_NEW]; - await weigh(other, recordOf()); - assert.equal(other.written.length, 2); - const onto = world(); - Object.assign(onto.host, { merged: true, state: "closed", merge_commit_sha: MERGE }); - onto.parents = [HOST_MOVED, HOST_HEAD]; - await weigh(onto, recordOf()); - assert.equal(onto.written.length, 2); -}); - -test("only the members whose verdict names the sibling are touched, and a member that moved on is dropped", async () => { - // Another sibling's move, or another repository's: nothing read, nothing written. - const w = world(); - w.host.head_sha = HOST_NEW; - await weigh(w, recordOf(), "novox/mesh-lab"); - await weigh(w, recordOf(), "novox/mesh-host", 999); - assert.deepEqual(w.written, []); - // A verdict that is none (a gate not yet judged) is left alone. - const none = world(); - none.host.head_sha = HOST_NEW; - none.checks = {}; - await weigh(none, recordOf()); - assert.deepEqual(none.written, []); - // The member has a new head: its old verdict is no verdict; the record is dropped, nothing written to the old head. - const moved = world(); - moved.host.head_sha = HOST_NEW; - moved.member.head_sha = h("9"); - const record = recordOf(); - assert.equal(await weigh(moved, record), true); - assert.deepEqual(moved.written, []); - assert.deepEqual(record, {}); - // A repository without a repo-check gets no pending one a verdict would never set. - assert.deepEqual(siblingStatuses({ "mesh/merge-gate": { state: "success" } }, "x").map((s) => s.context), ["mesh/merge-gate"]); -}); - -test("a trunk that moved tells the siblings' weighing; one first seen does not", async () => { - const told: string[] = []; - const forge = { listOpenPulls: async () => [{ number: 1, title: "", state: "open", merged: false, head_sha: h("2"), base: "main", html_url: "" }], - branchHead: async () => h("3") }; - const gates = { outOfDate: async () => [] }; - const trunks: Record = {}; - await weighTrunks(forge as any, gates as any, trunks, "novox", "mesh-host", async (b) => { told.push(b); }); - assert.deepEqual(told, [], "first seen"); - trunks["novox/mesh-host:main"] = h("4"); - await weighTrunks(forge as any, gates as any, trunks, "novox", "mesh-host", async (b) => { told.push(b); }); - assert.deepEqual(told, ["main"]); -}); - -// --- the merge rule ------------------------------------------------------------------------------------------- - -test("the group rule names every missing thing: the group status at each head read, and each head the Approve does not cover", async () => { - const self = { owner: "novox", repo: "mesh-controller", number: 346, head: MEMBER_HEAD }; - const statuses: Record = {}; - const forge = { - headChecks: async (_o: string, r: string, sha: string) => (statuses[`${r}@${sha}`] ? { "mesh/delivery-group": { state: statuses[`${r}@${sha}`] } } : {}), - }; - const siblings = siblingsOf([sibling]); - const none = await groupRefusal(forge, self, siblings, undefined); - assert.match(none!, /mesh\/delivery-group is missing at mesh-controller#346@aaaaaaaaaaaa; mesh-controller#346@aaaaaaaaaaaa is covered by no Approve: the merge was handed no approved heads; mesh\/delivery-group is missing at mesh-host#114@bbbbbbbbbbbb; mesh-host#114@bbbbbbbbbbbb is covered by no Approve/); - statuses[`mesh-controller@${MEMBER_HEAD}`] = "success"; - statuses[`mesh-host@${HOST_HEAD}`] = "pending"; - const approved = approvedHeadsOf([`novox/mesh-controller@${MEMBER_HEAD}`])!; - assert.match((await groupRefusal(forge, self, siblings, approved))!, /^mesh\/delivery-group is pending at mesh-host#114@bbbbbbbbbbbb; mesh-host#114@bbbbbbbbbbbb is not among the heads the Approve covers$/); - statuses[`mesh-host@${HOST_HEAD}`] = "success"; - assert.match((await groupRefusal(forge, self, siblings, approved))!, /^mesh-host#114@bbbbbbbbbbbb is not among the heads the Approve covers$/); - approved.set("novox/mesh-host", "c".repeat(40)); - assert.match((await groupRefusal(forge, self, siblings, approved))!, /^mesh-host#114@bbbbbbbbbbbb is not the head the Approve covers \(cccccccccccc\)$/); - approved.set("novox/mesh-host", HOST_HEAD.toLowerCase()); - assert.equal(await groupRefusal(forge, self, siblings, approved), undefined); - // A read that fails is named, never read as a pass. - const broken = { headChecks: async () => { throw new Error("the forge is away"); } }; - assert.match((await groupRefusal(broken, self, siblings, approved))!, /could not be read \(the forge is away\)/); - assert.equal(besideWords(siblings), "beside mesh-host#114@bbbbbbbb"); -}); - -test("a merged or closed member's entry is dropped, so a sibling's later push never re-pends its merged head", async () => { - // mesh-host#114 judged beside mesh-controller#346; #114 then merged; a push to #346 follows. - const w = world(); - w.host.merged = true; // the member (mesh-host#114) is merged - w.member.head_sha = h("9"); // the sibling (mesh-controller#346) has a new head - const record: SiblingRecord = { "novox/mesh-host#114": { head: HOST_HEAD, siblings: siblingsOf([ - { repository: "novox/mesh-controller", number: 346, head: MEMBER_HEAD, base: "main", base_commit: h("2") }]) } }; - assert.equal(await weigh(w, record, "novox/mesh-controller", 346), true); - assert.deepEqual(w.written, [], "the merged head is not put back to pending"); - assert.deepEqual(record, {}, "and its entry is gone"); - // On its own close or merge the member's entry goes too, whatever the siblings do. - const own = world(); - own.host.state = "closed"; - const kept = recordOf(); - const mine: SiblingRecord = { "novox/mesh-host#114": { head: HOST_HEAD, siblings: kept["novox/mesh-controller#346"].siblings } }; - assert.equal(await weigh(own, mine, "novox/mesh-host", 114), true); - assert.deepEqual(mine, {}); - assert.deepEqual(own.written, []); -}); - -// --- the composed verdict names the siblings of each member (issue 1049) -------------------------------------- - -// Issue 1049: the 2026-10-17 23:48 group (mesh-controller #375 beside mesh-catalog #353). #375's own verdict named #353 -// at its old head; #353 then got a new head, and the group's composed verdict passed for both new heads. The record still -// held the old head, so #353's own merge of the NEW head read as "merged otherwise than its head" and put #375's gate back -// to pending, and the group merged in two passes. -const composedMembers = () => [ - { owner: "novox", repo: "mesh-controller", number: 346, commit: MEMBER_HEAD, trunk: "111111111111", base: "main" }, - { owner: "novox", repo: "mesh-host", number: 114, commit: HOST_NEW, trunk: HOST_BASE.slice(0, 12), base: "main" }, -]; -/** The record a group's composed verdict once left: for each member, the other members at the heads and base commits it composed. */ -const composedRecord = (members: ReturnType): SiblingRecord => Object.fromEntries(members.map((m) => [ - `${m.owner}/${m.repo}#${m.number}`.toLowerCase(), { head: m.commit, siblings: members.filter((o) => o !== m).map((o) => ({ - repository: `${o.owner}/${o.repo}`, number: o.number, head: o.commit, base: o.base, base_commit: o.trunk })) }])); -const staleRecord = (): SiblingRecord => ({ "novox/mesh-controller#346": { head: MEMBER_HEAD, siblings: siblingsOf([sibling]) } }); - -test("without the composed verdict's siblings, a sibling's own merge of its new head is a move (the pin of issue 1049)", async () => { - const w = world(); - Object.assign(w.host, { merged: true, state: "closed", merge_commit_sha: MERGE, head_sha: HOST_NEW }); - w.parents = [HOST_BASE, HOST_NEW]; - await weigh(w, staleRecord()); - assert.equal(w.written.length, 2, "the record names the old head: the merge reads as another head's"); -}); - -test("a composed verdict names the siblings of each member at the heads and base commits it composed, so a sibling's own merge of its new head is no move (issue 1049)", async () => { - const record = composedRecord(composedMembers()); - assert.deepEqual(record["novox/mesh-controller#346"], { head: MEMBER_HEAD, - siblings: [{ repository: "novox/mesh-host", number: 114, head: HOST_NEW, base: "main", base_commit: HOST_BASE.slice(0, 12) }] }); - assert.deepEqual(record["novox/mesh-host#114"], { head: HOST_NEW, - siblings: [{ repository: "novox/mesh-controller", number: 346, head: MEMBER_HEAD, base: "main", base_commit: "111111111111" }] }); - const w = world(); - Object.assign(w.host, { merged: true, state: "closed", merge_commit_sha: MERGE, head_sha: HOST_NEW }); - w.parents = [HOST_BASE, HOST_NEW]; - await weigh(w, record); - assert.deepEqual(w.written, [], "its own merge of the head the composed check judged leaves the member's gate alone"); - assert.equal(record["novox/mesh-controller#346"].siblings[0].merged, true); - // A merge of any other head, or onto any other base, is still a move. - const other = world(); - const again = composedRecord(composedMembers()); - Object.assign(other.host, { merged: true, state: "closed", merge_commit_sha: MERGE, head_sha: HOST_NEW }); - other.parents = [HOST_MOVED, HOST_NEW]; - await weigh(other, again); - assert.equal(other.written.length, 2); -}); diff --git a/modules/gitea/test/tools-account.test.ts b/modules/gitea/test/tools-account.test.ts index f77b199ae..637d9ed1a 100644 --- a/modules/gitea/test/tools-account.test.ts +++ b/modules/gitea/test/tools-account.test.ts @@ -487,9 +487,9 @@ test("a glob rule covering main gives its approvals and override, not its status assert.deepEqual(rule.merge_whitelist_usernames, [TOOLS_ACCOUNT]); }); -test("a start with the token kept still puts main's rules right: the module's start asks for it each time (issue 948, review round 1)", async () => { - const src = await readFile(new URL("../index.ts", import.meta.url), "utf8"); - assert.match(src, /ensureMainMerges\("novox"\)/, "index.ts calls it outside the token's mint"); +// The module's start no longer puts main's rules right every ten minutes (design 47 H §764; H-A-100): ensureMainMerges is +// the mint's alone. +test("ensureMainMerges makes a main rule gone again with no token minted", async () => { const { GiteaAdmin } = await import("../dist/client.js"); const env = await environment(); forge.mainRules.delete("hq"); diff --git a/modules/gitea/test/trunk.test.ts b/modules/gitea/test/trunk.test.ts deleted file mode 100644 index 2323f0afd..000000000 --- a/modules/gitea/test/trunk.test.ts +++ /dev/null @@ -1,167 +0,0 @@ -// **A merge check's verdict holds for the trunk commit it judged** (novox/hq ADR 0323, issue 341): both statuses name -// the head and the trunk commit; a trunk's move puts the merge check of every open pull request into that trunk — and -// of none into another — back to pending with the reason, and runs nothing; a verdict that lands judged against a trunk -// that has moved since is said out of date. - -import { test } from "node:test"; -import assert from "node:assert/strict"; - -import { checkOnItsWay, outOfDateStatuses, outOfDateWords, trunkNamed, verdictAtTrunk, weighTrunks } from "../dist/trunk.js"; -import { GateWriter } from "../dist/gate.js"; - -const HEAD = "dfb1415aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; -const TRUNK = "a2c2c35bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; -const MOVED = "d28ca95ccccccccccccccccccccccccccccccccc"; - -test("a trunk's move puts an open head's merge check out of date, naming both commits, unless a check is on its way", () => { - const verdict = (trunk: string, state = "success") => ({ - "mesh/merge-gate": { state, description: `head ${HEAD.slice(0, 12)} merged into trunk ${trunk.slice(0, 12)} — pass: x` }, - "mesh/repo-check": { state, description: `head ${HEAD.slice(0, 12)} merged into trunk ${trunk.slice(0, 12)} — pass: y` } }); - const put = outOfDateStatuses(verdict(TRUNK), MOVED); - assert.deepEqual(put.map((s) => [s.context, s.state]), [["mesh/merge-gate", "pending"], ["mesh/repo-check", "pending"]]); - assert.equal(put[0].description, "out of date: judged against trunk a2c2c35bbbbb, the trunk is now d28ca95ccccc; " + - "judged again on a recheck or when it is merged"); - assert.equal(put[0].description, outOfDateWords(TRUNK, MOVED)); - assert.equal(trunkNamed(put[0].description), "a2c2c35bbbbb", "an out-of-date status still names what it judged"); - // A failure is out of date too: it judged another merge. - assert.equal(outOfDateStatuses(verdict(TRUNK, "failure"), MOVED).length, 2); - // Already judged against the trunk's head; a check on its way or already out of date; no check yet: left alone. - assert.deepEqual(outOfDateStatuses(verdict(MOVED), MOVED), []); - assert.deepEqual(outOfDateStatuses({ "mesh/merge-gate": { state: "pending", description: "building on ace since 14:02" } }, MOVED), []); - assert.deepEqual(outOfDateStatuses({ "mesh/merge-gate": { state: "pending", description: put[0].description } }, MOVED), []); - assert.deepEqual(outOfDateStatuses({}, MOVED), []); - // A head with no repository check of its own gets no pending one a verdict would never set. - assert.deepEqual(outOfDateStatuses({ "mesh/merge-gate": verdict(TRUNK)["mesh/merge-gate"] }, MOVED).map((s) => s.context), - ["mesh/merge-gate"]); - // A verdict naming no trunk, of a build seat from before the rule, judged an earlier trunk. - assert.match(outOfDateStatuses({ "mesh/merge-gate": { state: "success", description: "pass: x" } }, MOVED)[0].description, - /judged against a trunk it does not name, the trunk is now d28ca95ccccc/); - - assert.ok(checkOnItsWay({ state: "pending", description: "waiting in the build queue since 14:00" })); - assert.ok(checkOnItsWay({ state: "pending", description: "checking again: a person asked" })); - assert.ok(!checkOnItsWay({ state: "pending", description: put[0].description })); - assert.deepEqual(verdictAtTrunk(verdict(MOVED), MOVED), { current: true, onItsWay: false, judged: "d28ca95ccccc" }); - assert.equal(verdictAtTrunk(verdict(TRUNK), MOVED).current, false); -}); - -/** A forge holding open pull requests into two branches, each head's statuses, and what was written. */ -function aForge(pulls: { number: number; base: string; head: string }[], heads: Record) { - const statuses = new Map>(); - const writes: string[] = []; - const verdict = (trunk: string) => ({ - "mesh/merge-gate": { state: "success", description: `head x merged into trunk ${trunk.slice(0, 12)} — pass` }, - "mesh/repo-check": { state: "success", description: `head x merged into trunk ${trunk.slice(0, 12)} — pass` } }); - for (const p of pulls) statuses.set(p.head, verdict(heads[p.base])); - const forge = { - listOpenPulls: async () => pulls.map((p) => ({ number: p.number, title: "t", state: "open", merged: false, base: p.base, - head: "feat", head_sha: p.head, html_url: `http://forge/pulls/${p.number}` })), - branchHead: async (_o: string, _r: string, branch: string) => heads[branch], - setCommitStatus: async (_o: string, _r: string, sha: string, s: { context: string; state: string; description: string }) => { - writes.push(`${sha} ${s.context} ${s.state}`); - statuses.set(sha, { ...statuses.get(sha), [s.context]: { state: s.state, description: s.description } }); - }, - headChecks: async (_o: string, _r: string, sha: string) => statuses.get(sha) ?? {}, - }; - return { forge, writes, statuses }; -} - -test("a push to a trunk puts every open pull request into it out of date — twenty-five of them — and none into another", async () => { - const heads: Record = { main: TRUNK, release: "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" }; - const pulls = Array.from({ length: 25 }, (_, i) => ({ number: i + 1, base: "main", head: `${String(i).padStart(2, "0")}`.repeat(20) })); - pulls.push({ number: 99, base: "release", head: "9".repeat(40) }); - const { forge, writes, statuses } = aForge(pulls, heads); - const gates = new GateWriter(forge); - const trunks: Record = {}; - - // First sight: each trunk is taken as it is, and nothing is put out of date. - assert.equal(await weighTrunks(forge, gates, trunks, "novox", "mesh-host"), true); - assert.deepEqual(writes, []); - assert.equal(trunks["novox/mesh-host:main"], TRUNK); - // Nothing moved: nothing read past the trunks, nothing written. - assert.equal(await weighTrunks(forge, gates, trunks, "novox", "mesh-host"), false); - - heads.main = MOVED; - assert.equal(await weighTrunks(forge, gates, trunks, "novox", "mesh-host"), true); - assert.equal(writes.length, 50, "both statuses of each of the 25 pull requests into main"); - for (const p of pulls.filter((p) => p.base === "main")) { - const s = statuses.get(p.head)!; - assert.equal(s["mesh/merge-gate"].state, "pending"); - assert.match(s["mesh/merge-gate"].description!, /judged against trunk a2c2c35bbbbb, the trunk is now d28ca95ccccc/); - assert.equal(s["mesh/repo-check"].state, "pending"); - } - assert.equal(statuses.get("9".repeat(40))!["mesh/merge-gate"].state, "success", "a pull request into another branch is left"); - assert.equal(trunks["novox/mesh-host:main"], MOVED); - - // Weighed again, nothing more: the move was taken once, and the out-of-date statuses are left as they are. - writes.length = 0; - heads.main = "f".repeat(40); - await weighTrunks(forge, gates, trunks, "novox", "mesh-host"); - assert.deepEqual(writes, [], "a check already out of date is not written again"); -}); - -test("a trunk that cannot be read is weighed again on the next pass, never recorded half", async () => { - const heads: Record = { main: TRUNK }; - const { forge } = aForge([{ number: 1, base: "main", head: "1".repeat(40) }], heads); - const trunks: Record = { "novox/mesh-host:main": TRUNK }; - heads.main = MOVED; - const failing = { ...forge, setCommitStatus: async () => { throw new Error("the forge is away"); } }; - assert.equal(await weighTrunks(failing, new GateWriter(failing), trunks, "novox", "mesh-host"), false); - assert.equal(trunks["novox/mesh-host:main"], TRUNK, "not recorded: the next pass weighs it again"); -}); - -test("a verdict judged against a trunk newer than the pass's first read is not put out of date", async () => { - const NEWER = "ffffffffffffffffffffffffffffffffffffffff"; - const heads: Record = { main: TRUNK }; - const { forge, statuses } = aForge([{ number: 1, base: "main", head: HEAD }], heads); - const trunks: Record = { "novox/mesh-host:main": TRUNK }; - // The pass reads main at MOVED; by the head's turn the trunk moved again, and the head's check answered for it. - let reads = 0; - const moving = { ...forge, branchHead: async () => (reads++ === 0 ? MOVED : NEWER) }; - statuses.set(HEAD, { "mesh/merge-gate": { state: "success", description: `head x merged into trunk ${NEWER.slice(0, 12)} — pass` } }); - await weighTrunks(moving, new GateWriter(moving), trunks, "novox", "mesh-host"); - assert.equal(statuses.get(HEAD)!["mesh/merge-gate"].state, "success", "a fresh verdict was put out of date"); -}); - -test("a release branch's move puts every open pull request into it out of date, as a trunk's does (ADR 0358 §5)", async () => { - // novox/hq ADR 0358 §5: for a pull request into a release branch, the release branch takes the trunk's place in ADR - // 0323 — the check merges the head onto the release branch's head and names it as the trunk commit, so the release - // branch's move puts its open verdicts out of date, and leaves those into main alone. - const release = "feat/57-config-and-provisioning"; - const heads: Record = { main: TRUNK, [release]: "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" }; - const pulls = [{ number: 315, base: release, head: "3".repeat(40) }, { number: 1, base: "main", head: "1".repeat(40) }]; - const { forge, statuses } = aForge(pulls, heads); - const gates = new GateWriter(forge); - const trunks: Record = {}; - await weighTrunks(forge, gates, trunks, "novox", "mesh-controller"); - - heads[release] = MOVED; - assert.equal(await weighTrunks(forge, gates, trunks, "novox", "mesh-controller"), true); - const s = statuses.get("3".repeat(40))!; - assert.equal(s["mesh/merge-gate"].state, "pending"); - assert.match(s["mesh/merge-gate"].description!, /judged against trunk eeeeeeeeeeee, the trunk is now d28ca95ccccc/); - assert.equal(s["mesh/repo-check"].state, "pending"); - assert.equal(statuses.get("1".repeat(40))!["mesh/merge-gate"].state, "success", "a pull request into main is left"); - assert.equal(trunks[`novox/mesh-controller:${release}`], MOVED); - - // The merge tool's rule reads the same: a verdict judged against the release branch's old head is not current. - assert.equal(verdictAtTrunk({ "mesh/merge-gate": { state: "success", - description: "head x merged into trunk eeeeeeeeeeee — pass" } }, MOVED).current, false); -}); - -// Issue 1301: a trunk's move puts out of date only the controller's statuses the base still requires; on hq that is -// mesh/repo-check alone, judged by its own words; on a main requiring mesh/check, none (the checker's, ADR 0447 §4). -test("a trunk's move writes only the statuses the base still requires", async () => { - const { outOfDateStatuses, trunkNamed } = await import("../trunk.ts"); - const old = "1".repeat(40), now = "2".repeat(40); - const repo = { state: "success", description: `head ${"a".repeat(12)} merged into trunk ${old.slice(0, 12)} — pass: y` }; - const gate = { state: "success", description: `head ${"a".repeat(12)} merged into trunk ${old.slice(0, 12)} — pass: x` }; - assert.deepEqual(outOfDateStatuses({ "mesh/repo-check": repo }, now, ["mesh/repo-check"]).map((s: any) => s.context), ["mesh/repo-check"]); - assert.deepEqual(outOfDateStatuses({ "mesh/merge-gate": gate, "mesh/repo-check": repo }, now, ["mesh/repo-check"]).map((s: any) => s.context), - ["mesh/repo-check"]); - assert.deepEqual(outOfDateStatuses({ "mesh/merge-gate": gate, "mesh/repo-check": repo }, now, ["mesh/check"]), []); - assert.deepEqual(outOfDateStatuses({ "mesh/merge-gate": gate, "mesh/repo-check": repo }, now).map((s: any) => s.context), - ["mesh/merge-gate", "mesh/repo-check"], "a rule not read: as before"); - // The checker's line names its trunk as " on ". - assert.equal(trunkNamed(`pass ${"a".repeat(12)} on ${old.slice(0, 12)} | unit 3 run`), old.slice(0, 12)); - assert.equal(trunkNamed("building on shanks since 10:00"), undefined); -}); diff --git a/modules/gitea/test/watch.test.ts b/modules/gitea/test/watch.test.ts index 39572a399..5680f693c 100644 --- a/modules/gitea/test/watch.test.ts +++ b/modules/gitea/test/watch.test.ts @@ -1,9 +1,9 @@ import assert from "node:assert/strict"; -import { mock, test } from "node:test"; +import { test } from "node:test"; import type { GiteaPull } from "../client.ts"; -// **No poll of the forge** (issue 1422, notes 10 and 11): the forge's events announce heads and merges; a pass runs once at -// the start and when the receiver listens. +// **No poll of the forge for heads** (issue 1422; design 47 H §764, H-A-100): the forge's events say a pull request's new +// head as pull.updated, a merge and a close; nothing weighs a sibling or asks a merge check. const edited = (base: string) => ({ name: "forge.pull-request.edited", body: { owner: "novox", repo: "hq", number: 7, base, merged: false } }); @@ -12,10 +12,9 @@ function deps() { return { calls, d: { getRepo: async () => ({ r: 1 }), getPull: async () => ({ state: "open", base: "trunk" }) as any, - announceHead: async () => { calls.push("head"); }, + announceUpdated: async () => { calls.push("updated"); }, announceMerge: async () => { calls.push("merge"); }, announceClosed: async () => { calls.push("closed"); }, - siblingMoves: async () => { calls.push("siblings"); }, } }; } @@ -23,51 +22,15 @@ test("an edited event announces the head into the base it now has, without a pol const { actOn } = await import("../watch.ts"); const { calls, d } = deps(); await actOn(edited("trunk"), d); - assert.deepEqual(calls, ["head"]); + assert.deepEqual(calls, ["updated"]); }); test("a close without a merge is announced by its event, a merged close is left to the merge event", async () => { const { actOn } = await import("../watch.ts"); const { calls, d } = deps(); await actOn({ name: "forge.pull-request.closed", body: { owner: "novox", repo: "hq", number: 7, merged: false } }, d); - assert.deepEqual(calls, ["closed", "siblings"]); + assert.deepEqual(calls, ["closed"]); calls.length = 0; await actOn({ name: "forge.pull-request.closed", body: { owner: "novox", repo: "hq", number: 7, merged: true } }, d); assert.deepEqual(calls, []); }); - -test("no timer polls after the start: one pass ends and nothing is scheduled; a failed one is asked again", async () => { - const { startPass } = await import("../watch.ts"); - mock.timers.enable({ apis: ["setTimeout", "setInterval"] }); - try { - let runs = 0; - await startPass(async () => { runs++; }, { retryMs: 60_000, log: () => {} }); - mock.timers.tick(24 * 3600_000); - assert.equal(runs, 1, "a day later the forge was not asked again"); - let tries = 0; - const retried = startPass(async () => { if (++tries < 2) throw new Error("forge down"); }, { retryMs: 60_000, log: () => {} }); - await Promise.resolve(); await Promise.resolve(); - mock.timers.tick(60_000); - await retried; - assert.equal(tries, 2); - } finally { - mock.timers.reset(); - } -}); - -test("a start pass announces a head nobody announced, and only remembers one the forge shows a check of", async () => { - const { announceNewHeads } = await import("../watch.ts"); - const pull = (n: number, sha: string): GiteaPull => ({ number: n, state: "open", head_sha: sha, base: "main", - updated_at: new Date().toISOString() } as unknown as GiteaPull); - const announced: number[] = [], said: string[] = []; - const heads: Record = {}; - await announceNewHeads("novox/hq", [pull(1, "a".repeat(40)), pull(2, "b".repeat(40))], heads, false, - new Date(Date.now() - 24 * 3600_000).toISOString(), { - alreadyChecked: async (p) => p.number === 2, - announceHead: async (p) => { announced.push(p.number); return true; }, - missed: (w) => said.push(w), - }); - assert.deepEqual(announced, [1]); - assert.equal(heads["novox/hq#2@main"], "b".repeat(40), "the checked head is remembered, not announced"); - assert.equal(said.length, 1); -}); diff --git a/modules/gitea/trunk.ts b/modules/gitea/trunk.ts deleted file mode 100644 index c1e2d98da..000000000 --- a/modules/gitea/trunk.ts +++ /dev/null @@ -1,211 +0,0 @@ -// **A merge check's verdict holds for the trunk commit it judged** (novox/hq ADR 0323, issue 341). -// -// The build seat checks a pull request's head merged into its trunk's head at that moment — the verdict's trunk -// commit — and the verdict names both: "head 1a2b3c4d5e6f merged into trunk 7a8b9c0d1e2f", in both statuses' -// descriptions. When the trunk moves, every open pull request's verdict into it is out of date: -// -// - **the forge's holder** (index.ts) hears the move on its own — it reads each trunk's head on every pass that -// looks at the repository, never through mesh-delivery (ADR 0239 §36) — and sets mesh/merge-gate and -// mesh/repo-check on the head of every open pull request into that trunk back to pending, with the reason. -// Nothing is run for it: a recheck, a new head, or the merge tool asks the check again; -// - **the merge tool** (tools/index.ts) compares the trunk commit the head's verdict names with the trunk's head at -// the moment it is asked, merges nothing when they differ, asks the head's check once — the same announcement a -// new head makes — and never merges by itself after. -// -// Since issue 1301 (ADR 0447 §4) a main that requires mesh/check is the checker's: its line names the trunk commit it judged -// ("pass on "), the checker sets it out of date when the trunk moves, and the merge tool refuses a verdict -// of another trunk and asks nothing. The two statuses above are kept only where a base still requires them (a revert, -// pulls.ts maintained). -// -// Pure functions and two small files of the module's own state, so this is tested without a forge. - -import type { CommitStatus, GiteaClient, GiteaPull, HeadCheck } from "./client.js"; -import { CHECK_CONTEXT, WAITS_FOR_COMPOSED, maintained, requiredOf } from "./pulls.js"; - -/** A commit as a verdict names it: its first twelve characters. */ -export function twelve(sha: string | undefined): string { - return String(sha ?? "").slice(0, 12).toLowerCase(); -} - -/** Whether two commits are one, however either is abbreviated (seven characters at least). */ -export function sameCommit(a: string | undefined, b: string | undefined): boolean { - const x = String(a ?? "").toLowerCase(), y = String(b ?? "").toLowerCase(); - if (x.length < 7 || y.length < 7) return false; - return x.length <= y.length ? y.startsWith(x) : x.startsWith(y); -} - -/** What a verdict judged, as both statuses' descriptions begin (ADR 0323 §3). */ -export function judgedWords(head: string, trunk: string): string { - return `head ${twelve(head)} merged into trunk ${twelve(trunk)}`; -} - -/** The trunk commit a merge check's status names: the one its verdict judged ("merged into trunk …"), or, for a - * verdict put out of date, the one it had judged ("judged against trunk …"). Undefined when it names none, as a - * verdict of a build seat from before ADR 0323 does. */ -export function trunkNamed(description: string | undefined): string | undefined { - const m = /(?:merged into|judged against) trunk ([0-9a-f]{7,64})\b/i.exec(description ?? "") - // The checker's mesh/check line (ADR 0447 §3): " on ". - ?? /\b[0-9a-f]{12} on ([0-9a-f]{12})\b/i.exec(description ?? ""); - return m ? m[1].toLowerCase() : undefined; -} - -/** A verdict out of date, as its statuses say it (ADR 0323 §4). */ -export function outOfDateWords(judged: string | undefined, now: string): string { - const was = judged ? `judged against trunk ${twelve(judged)}` : "judged against a trunk it does not name"; - return `out of date: ${was}, the trunk is now ${twelve(now)}; judged again on a recheck or when it is merged`; -} - -/** Whether a pending gate says a check of the head is asked and not yet answered: waiting in the build queue, - * building on a machine (gate.ts), or asked again by a recheck (mesh-delivery). Such a check is not asked again. */ -export function checkOnItsWay(gate: HeadCheck | undefined): boolean { - if (!gate || gate.state !== "pending") return false; - const d = gate.description ?? ""; - return d.startsWith("waiting in the build queue") || d.startsWith("building on ") || d.startsWith("checking again"); -} - -/** Whether a gate says it waits for its group's composed check. */ -export function waitsForComposed(gate: HeadCheck | undefined): boolean { - return !!gate && gate.state === "pending" && (gate.description ?? "").startsWith(WAITS_FOR_COMPOSED); -} - -/** - * The statuses a trunk's move puts back to pending on one open pull request's head, from what the forge holds on it - * now: none when it has no merge check yet, when a check is pending (on its way, or already out of date — its - * verdict is weighed against the trunk when it lands), or when its verdict judged the trunk's head. Otherwise the - * gate, and the repository's own check when the head has one — a pending repo-check a verdict will not set would - * stand for ever (novox/hq issue 305's rule). - */ -export function outOfDateStatuses(checks: Record, trunkHead: string, required?: string[]): CommitStatus[] { - // Only the statuses the base still requires (issue 1301): the first of them the head holds judges. - const kept = maintained(required).filter((c) => checks[c]); - const judge = kept.length ? checks[kept[0]] : undefined; - if (!judge || judge.state === "pending") return []; - const judged = trunkNamed(judge.description); - if (judged && sameCommit(judged, trunkHead)) return []; - const description = outOfDateWords(judged, trunkHead); - return kept.map((context) => ({ state: "pending" as const, context, description })); -} - -/** Where the merge tool stands with a head's verdict and the trunk's head (ADR 0323 §5). */ -export interface VerdictAtTrunk { - /** The verdict judged the trunk's head: the required statuses decide, as before. */ - current: boolean; - /** A check of the head is asked and not yet answered: nothing is asked again. */ - onItsWay: boolean; - /** The trunk commit the verdict names, when it names one. */ - judged?: string; -} - -export function verdictAtTrunk(checks: Record, trunkHead: string, context = CHECK_CONTEXT): VerdictAtTrunk { - const gate = checks[context]; - const judged = trunkNamed(gate?.description); - if (checkOnItsWay(gate)) return { current: false, onItsWay: true, judged }; - return { current: !!gate && gate.state !== "pending" && !!judged && sameCommit(judged, trunkHead), onItsWay: false, judged }; -} - -/** The pending words the merge tool's ask of a check is said with: in the build queue from now, as an announced head's. */ -export function askedWords(at: Date, trunkHead: string): string { - const two = (n: number) => String(n).padStart(2, "0"); - return `waiting in the build queue since ${two(at.getHours())}:${two(at.getMinutes())}: asked by the merge tool ` + - `against trunk ${twelve(trunkHead)}`; -} - -// --- a trunk's move, weighed -------------------------------------------------------------------------------------- - -/** What weighing a trunk's move reads of the forge. */ -export interface TrunkForge { - listOpenPulls(owner: string, repo: string): Promise; - branchHead(owner: string, repo: string, branch: string): Promise; - /** The rule the forge applies to a branch: which of the controller's statuses are kept there (issue 1301). Not given, - * or not read: both, as before. */ - appliedProtection?(owner: string, repo: string, branch: string): Promise<{ enable_status_check?: boolean; status_check_contexts?: string[] | null } | null>; -} - -/** What it writes with: the merge check's one writer (gate.ts), which decides in the head's own turn. */ -export interface OutOfDateWriter { - outOfDate(owner: string, repo: string, sha: string, - decide: (checks: Record) => CommitStatus[] | Promise, target?: string): Promise; -} - -/** - * Every trunk of one repository that an open pull request merges into, read; for one that moved since it was last read - * (`trunks`, by `owner/repo:branch`, which this keeps current), the merge check of every open pull request into it put - * out of date (ADR 0323 §4). A trunk first seen is recorded as it is and nothing is put out of date. Bounded however - * many are open: one listing of the open pull requests (paged), one read of each trunk, then per open pull request into - * a trunk that moved one read and at most two writes, one at a time. A trunk that could not be weighed whole is not - * recorded, so the next pass weighs it again. Answers whether the record changed. `moved` is told of each base that moved, for the siblings whose base it is. - */ -export async function weighTrunks(forge: TrunkForge, gates: OutOfDateWriter, trunks: Record, owner: string, - name: string, moved?: (base: string) => Promise): Promise { - let changed = false; - try { - const open = (await forge.listOpenPulls(owner, name)).filter((p) => p.state === "open" && !!p.head_sha && !!p.base); - for (const base of new Set(open.map((p) => String(p.base)))) { - const key = `${owner}/${name}:${base}`.toLowerCase(); - const head = await forge.branchHead(owner, name, base); - const before = trunks[key]; - if (before && sameCommit(before, head)) continue; - if (before) { - let put = 0; - const required = forge.appliedProtection - ? requiredOf(await forge.appliedProtection(owner, name, base).catch(() => undefined)) : undefined; - for (const pull of open.filter((p) => p.base === base)) { - // The trunk is read again in the head's own turn: a verdict judged against a head newer than the pass's first - // read — the trunk moved again meanwhile, and a check answered — is not put out of date. - const written = await gates.outOfDate(owner, name, String(pull.head_sha), - async (checks) => outOfDateStatuses(checks, await forge.branchHead(owner, name, base), required), pull.html_url || undefined); - if (written.length) put++; - } - console.log(`[gitea] ${owner}/${name}'s ${base} moved from ${twelve(before)} to ${twelve(head)}: ${put} open pull ` + - `request(s) into it put out of date, nothing run (novox/hq ADR 0323)`); - // A verdict that read a pull request into this trunk as a sibling is out of date by its move too (ADR 0382 §5). - if (moved) await moved(base); - } - trunks[key] = head; - changed = true; - } - } catch (err) { - console.error(`[gitea] ${owner}/${name}: whether a trunk moved could not be weighed, so it is weighed again on the next ` + - `pass — ${err instanceof Error ? err.message : err}`); - } - return changed; -} - -// --- the announcement of a head, shared by the watcher and the merge tool --------------------------------------- - -/** `pull.updated` for one open pull request's head: what the controller asks the build seat to check (novox/hq to-be - * 45 §9). The merge tool's ask is this same announcement (ADR 0323 §5). */ -export async function announcementOf(client: GiteaClient, owner: string, name: string, cloneURL: string | undefined, - pull: GiteaPull): Promise> { - const files = await client.listPullFiles(owner, name, pull.number); - const head = String(pull.head_sha); - // What the controller maps the change onto the mesh's module graph with (novox/hq ADR 0237 as amended): which - // changed directories hold a module at the head — the merge's rule (issue 278). Not said when it could not be read; the controller then reads the change as - // touching everything built from the repository. - let moduleDirs: string[] | null = null; - try { - if (!files.truncated) moduleDirs = await client.moduleDirsAt(owner, name, head, files.paths); - } catch (err) { - console.error(`[gitea] ${owner}/${name}#${pull.number}: what the head holds could not be read — ${err instanceof Error ? err.message : err}`); - } - // The base branch's head as the head is announced: the trunk commit a verdict no build judges is said against - // (novox/hq ADR 0323 §3). Not said when it cannot be read; that verdict then names none. - const baseSHA = pull.base ? await client.branchHead(owner, name, String(pull.base)).catch(() => undefined) : undefined; - return { - owner, - repo: name, - number: pull.number, - ...(baseSHA ? { base_sha: baseSHA } : {}), - title: pull.title, - body: pull.body, - base: pull.base, - head: pull.head, - head_sha: pull.head_sha, - clone_url: cloneURL, - html_url: pull.html_url, - paths: files.paths, - paths_truncated: files.truncated, - removed: files.removed, - ...(moduleDirs ? { module_dirs: moduleDirs, module_dirs_said: true } : {}), - }; -} diff --git a/modules/gitea/updated.ts b/modules/gitea/updated.ts new file mode 100644 index 000000000..8ed934da8 --- /dev/null +++ b/modules/gitea/updated.ts @@ -0,0 +1,42 @@ +// **A pull request's new head is said as the seat git's pull.updated** (novox/hq design 47 H §764; H-A-100): from the forge's +// event of an opened, pushed, reopened or retargeted pull request alone; nothing polls for heads and no merge check is +// asked or written (the merge-check machinery went with milestone H). + +import type { GiteaClient, GiteaPull } from "./client.js"; + +/** `pull.updated` for one open pull request's head: what the controller asks the build seat to check (novox/hq to-be + * 45 §9). The merge tool's ask is this same announcement (ADR 0323 §5). */ +export async function announcementOf(client: GiteaClient, owner: string, name: string, cloneURL: string | undefined, + pull: GiteaPull): Promise> { + const files = await client.listPullFiles(owner, name, pull.number); + const head = String(pull.head_sha); + // What the controller maps the change onto the mesh's module graph with (novox/hq ADR 0237 as amended): which + // changed directories hold a module at the head — the merge's rule (issue 278). Not said when it could not be read; the controller then reads the change as + // touching everything built from the repository. + let moduleDirs: string[] | null = null; + try { + if (!files.truncated) moduleDirs = await client.moduleDirsAt(owner, name, head, files.paths); + } catch (err) { + console.error(`[gitea] ${owner}/${name}#${pull.number}: what the head holds could not be read — ${err instanceof Error ? err.message : err}`); + } + // The base branch's head as the head is announced: the trunk commit a verdict no build judges is said against + // (novox/hq ADR 0323 §3). Not said when it cannot be read; that verdict then names none. + const baseSHA = pull.base ? await client.branchHead(owner, name, String(pull.base)).catch(() => undefined) : undefined; + return { + owner, + repo: name, + number: pull.number, + ...(baseSHA ? { base_sha: baseSHA } : {}), + title: pull.title, + body: pull.body, + base: pull.base, + head: pull.head, + head_sha: pull.head_sha, + clone_url: cloneURL, + html_url: pull.html_url, + paths: files.paths, + paths_truncated: files.truncated, + removed: files.removed, + ...(moduleDirs ? { module_dirs: moduleDirs, module_dirs_said: true } : {}), + }; +} diff --git a/modules/gitea/watch.ts b/modules/gitea/watch.ts index 7dc1f135e..dc0f97468 100644 --- a/modules/gitea/watch.ts +++ b/modules/gitea/watch.ts @@ -1,29 +1,24 @@ // What the forge's events ask of the announcer, and the one pass at a start (issue 1422, notes 10 and 11). Nothing polls the -// forge: a head or merge is announced when its event is heard, and a pass over every repository runs once when the module -// starts and again when the receiver is listening, so what happened while it was down is announced too. +// forge for heads: a pull request's new head is said as pull.updated when its event is heard, a merge or a close by its +// event and by the pass over every repository's merges at the start (design 47 H §764; H-A-100). // // Apart from index.ts, which has side effects at import, so these are tested with the announcers injected. -import type { GiteaPull, GiteaRepo } from "./client.js"; -import type { Announced } from "./pulls.js"; -import { headKey, headsToAnnounce } from "./pulls.js"; import type { ForgeEvent } from "./webhook.js"; export interface ActDeps { getRepo(owner: string, repo: string): Promise; getPull(owner: string, repo: string, number: number): Promise

; - announceHead(repo: R, pull: P): Promise; + announceUpdated(repo: R, pull: P): Promise; announceMerge(repo: R, pull: P): Promise; announceClosed(repo: R, pull: P): Promise; - siblingMoves(full: string, number: number): Promise; } const HEAD_EVENTS = ["forge.pull-request.opened", "forge.pull-request.synchronized", "forge.pull-request.reopened"]; /** - * What the forge's event asks of the announcer at once: a new head is announced, a merge, a close without a merge, and a - * pull request retargeted (an edit: the head is announced into the base it now has — the base is in the head's key, so an - * edit that changed nothing about the base announces nothing). + * What the forge's event asks of the announcer at once: a new head is said, a merge, a close without a merge, and a pull + * request retargeted (an edit: the head is said into the base it now has). */ export async function actOn(event: ForgeEvent, d: ActDeps): Promise { const b = event.body as { owner?: string; repo?: string; number?: number; merged?: boolean }; @@ -37,51 +32,8 @@ export async function actOn(event: ForgeEvent, d: ActDeps): Promise< const [repo, pull] = await Promise.all([d.getRepo(b.owner, b.repo), d.getPull(b.owner, b.repo, b.number)]); if (closed) { await d.announceClosed(repo, pull); - await d.siblingMoves(`${b.owner}/${b.repo}`, b.number); return; } - if (head && pull.state === "open") await d.announceHead(repo, pull); + if (head && pull.state === "open") await d.announceUpdated(repo, pull); if (merged) await d.announceMerge(repo, pull); } - -/** - * The one pass at a start, and its retry: run now; if it fails, say so and run again after `retryMs`, until one pass has - * ended. A retry of a failed pass, never a poll: after a pass has ended nothing is scheduled. - */ -export function startPass(run: () => Promise, opts: { retryMs: number; log?: (l: string) => void }): Promise { - const log = opts.log ?? ((l) => console.error(`[gitea] ${l}`)); - return run().catch((err) => { - log(`the pass over every repository failed, asked again in ${opts.retryMs / 1000} s — ${err instanceof Error ? err.message : err}`); - return new Promise((resolve) => setTimeout(() => resolve(startPass(run, opts)), opts.retryMs)); - }); -} - -export interface HeadDeps { - /** Whether the forge shows a merge check of the head: only an announced head has one. */ - alreadyChecked(pull: GiteaPull): Promise; - /** Announce it; true when it was this call that announced it (not an event before it). */ - announceHead(pull: GiteaPull): Promise; - /** Told of a head this pass announced that no event had. */ - missed(what: string): void; -} - -/** - * The heads of one repository's open pull requests a pass announces. A head is announced when it is new and fresh (moved in - * the last day); at the first pass after a start (`primed` false) one the forge shows a merge check of was announced - * already, and is only remembered. - */ -export async function announceNewHeads(full: string, open: GiteaPull[], heads: Announced, primed: boolean, dayAgo: string, d: HeadDeps): Promise { - for (const pull of headsToAnnounce(full, open, heads)) { - const key = headKey(full, pull.number, pull.base); - const fresh = primed || (!!pull.updated_at && pull.updated_at > dayAgo); - if (fresh && !primed && await d.alreadyChecked(pull)) { - heads[key] = String(pull.head_sha); - continue; - } - if (fresh) { - if (await d.announceHead(pull)) d.missed(`${key} at ${String(pull.head_sha).slice(0, 8)}`); - } else heads[key] = String(pull.head_sha); - } -} - -export type { GiteaRepo };