From d6cd0af9ee4ac976342ebd1bff8fc56bacb348e7 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 10:33:28 +0000 Subject: [PATCH 1/3] feat(ci): claim the red-main fix atomically and collect incident evidence (#2944) Co-Authored-By: Claude Opus 5.5 --- .agents/skills/work-issue/SKILL.md | 16 ++ .../work-issue/references/ci-and-merge.md | 7 + .../skills/work-issue/references/red-main.md | 139 +++++++++++ docs/decisions/ci-utility.md | 49 ++++ scripts/red-main-coordinator.ts | 6 +- scripts/red-main-incident.ts | 223 ++++++++++++++++++ scripts/red-main.ts | 71 +++++- tests/fixtures/red-main-incident/record.json | 39 +++ tests/red-main-incident.test.ts | 201 ++++++++++++++++ 9 files changed, 746 insertions(+), 5 deletions(-) create mode 100644 .agents/skills/work-issue/references/red-main.md create mode 100644 scripts/red-main-incident.ts create mode 100644 tests/fixtures/red-main-incident/record.json create mode 100644 tests/red-main-incident.test.ts diff --git a/.agents/skills/work-issue/SKILL.md b/.agents/skills/work-issue/SKILL.md index f1be15a346..d07fb2a220 100644 --- a/.agents/skills/work-issue/SKILL.md +++ b/.agents/skills/work-issue/SKILL.md @@ -324,6 +324,22 @@ type/area/`contract` labels; do not copy readiness labels onto the PR. monitor actual completion. Do not ask again for permission included in the end-to-end request. +## Main is red + +When any command prints `main red at ` (the hosted gate, a cancelled +proof run or an `integrate.ts` refusal), or `bun scripts/integrate.ts +main-status --json` reports `"red": true`, follow +[the red-main incident steps](references/red-main.md). In short: stop +requesting proof for non-fix PRs; find the one incident issue named in the +record and link duplicates there; try `bun scripts/red-main-incident.ts claim` +— exactly one orchestrator wins it; the claimant assesses the cause, records +its choice of a fix PR or a targeted revert PR (or explicit uncertainty) with +the rationale, declares the PR and merges it through the normal route; +everyone else posts evidence with `bun scripts/red-main-incident.ts evidence`. +Keep coding and running fast checks meanwhile, and resume proof when +`main-status` reports green. Never open a second incident. This does not end +or replace work on your own claimed issue. + ## Finish or hand off For a stack, the actor merging it owns closure reconciliation for **every diff --git a/.agents/skills/work-issue/references/ci-and-merge.md b/.agents/skills/work-issue/references/ci-and-merge.md index a779e39c98..bcb8b7abfa 100644 --- a/.agents/skills/work-issue/references/ci-and-merge.md +++ b/.agents/skills/work-issue/references/ci-and-merge.md @@ -276,6 +276,13 @@ actor/time/reason and immediately removes the old authority without waiving proof. Native candidates need separately qualified prefix integration; this ordinary command rejects them. See the [binding decision](../../../../docs/decisions/ci-utility.md#exact-candidate-integration-reservation). +While main is red, `confirm` and `merge` refuse every PR that is not a +declared fix, and hosted proof containing the bad commit is refused or +cancelled. Do not retry it; follow [the red-main incident steps](red-main.md) +and resume when `main-status` reports green. A fix or targeted revert PR for +the incident is declared with `bun scripts/integrate.ts declare-fix ` and +then uses this same reservation and merge procedure. + ## Merge and verify Before every merge, assign the PR and each completed/advanced issue a release diff --git a/.agents/skills/work-issue/references/red-main.md b/.agents/skills/work-issue/references/red-main.md new file mode 100644 index 0000000000..cf33f0cfa1 --- /dev/null +++ b/.agents/skills/work-issue/references/red-main.md @@ -0,0 +1,139 @@ +# Main is red: work the incident + +Read this when any command prints `main red at ` — the hosted gate on +your PR's proof, a cancelled proof run, or `bun scripts/integrate.ts` +refusing `confirm`/`merge` — or when `main-status` reports `"red": true`. +The binding rules are in +[the CI decision](../../../../docs/decisions/ci-utility.md#red-main-record-and-coordinator). + +Every orchestrator notices the same red main. Coordination goes only through +the red-main record and the one incident issue the coordinator filed; never +message other agents and never open a second incident. + +## Identities + +- **Worker ID**: the claim token of the issue you are working + (`wi--`). A worker with no claimed issue makes a fresh token. +- **Orchestrator ID**: a stable random token for your orchestrator session, + such as `orch-`, reused by every worker it runs. + +Both are opaque tokens (`[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}`), written to the +public coordination ref and incident: never a hostname, path, account or +person's name. + +## Detect + +1. Read `bun scripts/integrate.ts main-status --json` at most every 15 + minutes while you hold work that needs proof, and immediately after any + `main red at ` message. Never tight-poll. +2. `red: false` means there is nothing to do here. `record.open` is the + incident: `firstBad`, `failures`, `incident` (issue number or `null`), + `fixes` (declared PRs) and `claim`. +3. `incident: null` means the coordinator has not filed the issue yet. Do not + file one. Keep working (see **Wait and resume**) and read again later. + +## Stop doomed proof + +4. Do not request proof, `confirm` or `merge` for a PR that is not a declared + fix while main is red. Do not rerun refused or cancelled proof. Your own + issue stays claimed and its branch stays yours. + +## Find and deduplicate + +5. Open the incident issue named in the record and read its body and every + comment, newest last, before doing anything else. +6. Search open issues for each failing test path. Link any other open issue + for the same failure on the incident instead of filing a new one: + + ```sh + bun scripts/red-main-incident.ts evidence --worker --orchestrator \ + --kind duplicate --issue --summary "" + ``` + + Use `--kind related --issue ` for an issue that is related but not the + same failure. + +## Claim the fix, or contribute + +7. If `record.open.claim` is absent, `null` or expired, try to claim it: + + ```sh + bun scripts/red-main-incident.ts claim --worker --orchestrator + ``` + + The claim is written into the record by compare-and-swap, so exactly one + concurrent claimant wins. The winner is mirrored to the issue's assignment + and a claim comment; taking over an expired claim posts a takeover comment + naming the previous claimant. +8. `Fix claimed by worker … until …` means someone else owns the fix. You are + a contributor: go to step 12. +9. As claimant, renew before the term ends (one hour from the last renewal), + for example with every push or every 30 minutes: + `bun scripts/red-main-incident.ts renew --worker --orchestrator `. + If you stop owning the fix, `release` it so the next orchestrator can claim + it without waiting for expiry. + +## Claimant: assess, choose, record + +10. Make a quick assessment, then choose a **fix PR** or a **targeted revert + PR**. Decide from causal and current-tree evidence: a bisect or probe that + reproduces at the first bad SHA and passes at its parent, a reproduction + on current main, the failing assertion and the change that reaches it. A + red check or the latest squash alone is not proof of cause. Assess what + depends on or conflicts with the suspect change: a revert must preserve + unrelated and later good work, so revert only the causal change and only + when later squashes do not build on it. When neither change is + supportable yet, say so and keep gathering evidence; do not guess. +11. Record the choice and its rationale on the incident before opening the PR: + + ```sh + bun scripts/red-main-incident.ts evidence --worker --orchestrator \ + --kind decision --choice fix|revert|uncertain --sha \ + --summary "" --details-file + ``` + + The details file states the cause evidence, the dependency and conflict + assessment and, for `uncertain`, what evidence is still missing. + Then open the PR against `main` with `Refs #`, and declare it, + whether it is a fix or a revert: + `bun scripts/integrate.ts declare-fix `. It then follows the normal + route — required review, `check:pr`, hosted candidate proof, the + collisions check and `bun scripts/integrate.ts confirm --issues …` — + through the declared-red-main-fix path. Nothing merges it automatically, + and a failed fix gets a new assessment and decision comment, not a retry + loop. After the squash lands, read the main run that includes the failing + set: only its green result clears the record. Record the merged SHA and + that run on the incident as the exact recovery proof. + +## Everyone: add evidence + +12. Post what you learn in the fixed format, one comment per finding: + + ```sh + bun scripts/red-main-incident.ts evidence --worker --orchestrator \ + --kind reproduction|bisect|log|ruled-out|fix-attempt \ + --summary "" [--sha ] [--details-file ] + ``` + + Kinds: `reproduction` (reproduced or not, at which SHA), `bisect` (probe + results), `log` (an excerpt with a link to the run), `ruled-out` (a + hypothesis eliminated, and how), `fix-attempt` (an alternative change you + tried). Read existing evidence first and do not repeat it. The command + refuses while the incident is pending and never files an issue. +13. A contributor may also open an alternative declared fix PR when the + claimant's approach stalls; it names the incident and follows the same + route. Add a `fix-attempt` evidence comment linking it. + +Add `--dry-run` to any command above to print the writes instead of sending +them. + +## Wait and resume + +14. While red, a worker whose proof was refused or cancelled keeps working + without proof: code, `bun run test `, `bun run check:pr`, review + fixes, or evidence on the incident. Do not release your own issue's claim + because main is red. +15. Resume proof when `main-status` reports `red: false`: rebase only if your + change requires it, then request candidate confirmation as usual. A + claimant whose fix merged releases nothing extra: clearing the record + removes the claim. diff --git a/docs/decisions/ci-utility.md b/docs/decisions/ci-utility.md index 9c39456671..3b118e8fe8 100644 --- a/docs/decisions/ci-utility.md +++ b/docs/decisions/ci-utility.md @@ -1491,6 +1491,55 @@ trusted default-branch tooling and parses candidate logs and artifacts as data. `red-main-probe.yml` has `contents: read` only. The incident workflow in the skills is #2944, and the expedited fix merge is #2940. +#### Incident workflow and recovery + +[#2944](https://github.com/schlessera/brain-kit/issues/2944) is how +orchestrators work the incident, following the 2026-10-25 direction that they +work it like any other issue. All coordination goes through the record and +the incident issue; agents never message each other. + +- **One fix claim, written atomically.** `bun scripts/red-main-incident.ts + claim` writes `open.claim` into `red-main.json` through the same + compare-and-swap: the claimant's worker and orchestrator IDs (opaque + tokens), when it claimed and last renewed, and an expiry one hour after the + last renewal. Exactly one concurrent claimant wins. The claim is then + mirrored to the issue's assignment and a claim comment; a rerun mirrors it + once. `renew` extends the term and `release` drops it. An expired claim may + be taken over: the new claim keeps the expired claimant in `takeover`, and a + takeover comment names it on the issue. Clearing the record removes the + claim. Records written before claims existed have no `claim` field and stay + valid; a present claim is validated strictly. +- **Evidence in one fixed format.** `evidence` appends one comment to the + incident named in the record: a marker, the kind, the incident, who posted + it and whether they hold the claim, an optional SHA or issue, a one-line + summary and fenced details. The kinds are reproduction, bisect, log, + ruled-out, related, duplicate, fix-attempt and decision. A duplicate issue is + linked on the incident and pointed back to it. The command never files an + issue and never writes the record, and every comment passes the leakage + gate. +- **Waiting.** Workers whose proof was refused or cancelled keep coding, run + fast checks or add evidence, and resume proof when `main-status` reports + green. + +The [2026-11-02 recovery ruling](https://github.com/schlessera/brain-kit/issues/2934#issuecomment-6574880345) +settles what the claimant does: + +1. **Fix or targeted revert, from evidence.** After a quick assessment the + incident owner chooses a fix PR or a targeted revert PR. The choice rests on + causal and current-tree evidence; a red check or the latest squash alone is + not proof of cause. +2. **The rationale is on the incident.** The owner records the choice and why + as `decision` evidence (`--choice fix|revert|uncertain`, with details), + including the dependency and conflict assessment. A revert preserves + unrelated and later good work. When neither change is supportable, the + decision says so explicitly instead of guessing. +3. **The normal route, no shortcut.** Either PR is a declared fix and follows + normal required review, proof and recorded merge handling, including the + declared-red-main-fix route where it applies, with exact proof of the + resulting main: the green main run that includes the failing set. The + controller never merges anything itself, and there is no unbounded + recovery loop; a failed attempt gets a new assessment and decision. + ### Hosted heavy feedback on draft heads The [#2939 ruling](https://github.com/schlessera/brain-kit/issues/2939#issuecomment-6403978097) diff --git a/scripts/red-main-coordinator.ts b/scripts/red-main-coordinator.ts index 67b23f45e4..7b8649b78d 100644 --- a/scripts/red-main-coordinator.ts +++ b/scripts/red-main-coordinator.ts @@ -48,7 +48,7 @@ export const incidentMarker = (run: number) => ``; /** Retries a compare-and-swap update of the shared record; an unchanged result writes nothing. */ -export async function updateRecord(io: CoordinatorIO, update: (record: RedMainRecord, now: number) => RedMainRecord): Promise<{ before: RedMainRecord; after: RedMainRecord }> { +export async function updateRecord(io: Pick, update: (record: RedMainRecord, now: number) => RedMainRecord): Promise<{ before: RedMainRecord; after: RedMainRecord }> { for (let attempt = 0; attempt < 5; attempt++) { const snapshot = io.read(), after = update(snapshot.redMain, await io.now()); if (after === snapshot.redMain) return { before: snapshot.redMain, after }; @@ -114,7 +114,9 @@ export async function ensureIncident(io: CoordinatorIO, record: RedMainRecord): "Failing tests and categories:", ...open.failures.map(f => `- \`${f.test ?? f.category}\` (${f.category}; ${f.reasons.join(", ")}; run ${runUrl(io, f.run)})`), "", - "Hosted proof whose merge ref contains this commit is refused or cancelled, and `integrate.ts` refuses ordinary confirmation and merges, until a main run that includes this failing set is green. Declare a fix PR with `bun scripts/integrate.ts declare-fix `; the first confirmed fix wins. Only a green main run that includes this failing set clears the record, so a failure that does not reproduce still needs a declared fix to land.", + "Hosted proof whose merge ref contains this commit is refused or cancelled, and `integrate.ts` refuses ordinary confirmation and merges, until a main run that includes this failing set is green. Declare a fix or targeted revert PR with `bun scripts/integrate.ts declare-fix `; the first confirmed fix wins. Only a green main run that includes this failing set clears the record, so a failure that does not reproduce still needs a declared fix to land.", + "", + "One orchestrator owns the fix: it claims it with `bun scripts/red-main-incident.ts claim --worker --orchestrator `, which writes the claim into the red-main record. After a quick assessment the claimant chooses a fix PR or a targeted revert PR from causal and current-tree evidence, and records that choice and its rationale here as `decision` evidence; a red check or the latest squash alone is not proof of cause. Every other orchestrator adds evidence here with `bun scripts/red-main-incident.ts evidence ...` instead of opening another issue.", ...(related.size ? ["", `Possibly related open issues: ${[...related].sort((a, b) => a - b).map(n => `#${n}`).join(", ")}.`] : []), ]; const issue = await io.write("POST", `repos/${io.repository}/issues`, { diff --git a/scripts/red-main-incident.ts b/scripts/red-main-incident.ts new file mode 100644 index 0000000000..d346792fae --- /dev/null +++ b/scripts/red-main-incident.ts @@ -0,0 +1,223 @@ +/** + * Red-main incident workflow (#2944): one orchestrator claims the fix, every + * orchestrator adds evidence to the one incident issue the coordinator filed. + * + * bun scripts/red-main-incident.ts claim --worker --orchestrator + * bun scripts/red-main-incident.ts renew --worker --orchestrator + * bun scripts/red-main-incident.ts release --worker --orchestrator + * bun scripts/red-main-incident.ts evidence --worker --orchestrator --kind --summary + * [--sha ] [--issue ] [--details-file ] [--choice fix|revert|uncertain] + * + * Add `--dry-run` to print every write instead of sending it, and + * `--record --repository ` to replay against a fixture record + * with no GitHub or Git access at all. + * + * The claim is written into the red-main record through the coordination ref's + * compare-and-swap, then mirrored to the issue's assignment and a claim comment. + * Nothing here opens an incident issue: that is the coordinator's job alone. + */ +import { randomUUID } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { scanText } from "./check-leakage"; +import { GitReservationStore, reservationServerTime } from "./integration-reservation"; +import { claimFix, liveClaim, parseRedMain, releaseFixClaim, renewFixClaim, type Claimant, type FixClaim, type RedIncident, type RedMainRecord } from "./red-main"; +import { updateRecord, type Snapshot } from "./red-main-coordinator"; + +export interface IncidentIO { + repository: string; + /** GitHub login the claim is mirrored to as an assignee. */ + login: string; + read(): Snapshot; + publish(snapshot: Snapshot, record: RedMainRecord): boolean; + /** Authoritative GitHub server time. */ + now(): Promise; + json(path: string): Promise; + write(method: "POST" | "DELETE", path: string, body?: unknown): Promise; +} + +export const EVIDENCE_KINDS = ["reproduction", "bisect", "log", "ruled-out", "related", "duplicate", "fix-attempt", "decision"] as const; +/** The claimant's recovery choice (#2934 ruling, 2026-11-02): a fix PR, a targeted revert PR, or explicit uncertainty. */ +export const CHOICES = ["fix", "revert", "uncertain"] as const; +export type Choice = typeof CHOICES[number]; +export type EvidenceKind = typeof EVIDENCE_KINDS[number]; +export interface Evidence extends Claimant { kind: EvidenceKind; summary: string; sha?: string; issue?: number; details?: string; choice?: Choice; } + +export const claimMarker = (run: number, claim: FixClaim) => ``; +export const releaseMarker = (run: number, claim: FixClaim) => ``; +export const evidenceMarker = (run: number, kind: EvidenceKind) => ``; +const iso = (ms: number) => new Date(ms).toISOString(); +const short = (sha: string) => sha.slice(0, 12); +const issuePath = (io: IncidentIO, n: number) => `repos/${io.repository}/issues/${n}`; + +export function claimComment(open: RedIncident, claim: FixClaim): string { + const lines = [claimMarker(open.run, claim)]; + if (claim.takeover) lines.push(`**Fix claim takeover**: worker \`${claim.worker}\` (orchestrator \`${claim.orchestrator}\`) took over the fix from worker \`${claim.takeover.worker}\` (orchestrator \`${claim.takeover.orchestrator}\`), whose claim expired at ${iso(claim.takeover.expired)}.`); + else lines.push(`**Fix claimed** by worker \`${claim.worker}\` (orchestrator \`${claim.orchestrator}\`).`); + lines.push("", `- Main red at \`${short(open.firstBad)}\` (record run ${open.run}).`, `- Claim term ends ${iso(claim.expires)}; the claimant renews it with \`bun scripts/red-main-incident.ts renew\`. After it ends, any orchestrator may take the fix over with \`claim\`.`, + "- Everyone else: add evidence here with `bun scripts/red-main-incident.ts evidence`; do not open another incident."); + return lines.join("\n"); +} + +/** Fenced so any backtick run inside the details stays literal. */ +function fence(text: string): string { + const longest = Math.max(2, ...[...text.matchAll(/`+/g)].map(m => m[0].length)); + const bar = "`".repeat(longest + 1); + return `${bar}text\n${text.replace(/\s+$/, "")}\n${bar}`; +} + +/** The fixed evidence format: a marker, a heading naming the kind, then fixed fields in a fixed order. */ +export function formatEvidence(open: RedIncident, evidence: Evidence, role: "claimant" | "contributor"): string { + const lines = [evidenceMarker(open.run, evidence.kind), `### Red-main evidence: ${evidence.kind}`, "", + `- **Incident:** main red at \`${short(open.firstBad)}\` (record run ${open.run})`, + `- **From:** worker \`${evidence.worker}\`, orchestrator \`${evidence.orchestrator}\` (${role})`]; + if (evidence.sha) lines.push(`- **SHA:** \`${evidence.sha}\``); + if (evidence.choice) lines.push(`- **Choice:** ${evidence.choice === "fix" ? "fix PR" : evidence.choice === "revert" ? "targeted revert PR" : "uncertain: neither a fix nor a revert is supportable yet"}`); + if (evidence.issue) lines.push(`- **${evidence.kind === "duplicate" ? "Duplicate" : "Related"} issue:** #${evidence.issue}`); + lines.push(`- **Summary:** ${evidence.summary}`); + if (evidence.details?.trim()) lines.push("", fence(evidence.details)); + return lines.join("\n"); +} + +function validateEvidence(evidence: Evidence): void { + if (!EVIDENCE_KINDS.includes(evidence.kind)) throw new Error(`Evidence kind must be one of ${EVIDENCE_KINDS.join(", ")}`); + if (!evidence.summary.trim() || evidence.summary.length > 300 || /[\r\n]/.test(evidence.summary)) throw new Error("Evidence needs a one-line summary of at most 300 characters"); + if (evidence.sha !== undefined && !/^[a-f0-9]{7,40}$/.test(evidence.sha)) throw new Error("Invalid evidence SHA"); + if (evidence.issue !== undefined && !(Number.isSafeInteger(evidence.issue) && evidence.issue > 0)) throw new Error("Invalid related issue number"); + if ((evidence.kind === "related" || evidence.kind === "duplicate") !== (evidence.issue !== undefined)) throw new Error("--issue is required for, and only for, related and duplicate evidence"); + if ((evidence.kind === "decision") !== (evidence.choice !== undefined)) throw new Error("--choice is required for, and only for, decision evidence"); + if (evidence.choice !== undefined && !CHOICES.includes(evidence.choice)) throw new Error(`--choice must be one of ${CHOICES.join(", ")}`); + if (evidence.kind === "decision" && !evidence.details?.trim()) throw new Error("Decision evidence needs --details-file with the causal and current-tree rationale"); + if ((evidence.details?.length ?? 0) > 20_000) throw new Error("Evidence details are limited to 20000 characters; link a run or artifact instead"); +} + +function publicText(name: string, text: string): string { + if (scanText(name, text).length) throw new Error(`The ${name} failed the leakage gate; remove personal data before posting`); + return text; +} + +/** Whether a comment carrying this marker already exists, so a rerun after a crash mirrors once. */ +async function hasComment(io: IncidentIO, incident: number, marker: string, since: number): Promise { + const comments = await io.json(`${issuePath(io, incident)}/comments?since=${encodeURIComponent(iso(since))}&per_page=100`); + return Array.isArray(comments) && comments.some((comment: { body?: string }) => comment.body?.includes(marker)); +} + +export type ClaimMode = "claim" | "renew" | "release"; +export interface ClaimResult { mode: ClaimMode; incident: number; claim: FixClaim | null; action: string | undefined; mirrored: string[]; } + +/** Writes the claim through the record's compare-and-swap first; the issue only mirrors what won. */ +export async function claimIncident(io: IncidentIO, who: Claimant, mode: ClaimMode): Promise { + const transition = mode === "claim" ? claimFix : mode === "renew" ? renewFixClaim : releaseFixClaim; + const { before, after } = await updateRecord(io, (record, now) => transition(record, who, now)); + const open = after.open!, incident = open.incident!, mirrored: string[] = []; + if (mode === "claim") { + const claim = open.claim!; + await io.write("POST", `${issuePath(io, incident)}/assignees`, { assignees: [io.login] }); + mirrored.push("assignee"); + if (!await hasComment(io, incident, claimMarker(open.run, claim), claim.claimed)) { + await io.write("POST", `${issuePath(io, incident)}/comments`, { body: publicText("claim comment", claimComment(open, claim)) }); + mirrored.push(claim.takeover ? "takeover-comment" : "claim-comment"); + } + } else if (mode === "release") { + const held = before.open!.claim!; + await io.write("POST", `${issuePath(io, incident)}/comments`, { body: [releaseMarker(open.run, held), + `**Fix claim released** by worker \`${held.worker}\` (orchestrator \`${held.orchestrator}\`). Any orchestrator may claim the fix with \`bun scripts/red-main-incident.ts claim\`.`].join("\n") }); + await io.write("DELETE", `${issuePath(io, incident)}/assignees`, { assignees: [io.login] }); + mirrored.push("release-comment", "assignee-removed"); + } + return { mode, incident, claim: open.claim ?? null, action: after.last?.action, mirrored }; +} + +/** Appends one evidence comment to the record's incident; it never files an issue and never writes the record. */ +export async function postEvidence(io: IncidentIO, evidence: Evidence): Promise<{ incident: number; role: "claimant" | "contributor"; body: string }> { + validateEvidence(evidence); + const open = io.read().redMain.open; + if (!open) throw new Error("Main is not red; there is no incident to add evidence to"); + if (open.incident === null) throw new Error("Incident pending: the coordinator has not filed the incident issue yet; retry when main-status names it"); + const now = await io.now(), claim = open.claim ?? null; + const role = liveClaim(claim, now) && claim.worker === evidence.worker && claim.orchestrator === evidence.orchestrator ? "claimant" : "contributor"; + const body = publicText("evidence comment", formatEvidence(open, evidence, role)); + await io.write("POST", `${issuePath(io, open.incident)}/comments`, { body }); + if (evidence.kind === "duplicate") await io.write("POST", `${issuePath(io, evidence.issue!)}/comments`, { + body: publicText("duplicate note", `This failure is tracked by red-main incident #${open.incident} (main red at \`${short(open.firstBad)}\`). Please add evidence there.`) }); + return { incident: open.incident, role, body }; +} + +export function parseArgs(argv: string[]): { command: string; flags: Map; dryRun: boolean } { + const [command = "", ...rest] = argv, flags = new Map(); + let dryRun = false; + const known = ["--worker", "--orchestrator", "--kind", "--summary", "--sha", "--issue", "--details-file", "--choice", "--record", "--repository", "--now"]; + for (let index = 0; index < rest.length; index++) { + const key = rest[index]!; + if (key === "--dry-run") { dryRun = true; continue; } + const value = rest[++index]; + if (!known.includes(key) || value === undefined || value.startsWith("--") || flags.has(key)) throw new Error(`Invalid option ${key}`); + flags.set(key, value); + } + if ((flags.has("--record") || flags.has("--now")) && !dryRun) throw new Error("--record and --now only replay a fixture with --dry-run"); + return { command, flags, dryRun }; +} + +async function gh(args: string[], input?: string): Promise { + const child = Bun.spawn(["gh", ...args], { stdout: "pipe", stderr: "pipe", stdin: input === undefined ? "ignore" : new TextEncoder().encode(input) }); + const [code, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + if (code !== 0) throw new Error(`gh ${args.slice(0, 2).join(" ")} failed: ${err.trim()}`); + return out.trim(); +} + +async function liveIO(): Promise { + const repository = await gh(["repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner"]); + const store = new GitReservationStore(process.cwd()); + const remote = store.git(["remote", "get-url", "origin"]).replace(/^git@github.com:/, "https://github.com/").replace(/\.git$/, ""); + if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository) || remote !== `https://github.com/${repository}`) throw new Error("Authenticated repository and origin differ"); + return { + repository, login: await gh(["api", "user", "--jq", ".login"]), + read: () => store.read(), + publish: (snapshot, record) => store.publishRedMain(snapshot as Parameters[0], record), + async now() { return reservationServerTime(await gh(["api", "--include", "-H", "Cache-Control: no-cache", `repos/${repository}/git/ref/heads/main?red_main_clock=${randomUUID()}`])); }, + async json(path) { return JSON.parse(await gh(["api", path])); }, + async write(method, path, body) { + const out = await gh(["api", "-X", method, path, ...(body === undefined ? [] : ["--input", "-"])], body === undefined ? undefined : JSON.stringify(body)); + return out ? JSON.parse(out) : {}; + }, + }; +} + +/** Dry runs read for real (or from a fixture record) and print every write instead of sending it. */ +function dryRunIO(base: IncidentIO | null, flags: Map, print: (line: string) => void): IncidentIO { + const fixture = flags.get("--record"); + let snapshot: Snapshot = fixture ? { oid: "fixture", redMain: parseRedMain(readFileSync(fixture, "utf8")) } : base!.read(); + const repository = flags.get("--repository") ?? base?.repository ?? ""; + if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository)) throw new Error("A fixture dry run needs --repository "); + const fixedNow = flags.has("--now") ? Date.parse(flags.get("--now")!) : NaN; + if (flags.has("--now") && !Number.isFinite(fixedNow)) throw new Error("Invalid --now"); + return { + repository, login: base?.login ?? "fixture-login", + read: () => snapshot, + publish(_seen, record) { snapshot = { oid: `${snapshot.oid}+1`, redMain: record }; print(`DRY_RUN record ${JSON.stringify(record)}`); return true; }, + now: async () => Number.isFinite(fixedNow) ? fixedNow : base ? base.now() : Date.now(), + json: async path => base ? base.json(path) : [], + async write(method, path, body) { print(`DRY_RUN ${method} ${path} ${JSON.stringify(body ?? null)}`); return {}; }, + }; +} + +export async function main(argv: string[], print: (line: string) => void = console.log): Promise { + const { command, flags, dryRun } = parseArgs(argv); + const usage = "usage: bun scripts/red-main-incident.ts claim|renew|release|evidence --worker --orchestrator [--kind --summary [--sha ] [--issue ] [--details-file ] [--choice fix|revert|uncertain]] [--dry-run [--record --repository --now ]]"; + if (!["claim", "renew", "release", "evidence"].includes(command)) throw new Error(usage); + const who = { worker: flags.get("--worker") ?? "", orchestrator: flags.get("--orchestrator") ?? "" }; + if (!who.worker || !who.orchestrator) throw new Error(usage); + const base = flags.has("--record") ? null : await liveIO(); + const io = dryRun ? dryRunIO(base, flags, print) : base!; + if (command === "evidence") { + const issue = flags.get("--issue"), file = flags.get("--details-file"); + if (issue !== undefined && !/^[1-9]\d*$/.test(issue)) throw new Error("Invalid related issue number"); + const result = await postEvidence(io, { ...who, kind: (flags.get("--kind") ?? "") as EvidenceKind, summary: flags.get("--summary") ?? "", + ...(flags.has("--sha") ? { sha: flags.get("--sha")! } : {}), ...(issue ? { issue: Number(issue) } : {}), ...(flags.has("--choice") ? { choice: flags.get("--choice") as Choice } : {}), ...(file ? { details: readFileSync(file, "utf8") } : {}) }); + print(JSON.stringify({ evidence: true, incident: result.incident, role: result.role, dryRun })); + } else print(JSON.stringify({ ...await claimIncident(io, who, command as ClaimMode), dryRun })); +} + +if (import.meta.main) { + try { await main(process.argv.slice(2)); } + catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exit(1); } +} diff --git a/scripts/red-main.ts b/scripts/red-main.ts index 15f54c7209..a63b3ad3e5 100644 --- a/scripts/red-main.ts +++ b/scripts/red-main.ts @@ -20,12 +20,27 @@ export interface RedIncident { /** First red after the last run where the failing set actually ran green. */ firstBad: string; run: number; opened: number; failures: RedFailure[]; incident: number | null; fixes: number[]; reported: string[]; + /** The one fix claim (#2944). Absent in records written before claims existed. */ + claim?: FixClaim | null; } +/** Who owns the fix: a worker under an orchestrator, for a renewable term. */ +export interface FixClaim { + worker: string; orchestrator: string; claimed: number; renewed: number; expires: number; + /** The expired claim this one replaced, when it was a takeover. */ + takeover: { worker: string; orchestrator: string; expired: number } | null; +} +export interface Claimant { worker: string; orchestrator: string; } export interface Suspect { test: string; category: Category; run: number; sha: string; at: number; probe: "pending" | "passed" | "failed" | "unavailable"; issue: number | null; } export interface RedMainRecord { version: 1; updated: number; open: RedIncident | null; suspects: Suspect[]; - last: { action: "open" | "update" | "refine" | "incident" | "declare-fix" | "report" | "clear" | "suspect" | "probe"; at: number; run: number | null } | null; + last: { action: Action; at: number; run: number | null } | null; } +const ACTIONS = ["open", "update", "refine", "incident", "declare-fix", "report", "clear", "suspect", "probe", "claim", "takeover", "renew-claim", "release-claim"] as const; +type Action = typeof ACTIONS[number]; +/** A claim lasts this long from its last renewal; after that any orchestrator may take it over. */ +export const CLAIM_TERM_MS = 60 * 60_000; +/** Opaque worker and orchestrator tokens: never a hostname, path or person's name. */ +export const AGENT_ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/; export const emptyRedMain = (): RedMainRecord => ({ version: 1, updated: 0, open: null, suspects: [], last: null }); const positive = (value: unknown) => Number.isSafeInteger(value) && Number(value) > 0; @@ -46,13 +61,25 @@ export function parseRedMain(text: string): RedMainRecord { !Array.isArray(o.reported) || o.reported.length > MAX_REPORTED || !o.reported.every(sha => SHA.test(sha)) || o.failures.some(f => !f || !(f.test === null || testPath(f.test)) || !category(f.category) || f.verdict !== "real" || !Array.isArray(f.reasons) || !f.reasons.length || f.reasons.some(x => typeof x !== "string" || !/^[a-z0-9-]{1,60}$/.test(x)) || !positive(f.run) || !SHA.test(f.sha)))) throw new Error("Invalid red-main incident"); + if (o && Object.hasOwn(o, "claim") && !validClaim(o.claim, o, r.updated)) throw new Error("Invalid red-main fix claim"); if (r.last !== null && (!r.last || r.last.at !== r.updated || !(r.last.run === null || positive(r.last.run)) || - !["open", "update", "refine", "incident", "declare-fix", "report", "clear", "suspect", "probe"].includes(r.last.action))) throw new Error("Invalid red-main audit"); + !ACTIONS.includes(r.last.action))) throw new Error("Invalid red-main audit"); return r; } +const agent = (value: unknown) => typeof value === "string" && AGENT_ID.test(value); +function validClaim(c: FixClaim | null | undefined, o: RedIncident, updated: number): boolean { + if (c === null) return true; + const t = c?.takeover; + return !!c && typeof c === "object" && Object.keys(c).sort().join() === "claimed,expires,orchestrator,renewed,takeover,worker" && + agent(c.worker) && agent(c.orchestrator) && o.incident !== null && [c.claimed, c.renewed, c.expires].every(Number.isSafeInteger) && + o.opened <= c.claimed && c.claimed <= c.renewed && c.renewed <= updated && c.expires === c.renewed + CLAIM_TERM_MS && + (t === null || !!t && typeof t === "object" && Object.keys(t).sort().join() === "expired,orchestrator,worker" && + agent(t.worker) && agent(t.orchestrator) && Number.isSafeInteger(t.expired) && t.expired <= c.claimed); +} + const key = (f: { test: string | null; category: Category }) => f.test ?? `category:${f.category}`; -function next(record: RedMainRecord, now: number, action: NonNullable["action"], run: number | null, change: Partial): RedMainRecord { +function next(record: RedMainRecord, now: number, action: Action, run: number | null, change: Partial): RedMainRecord { if (!Number.isSafeInteger(now) || now < record.updated) throw new Error("Backwards or unavailable clock"); return parseRedMain(JSON.stringify({ ...record, ...change, version: 1, updated: now, last: { action, at: now, run } })); } @@ -89,6 +116,44 @@ export function declareFix(record: RedMainRecord, pr: number, now: number): RedM return next(record, now, "declare-fix", null, { open: { ...record.open, fixes: [...record.open.fixes, pr] } }); } +const sameClaimant = (claim: FixClaim, who: Claimant) => claim.worker === who.worker && claim.orchestrator === who.orchestrator; +export const liveClaim = (claim: FixClaim | null | undefined, now: number): claim is FixClaim => !!claim && now < claim.expires; +function claimable(record: RedMainRecord, who: Claimant): RedIncident { + if (!agent(who.worker) || !agent(who.orchestrator)) throw new Error("Worker and orchestrator IDs must be opaque tokens matching " + AGENT_ID); + if (!record.open) throw new Error("Main is not red; there is no incident to claim"); + if (record.open.incident === null) throw new Error("Incident pending: the coordinator has not filed the incident issue yet; retry when main-status names it"); + return record.open; +} + +/** + * Claims the fix, written through the same compare-and-swap as the rest of the + * record. A live claim by someone else refuses; an expired one is taken over and + * the takeover kept in the claim. The live claimant claiming again renews. + */ +export function claimFix(record: RedMainRecord, who: Claimant, now: number): RedMainRecord { + const open = claimable(record, who), held = open.claim ?? null; + if (liveClaim(held, now)) { + if (sameClaimant(held, who)) return renewFixClaim(record, who, now); + throw new Error(`Fix claimed by worker ${held.worker} (orchestrator ${held.orchestrator}) until ${new Date(held.expires).toISOString()}; add evidence to incident #${open.incident} instead`); + } + const takeover = held && !sameClaimant(held, who) ? { worker: held.worker, orchestrator: held.orchestrator, expired: held.expires } : null; + return next(record, now, takeover ? "takeover" : "claim", open.run, { open: { ...open, + claim: { worker: who.worker, orchestrator: who.orchestrator, claimed: now, renewed: now, expires: now + CLAIM_TERM_MS, takeover } } }); +} + +export function renewFixClaim(record: RedMainRecord, who: Claimant, now: number): RedMainRecord { + const open = claimable(record, who), held = open.claim ?? null; + if (!liveClaim(held, now) || !sameClaimant(held, who)) throw new Error("This worker holds no live fix claim; claim again (an expired claim may already be taken over)"); + return next(record, now, "renew-claim", open.run, { open: { ...open, claim: { ...held, renewed: now, expires: now + CLAIM_TERM_MS } } }); +} + +/** The claimant may release its own claim, even after expiry; never a successor's. */ +export function releaseFixClaim(record: RedMainRecord, who: Claimant, now: number): RedMainRecord { + const open = claimable(record, who), held = open.claim ?? null; + if (!held || !sameClaimant(held, who)) throw new Error("This worker does not hold the fix claim"); + return next(record, now, "release-claim", open.run, { open: { ...open, claim: null } }); +} + export function reportLanded(record: RedMainRecord, sha: string, now: number): RedMainRecord { if (!record.open || record.open.reported.includes(sha)) return record; return next(record, now, "report", null, { open: { ...record.open, reported: [...record.open.reported, sha].slice(-MAX_REPORTED) } }); diff --git a/tests/fixtures/red-main-incident/record.json b/tests/fixtures/red-main-incident/record.json new file mode 100644 index 0000000000..c561649b81 --- /dev/null +++ b/tests/fixtures/red-main-incident/record.json @@ -0,0 +1,39 @@ +{ + "version": 1, + "updated": 1783814460000, + "open": { + "firstBad": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "run": 100, + "opened": 1783814400000, + "failures": [ + { + "test": "packages/core/tests/raft.test.ts", + "category": "unit", + "verdict": "real", + "reasons": [ + "in-affected-closure", + "assertion-signature" + ], + "run": 100, + "sha": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + } + ], + "incident": 500, + "fixes": [], + "reported": [], + "claim": { + "worker": "wi-20260712-penelope", + "orchestrator": "orch-ithaca", + "claimed": 1783814460000, + "renewed": 1783814460000, + "expires": 1783818060000, + "takeover": null + } + }, + "suspects": [], + "last": { + "action": "claim", + "at": 1783814460000, + "run": 100 + } +} diff --git a/tests/red-main-incident.test.ts b/tests/red-main-incident.test.ts new file mode 100644 index 0000000000..c9f599109e --- /dev/null +++ b/tests/red-main-incident.test.ts @@ -0,0 +1,201 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { GitReservationStore } from "../scripts/integration-reservation"; +import { attachIncident, CLAIM_TERM_MS, claimFix, emptyRedMain, openRed, parseRedMain, releaseFixClaim, renewFixClaim, type RedMainRecord } from "../scripts/red-main"; +import { claimIncident, evidenceMarker, formatEvidence, postEvidence, type IncidentIO } from "../scripts/red-main-incident"; +import type { Snapshot } from "../scripts/red-main-coordinator"; + +const ROOT = resolve(import.meta.dir, ".."); +const FIXTURE = join(ROOT, "tests/fixtures/red-main-incident/record.json"); +const scratch: string[] = []; +afterEach(() => { for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true }); }); +const NOW = Date.parse("2026-07-12T00:00:00Z"), B = "b".repeat(40); +const PENELOPE = { worker: "wi-20260712-penelope", orchestrator: "orch-ithaca" }; +const TELEMACHUS = { worker: "wi-20260712-telemachus", orchestrator: "orch-pylos" }; + +function redWithIncident(): RedMainRecord { + const red = openRed(emptyRedMain(), { firstBad: B, run: 100, failures: [{ test: "packages/core/tests/raft.test.ts", category: "unit", verdict: "real", reasons: ["in-affected-closure"], run: 100, sha: B }] }, NOW); + return attachIncident(red, 500, NOW + 1000); +} + +/** In-memory record store plus a fake issue API that records every write. */ +function fakeIssues(record: RedMainRecord, start = NOW + 2000) { + let snapshot: Snapshot = { oid: "0", redMain: record }, version = 0, clock = start; + const writes: { method: string; path: string; body: any }[] = []; + const io: IncidentIO = { + repository: "odysseus/brain-kit", login: "odysseus", + read: () => snapshot, + publish(seen, next) { if (seen.oid !== String(version)) return false; snapshot = { oid: String(++version), redMain: parseRedMain(JSON.stringify(next)) }; return true; }, + now: async () => clock, + async json(path) { + const match = /issues\/(\d+)\/comments/.exec(path); + if (match) return writes.filter(w => w.method === "POST" && w.path.endsWith(`/issues/${match[1]}/comments`)).map(w => ({ body: w.body.body })); + throw new Error(`Unexpected offline API ${path}`); + }, + async write(method, path, body) { writes.push({ method, path, body }); return {}; }, + }; + return { io, writes, record: () => snapshot.redMain, at: (ms: number) => { clock = ms; }, + comments: (issue: number) => writes.filter(w => w.method === "POST" && w.path === `repos/odysseus/brain-kit/issues/${issue}/comments`).map(w => w.body.body as string) }; +} + +describe("fix claim record", () => { + test("records without a claim still parse, a malformed claim is refused, and claims need a filed incident", () => { + const legacy = redWithIncident(); + expect(Object.hasOwn(legacy.open!, "claim")).toBe(false); + expect(parseRedMain(JSON.stringify(legacy))).toEqual(legacy); + const claimed = claimFix(legacy, PENELOPE, NOW + 2000); + expect(parseRedMain(JSON.stringify(claimed))).toEqual(claimed); + expect(claimed.open!.claim).toEqual({ ...PENELOPE, claimed: NOW + 2000, renewed: NOW + 2000, expires: NOW + 2000 + CLAIM_TERM_MS, takeover: null }); + const tamper = (claim: unknown) => JSON.stringify({ ...claimed, open: { ...claimed.open, claim } }); + expect(() => parseRedMain(tamper({ ...claimed.open!.claim, expires: NOW + 10 * CLAIM_TERM_MS })), "CLAIM_TERM_IS_FIXED").toThrow("Invalid red-main fix claim"); + expect(() => parseRedMain(tamper({ ...claimed.open!.claim, worker: "Odysseus of Ithaca" }))).toThrow("Invalid red-main fix claim"); + expect(() => parseRedMain(tamper({ ...claimed.open!.claim, extra: 1 }))).toThrow("Invalid red-main fix claim"); + expect(() => parseRedMain(tamper("penelope"))).toThrow("Invalid red-main fix claim"); + expect(parseRedMain(tamper(null)).open!.claim).toBeNull(); + const pending = openRed(emptyRedMain(), { firstBad: B, run: 100, failures: legacy.open!.failures }, NOW); + expect(() => claimFix(pending, PENELOPE, NOW + 1)).toThrow("Incident pending"); + expect(() => claimFix(emptyRedMain(), PENELOPE, NOW)).toThrow("Main is not red"); + }); + + test("a live claim refuses others, renews for its owner, and is released only by its owner", () => { + let record = claimFix(redWithIncident(), PENELOPE, NOW + 2000); + expect(() => claimFix(record, TELEMACHUS, NOW + 3000)).toThrow("Fix claimed by worker wi-20260712-penelope"); + expect(() => renewFixClaim(record, TELEMACHUS, NOW + 3000)).toThrow("no live fix claim"); + expect(() => releaseFixClaim(record, TELEMACHUS, NOW + 3000)).toThrow("does not hold the fix claim"); + record = claimFix(record, PENELOPE, NOW + 5000); + expect(record.last?.action).toBe("renew-claim"); + expect(record.open!.claim).toMatchObject({ claimed: NOW + 2000, renewed: NOW + 5000, expires: NOW + 5000 + CLAIM_TERM_MS }); + expect(() => renewFixClaim(record, PENELOPE, NOW + 5000 + CLAIM_TERM_MS)).toThrow("no live fix claim"); + record = releaseFixClaim(record, PENELOPE, NOW + 6000); + expect(record.open!.claim).toBeNull(); + expect(claimFix(record, TELEMACHUS, NOW + 7000).open!.claim).toMatchObject({ ...TELEMACHUS, takeover: null }); + }); +}); + +describe("claiming the incident", () => { + test("two orchestrators claiming concurrently through the shared ref produce exactly one claim", async () => { + const dir = mkdtempSync(join(tmpdir(), "odysseus-red-main-claim-")); scratch.push(dir); + const git = (cwd: string, ...args: string[]) => { + const p = Bun.spawnSync(["git", "-c", "commit.gpgsign=false", ...args], { cwd, stdout: "pipe", stderr: "pipe", env: { ...process.env, + GIT_AUTHOR_NAME: "Odysseus", GIT_AUTHOR_EMAIL: "odysseus@example.invalid", GIT_COMMITTER_NAME: "Odysseus", GIT_COMMITTER_EMAIL: "odysseus@example.invalid", + GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null" } }); + expect(p.exitCode, new TextDecoder().decode(p.stderr)).toBe(0); + }; + const remote = join(dir, "remote.git"); git(dir, "init", "--bare", remote); + for (const name of ["seed", "one", "two"]) { mkdirSync(join(dir, name)); git(join(dir, name), "init"); git(join(dir, name), "remote", "add", "origin", remote); } + const seed = new GitReservationStore(join(dir, "seed")); + expect(seed.publishRedMain(seed.read(), redWithIncident())).toBe(true); + const script = join(dir, "orchestrator.ts"); + // Both orchestrators read the same coordination commit before either writes; + // the second pushes only after the first has, so its push races a moved ref. + writeFileSync(script, `import { appendFileSync, existsSync, writeFileSync } from "node:fs"; + import { GitReservationStore } from ${JSON.stringify(join(ROOT, "scripts/integration-reservation.ts"))}; + import { claimIncident } from ${JSON.stringify(join(ROOT, "scripts/red-main-incident.ts"))}; + const [root, number, barrier, log] = process.argv.slice(2), store = new GitReservationStore(root); + let reads = 0; + const io = { repository: "odysseus/brain-kit", login: "odysseus", + read() { const snapshot = store.read(); if (reads++ === 0) { writeFileSync(barrier + number, "ready"); while (!existsSync(barrier + "1") || !existsSync(barrier + "2")) Bun.sleepSync(5); } return snapshot; }, + publish(snapshot, record) { + if (number === "2") while (!existsSync(barrier + "published")) Bun.sleepSync(5); + const pushed = store.publishRedMain(snapshot, record); appendFileSync(log, JSON.stringify({ number, pushed }) + "\\n"); + if (number === "1") writeFileSync(barrier + "published", "done"); + return pushed; + }, + now: async () => ${NOW + 2000} + Number(number), json: async () => [], + async write(method, path, body) { appendFileSync(log, JSON.stringify({ number, method, path }) + "\\n"); return {}; } }; + try { const result = await claimIncident(io, { worker: "wi-" + number, orchestrator: "orch-" + number }, "claim"); console.log(JSON.stringify({ claimed: true, action: result.action })); } + catch (error) { console.log(JSON.stringify({ claimed: false, error: String(error) })); }`); + const log = join(dir, "log.jsonl"); + const children = ["1", "2"].map((id, index) => Bun.spawn([process.execPath, script, join(dir, index ? "two" : "one"), id, join(dir, "barrier-"), log], { stdout: "pipe", stderr: "pipe" })); + const results = await Promise.all(children.map(async child => { + const [code, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + expect(code, err).toBe(0); return JSON.parse(out) as { claimed: boolean; action?: string; error?: string }; + })); + expect(results.map(r => r.claimed), "EXACTLY_ONE_CLAIM_SUCCEEDS").toEqual([true, false]); + expect(results[1]!.error).toContain("Fix claimed by worker wi-1 (orchestrator orch-1)"); + const events = readFileSync(log, "utf8").trim().split("\n").map(line => JSON.parse(line)); + // The loser's push really reached the remote and was rejected by the compare-and-swap. + expect(events.filter(e => "pushed" in e)).toEqual([{ number: "1", pushed: true }, { number: "2", pushed: false }]); + expect(events.filter(e => e.method).map(e => `${e.number} ${e.method} ${e.path}`), "ONLY_THE_WINNER_MIRRORS").toEqual([ + "1 POST repos/odysseus/brain-kit/issues/500/assignees", "1 POST repos/odysseus/brain-kit/issues/500/comments"]); + expect(new GitReservationStore(join(dir, "two")).read().redMain.open!.claim).toMatchObject({ worker: "wi-1", orchestrator: "orch-1" }); + }); + + test("an expired claim is taken over and the takeover is recorded on the issue", async () => { + const gh = fakeIssues(redWithIncident()); + const first = await claimIncident(gh.io, PENELOPE, "claim"); + expect(first.mirrored).toEqual(["assignee", "claim-comment"]); + gh.at(NOW + 2000 + CLAIM_TERM_MS - 1); + await expect(claimIncident(gh.io, TELEMACHUS, "claim")).rejects.toThrow("Fix claimed by worker wi-20260712-penelope"); + gh.at(NOW + 2000 + CLAIM_TERM_MS); + const takeover = await claimIncident(gh.io, TELEMACHUS, "claim"); + expect(takeover.action).toBe("takeover"); + expect(gh.record().open!.claim).toMatchObject({ ...TELEMACHUS, takeover: { ...PENELOPE, expired: NOW + 2000 + CLAIM_TERM_MS } }); + const comments = gh.comments(500); + expect(comments).toHaveLength(2); + expect(comments[1], "TAKEOVER_ON_ISSUE").toContain("**Fix claim takeover**: worker `wi-20260712-telemachus` (orchestrator `orch-pylos`) took over the fix from worker `wi-20260712-penelope` (orchestrator `orch-ithaca`), whose claim expired at 2026-07-12T01:00:02.000Z."); + expect(gh.writes.filter(w => w.path.endsWith("/assignees")).map(w => w.body)).toEqual([{ assignees: ["odysseus"] }, { assignees: ["odysseus"] }]); + // The previous claimant can no longer renew, and claiming again only renews, mirrored once. + await expect(claimIncident(gh.io, PENELOPE, "renew")).rejects.toThrow("no live fix claim"); + expect((await claimIncident(gh.io, TELEMACHUS, "claim")).mirrored).toEqual(["assignee"]); + expect(gh.comments(500)).toHaveLength(2); + const released = await claimIncident(gh.io, TELEMACHUS, "release"); + expect(released.claim).toBeNull(); + expect(gh.comments(500)[2]).toContain("**Fix claim released** by worker `wi-20260712-telemachus`"); + expect(gh.writes.at(-1)).toMatchObject({ method: "DELETE", path: "repos/odysseus/brain-kit/issues/500/assignees" }); + }); +}); + +describe("evidence", () => { + test("a non-claimant posts evidence in the fixed format to the one incident and opens nothing", async () => { + const fixture = parseRedMain(readFileSync(FIXTURE, "utf8")); + const gh = fakeIssues(fixture, NOW + 600_000); + const result = await postEvidence(gh.io, { ...TELEMACHUS, kind: "reproduction", sha: B, summary: "raft.test.ts fails at the first bad SHA on a clean checkout", details: "expect(received).toBe(expected)\n```nested```" }); + expect(result).toMatchObject({ incident: 500, role: "contributor" }); + expect(gh.writes.map(w => `${w.method} ${w.path}`), "NO_SECOND_INCIDENT").toEqual(["POST repos/odysseus/brain-kit/issues/500/comments"]); + expect(gh.record()).toBe(fixture); + expect(result.body.split("\n").slice(0, 8)).toEqual([evidenceMarker(100, "reproduction"), "### Red-main evidence: reproduction", "", + "- **Incident:** main red at `bbbbbbbbbbbb` (record run 100)", "- **From:** worker `wi-20260712-telemachus`, orchestrator `orch-pylos` (contributor)", + `- **SHA:** \`${B}\``, "- **Summary:** raft.test.ts fails at the first bad SHA on a clean checkout", ""]); + expect(result.body).toContain("````text\nexpect(received).toBe(expected)\n```nested```\n````"); + expect(formatEvidence(fixture.open!, { ...PENELOPE, kind: "bisect", summary: "x" }, "claimant")).toContain("(claimant)"); + // A duplicate is linked on the incident and pointed at it, never filed again. + await postEvidence(gh.io, { ...TELEMACHUS, kind: "duplicate", issue: 321, summary: "the same raft failure was filed separately" }); + expect(gh.writes.slice(1).map(w => w.path)).toEqual(["repos/odysseus/brain-kit/issues/500/comments", "repos/odysseus/brain-kit/issues/321/comments"]); + expect(gh.writes[2]!.body.body).toContain("tracked by red-main incident #500"); + await expect(postEvidence(gh.io, { ...TELEMACHUS, kind: "related", summary: "no issue" })).rejects.toThrow("--issue is required"); + // The claimant's recovery choice is recorded with its rationale; uncertainty stays explicit. + const decision = await postEvidence(gh.io, { ...PENELOPE, kind: "decision", choice: "revert", sha: B, summary: "revert the squash at the first bad SHA; the bisect probe isolates it and later squashes do not depend on it", + details: "Cause: probe reproduced at the first bad SHA and passed at its parent.\nDependencies: no later squash touches the reverted files." }); + expect(decision.role).toBe("claimant"); + expect(decision.body, "DECISION_RECORDS_CHOICE").toContain("- **Choice:** targeted revert PR"); + expect(decision.body).toContain("Cause: probe reproduced"); + expect(formatEvidence(fixture.open!, { ...PENELOPE, kind: "decision", choice: "uncertain", summary: "x" }, "claimant")).toContain("uncertain: neither a fix nor a revert is supportable yet"); + await expect(postEvidence(gh.io, { ...PENELOPE, kind: "decision", summary: "no choice", details: "why" })).rejects.toThrow("--choice is required"); + await expect(postEvidence(gh.io, { ...PENELOPE, kind: "decision", choice: "fix", summary: "no rationale" })).rejects.toThrow("causal and current-tree rationale"); + await expect(postEvidence(gh.io, { ...PENELOPE, kind: "log", choice: "fix", summary: "stray choice" })).rejects.toThrow("--choice is required"); + await expect(postEvidence(gh.io, { ...TELEMACHUS, kind: "log", summary: "two\nlines" })).rejects.toThrow("one-line summary"); + await expect(postEvidence(fakeIssues(emptyRedMain()).io, { ...TELEMACHUS, kind: "log", summary: "late" })).rejects.toThrow("Main is not red"); + }); + + test("the CLI dry run against the fixture incident posts evidence, refuses the second claim and writes nothing else", () => { + const cli = (...args: string[]) => { + const p = Bun.spawnSync([process.execPath, "scripts/red-main-incident.ts", ...args, "--dry-run", "--record", FIXTURE, "--repository", "odysseus/brain-kit", "--now", "2026-07-12T00:10:00Z", + "--worker", TELEMACHUS.worker, "--orchestrator", TELEMACHUS.orchestrator], { cwd: ROOT, stdout: "pipe", stderr: "pipe", env: { ...process.env, PATH: "" } }); + return { code: p.exitCode, out: new TextDecoder().decode(p.stdout), err: new TextDecoder().decode(p.stderr) }; + }; + const evidence = cli("evidence", "--kind", "ruled-out", "--summary", "not the shared fixture clock: the failure reproduces with it pinned"); + expect(evidence.code, evidence.err).toBe(0); + const writes = evidence.out.split("\n").filter(line => line.startsWith("DRY_RUN")); + expect(writes).toHaveLength(1); + expect(writes[0]).toStartWith("DRY_RUN POST repos/odysseus/brain-kit/issues/500/comments "); + expect(writes[0]).toContain("(contributor)"); + expect(evidence.out).toContain('{"evidence":true,"incident":500,"role":"contributor","dryRun":true}'); + const claim = cli("claim"); + expect(claim.code).toBe(1); + expect(claim.out).toBe(""); + expect(claim.err).toContain("Fix claimed by worker wi-20260712-penelope (orchestrator orch-ithaca) until 2026-07-12T01:01:00.000Z; add evidence to incident #500 instead"); + }); +}); From 63d381680ddcd1bb9190fa15b702ee5e104753ec Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 10:37:26 +0000 Subject: [PATCH 2/3] fix(ci): narrow the fix-claim liveness check for the typechecker (#2944) Co-Authored-By: Claude Opus 5.5 --- scripts/red-main-incident.ts | 2 +- scripts/red-main.ts | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/scripts/red-main-incident.ts b/scripts/red-main-incident.ts index d346792fae..c66b8850e0 100644 --- a/scripts/red-main-incident.ts +++ b/scripts/red-main-incident.ts @@ -134,7 +134,7 @@ export async function postEvidence(io: IncidentIO, evidence: Evidence): Promise< if (!open) throw new Error("Main is not red; there is no incident to add evidence to"); if (open.incident === null) throw new Error("Incident pending: the coordinator has not filed the incident issue yet; retry when main-status names it"); const now = await io.now(), claim = open.claim ?? null; - const role = liveClaim(claim, now) && claim.worker === evidence.worker && claim.orchestrator === evidence.orchestrator ? "claimant" : "contributor"; + const role = claim && liveClaim(claim, now) && claim.worker === evidence.worker && claim.orchestrator === evidence.orchestrator ? "claimant" : "contributor"; const body = publicText("evidence comment", formatEvidence(open, evidence, role)); await io.write("POST", `${issuePath(io, open.incident)}/comments`, { body }); if (evidence.kind === "duplicate") await io.write("POST", `${issuePath(io, evidence.issue!)}/comments`, { diff --git a/scripts/red-main.ts b/scripts/red-main.ts index a63b3ad3e5..34a7fd0d18 100644 --- a/scripts/red-main.ts +++ b/scripts/red-main.ts @@ -117,7 +117,7 @@ export function declareFix(record: RedMainRecord, pr: number, now: number): RedM } const sameClaimant = (claim: FixClaim, who: Claimant) => claim.worker === who.worker && claim.orchestrator === who.orchestrator; -export const liveClaim = (claim: FixClaim | null | undefined, now: number): claim is FixClaim => !!claim && now < claim.expires; +export const liveClaim = (claim: FixClaim | null | undefined, now: number): boolean => !!claim && now < claim.expires; function claimable(record: RedMainRecord, who: Claimant): RedIncident { if (!agent(who.worker) || !agent(who.orchestrator)) throw new Error("Worker and orchestrator IDs must be opaque tokens matching " + AGENT_ID); if (!record.open) throw new Error("Main is not red; there is no incident to claim"); @@ -132,7 +132,7 @@ function claimable(record: RedMainRecord, who: Claimant): RedIncident { */ export function claimFix(record: RedMainRecord, who: Claimant, now: number): RedMainRecord { const open = claimable(record, who), held = open.claim ?? null; - if (liveClaim(held, now)) { + if (held && liveClaim(held, now)) { if (sameClaimant(held, who)) return renewFixClaim(record, who, now); throw new Error(`Fix claimed by worker ${held.worker} (orchestrator ${held.orchestrator}) until ${new Date(held.expires).toISOString()}; add evidence to incident #${open.incident} instead`); } @@ -143,7 +143,7 @@ export function claimFix(record: RedMainRecord, who: Claimant, now: number): Red export function renewFixClaim(record: RedMainRecord, who: Claimant, now: number): RedMainRecord { const open = claimable(record, who), held = open.claim ?? null; - if (!liveClaim(held, now) || !sameClaimant(held, who)) throw new Error("This worker holds no live fix claim; claim again (an expired claim may already be taken over)"); + if (!held || !liveClaim(held, now) || !sameClaimant(held, who)) throw new Error("This worker holds no live fix claim; claim again (an expired claim may already be taken over)"); return next(record, now, "renew-claim", open.run, { open: { ...open, claim: { ...held, renewed: now, expires: now + CLAIM_TERM_MS } } }); } From 195c2a1f24499c423da18a66373e2145687f795f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 10:32:01 +0000 Subject: [PATCH 3/3] docs(ci): record the conditional concurrency direction for #2934 Co-Authored-By: Claude Opus 5.5 --- docs/decisions/ci-utility.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/docs/decisions/ci-utility.md b/docs/decisions/ci-utility.md index 3b118e8fe8..3721006bb8 100644 --- a/docs/decisions/ci-utility.md +++ b/docs/decisions/ci-utility.md @@ -1609,6 +1609,31 @@ branch, so the request always runs main's admission code. [#2942](https://github.com/schlessera/brain-kit/issues/2942). Whichever of #2942 and #3272 lands second adds that gate to the admission job. +### Conditional concurrency direction + +The [2026-11-02 maintainer decision on #2934](https://github.com/schlessera/brain-kit/issues/2934#issuecomment-6574700840) +replaces the October deferral with a conditional direction. Concurrent integration +is permitted: base-tolerant confirmation for candidates whose affected closures are +disjoint, with reservations keyed by closure. That permission only takes effect +once all three of these hold: + +1. **Stability gate.** Seven consecutive days within one proof-policy epoch, + first-main green at or above 80%, and every red incident attributed. +2. **Measured benefit.** A complete measured baseline shows a material benefit + from reducing lease waits and reconfirmation. +3. **Qualification.** + - Complete affected closures and global inputs are qualified. + - Unknown or changed graphs, and conflicts, are serialized conservatively. + - Coordination is deterministic. + - Each merge has an exact head/base/squash audit. + - Main runs full combined-tree proof, and each incident has an owner. + +Selected proof, the red-main controls and the current permissions are preserved. +This is a policy direction, not a finding that any gate is met. Until a +qualified rollout, the exact-base confirmation and the single exact-candidate +reservation above still apply. Before any implementation, this record and the +concrete child task briefs on #2934 are updated. + ## Historical measurement and upstream guidance The following guidance records the paid-provider investigation which motivated