diff --git a/modules/gitea/index.ts b/modules/gitea/index.ts index 6096a9720..11bf2f3d9 100644 --- a/modules/gitea/index.ts +++ b/modules/gitea/index.ts @@ -51,6 +51,8 @@ import { REGISTRATION_CHANGED_EVENT, Registrations } from "./registrations.js"; import { FailedSteps, Heads, readHeads } from "./failedsteps.js"; import { failedStepsTools } from "./tools/failedsteps.js"; import { Calls, callRetentionDays, sayUnsaid } from "./calls.js"; +import { Partials } from "./partials.js"; +import { callTools } from "./tools/calls.js"; import { seatPublish } from "@novox/mesh-sdk/runtime"; import { seat as GIT, events as GIT_EVENTS, type BranchMovedEvent, type PullClosedEvent, type PullMergedEvent, type PullUpdatedEvent } from "@novox/mesh-delivery-contracts-git"; import { seat as RUNNER, events as RUNNER_EVENTS, type StepEndedEvent } from "@novox/mesh-delivery-contracts-mesh-pipeline-runner"; @@ -405,6 +407,7 @@ let reloadHeads: () => Promise = async () => {}; // The merge calls, each written before its first merge (calls.ts; design 47 H §766). const calls = new Calls(state("calls"), () => callRetentionDays(), (line) => console.log(`[gitea] ${line}`)); // At the start, every call whose merge-called is not said says it for what landed (§766). +const partials = new Partials(state("findings"), calls, (line) => console.log(`[gitea] ${line}`)); void sayUnsaid(calls, seatPublish, (line) => console.log(`[gitea] ${line}`)).catch((err) => console.error(`[gitea] the merge calls not said could not be said at the start — ${err instanceof Error ? err.message : err}`)); const failedSteps = new FailedSteps(state("failed-steps"), (line) => console.log(`[gitea] ${line}`), (commit) => heldHeads.has(commit)); @@ -418,7 +421,8 @@ void failedSteps.expireSeen().catch((err) => console.log(`[gitea] the seen keys 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), - watched: () => registrations.watched, calls, say: seatPublish }) : []), + watched: () => registrations.watched, calls, say: seatPublish, partials }) : []), + ...callTools(partials, 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); })]); /** What the forge's event asks of the announcer at once (issue 729, 1422): see watch.ts. */ diff --git a/modules/gitea/mergecall.ts b/modules/gitea/mergecall.ts index 11c772c29..8525d1645 100644 --- a/modules/gitea/mergecall.ts +++ b/modules/gitea/mergecall.ts @@ -14,6 +14,7 @@ import type { GiteaClient } from "./client.js"; import { Refused, checkName } from "./guard.js"; import type { Judged } from "./failedsteps.js"; import { keptMember, sayCall, type Calls, type Say } from "./calls.js"; +import type { Partials } from "./partials.js"; /** What a merge call reaches beside the forge's API. */ export interface CallDeps { @@ -30,6 +31,8 @@ export interface CallDeps { now?: () => Date; /** Says a seat event on its subject under an id the bus keeps once (mesh-sdk runtime.seatPublish): merge-called (§736). */ say?: Say; + /** The findings merge-partial (partials.ts; §767). */ + partials?: Partials; } /** The forge's API a merge call uses. */ @@ -164,6 +167,8 @@ export async function mergeCall(forge: CallForge, args: Record, rest.why = `not merged: ${m.repository}#${m.number} before it was refused by the forge`; } await keep(false); + // Raised for the refused members, the landed ones delivered as any call's (§767). + await deps.partials?.raise({ ...value(false), call }); break; } } @@ -176,5 +181,9 @@ export async function mergeCall(forge: CallForge, args: Record, console.error(`[gitea] the merge call ${call} landed and its merge-called is not said yet; it is said at the next start — ${err instanceof Error ? err.message : err}`); } } + // A call that landed members clears every merge-partial whose refused members are now all landed (§767). + if (members.some((m) => m.state === "merged")) { + await deps.partials?.landed().catch((err) => console.error(`[gitea] the merge-partial findings could not be judged after the call ${call} — ${err instanceof Error ? err.message : err}`)); + } return { call, members: members.map(outcomeOf) }; } diff --git a/modules/gitea/partials.ts b/modules/gitea/partials.ts new file mode 100644 index 000000000..25d0ea0bd --- /dev/null +++ b/modules/gitea/partials.ts @@ -0,0 +1,78 @@ +// **A member refused after every member was judged is said and raised** (novox/hq design 47 H §767; H-A-1, H-A-18, +// H-A-81): when the forge refuses a member after all were judged, the call stops merging and the forge module raises the +// finding `merge-partial`, scope `delivery`, id the call, naming each refused member, severity urgent, resolver operator, +// in its own state `findings`, which the condition keeper reads. It clears it when a later call lands every refused member +// (read from its own `calls`), or by its tool `forge_partial_clear` with `call` and `why`, written in the hand-act log. + +import type { State } from "@novox/mesh-sdk/state"; +import { findingKey } from "./catalog.js"; +import type { Calls, KeptCall } from "./calls.js"; + +export const MERGE_PARTIAL = "merge-partial"; +const SCOPE = "delivery"; + +/** The key of a call's merge-partial in the state findings. */ +export const partialKey = (call: string): string => findingKey(SCOPE, call, MERGE_PARTIAL); + +/** A member's name in a finding, `#`. */ +const named = (m: { repository: string; number: number }) => `${m.repository}#${m.number}`; + +/** The merge-partial of a call the forge refused a member of after judging, as the condition keeper reads it. */ +export function partialValue(c: KeptCall, observer = "gitea"): { key: string; value: Record } { + const key = partialKey(c.call); + const landed = c.members.filter((m) => m.state === "merged").map(named); + const refused = c.members.filter((m) => m.state === "refused"); + const summary = `the merge call ${c.call} by ${c.by} landed ${landed.length ? landed.join(", ") : "none"} and not ` + + refused.map((m) => `${named(m)} (${m.why ?? "refused"})`).join(", "); + return { key, value: { + v: 1, key, kind: MERGE_PARTIAL, subject: { scope: SCOPE, id: c.call }, severity: "urgent", resolver: "operator", summary, + headline: `A merge call landed in part: ${refused.map(named).join(", ")} not merged`, + explanation: `The forge refused ${refused.map(named).join(", ")} after every member of the merge call ${c.call} was judged, so ` + + `the repositories stand half-merged. A later merge call that lands them clears this, or forge_partial_clear with why.`, + resolved: "", evidence: [{ at: c.at, said: summary }], source: `${observer}.${MERGE_PARTIAL}`, observer, at: c.at, + } }; +} + +export class Partials { + constructor(private readonly findings: State, private readonly calls: Calls, + private readonly log: (line: string) => void = () => {}) {} + + /** Raises merge-partial for a call the forge refused a member of after judging. */ + async raise(c: KeptCall): Promise { + const f = partialValue(c); + await this.findings.put(f.key, f.value); + this.log(`merge-partial raised: ${String(f.value.summary)}`); + } + + /** The calls whose merge-partial is held, newest first. */ + async held(): Promise { + const out: KeptCall[] = []; + for (const c of await this.calls.all()) if ((await this.findings.get(partialKey(c.call)))?.value) out.push(c); + return out; + } + + /** After a call landed members: every held merge-partial whose refused members a later call landed, each, is cleared. + * Answers the calls cleared. */ + async landed(): Promise { + const all = await this.calls.all(); // newest first + const cleared: string[] = []; + for (const [i, c] of all.entries()) { + if (!(await this.findings.get(partialKey(c.call)))?.value) continue; + const later = new Set(all.slice(0, i).flatMap((x) => x.members.filter((m) => m.state === "merged").map(named))); + const refused = c.members.filter((m) => m.state === "refused").map(named); + if (refused.every((r) => later.has(r))) { + await this.findings.delete(partialKey(c.call)); + cleared.push(c.call); + this.log(`merge-partial of ${c.call} cleared: a later call landed ${refused.join(", ")}`); + } + } + return cleared; + } + + /** Clears one call's merge-partial by hand (forge_partial_clear); answers whether one was held. */ + async clear(call: string): Promise { + const held = !!(await this.findings.get(partialKey(call)))?.value; + if (held) await this.findings.delete(partialKey(call)); + return held; + } +} diff --git a/modules/gitea/seat.ts b/modules/gitea/seat.ts index baa7e5bb1..2e9cda399 100644 --- a/modules/gitea/seat.ts +++ b/modules/gitea/seat.ts @@ -28,6 +28,7 @@ import { appendNote, viewBody, viewComment, type Runner } from "./delivery.js"; import type { Judged } from "./failedsteps.js"; import { mergeCall } from "./mergecall.js"; import type { Calls, Say } from "./calls.js"; +import type { Partials } from "./partials.js"; /** The verbs of the seat, in its definition's order. */ export const VERBS: readonly string[] = Object.values(GIT_VERBS); @@ -61,6 +62,8 @@ export interface SeatDeps { calls?: Calls; /** Says merge-called on the seat (mesh-sdk runtime.seatPublish; design 47 H §736). */ say?: Say; + /** The findings merge-partial (partials.ts; design 47 H §767). */ + partials?: Partials; } /** A failure as the contract says it: the forge's or this holder's refusal, or a forge that failed. */ diff --git a/modules/gitea/test/calls.test.ts b/modules/gitea/test/calls.test.ts index d45afdb06..5caeb15b0 100644 --- a/modules/gitea/test/calls.test.ts +++ b/modules/gitea/test/calls.test.ts @@ -1,5 +1,6 @@ import assert from "node:assert/strict"; import { test } from "node:test"; +import { memory } from "./memstate.ts"; // **The call is written before its first merge** (novox/hq design 47 H §766; H-A-18, H-A-47, H-A-71): the key // call. of the state calls holds by, the proved account, at, each member with its base and its state (judged before @@ -8,17 +9,6 @@ import { test } from "node:test"; const A = "a".repeat(40), B = "b".repeat(40); -export function memory() { - const kv = new Map(); - return { kv, st: { - get: async (k: string) => (kv.has(k) ? { key: k, value: structuredClone(kv.get(k)), revision: 1 } : null), - put: async (k: string, v: unknown) => { kv.set(k, structuredClone(v)); return 1; }, - delete: async (k: string) => { kv.delete(k); }, - keys: async () => [...kv.keys()].sort(), - watch: async () => {}, - } }; -} - test("a merge call is kept before its first merge, each member judged, then merged with its commit", async () => { const { mergeCall } = await import("../dist/mergecall.js"); const { Calls } = await import("../dist/calls.js"); diff --git a/modules/gitea/test/memstate.ts b/modules/gitea/test/memstate.ts new file mode 100644 index 000000000..afddeed9c --- /dev/null +++ b/modules/gitea/test/memstate.ts @@ -0,0 +1,11 @@ +// A state of the runtime in memory, for the tests of the merge calls (calls.ts, partials.ts). +export function memory() { + const kv = new Map(); + return { kv, st: { + get: async (k: string) => (kv.has(k) ? { key: k, value: structuredClone(kv.get(k)), revision: 1 } : null), + put: async (k: string, v: unknown) => { kv.set(k, structuredClone(v)); return 1; }, + delete: async (k: string) => { kv.delete(k); }, + keys: async () => [...kv.keys()].sort(), + watch: async () => {}, + } }; +} diff --git a/modules/gitea/test/merge-partial.test.ts b/modules/gitea/test/merge-partial.test.ts new file mode 100644 index 000000000..fbb1b1ffd --- /dev/null +++ b/modules/gitea/test/merge-partial.test.ts @@ -0,0 +1,67 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { memory } from "./memstate.ts"; + +// **A member refused after every member was judged is said and raised** (novox/hq design 47 H §767; acceptance test 115; +// H-A-81): a forge that refuses the second merge gives one merge-called with the first member and `refused`, and +// merge-partial (scope delivery, id the call, urgent, resolver operator) raised; a later call landing the refused member +// clears it, and forge_partial_clear clears one by hand after the hand-act log took it. + +const A = "a".repeat(40), B = "b".repeat(40); + +test("the forge refusing the second merge says what landed, raises merge-partial, and a later call landing it clears it", async () => { + const { mergeCall } = await import("../dist/mergecall.js"); + const { Calls } = await import("../dist/calls.js"); + const { Partials, partialKey } = await import("../dist/partials.js"); + const { callTools } = await import("../dist/tools/calls.js"); + const { runAs } = await import("@novox/mesh-sdk/callers"); + const { st } = memory(); + const findings = memory(); + const calls = new Calls(st as any); + const partials = new Partials(findings.st as any, calls); + const said: any[] = []; + const pulls: Record = { 5: { head: A, merged: false, refuse: false }, 9: { head: B, merged: false, refuse: true } }; + const forge = { + getPullRequest: async (_o: string, _r: string, n: number) => ({ number: n, state: "open", merged: pulls[n].merged, base: "main", + head_sha: pulls[n].head, ...(pulls[n].merged ? { merge_commit_sha: String(n).repeat(40) } : {}) }), + mergePullRequest: async (_o: string, r: string, n: number) => { + if (pulls[n].refuse) throw new Error(`Gitea API POST /repos/novox/${r}/pulls/${n}/merge: 409 merge conflict`); + pulls[n].merged = true; + }, + commitParents: async () => [], + }; + let clock = Date.parse("2026-11-20T03:00:00Z"); + const run = (call: string, numbers: number[]) => { + const args = { by: "lead@shanks", pulls: numbers.map((n) => ({ repository: n === 5 ? "novox/app" : "novox/lib", number: n, head: pulls[n].head })) }; + return runAs({ "mesh/caller": "shanks.claude-code" }, args, () => mergeCall(forge as any, args, { registered: () => true, + watched: () => new Map([["novox/app", new Set(["main"])], ["novox/lib", new Set(["main"])]]), judge: async () => null, + newCall: () => call, calls, partials, say: async (_s: string, body: unknown) => { said.push(body); }, + now: () => new Date((clock += 1000)) } as any)) as Promise; + }; + const got = await run("00000000000000aa", [5, 9]); + assert.deepEqual(got.members.map((m: any) => m.state), ["merged", "refused"]); + assert.equal(said.length, 1); + assert.deepEqual(said[0].members.map((m: any) => m.number), [5]); + assert.deepEqual(said[0].refused.map((m: any) => [m.repository, m.number]), [["novox/lib", 9]]); + assert.match(said[0].refused[0].why, /merge conflict/); + const raised: any = findings.kv.get(partialKey("00000000000000aa")); + assert.deepEqual([raised?.kind, raised?.subject, raised?.severity, raised?.resolver], ["merge-partial", { scope: "delivery", id: "00000000000000aa" }, "urgent", "operator"]); + assert.match(raised.summary, /landed novox\/app#5 and not novox\/lib#9/); + // A later call landing the refused member clears it. + pulls[9].refuse = false; + await run("00000000000000bb", [9]); + assert.equal(findings.kv.has(partialKey("00000000000000aa")), false, "cleared by the later call"); + // By hand: written in the hand-act log first, then cleared. + pulls[9] = { head: B, merged: false, refuse: true }; + pulls[5] = { head: A, merged: false, refuse: false }; + await run("00000000000000cc", [5, 9]); + assert.equal(findings.kv.has(partialKey("00000000000000cc")), true); + const acts: any[] = []; + const tool = callTools(partials, async (a) => { acts.push(a); }).find((t) => t.name === "forge_partial_clear")!; + await assert.rejects(tool.run({ call: "00000000000000cc" }), /names the call .* and why/); + const failing = callTools(partials, async () => { throw new Error("down"); }).find((t) => t.name === "forge_partial_clear")!; + await assert.rejects(failing.run({ call: "00000000000000cc", why: "dropped" }), /not recorded, so nothing was cleared/); + assert.equal(findings.kv.has(partialKey("00000000000000cc")), true); + const done: any = await runAs({ "mesh/caller": "person.jochen" }, {}, () => tool.run({ call: "00000000000000cc", why: "the lib change is dropped" })); + assert.deepEqual([done.cleared, acts[0].verb, findings.kv.has(partialKey("00000000000000cc"))], [true, "forge_partial_clear", false]); +}); diff --git a/modules/gitea/tools/calls.ts b/modules/gitea/tools/calls.ts new file mode 100644 index 000000000..15ddaa5a4 --- /dev/null +++ b/modules/gitea/tools/calls.ts @@ -0,0 +1,33 @@ +// The tools of the forge module's merge calls (novox/hq design 47 H §766, §767): forge_partial_clear clears a call's +// merge-partial by hand, written in the hand-act log before it is done. + +import type { ToolDefinition } from "@novox/mesh-sdk/tools"; +import { callerOf } from "@novox/mesh-sdk/callers"; +import type { HandAct } from "@novox/mesh-sdk/views"; +import type { Partials } from "../partials.js"; + +const word = (v: unknown): string => (typeof v === "string" ? v.trim() : ""); + +export function callTools(partials: Partials, acts: (act: HandAct) => Promise): ToolDefinition[] { + return [ + { + name: "forge_partial_clear", + description: "Clears the finding merge-partial of one merge call (a call the forge refused a member of after every member was judged), " + + "with why, when its refused members are not to be merged. Written in the hand-act log first (design 47 H §767).", + input: { type: "object", required: ["call", "why"], properties: { + call: { type: "string", description: "the merge call, 16 lowercase hex characters" }, + why: { type: "string", description: "why it is cleared, in plain words" } } }, + run: async (args: Record) => { + const call = word(args.call), why = word(args.why); + if (!/^[0-9a-f]{16}$/.test(call) || !why) throw new Error("forge_partial_clear names the call (16 lowercase hex characters) and why"); + const by = callerOf(args); + try { + await acts({ what: `cleared the merge-partial of the merge call ${call}`, why: `${why} (${by})`, cause: "merge-partial-cleared", verb: "forge_partial_clear" }); + } catch (err) { + throw new Error(`the hand act was not recorded, so nothing was cleared: ${err instanceof Error ? err.message : String(err)}`); + } + return { call, cleared: await partials.clear(call), why, by }; + }, + }, + ]; +}