From e2ddcd6ed343ae73679cabfe3cb591d7ad61de27 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Wed, 4 Nov 2026 11:56:47 +0000 Subject: [PATCH] Tighten six guard, usage, runner and dupe-group edge cases Item and repo writes no longer accept a PR grant; a push refuses an ask or rerun grant. Claude steps write a usage row only when a call answered. The runner checks the group and claims the job in one transaction. A duplicate close computes a missing text hash and skips when the text changed. A batch PR with no members is not in scope. safe-merge refuses an empty --head. --- src/act/dupe-groups.ts | 7 +++++-- src/agents/step.ts | 2 +- src/core/facts.ts | 2 +- src/core/guard.ts | 4 ++-- src/github/write.ts | 4 +++- src/merge/safe-merge.ts | 4 ++-- src/runner/runner.ts | 18 ++++++++++++++---- test/safe-merge.test.ts | 1 + 8 files changed, 29 insertions(+), 13 deletions(-) diff --git a/src/act/dupe-groups.ts b/src/act/dupe-groups.ts index afc869ea..0440d344 100644 --- a/src/act/dupe-groups.ts +++ b/src/act/dupe-groups.ts @@ -5,6 +5,7 @@ // is skipped, and so is a whole decision whose answer or roles changed (undo, refresh) while the run went on. import type { DatabaseSync } from "node:sqlite"; import { audit } from "../dash/audit.ts"; +import { embedHash } from "../itemhash.ts"; import { backlogHeld } from "../dupes/held.ts"; import { inPilot } from "../pilot.ts"; import { textsFor } from "../dupes/texts.ts"; @@ -128,8 +129,10 @@ export async function actOnGroups(db: DatabaseSync, run: GroupRun): Promise(db: DatabaseSync, step: Claud } if (!values.length && fallback !== null) { values.push(fallback); rest = undefined; } const ok = values.length > 0; - if (opts.usage && !(opts.usage.skipWhen?.({ ok }) ?? false) && (step.provider === "claude" || sawUsage || opts.usage.withoutUsage)) { + if (opts.usage && !(opts.usage.skipWhen?.({ ok }) ?? false) && (sawUsage || opts.usage.withoutUsage)) { const u = opts.usage; const total = sizeOf(step, input); const items = u.items ? u.items(ok, total, rest === undefined ? 0 : sizeOf(step, rest)) : total - (rest === undefined ? 0 : sizeOf(step, rest)); diff --git a/src/core/facts.ts b/src/core/facts.ts index 95e5935d..fe64c907 100644 --- a/src/core/facts.ts +++ b/src/core/facts.ts @@ -171,7 +171,7 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[] const integration = !r.not_integration; // An integration PR takes part when its repo's pipeline is on or every member is in scope (fast track); its head is the batch tip, where the run approvals are recorded. const batchRow = integration ? (batchOf.get(r.repo, r.number) as { id: number; commit_sha: string } | undefined) : undefined; - const inScope = integration ? pipelineOn_.has(r.repo) || (!!batchRow && membersOf(db, batchRow.id).every((m) => inPilot(db, r.repo, m.number))) : !!r.in_pilot; + const inScope = integration ? pipelineOn_.has(r.repo) || (!!batchRow && (members => members.length > 0 && members.every((m) => inPilot(db, r.repo, m.number)))(membersOf(db, batchRow.id))) : !!r.in_pilot; const head = batchRow?.commit_sha ?? headOf(r); const lines = (r.additions ?? 0) + (r.deletions ?? 0); const base: PrFacts = { diff --git a/src/core/guard.ts b/src/core/guard.ts index 4a63be41..9c43b50d 100644 --- a/src/core/guard.ts +++ b/src/core/guard.ts @@ -27,8 +27,8 @@ export type Guarded = { readonly [guarded]: t export type GuardedItem = { readonly [guarded]: true; readonly scope: "item"; readonly action: ItemWant; readonly repo: string; readonly number: number }; /** What the guard let through for a repo-level write (a label set, a fork, an issue, a batch branch): the approval and the global switch held. Only `guardRepo` makes one. */ export type GuardedRepo = { readonly [guarded]: true; readonly scope: "repo"; readonly need: Approval | null; readonly repo: string }; -/** Any of the three: what a write function that is not tied to one kind of target accepts. */ -export type Grant = Guarded | GuardedItem | GuardedRepo; +/** What an item or repo write accepts. A PR grant is left out: no caller writes with one, and a merge or CI grant must not type-check there. */ +export type Grant = GuardedItem | GuardedRepo; export type Refused = { refused: string }; /** An item action to guard: the Plan must hold the kind with the bucket, decision and source given. */ export type ItemWant = Want & { decisionId?: string; source?: string }; diff --git a/src/github/write.ts b/src/github/write.ts index 0bcbc9ef..24bbf5ec 100644 --- a/src/github/write.ts +++ b/src/github/write.ts @@ -32,7 +32,7 @@ const repoName = (slug: string): string => (slug.startsWith(`${ORG}/`) ? slug.sl const refOf = (repo: string, number: number): string => `${repo}#${number}`; /** A grant covers writes to its own repo (and, for a PR or item grant, its own number); a write elsewhere is a bug. */ -function covers(g: Grant, repo: string, number?: number): void { +function covers(g: Guarded | Grant, repo: string, number?: number): void { if (g.repo !== repo || (number !== undefined && "number" in g && g.number !== number)) throw new Error(`the guard covers ${g.repo}${"number" in g ? `#${g.number}` : ""}, not ${repo}${number === undefined ? "" : `#${number}`}`); } @@ -271,6 +271,8 @@ export function ghRerunMainFailed(w: Writer, g: GuardedRepo, exec: Exec, o: { re /** Pushes `sha` to a PR's branch `branch` of `remote` (owner/name); refused by git when the branch is no longer at the guarded head. */ export function pushBranch(w: Writer, git: Pick, action: string, g: Guarded, o: { remote: string; branch: string; sha: string }, details: Details = {}): Promise { + const b = g.action.bucket; + if ((g.action.kind === "fixup" && b === "ask") || (g.action.kind === "cifix" && b === "rerun")) throw new Error(`a ${g.action.kind}:${b} grant does not allow a push`); return pushed(w, git, action, refOf(g.repo, g.number), o, `--force-with-lease=refs/heads/${o.branch}:${g.head}`, details); } diff --git a/src/merge/safe-merge.ts b/src/merge/safe-merge.ts index 3c6af072..cf059ff7 100644 --- a/src/merge/safe-merge.ts +++ b/src/merge/safe-merge.ts @@ -174,10 +174,10 @@ export function parseSafeMergeArgs(args: string[]): { repo: string; pr: string; if (name === undefined) return null; if (rest[i] === "--allow-pending") allow.push(name); else if (rest[i] === "--allow-failed") allowFailed.push(name); - else if (rest[i] === "--head") head = name; + else if (rest[i] === "--head") { if (!name) return null; head = name; } else return null; } - return { repo, pr, method, allow, allowFailed, ...(head ? { head } : {}) }; + return { repo, pr, method, allow, allowFailed, ...(head !== undefined && { head }) }; } export const commands = { diff --git a/src/runner/runner.ts b/src/runner/runner.ts index efca02db..bb905b0c 100644 --- a/src/runner/runner.ts +++ b/src/runner/runner.ts @@ -249,8 +249,8 @@ export class Runner { this.db.prepare("UPDATE jobs SET state = 'failed', ended_at = ?, error = ? WHERE id = ? AND state = 'queued'").run(now(), "This step does not exist in this build.", q.id); continue; } - if ([...this.running.values()].some((r) => r.group === step.group) || this.outsideRunning(steps).has(step.group)) continue; - this.start(q.id, step.group); + if ([...this.running.values()].some((r) => r.group === step.group)) continue; + this.start(q.id, step.group, steps); } } @@ -260,9 +260,19 @@ export class Runner { return new Set(rows.filter((r) => !this.running.has(r.id)).map((r) => steps.get(r.step)?.group ?? r.step)); } - private start(id: number, group: string): void { + private start(id: number, group: string, steps: Awaited>): void { const logPath = join(this.o.logs, `job-${id}.log`); - const claimed = this.db.prepare("UPDATE jobs SET state = 'running', started_at = ?, log_path = ? WHERE id = ? AND state = 'queued'").run(now(), logPath, id).changes; + // The group check and the claim are one write transaction, so a command-line run cannot take the group in between. + this.db.exec("BEGIN IMMEDIATE"); + let claimed: number | bigint; + try { + claimed = this.outsideRunning(steps).has(group) ? 0 + : this.db.prepare("UPDATE jobs SET state = 'running', started_at = ?, log_path = ? WHERE id = ? AND state = 'queued'").run(now(), logPath, id).changes; + this.db.exec("COMMIT"); + } catch (e) { + this.db.exec("ROLLBACK"); + throw e; + } if (!claimed) return; const fd = openSync(logPath, "a"); let child: ChildProcess; diff --git a/test/safe-merge.test.ts b/test/safe-merge.test.ts index 3e4fddce..90d9d487 100644 --- a/test/safe-merge.test.ts +++ b/test/safe-merge.test.ts @@ -47,6 +47,7 @@ test("--allow-failed accepts a listed failed check only while the merge state is for (const state of ["CLEAN", "UNSTABLE", "HAS_HOOKS"]) assert.equal(refuseView(v({ mergeStateStatus: state }), [], [sonar]), null, state); for (const state of ["UNKNOWN", "BEHIND", "DIRTY", "DRAFT"]) assert.notEqual(refuseView(v({ mergeStateStatus: state }), [], [sonar]), null, state); assert.deepEqual(parseSafeMergeArgs(["o/r", "5", "--merge", "--allow-failed", sonar]), { repo: "o/r", pr: "5", method: "--merge", allow: [], allowFailed: [sonar] }); + assert.equal(parseSafeMergeArgs(["o/r", "5", "--merge", "--head", ""]), null); }); test("a failed workflow run is accepted only when every failed job in it is a listed check", async () => {