diff --git a/scripts/pm/check-governed-merges.mjs b/scripts/pm/check-governed-merges.mjs index 4dead9bca27..48812bf6a54 100644 --- a/scripts/pm/check-governed-merges.mjs +++ b/scripts/pm/check-governed-merges.mjs @@ -1256,6 +1256,10 @@ const SELF_TEST_BATTERIES = Object.freeze({ '⭐ the SIZE predicate: over the human-merge line threshold, whatever the paths': 44, '⭐ #18989: the guard is the CALLER\'s name, and the mirror is pinned to its owner': 16, '⭐ #19036: the sweep lists an OVERSIZED landing beside the governed ones': 20, + // The per-card count (ruling 7303003476): the split case both ways, its control, the card-limb words, the lift, + // the unread reading, the modes that read no card, `pullCardReading`'s refusals and counting, and the sweep's words. + '⭐ the per-card count (ruling 7303003476): a pull under the line is over it when its card totals more': 11, + '⭐ the per-card module (ruling 7303003476): what counts, the exemption read first, the landed list, every unread input': 20, '⭐ the FORK predicate: head repo ≠ base repo is a proposal, never a delivery': 6, '⭐ the argv is CLOSED: a flag the mode does not read, or a second repository beside a bare --pr, is refused': 22, 'the per-row repository scope (ruled B2, 2026-10-13)': 20, @@ -1290,8 +1294,9 @@ const SELF_TEST_BATTERIES = Object.freeze({ // Raised 36 → 37 with the low-risk skills arm battery (#33501), 37 → 38 with its post-merge leg (#33603), // 38 → 39 with the weekly audit card's battery (#33814), 39 → 40 with the arm's ADR leg (#33539), // 40 → 41 with the guard-instrument rows and the `.claude/**` declaration split (#35321), 41 → 42 with the -// stdin-carrying git reader, 42 → 43 with the sweep's `.claude/**` split leg (#35612). -const SELF_TEST_BATTERY_FLOOR = 43; +// stdin-carrying git reader, 42 → 43 with the sweep's `.claude/**` split leg (#35612), 43 → 44 with the per-card count +// (ruling 7303003476), 44 → 45 with the per-card module battery (the predicate moved onto the register). +const SELF_TEST_BATTERY_FLOOR = 45; // The key an assertion is filed under when no battery is open. It is not a // declared battery, so it reds by the same set difference rather than silently @@ -3589,6 +3594,262 @@ export function sizeLiftFrom(approval = null) { return null; } +// ── The per-card count (ruling 7303003476, #38296) ────────────────────────── +// +// The 3,000-line human-review line (`HUMAN_MERGE_LINE_THRESHOLD`) is counted per card, across every pull request +// the card produces: a card whose pull requests total more than the line makes EVERY one of them land the way a +// Tier H pull does — two 2,000-line pulls on one card are both over the line (`references/landing-operations.md`). +// The maintainer's ruling 7303003476 on objectstack#38296 settled what "the card's pull requests" means (the card's +// option B, plus row 7239077861): +// +// - every pull request that NAMES the card counts, open or merged; +// - a closed, unmerged pull request does not count; +// - an epic or tracker card does not accumulate; +// - a sibling that merged before the card crossed the line is LISTED for the maintainer's after-the-fact look in +// the later pull request's hand-off — no revert, no block. +// +// It lives HERE, in the guard register's own file, so the predicate three Tier H instruments call (this file's +// `--pr`, the queue guard's size leg, the relay's front-of-queue fence) is itself on the register: an edit to the +// exempt labels or the counting lands by the maintainer. +// +// Readings that are the seat's, not the ruling's, stated in the PR that built them for the maintainer to confirm: +// +// - NAMES is `record-recognisers.mjs`'s `countedCardNumbers` (a closing keyword, `Part of`, the protocol dev +// branch — ⛔ not `Refs`), reached as the recognisers' `countedCards` and handed in as `namesCard`: one parser. +// - the EXEMPTION reads only a `CARD_EXEMPT_LABELS` label whose latest `labeled` event is at or before the card's +// first pull: the earliest of this pull's opening and the card's first same-repository pull cross-reference. +// It is read off the timeline alone, BEFORE any sibling is read, so an epic or tracker with more siblings than +// `CARD_SIBLING_CAP` is exempt, never unread. Relabelling a card as a tracker once its pulls exist exempts nothing. +// +// Where the siblings come from, and what that cannot see: the same-repository pull requests the card's timeline +// lists as `cross-referenced` (GitHub writes that event when a pull request's body mentions the card), each read by +// its own GET and kept only when it names the card. The pull request under test is always counted. ⛔ Not seen: a +// sibling whose body never mentions the card (named by its branch alone), one in another repository, and one whose +// naming was edited out before it merged (its cross-reference stays; it is read and excluded as not naming). +// +// Fail closed, and to the human path: a read that throws, a truncated timeline, or a sibling whose GET does not +// answer makes the reading `measured: false` with the reason — ⛔ never a smaller total. `sizeVerdict` reads an +// unread card as OVER the line, so it lands the way an over-line card does: by the maintainer, or on this pull's +// own authorised approval (the 2026-09-27 lift), never on the seat alone. + +/** The labels that make a card a parent of work (an epic or tracker), exempt from accumulating. ⛔ A mirror of `card-pick.mjs`'s `PARENT_LABELS`, pinned equal by the self-test (that file's import graph reaches back here, so it is read as text). */ +export const CARD_EXEMPT_LABELS = Object.freeze(['pm:epic', 'tracking']); + +/** The citation every card reading carries. */ +export const CARD_SIZE_RULING = 'ruling 7303003476: per card, the open and merged pulls naming it; epic/tracker cards exempt'; + +/** How many cross-referenced pulls one non-exempt card reading reads before it refuses rather than answer on a subset. */ +export const CARD_SIBLING_CAP = 60; + +/** The pages of 100 a card timeline is read to (3,000 events) before the reading is unread — wider than the low-risk arm's 10, since an epic's timeline is long. */ +export const CARD_TIMELINE_PAGES = 30; + +/** + * The fields of a REST pull row the card reading reads, as one plain object — `body` and `head.ref` kept in the REST + * shape so `namesCard` (the recognisers' `countedCards`) reads it as it reads a pull row. Pure; never throws. + */ +export function cardPullView(row) { + const r = row && typeof row === 'object' ? row : {}; + const int = (v) => (Number.isInteger(v) && v >= 0 ? v : null); + return { + number: Number.isInteger(r.number) ? r.number : null, + state: typeof r.state === 'string' ? r.state : null, + mergedAt: typeof r.merged_at === 'string' && r.merged_at !== '' ? r.merged_at : null, + createdAt: typeof r.created_at === 'string' && r.created_at !== '' ? r.created_at : null, + additions: int(r.additions), + deletions: int(r.deletions), + body: typeof r.body === 'string' ? r.body : '', + head: { ref: typeof r.head?.ref === 'string' ? r.head.ref : null }, + }; +} + +/** The same-repository pull cross-reference events on a card's timeline, in timeline order. Pure. */ +function crossReferenceEvents(timeline, slug) { + const want = String(slug ?? '').toLowerCase(); + return (Array.isArray(timeline) ? timeline : []).filter((ev) => { + const issue = ev?.event === 'cross-referenced' ? ev?.source?.issue : null; + return Boolean(issue && issue.pull_request && Number.isInteger(issue.number) && String(issue.repository?.full_name ?? '').toLowerCase() === want); + }); +} + +/** The same-repository pull numbers a card's timeline lists as `cross-referenced`, ascending, deduplicated. Pure. */ +export function crossReferencedPulls(timeline, slug) { + return [...new Set(crossReferenceEvents(timeline, slug).map((ev) => ev.source.issue.number))].sort((a, b) => a - b); +} + +/** + * When the card's first pull appeared, off what is read before any sibling: the earliest of `selfCreatedAt` and + * the `created_at` of the card's first same-repository pull cross-reference. Null when neither is dated. Pure. + */ +export function cardFirstPullAt(timeline, slug, selfCreatedAt = null) { + const times = [selfCreatedAt, ...crossReferenceEvents(timeline, slug).map((ev) => ev?.created_at)] + .filter((t) => typeof t === 'string' && Number.isFinite(Date.parse(t))); + if (times.length === 0) return null; + return times.reduce((a, b) => (Date.parse(b) < Date.parse(a) ? b : a)); +} + +/** + * The exemption, off the card's timeline. Pure. A `CARD_EXEMPT_LABELS` label the card carries NOW (the + * labeled/unlabeled events replayed in order) exempts it only when the `labeled` event that put it there is at or + * before `firstPullAt` (`cardFirstPullAt`). No pull dated (`firstPullAt` null) ⇒ a carried label exempts. + * `{ exempt, label, labelledAt, reason }`. + */ +export function cardExemption(timeline, firstPullAt) { + const current = new Map(); // label → the created_at of the labeled event that put it there + for (const ev of Array.isArray(timeline) ? timeline : []) { + const name = ev?.label?.name; + if (typeof name !== 'string' || !CARD_EXEMPT_LABELS.includes(name)) continue; + if (ev.event === 'labeled') current.set(name, typeof ev.created_at === 'string' ? ev.created_at : null); + else if (ev.event === 'unlabeled') current.delete(name); + } + if (current.size === 0) return { exempt: false, label: null, labelledAt: null, reason: `carries no ${CARD_EXEMPT_LABELS.map((l) => `\`${l}\``).join(' or ')} label` }; + const first = firstPullAt ? Date.parse(firstPullAt) : null; + for (const [label, at] of current) { + const t = at ? Date.parse(at) : NaN; + if (Number.isFinite(t) && (first === null || t <= first)) { + return { exempt: true, label, labelledAt: at, reason: `\`${label}\` since ${at}${firstPullAt ? `, before its first pull (${firstPullAt})` : ', and no pull is dated yet'}` }; + } + } + const [label, at] = [...current][0]; + return { + exempt: false, + label, + labelledAt: at, + reason: `\`${label}\` was put on at ${at ?? 'an unreadable time'}, after its first pull (${firstPullAt}) — a label added once the pulls exist exempts nothing`, + }; +} + +/** + * ONE card's total, judged. Pure. `views` are `cardPullView`s of every pull read for the card (the pull under test + * included, by `self`); `namesCard(view, card)` is the naming relation; `exemption` is `cardExemption`'s answer (not + * exempt when omitted). A pull counts when it names the card and is open or merged; each other read pull is listed + * in `excluded` with its reason. + * + * `landedBeforeCrossing` (row 7239077861): on a card read over the line, EVERY merged sibling (never `self`). Each + * merged before this reading put the card over — the moment the fleet first sees the crossing — so each is listed + * for the maintainer's after-the-fact look; a sibling the maintainer already merged is listed too, at the cost of a + * line. ⛔ Never a subset by opening order: a pull counts at its size NOW, so an order-based crossing time misplaces a + * pull that grew. `crossedAt` stays as information only: the opening of the pull, in opening order, that took the + * running total past `threshold`. + */ +export function cardTotalVerdict({ card, views, self = null, namesCard, threshold, exemption = null }) { + if (!Number.isInteger(threshold) || threshold < 0) throw new TypeError('cardTotalVerdict: a numeric threshold is required'); + if (typeof namesCard !== 'function') throw new TypeError('cardTotalVerdict: a namesCard relation is required'); + const exempted = exemption && typeof exemption === 'object' ? exemption : { exempt: false, label: null, labelledAt: null, reason: 'no exemption was read' }; + const counted = []; + const excluded = []; + for (const v of views) { + const isSelf = self !== null && v.number === self; + if (!isSelf && !namesCard(v, card)) { excluded.push({ number: v.number, why: 'mentions the card without naming it' }); continue; } + if (v.state !== 'open' && v.mergedAt === null) { excluded.push({ number: v.number, why: 'closed without merging' }); continue; } + if (v.additions === null || v.deletions === null) return { card, measured: false, reason: `pull #${v.number} carries no additions/deletions pair, so the card total cannot be read` }; + counted.push({ number: v.number, state: v.mergedAt ? 'merged' : 'open', mergedAt: v.mergedAt, createdAt: v.createdAt, changedLines: v.additions + v.deletions, self: isSelf }); + } + counted.sort((a, b) => (Date.parse(a.createdAt ?? '') || 0) - (Date.parse(b.createdAt ?? '') || 0) || a.number - b.number); + const total = counted.reduce((s, p) => s + p.changedLines, 0); + let running = 0; + let crossedAt = null; + for (const p of counted) { + running += p.changedLines; + if (running > threshold) { crossedAt = p.createdAt; break; } + } + const exceeds = !exempted.exempt && total > threshold; + return { + card, + measured: true, + total, + threshold, + exceeds, + exempt: exempted.exempt === true, + exemption: exempted, + counted, + excluded, + crossedAt: exceeds ? crossedAt : null, + landedBeforeCrossing: exceeds ? counted.filter((p) => !p.self && p.mergedAt !== null).map((p) => ({ number: p.number, mergedAt: p.mergedAt, changedLines: p.changedLines })) : [], + }; +} + +/** + * The per-card reading for one pull request: every card it counts toward, each read and judged. Async; never throws. + * `self` is the pull's own `cardPullView` (its number set); `named` the cards it counts toward (the recognisers' + * `countedCards`); `fetchTimeline(card)` the card's whole timeline (throws when it cannot read all of it); + * `fetchPullView(n)` a sibling's `cardPullView`. The exemption is read off the timeline FIRST: an exempt card reads + * no sibling, so no cap can make it unread. Answers `{ measured: true, cards, exceeds, over, apiCalls }` — `over` + * the cards over the line — or `{ measured: false, reason, apiCalls }`. + */ +export async function readCardSize({ self, named, slug, threshold, namesCard, fetchTimeline, fetchPullView, siblingCap = CARD_SIBLING_CAP }) { + let apiCalls = 0; + const unread = (reason) => ({ measured: false, reason, apiCalls }); + if (!self || !Number.isInteger(self.number)) return unread('the pull request itself could not be read, so the cards it names are unknown'); + if (!Array.isArray(named)) return unread('the cards this pull names could not be read (the naming relation did not load)'); + if (typeof fetchTimeline !== 'function' || typeof fetchPullView !== 'function') return unread('no card timeline or pull reader was supplied, so no card total was read'); + const cards = []; + for (const card of named) { + let timeline; + try { + apiCalls += 1; + timeline = await fetchTimeline(card); + } catch (error) { + return unread(`card #${card}'s timeline could not be read whole (${String(error?.message ?? error).split('\n')[0]})`); + } + if (!Array.isArray(timeline)) return unread(`card #${card}'s timeline answered no list`); + const exemption = cardExemption(timeline, cardFirstPullAt(timeline, slug, self.createdAt)); + if (exemption.exempt) { + cards.push(cardTotalVerdict({ card, views: [self], self: self.number, namesCard, threshold, exemption })); + continue; + } + const siblings = crossReferencedPulls(timeline, slug).filter((n) => n !== self.number); + if (siblings.length > siblingCap) return unread(`card #${card} is cross-referenced by ${siblings.length} pulls, over the ${siblingCap} this reading reads — it refuses rather than total a subset`); + const views = [self]; + for (const n of siblings) { + try { + apiCalls += 1; + const v = await fetchPullView(n); + if (!v || !Number.isInteger(v.number)) return unread(`pull #${n}, cross-referenced by card #${card}, answered no readable pull`); + views.push(v); + } catch (error) { + return unread(`pull #${n}, cross-referenced by card #${card}, could not be read (${String(error?.message ?? error).split('\n')[0]})`); + } + } + const verdict = cardTotalVerdict({ card, views, self: self.number, namesCard, threshold, exemption }); + if (!verdict.measured) return unread(verdict.reason); + cards.push(verdict); + } + const over = cards.filter((c) => c.exceeds); + return { measured: true, cards, exceeds: over.length > 0, over: over.map((c) => c.card), apiCalls }; +} + +/** + * The words for a card reading, one line per fact, each indented for a size block. Pure. `null` (no reading handed + * in) says NOT MEASURED and where it is read; an unread reading says why and that it lands as over the line. + */ +export function renderCardLines(reading, { notMeasuredWhy = null } = {}) { + if (reading === null || reading === undefined) { + return [ + ` ⚠️ card total: NOT MEASURED${notMeasuredWhy ? ` — ${notMeasuredWhy}` : ''}. The line is counted per card (${CARD_SIZE_RULING}):`, + ' a pull under the line is still over it when the open and merged pulls naming its card total more;', + ' `check-governed-merges.mjs --pr ` reads that total.', + ]; + } + if (reading.measured !== true) return [` ⛔ card total: UNREAD — ${reading.reason}. An unread total is never a total under the line: this pull lands as an over-line card does (by the maintainer, or on its own authorised approval).`]; + if (reading.cards.length === 0) return [' card total: this pull counts toward no card (no closing keyword, `Part of` or dev branch), so the per-card count adds nothing to its own size.']; + const lines = []; + for (const c of reading.cards) { + const list = c.counted.map((p) => `#${p.number} ${p.self ? 'this pull' : p.state} ${p.changedLines}`).join(', '); + const head = `card #${c.card}: ${c.total} changed line(s) across ${c.counted.length} pull(s) (${list})`; + if (c.exempt) lines.push(` card total: card #${c.card} — EXEMPT, an epic/tracker card does not accumulate (no sibling read): ${c.exemption.reason}.`); + else if (c.exceeds) lines.push(` ⛔ card total: ${head} > ${c.threshold} — OVER the line BY THE CARD (${CARD_SIZE_RULING}).`); + else lines.push(` card total: ${head} ≤ ${c.threshold} — under the line.`); + if (c.landedBeforeCrossing.length > 0) { + lines.push( + ` merged before this reading found the card over the line: ${c.landedBeforeCrossing.map((p) => `#${p.number} (merged ${p.mergedAt}, ${p.changedLines} lines)`).join(', ')}`, + " — listed for the maintainer's after-the-fact look in this pull's hand-off (row 7239077861); no revert, no block.", + ); + } + } + return lines; +} + /** * The SIZE limb (maintainer ruling 2026-09-18, header section "The SIZE * predicate"), as data. Pure. `size` is `{ additions, deletions, source? }` or @@ -3606,11 +3867,22 @@ export function sizeVerdict(size = null, approval = null) { const approvalState = typeof approval?.state === 'string' ? approval.state : null; const measured = Number.isInteger(additions) && additions >= 0 && Number.isInteger(deletions) && deletions >= 0; + // The CARD reading (ruling 7303003476, `readCardSize` above): the total of every open or merged pull naming this + // pull's card(s), handed in by a mode that read it (`--pr`, the queue guard, the relay's fence). `null` is NOT + // MEASURED — `--test` and `--branch`, which read no card and say so. An UNREAD reading is read as over the line: + // the card could put this pull over, so it lands as an over-line card does — on its own authorised approval (the + // lift below) or by the maintainer — and ⛔ never on the seat alone. + const card = size && typeof size === 'object' && size.card && typeof size.card === 'object' ? size.card : null; if (!measured) { - return { measured: false, additions: null, deletions: null, changedLines: null, threshold: HUMAN_MERGE_LINE_THRESHOLD, exceeds: false, lifted: null, approvalState, source: null }; + return { measured: false, additions: null, deletions: null, changedLines: null, threshold: HUMAN_MERGE_LINE_THRESHOLD, exceeds: false, lifted: null, approvalState, source: null, card, exceedsBy: null }; } const changedLines = additions + deletions; - const exceeds = changedLines > HUMAN_MERGE_LINE_THRESHOLD; + // ⭐ Per card: over the line when this pull is, OR when a non-exempt card it names totals more (two 2,000-line + // pulls on one card are both over), OR when the card reading did not read. The lift below is this pull's own, + // whichever limb fired. + const pullExceeds = changedLines > HUMAN_MERGE_LINE_THRESHOLD; + const cardExceeds = card !== null && (card.measured !== true || card.exceeds === true); + const exceeds = pullExceeds || cardExceeds; return { measured: true, additions, @@ -3621,6 +3893,8 @@ export function sizeVerdict(size = null, approval = null) { lifted: exceeds ? sizeLiftFrom(approval) : null, approvalState, source: typeof size?.source === 'string' && size.source !== '' ? size.source : null, + card, + exceedsBy: !exceeds ? null : pullExceeds ? 'pull' : 'card', }; } @@ -3769,13 +4043,16 @@ export function renderSizeLines(size) { // The provenance of the number is NOT in these words — it is on the // derivation line (`--pr`, `--branch`) or the stderr note (`--test`), so the // verdict stays byte-identical across modes on the same list and numbers. - const reading = `${s.changedLines} changed line(s) (+${s.additions} / -${s.deletions})`; - if (!s.exceeds) return ` size: ${reading} ≤ ${t} — under the human-merge threshold (generated files included in the count).`; + const card = `\n${renderCardLines(s.card ?? null).join('\n')}`; + const own = `${s.changedLines} changed line(s) (+${s.additions} / -${s.deletions})`; + if (!s.exceeds) return ` size: ${own} ≤ ${t} — under the human-merge threshold (generated files included in the count).${card}`; + // Over BY THE CARD alone (ruling 7303003476): the pull's own number is under, and the verdict says so. + const reading = s.exceedsBy === 'card' ? `the card total (below; this pull alone ${own})` : own; if (s.lifted) { return ( ` ✅ SIZE LIFTED — ${reading} > ${t}, over the human-merge line, and an authorized APPROVED review lifts it\n` + ` (${s.lifted.ruling}): ${renderLiftApprovals(s.lifted)}.\n` + - ` The OWNING seat lands this PR through the queue (席位落地); the maintainer's direct merge is the other landing.` + ` The OWNING seat lands this PR through the queue (席位落地); the maintainer's direct merge is the other landing.${card}` ); } return ( @@ -3784,7 +4061,7 @@ export function renderSizeLines(size) { ` as a Tier H governed diff: no seat flips it ready, enqueues it, or arms auto-merge until an account in\n` + ` GOVERNED_APPROVERS has APPROVED it, on ANY commit (${SIZE_LIFT_RULING}) — then the OWNING seat lands it\n` + ` through the queue; the maintainer's own merge is the other landing. ACCEPT on the card,\n` + - ` \`pm:awaiting-merge\` on the PR, the final 维护者速读, review requested from GOVERNED_APPROVERS.` + ` \`pm:awaiting-merge\` on the PR, the final 维护者速读, review requested from GOVERNED_APPROVERS.${card}` ); } @@ -5153,6 +5430,8 @@ export async function fetchPullFiles({ apiUrl, slug, pull, channels, fetchImpl = lowRisk: pullLowRiskReading(head, paths, { timeline: lowRiskRowHit(paths) ? await fetchTimelineOver({ fetchImpl, url: `${apiUrl}/repos/${slug}/issues/${pull}/timeline`, channel: chosen, pageCap }) : null, }), + // The per-card reading's view of this pull (`cardPullView`): the same GET, nothing re-read. + view: cardPullView(head), // What the arm's record stage derives the card from (`pullRecordStage`): the body and the head branch. pullHead: { number: pull, body: typeof head?.body === 'string' ? head.body : '', head: { ref: typeof head?.head?.ref === 'string' ? head.head.ref : null } }, derivation: { @@ -6242,6 +6521,10 @@ export function renderReport({ window, repos, scanned, entries, lookups, sweepCo ` An entry the maintainer does not recognise is the violation signal — file it as an incident (#9495 regime).`, ` A landing over ${HUMAN_MERGE_LINE_THRESHOLD} changed lines (additions + deletions, generated files INCLUDED) is listed too, on SIZE`, ` alone — it was due a human merge (2026-09-18 ruling), whatever its paths; the number is the LANDED diff's, read locally.`, + ` The line is counted per card (ruling 7303003476), and this sweep does NOT read card totals: it reads landed diffs locally,`, + ` and a card total costs a card timeline plus a GET per sibling for EVERY landing in the window. The per-card line is held`, + ` before the merge instead — by \`--pr\`, the queue guard's size leg and the relay's front-of-queue fence — and a sibling`, + ` that landed before its card crossed is listed in the later pull's hand-off (\`label-write.mjs --handoff\`).`, ]; const preamble = [head, ...auditedLines, ...unauditedLines, ...edgeLines, ...unauditedNote, ...nextRoundRefLine(repos), ...contract].join('\n'); @@ -7055,7 +7338,42 @@ async function runPullMode(args) { }, runGit: sameCheckout ? checkoutGitReader(root) : null, }); - return await emitVerdict(derived.paths, args, derived.derivation, derived.size, { fork: derived.fork, checks: derived.checks }, repo, workflowDiff, staged); + // ⭐ The line is counted PER CARD (ruling 7303003476): every open or merged pull naming this pull's card(s) is + // read and summed. An unread total rides on the verdict as `measured: false`, which `sizeVerdict` reads as OVER + // the line — the human path, liftable by this pull's authorised approval — ⛔ never this pull's size alone. + const token = derived.derivation.channel === 'env-token' ? process.env.GITHUB_TOKEN || process.env.GH_TOKEN || null : null; + const card = await pullCardReading({ view: derived.view, slug: target.slug, readers: () => loadArmReaders(), api: { ...apiContext(process.env), slug: target.slug, token } }); + return await emitVerdict(derived.paths, args, derived.derivation, derived.size ? { ...derived.size, card } : derived.size, { fork: derived.fork, checks: derived.checks }, repo, workflowDiff, staged); +} + +/** + * `--pr`'s per-card reading (ruling 7303003476, `readCardSize`): the cards the pull COUNTS toward through the record + * recognisers' `countedCards` (the one naming relation), each card's timeline (to `CARD_TIMELINE_PAGES`) and its + * cross-referenced pulls read with the guard's own readers over `api`. `readers` is `loadArmReaders` (lazy: the guard imports this file). Answers + * `readCardSize`'s reading; a reader that did not load is `measured: false`, never "names no card". Never throws. + */ +export async function pullCardReading({ view, slug, readers, api }) { + let loaded; + try { + loaded = await readers(); + } catch (error) { + loaded = { available: false, reason: String(error?.message ?? error).split('\n')[0] }; + } + if (loaded?.available !== true) return { measured: false, reason: `the guard's readers did not load (${loaded?.reason ?? 'no reason given'})`, apiCalls: 0 }; + const { guard, recognisers } = loaded; + if (recognisers?.available !== true || typeof recognisers.countedCards !== 'function') { + return { measured: false, reason: `the naming relation did not load (${recognisers?.reason ?? 'the recognisers carry no countedCards'})`, apiCalls: 0 }; + } + const fetchPull = guard.makePullReader(api); + return readCardSize({ + self: view, + named: recognisers.countedCards(view ?? {}), + slug, + threshold: HUMAN_MERGE_LINE_THRESHOLD, + namesCard: (pull, card) => recognisers.countedCards(pull).includes(card), + fetchTimeline: guard.makeTimelineReader({ ...api, maxPages: CARD_TIMELINE_PAGES }), + fetchPullView: async (n) => (await fetchPull(n))?.view ?? null, + }); } /** @@ -10671,6 +10989,143 @@ async function selfTest() { assert('⭐ --pr-reads-the-head-repo-off-its-own-GET-and-the-check-run-count-off-the-head-sha-on-the-same-channel', forkWalk.ok === true && forkWalk.fork.isFork === true && forkWalk.fork.headRepo === 'someone/r' && forkWalk.checks.total === 0 && forkWalk.checks.sha === 'feedface0001', JSON.stringify({ fork: forkWalk.fork, checks: forkWalk.checks })); + // ── ⭐ the per-card count (ruling 7303003476): the line is counted per card ─ + // + // A pull under the line is over it when the open and merged pulls naming its + // card total more — the split case, two 2,000-line pulls on one card, is over + // in BOTH. `--pr` reads the total (`pullCardReading`, `readCardSize`) and + // hands it to `sizeVerdict` as `size.card`; `--test` and `--branch` read none + // and say so; the sweep says why it does not. + battery('⭐ the per-card count (ruling 7303003476): a pull under the line is over it when its card totals more'); + const CARD_LINE = HUMAN_MERGE_LINE_THRESHOLD; + const cardNames = (pull) => [...String(pull?.body ?? '').matchAll(/(?:Fixes|Part of)\s+#(\d+)/g)].map((m) => Number(m[1])); + const cardRow = (number, body, add, extra = {}) => ({ number, state: 'open', merged_at: null, created_at: `2026-11-0${number % 9 + 1}T00:00:00Z`, additions: add, deletions: 0, body, head: { ref: 'x' }, ...extra }); + const cardReaders = (rows, { loaded = true, named = true } = {}) => async () => (!loaded ? { available: false, reason: 'fixture: the guard did not load' } : { + available: true, + recognisers: named ? { available: true, countedCards: cardNames } : { available: true }, + guard: { + makePullReader: () => async (n) => ({ view: cardPullView(rows.find((r) => r.number === n)) }), + makeTimelineReader: () => async () => rows.map((r) => ({ event: 'cross-referenced', source: { issue: { number: r.number, pull_request: {}, repository: { full_name: 'o/r' } } } })), + }, + }); + const splitA = cardRow(301, 'Part of #77', 2000); + const splitB = cardRow(302, 'Fixes #77', 2000); + const readA = await pullCardReading({ view: cardPullView(splitA), slug: 'o/r', readers: cardReaders([splitA, splitB]), api: {} }); + const readB = await pullCardReading({ view: cardPullView(splitB), slug: 'o/r', readers: cardReaders([splitA, splitB]), api: {} }); + const verdictA = testVerdict(['src/a.ts'], { repo: REPO, size: { additions: 2000, deletions: 0, card: readA } }); + const verdictB = testVerdict(['src/b.ts'], { repo: REPO, size: { additions: 2000, deletions: 0, card: readB } }); + assert('⭐ the-split-case-two-2000-line-pulls-on-one-card-are-OVER-the-line-in-BOTH-and-each-lands-by-human-merge', + readA.measured && readB.measured && verdictA.size.exceeds && verdictB.size.exceeds && landsByHumanMerge(verdictA) && landsByHumanMerge(verdictB) && + verdictA.size.exceedsBy === 'card' && verdictA.size.changedLines === 2000, JSON.stringify({ a: verdictA.size.exceedsBy, b: verdictB.size.exceedsBy, readA })); + assert('control: a-2000-line-pull-alone-on-its-card-is-under-and-the-card-reading-rides-on-the-verdict', + (() => { const alone = testVerdict(['src/a.ts'], { repo: REPO, size: { additions: 2000, deletions: 0, card: { measured: true, cards: [], exceeds: false, over: [] } } }); return alone.size.exceeds === false && alone.size.exceedsBy === null && alone.size.card?.measured === true && !landsByHumanMerge(alone); })()); + assert('a-pull-over-the-line-on-its-own-number-says-exceedsBy-pull-whatever-its-card-reads', + sizeVerdict({ additions: CARD_LINE + 1, deletions: 0, card: { measured: true, cards: [], exceeds: false } }).exceedsBy === 'pull'); + assert('⛔ an-UNREAD-card-reading-is-read-as-OVER-the-line-the-human-path-and-this-pulls-own-approval-lifts-it', + (() => { const v = sizeVerdict({ additions: 10, deletions: 0, card: { measured: false, reason: 'r' } }); const l = sizeVerdict({ additions: 10, deletions: 0, card: { measured: false, reason: 'r' } }, authorizedVerdict([{ login: 'os-zhuang', commitId: LIFT_SHA }])); return v.exceeds === true && v.exceedsBy === 'card' && sizeLimbFires(v) && l.lifted !== null && !sizeLimbFires(l) && renderSizeLines(v).includes("card total: UNREAD"); })()); + assert('control: NO-card-reading-(null)-is-NOT-MEASURED-and-judged-on-the-pulls-own-number-as---test-and---branch-hand-it', + sizeVerdict({ additions: 10, deletions: 0 }).exceeds === false && sizeVerdict({ additions: 10, deletions: 0, card: null }).exceeds === false); + assert('⭐ the-LIFT-lifts-a-card-limb-exceed-too-an-authorized-approval-on-this-pull-lands-it-through-the-seat', + (() => { const v = sizeVerdict({ additions: 10, deletions: 0, card: readA }, authorizedVerdict([{ login: 'os-zhuang', commitId: LIFT_SHA }])); return v.exceeds === true && v.lifted !== null && sizeLimbFires(v) === false; })()); + const cardWords = renderSizeLines(verdictA.size); + assert('the-words-say-the-CARD-total-put-it-over-name-the-card-its-pulls-and-the-ruling', + cardWords.includes('the card total (below; this pull alone 2000 changed line(s)') && cardWords.includes('card #77: 4000 changed line(s) across 2 pull(s)') && cardWords.includes('OVER the line BY THE CARD') && cardWords.includes('7303003476'), cardWords); + assert('⛔ --test-and---branch-read-no-card-and-SAY-so-a-silent-leg-would-read-as-a-clearance', + renderTestVerdict(testVerdict(['src/x.ts'], { repo: REPO, size: { additions: 10, deletions: 0 } })).includes('card total: NOT MEASURED')); + assert('⛔ pullCardReading-fails-closed-when-the-guard-or-the-naming-relation-did-not-load', + (await pullCardReading({ view: cardPullView(splitA), slug: 'o/r', readers: cardReaders([], { loaded: false }), api: {} })).measured === false && + (await pullCardReading({ view: cardPullView(splitA), slug: 'o/r', readers: cardReaders([], { named: false }), api: {} })).measured === false && + (await pullCardReading({ view: cardPullView(splitA), slug: 'o/r', readers: async () => { throw new Error('boom'); }, api: {} })).measured === false); + assert('a-closed-unmerged-sibling-does-not-count-toward-the-card-and-a-merged-one-does', + (await pullCardReading({ view: cardPullView(splitA), slug: 'o/r', readers: cardReaders([splitA, { ...splitB, state: 'closed' }]), api: {} })).exceeds === false && + (await pullCardReading({ view: cardPullView(splitA), slug: 'o/r', readers: cardReaders([splitA, { ...splitB, state: 'closed', merged_at: '2026-11-05T00:00:00Z' }]), api: {} })).exceeds === true); + const sweepWords = renderReport({ window: { since: '2026-11-30T00:00:00Z' }, repos: [], scanned: 0, entries: [], lookups: 0 }); + assert('the-sweep-says-it-reads-no-card-totals-and-names-where-the-per-card-line-is-held', + sweepWords.includes('does NOT read card totals') && sweepWords.includes('--handoff'), sweepWords.slice(0, 400)); + + // ── ⭐ the per-card module (ruling 7303003476): the total, the exemption, the landed list ─ + // + // The predicate the three per-card readers call, judged on its own: what counts, + // when an epic or tracker is exempt (read off the timeline BEFORE any sibling, + // so no cap can make it unread), which merged siblings the hand-off lists, and + // that every unread input is `measured: false`, never a smaller total. + battery('⭐ the per-card module (ruling 7303003476): what counts, the exemption read first, the landed list, every unread input'); + { + const SLUG = 'objectstack-ai/objectstack'; + const LINE = HUMAN_MERGE_LINE_THRESHOLD; + const names = (v, card) => new RegExp(`(?:Fixes|Part of)\\s+#${card}\\b`).test(v.body) || v.head?.ref?.startsWith(`claude/issue-${card}-`); + const pull = (number, { state = 'open', merged = null, created = '2026-11-01T00:00:00Z', add = 0, del = 0, body = '' } = {}) => + cardPullView({ number, state, merged_at: merged, created_at: created, additions: add, deletions: del, body, head: { ref: 'x' } }); + const xref = (n, at = '2026-11-01T00:00:00Z', repo = SLUG, pr = true) => ({ event: 'cross-referenced', created_at: at, source: { issue: { number: n, pull_request: pr ? {} : undefined, repository: { full_name: repo } } } }); + const lab = (name, at, event = 'labeled') => ({ event, label: { name }, created_at: at }); + try { + const text = readFileSync(new URL('./card-pick.mjs', import.meta.url), 'utf8'); + const m = text.match(/export const PARENT_LABELS = Object\.freeze\((\[[^\]]*\])\);/); + const theirs = m ? JSON.parse(m[1].replace(/'/g, '"')) : null; + assert('the-mirror-CARD_EXEMPT_LABELS-equals-card-pick-PARENT_LABELS-in-order-read-as-text-never-imported-a-cycle', JSON.stringify(theirs) === JSON.stringify(CARD_EXEMPT_LABELS), JSON.stringify(theirs)); + } catch (error) { + assert('the-mirror-CARD_EXEMPT_LABELS-equals-card-pick-PARENT_LABELS-in-order-read-as-text-never-imported-a-cycle', false, String(error?.message ?? error)); + } + const v = cardPullView({ number: 7, state: 'closed', merged_at: '2026-11-02T00:00:00Z', created_at: '2026-11-01T00:00:00Z', additions: 10, deletions: 2, body: 'Fixes #5', head: { ref: 'claude/issue-5-x' } }); + assert('cardPullView-reads-the-REST-row-and-nothing-else', v.number === 7 && v.mergedAt === '2026-11-02T00:00:00Z' && v.additions === 10 && v.head.ref === 'claude/issue-5-x', JSON.stringify(v)); + assert('⛔ cardPullView-a-missing-pair-is-null-never-zero-and-a-non-object-row-reads-as-empty', cardPullView({ number: 1 }).additions === null && cardPullView({ number: 1, additions: -1 }).additions === null && cardPullView(null).number === null && cardPullView(null).body === ''); + assert('crossReferencedPulls-same-repository-pulls-only-deduplicated-ascending-case-insensitive', + JSON.stringify(crossReferencedPulls([xref(9), xref(3), xref(9)], SLUG)) === '[3,9]' && crossReferencedPulls([xref(4, undefined, SLUG, false)], SLUG).length === 0 && + crossReferencedPulls([xref(4, undefined, 'objectstack-ai/hotcrm')], SLUG).length === 0 && JSON.stringify(crossReferencedPulls([xref(4, undefined, 'ObjectStack-AI/ObjectStack'), lab('x', 'y')], SLUG)) === '[4]'); + assert('cardFirstPullAt-is-the-earliest-of-this-pulls-opening-and-the-first-pull-cross-reference', + cardFirstPullAt([xref(9, '2026-11-03T00:00:00Z'), xref(8, '2026-11-02T00:00:00Z')], SLUG, '2026-11-05T00:00:00Z') === '2026-11-02T00:00:00Z' && + cardFirstPullAt([xref(9, '2026-11-03T00:00:00Z')], SLUG, '2026-11-01T00:00:00Z') === '2026-11-01T00:00:00Z' && cardFirstPullAt([xref(4, '2026-10-01T00:00:00Z', 'o/other')], SLUG, null) === null); + const FIRST = '2026-11-10T00:00:00Z'; + assert('cardExemption-a-label-at-or-before-the-first-pull-exempts', cardExemption([lab('tracking', '2026-11-01T00:00:00Z')], FIRST).exempt === true && cardExemption([lab('pm:epic', FIRST)], FIRST).exempt === true); + assert('⛔ cardExemption-a-label-added-after-the-first-pull-is-NOT-exempt-and-says-so', (() => { const e = cardExemption([lab('tracking', '2026-11-11T00:00:00Z')], FIRST); return e.exempt === false && /after its first pull/.test(e.reason); })()); + assert('⛔ cardExemption-a-removed-label-exempts-nothing-and-a-re-added-one-is-dated-by-its-LATEST-labeled-event', + cardExemption([lab('tracking', '2026-11-01T00:00:00Z'), lab('tracking', '2026-11-02T00:00:00Z', 'unlabeled')], FIRST).exempt === false && + cardExemption([lab('tracking', '2026-11-01T00:00:00Z'), lab('tracking', '2026-11-05T00:00:00Z', 'unlabeled'), lab('tracking', '2026-11-12T00:00:00Z')], FIRST).exempt === false && + cardExemption([lab('priority:p1', '2026-11-01T00:00:00Z')], FIRST).exempt === false); + const A = pull(101, { add: 2000, body: 'Part of #50', created: '2026-11-01T00:00:00Z' }); + const Bp = pull(102, { add: 2000, body: 'Fixes #50', created: '2026-11-02T00:00:00Z' }); + assert('⭐ the-split-case-two-2000-line-pulls-on-one-card-are-over-read-from-EITHER-and-one-alone-is-under', + cardTotalVerdict({ card: 50, views: [A, Bp], self: 101, namesCard: names, threshold: LINE }).exceeds === true && cardTotalVerdict({ card: 50, views: [Bp, A], self: 102, namesCard: names, threshold: LINE }).total === 4000 && + cardTotalVerdict({ card: 50, views: [A], self: 101, namesCard: names, threshold: LINE }).exceeds === false); + const mixed = cardTotalVerdict({ card: 50, views: [A, pull(103, { state: 'closed', merged: '2026-11-03T00:00:00Z', add: 1500, body: 'Part of #50' }), pull(104, { state: 'closed', add: 5000, body: 'Fixes #50' }), pull(105, { add: 5000, body: 'Refs #50 for context' })], self: 101, namesCard: names, threshold: LINE }); + assert('counting-a-merged-sibling-counts-a-closed-unmerged-one-and-a-mere-mention-do-not', mixed.total === 3500 && mixed.exceeds && mixed.excluded.some((e) => e.number === 104 && /closed without merging/.test(e.why)) && mixed.excluded.some((e) => e.number === 105 && /without naming/.test(e.why)), JSON.stringify(mixed)); + assert('⛔ a-counted-pull-with-no-size-pair-is-UNREADABLE-never-zero', cardTotalVerdict({ card: 50, views: [cardPullView({ number: 9, state: 'open', body: 'Fixes #50' })], self: 9, namesCard: names, threshold: LINE }).measured === false); + // Row 7239077861: every merged sibling of a card read over the line is listed — including the S3 shape, where a + // pull that opened EARLY and grew later would have placed a by-opening-order crossing before the sibling's merge. + const grewLater = pull(111, { add: 2500, body: 'Fixes #50', created: '2026-11-01T00:00:00Z' }); + const mergedSmall = pull(110, { state: 'closed', merged: '2026-11-03T00:00:00Z', add: 900, body: 'Part of #50', created: '2026-11-02T00:00:00Z' }); + const grew = cardTotalVerdict({ card: 50, views: [grewLater, mergedSmall], self: 111, namesCard: names, threshold: LINE }); + assert('⭐ the-landed-list-names-EVERY-merged-sibling-of-an-over-card-even-one-merged-after-a-by-opening-order-crossing-a-pull-that-grew-would-place', + grew.exceeds && grew.landedBeforeCrossing.length === 1 && grew.landedBeforeCrossing[0].number === 110 && grew.crossedAt === '2026-11-02T00:00:00Z', JSON.stringify(grew)); + assert('control: an-under-card-lists-nothing-and-never-lists-this-pull-itself', + cardTotalVerdict({ card: 50, views: [A, pull(112, { state: 'closed', merged: '2026-11-02T00:00:00Z', add: 10, body: 'Part of #50' })], self: 101, namesCard: names, threshold: LINE }).landedBeforeCrossing.length === 0 && + cardTotalVerdict({ card: 50, views: [pull(113, { state: 'closed', merged: '2026-11-02T00:00:00Z', add: 4000, body: 'Fixes #50' })], self: 113, namesCard: names, threshold: LINE }).landedBeforeCrossing.length === 0); + const self = pull(201, { add: 2000, body: 'Fixes #60', created: '2026-11-05T00:00:00Z' }); + const sib = pull(202, { add: 2000, body: 'Part of #60' }); + const tl = async () => [xref(202), xref(201, '2026-11-05T00:00:00Z')]; + const pv = async (n) => (n === 202 ? sib : null); + const ok = await readCardSize({ self, named: [60], slug: SLUG, threshold: LINE, namesCard: names, fetchTimeline: tl, fetchPullView: pv }); + assert('readCardSize-a-readable-card-is-read-and-judged-over', ok.measured === true && ok.exceeds === true && JSON.stringify(ok.over) === '[60]' && ok.apiCalls === 2, JSON.stringify(ok)); + // ⭐ M1: an epic past the sibling cap is EXEMPT, read off the timeline alone — no sibling read, never unread. + const many = Array.from({ length: 80 }, (_, i) => xref(1000 + i, '2026-11-02T00:00:00Z')); + let siblingReads = 0; + const epic = await readCardSize({ self, named: [60], slug: SLUG, threshold: LINE, namesCard: names, fetchTimeline: async () => [lab('pm:epic', '2026-10-01T00:00:00Z'), ...many], fetchPullView: async () => { siblingReads += 1; return sib; } }); + assert('⭐ an-epic-or-tracker-PAST-the-sibling-cap-is-EXEMPT-read-off-the-timeline-before-any-sibling-never-unread', + epic.measured === true && epic.exceeds === false && epic.cards[0].exempt === true && siblingReads === 0 && epic.apiCalls === 1, JSON.stringify({ epic, siblingReads })); + const late = await readCardSize({ self, named: [60], slug: SLUG, threshold: LINE, namesCard: names, fetchTimeline: async () => [xref(202, '2026-11-01T00:00:00Z'), lab('tracking', '2026-11-04T00:00:00Z'), xref(201, '2026-11-05T00:00:00Z')], fetchPullView: pv }); + assert('⛔ a-tracker-label-put-on-after-the-cards-first-cross-referenced-pull-exempts-nothing-the-siblings-are-read-and-summed', late.measured === true && late.exceeds === true && late.cards[0].exempt === false, JSON.stringify(late)); + assert('⛔ a-NON-exempt-card-over-the-sibling-cap-refuses-rather-than-total-a-subset', (await readCardSize({ self, named: [60], slug: SLUG, threshold: LINE, namesCard: names, fetchTimeline: tl, fetchPullView: pv, siblingCap: 0 })).measured === false); + assert('⛔ readCardSize-a-timeline-or-sibling-that-throws-or-no-naming-relation-is-UNREADABLE-never-a-smaller-total', + (await readCardSize({ self, named: [60], slug: SLUG, threshold: LINE, namesCard: names, fetchTimeline: async () => { throw new Error('more than 3000 events'); }, fetchPullView: pv })).measured === false && + (await readCardSize({ self, named: [60], slug: SLUG, threshold: LINE, namesCard: names, fetchTimeline: tl, fetchPullView: async () => { throw new Error('HTTP 502'); } })).measured === false && + (await readCardSize({ self, named: null, slug: SLUG, threshold: LINE, namesCard: names, fetchTimeline: tl, fetchPullView: pv })).measured === false); + assert('a-pull-counting-toward-no-card-is-measured-with-nothing-to-add', (await readCardSize({ self, named: [], slug: SLUG, threshold: LINE, namesCard: names, fetchTimeline: tl, fetchPullView: pv })).exceeds === false); + const words = (r) => renderCardLines(r).join('\n'); + assert('renderCardLines-every-reading-says-what-it-read', + words(null).includes('NOT MEASURED') && words(null).includes('--pr') && words({ measured: false, reason: 'r' }).includes('UNREAD') && words({ measured: false, reason: 'r' }).includes('authorised approval') && + words(ok).includes('OVER the line BY THE CARD') && words({ measured: true, cards: [grew] }).includes('#110') && words({ measured: true, cards: [] }).includes('counts toward no card') && words(epic).includes('EXEMPT')); + } + // ── ⭐ #19036: the sweep lists an OVERSIZED landing beside the governed ones ─ // // The queue half of #19036 lives in the guard; this is the audit half. Until diff --git a/scripts/pm/check-governed-queue-guard.mjs b/scripts/pm/check-governed-queue-guard.mjs index 9fdd437be44..fbb7b3817d2 100644 --- a/scripts/pm/check-governed-queue-guard.mjs +++ b/scripts/pm/check-governed-queue-guard.mjs @@ -745,6 +745,10 @@ import { ruleChangeRecordReasons, repoIdForSlug, testVerdict, + CARD_TIMELINE_PAGES, + cardPullView, + readCardSize, + renderCardLines, } from './check-governed-merges.mjs'; import { CLAUSE2_ARMS, CLAUSE2_VALUES, METADATA_PROTOCOL_KINDS, readClause2Line, readMetadataProtocolLine } from './clause2-line.mjs'; import { gitFreeEnv } from '../git-env.mjs'; @@ -790,6 +794,9 @@ const SELF_TEST_BATTERIES = Object.freeze({ '⭐ #18020 → #19133 Tier S: a review of record, not an approval': 43, '⭐ #18701: the record lives on the PR or its card, and BOTH are read': 14, '⛔ #19036: the SIZE line at the queue — imported, per queued PR, fail-closed': 54, + // The per-card count at the queue (ruling 7303003476): the split case and its words, its control, closed vs merged + // siblings, three fail-closed readings, the lift (on a card over the line and on an unread one), and the reader's view. + '⭐ the per-card count at the queue (ruling 7303003476): a pull under the line refuses when its card totals more': 10, '⭐ #19344: the remedy names a path the ruleset actually offers': 5, '⛔ the queued pull-back: the landing seat sends the relay dequeue, never a DRAFT conversion': 4, '⭐ the 2026-09-20 ruling: a certified PURE REGENERATION carries the record to the queued head': 13, @@ -834,7 +841,8 @@ const SELF_TEST_BATTERIES = Object.freeze({ // Raised 30 → 31 with the low-risk skills arm battery (#33501): one battery, one row. // Raised 31 → 32 with its ADR leg battery (#33539): one battery, one row. // Raised 32 → 34 with the two #35321 batteries (the declaration split at the queue, the narrowed leg): two rows. -const SELF_TEST_BATTERY_FLOOR = 34; +// Raised 34 → 35 with the per-card count battery (ruling 7303003476): one battery, one row. +const SELF_TEST_BATTERY_FLOOR = 35; // The key an assertion is filed under when no battery is open. It is not a // declared battery, so it reds by the same set difference rather than silently @@ -1160,6 +1168,9 @@ export async function loadRecordRecognisers(load = (specifier) => import(specifi deliveredCard: tier?.deliveredCardNumber, // Every card the pull names (the arm's card conjunct reads the `security` label on each, not on the one above). namedCards: tier?.namedCardNumbers, + // The cards a pull's size COUNTS toward (ruling 7303003476): the option A pair and the dev branch, never `Refs`. + // Not in the required list below: its readers (the per-card size leg) fail closed on a missing one themselves. + countedCards: tier?.countedCardNumbers, servedTierStands: tier?.servedTierStands, isModelIdentifierToken: tier?.isModelIdentifierToken, reviewFace: tier?.reviewFace, @@ -2955,6 +2966,9 @@ export const SIZE_LEG_NAME = 'Human-Merge Size Line (2026-09-18 ruling)'; * that is precisely the fail-open reading this leg exists to refuse. */ export function sizeReading(pr, size, repo, approval = null) { + // ⭐ The per-card total (ruling 7303003476) rides in `size.card`: `sizeVerdict` reads a card over the line, AND a + // card reading that did not read, as over — so either is `oversized` here and the approval lift is consulted, the + // human path, ⛔ never `within`. A size handed with no `card` key is judged on its own number. const verdict = testVerdict([], { repo, size, approval }); if (verdict.size?.measured !== true) { return { @@ -3025,7 +3039,7 @@ export function sizeGuardVerdict({ event, repo, pulls = [], readings = new Map() * count is printed and pinned. A throw is caught into an `unreadable` reading, * never a pass and never an escaping rejection. */ -export async function runSizeGuard({ event, repo, rows, namedPull = null, fetchPull, fetchReviews = null, fetchTimeline = null, approvals = new Map() }) { +export async function runSizeGuard({ event, repo, rows, namedPull = null, fetchPull, fetchReviews = null, fetchTimeline = null, approvals = new Map(), readCard = null }) { assertGovernedRepo(repo, 'runSizeGuard'); if (event !== EVENT_MERGE_GROUP) return sizeGuardVerdict({ event, repo }); const pulls = queuedPullsInGroup(rows, namedPull); @@ -3035,7 +3049,20 @@ export async function runSizeGuard({ event, repo, rows, namedPull = null, fetchP try { apiCalls += 1; const pull = await fetchPull(pr); - let reading = sizeReading(pr, pull?.size ?? null, repo); + // ⭐ The card total (ruling 7303003476), read for EVERY queued pull — one under the line is over it when its + // card's open and merged pulls total more. No reader supplied is an unread total, read as over: fail closed to + // the human path (liftable by that pull's authorised approval). + let card = { measured: false, reason: 'no card reader was supplied to the size leg', apiCalls: 0 }; + if (pull?.size && typeof readCard === 'function') { + try { + card = await readCard(pull); + } catch (error) { + card = { measured: false, reason: String(error?.message ?? error).split('\n')[0], apiCalls: 0 }; + } + apiCalls += card?.apiCalls ?? 0; + } + const sized = pull?.size ? { ...pull.size, card } : null; + let reading = sizeReading(pr, sized, repo); if (reading.state === 'oversized') { // ⭐ THE LIFT (2026-09-27, #20153): over the line, so the approval is // consulted — the SAME verdict the governed leg computed on this build @@ -3074,7 +3101,7 @@ export async function runSizeGuard({ event, repo, rows, namedPull = null, fetchP } approval = { ...approval, enqueue }; } - reading = sizeReading(pr, pull?.size ?? null, repo, approval); + reading = sizeReading(pr, sized, repo, approval); } readings.set(pr, reading); } catch (error) { @@ -3089,6 +3116,35 @@ export async function runSizeGuard({ event, repo, rows, namedPull = null, fetchP return sizeGuardVerdict({ event, repo, pulls, readings, apiCalls }); } +/** + * The size leg's card reader (ruling 7303003476, `readCardSize` in `check-governed-merges.mjs`): for one pull the + * `fetchPull` above answered, every card it COUNTS toward (the record recognisers' `countedCards`, loaded once, + * lazily), each card's whole timeline and its cross-referenced pulls — siblings read through the SAME `fetchPull` + * (so a sibling queued beside it costs no second pull GET where that reader caches) and the timeline through + * `fetchTimeline`, once per queued pull that counts toward the card. Answers `readCardSize`'s reading; recognisers + * that did not load are an unread total. Never throws. + */ +export function makeCardReader({ slug, fetchPull, fetchTimeline, loadRecognisers = loadRecordRecognisers }) { + let loading = null; + return async function readCard(pull) { + loading ??= Promise.resolve().then(() => loadRecognisers()).catch((error) => ({ available: false, reason: String(error?.message ?? error).split('\n')[0] })); + const recognisers = await loading; + if (recognisers?.available !== true || typeof recognisers.countedCards !== 'function') { + return { measured: false, reason: `the naming relation did not load (${recognisers?.reason ?? 'the recognisers carry no countedCards'})`, apiCalls: 0 }; + } + const self = pull?.view ?? null; + return readCardSize({ + self, + named: self ? recognisers.countedCards(self) : null, + slug, + threshold: HUMAN_MERGE_LINE_THRESHOLD, + namesCard: (view, card) => recognisers.countedCards(view).includes(card), + fetchTimeline, + fetchPullView: async (n) => (await fetchPull(n))?.view ?? null, + }); + }; +} + // ── #19344: the remedy's terminal is a RULESET fact, so it is READ ───────── // // GitHub offers it only to an account ruleset `main` lists as a bypass actor, @@ -3135,7 +3191,9 @@ export function renderSizeVerdict(verdict) { `${SIZE_LEG_NAME} — ${verdict.event} — ${verdict.entries.length} queued pull request(s), ` + `${verdict.apiCalls} pull read(s).`, ); - const numbers = (e) => `${e.verdict.size.changedLines} changed line(s) (+${e.verdict.size.additions} / -${e.verdict.size.deletions})`; + const numbers = (e) => + `${e.verdict.size.changedLines} changed line(s) (+${e.verdict.size.additions} / -${e.verdict.size.deletions})` + + (e.verdict.size.exceedsBy !== 'card' ? '' : e.verdict.size.card?.measured === true ? ' on this pull, its CARD\'s pulls totalling more (below),' : ' on this pull, its CARD\'s total UNREAD (below) and so read as over,'); // Why an oversized entry was NOT lifted, off the approval verdict this leg // read (or reused): the four non-lift cases of the 2026-09-27 ruling, named. // ...and the enqueue reading beside it (2026-10-26), named the same way. @@ -3182,6 +3240,8 @@ export function renderSizeVerdict(verdict) { } else { lines.push('', ` #${entry.pr} — ✅ ${numbers(entry)}, at or under the human-merge line ${entry.verdict.size.threshold}.`); } + // The per-card total behind the entry (ruling 7303003476): an entry over by its CARD says which card, and why. + if (entry.state !== 'unreadable' && entry.verdict?.size?.card) lines.push(...renderCardLines(entry.verdict.size.card).map((l) => ` ${l}`)); } if (verdict.conclusion === 'clear') { @@ -3935,6 +3995,9 @@ export function makePullReader({ apiUrl, slug, token, fetchImpl = fetch }) { fork: forkVerdict(row), headRef: String(row?.head?.ref ?? ''), size: pair === null ? null : { ...pair, source: `GET /repos/${slug}/pulls/${pull}` }, + // The per-card reading's view of the same object (`cardPullView`): state, merge and open times, the pair, + // the body and the head branch — what a card total reads of this pull, and of each sibling. + view: cardPullView(row), }; }; } @@ -4186,6 +4249,9 @@ async function main() { fetchPull, fetchReviews, fetchTimeline, + // The per-card total (ruling 7303003476): the same pull reader, a card timeline read to `CARD_TIMELINE_PAGES`, the + // recognisers' `countedCards` relation. + readCard: makeCardReader({ slug: reader.slug, fetchPull, fetchTimeline: makeTimelineReader({ ...reader, maxPages: CARD_TIMELINE_PAGES }) }), // The enqueue reading rides WITH the approval verdict it was read beside, // so the size lift reads both off one object and never re-reads either. approvals: new Map(verdict.entries.map((e) => [e.pr, e.enqueue === undefined ? e.approval : { ...e.approval, enqueue: e.enqueue }])), @@ -4298,6 +4364,8 @@ const REPLAYS = [ let selfTestReachedVerdict = false; export async function selfTest() { + // The size leg's card reader for the cases that judge ONE pull's own number: a pull naming no card (ruling 7303003476's battery reads real ones). + const NO_CARD_READ = async () => ({ measured: true, cards: [], exceeds: false, over: [], apiCalls: 0 }); // The battery ledger this self-test's floor is evaluated against (#13489). // `battery()` opens a battery; every assertion below is attributed to the one // most recently opened, so a section that stops running stops registering and @@ -4395,7 +4463,7 @@ export async function selfTest() { const liftRejects = await liftGeneratedExceptions('/w', 'base', [], []).then(() => null, (error) => error); assert('⛔ and-so-are-the-verdict-builders-the-size-leg-and-the-lift', [() => guardVerdict({ event: 'merge_group' }), () => sizeGuardVerdict({ event: EVENT_MERGE_GROUP, pulls: [1] }), () => sizeReading(1, { additions: 1, deletions: 1 })].every((fn) => threw(fn) instanceof TypeError) && liftRejects instanceof TypeError, String(liftRejects?.message)); const guardRejects = await runGuard({ event: 'merge_group', rows: [row(1, [WF])], fetchReviews: async () => [], fetchPull: async () => pull() }).then(() => null, (error) => error); - const sizeRejects = await runSizeGuard({ event: EVENT_MERGE_GROUP, rows: [row(1, [WF])], fetchPull: async () => pull() }).then(() => null, (error) => error); + const sizeRejects = await runSizeGuard({ readCard: NO_CARD_READ, event: EVENT_MERGE_GROUP, rows: [row(1, [WF])], fetchPull: async () => pull() }).then(() => null, (error) => error); assert('⛔ runGuard-and-runSizeGuard-REJECT-without-a-repository', guardRejects instanceof TypeError && sizeRejects instanceof TypeError, `${guardRejects?.message}\n${sizeRejects?.message}`); assert('an-unknown-repository-is-refused-too-with-the-roster-in-the-words', threw(() => decomposeGovernedWork([row(1, [WF])], 'objectstack-ai/objectstack')) instanceof TypeError && /not a GOVERNED_REPOS id/.test(threw(() => decomposeGovernedWork([row(1, [WF])], 'objectstack-ai/objectstack')).message)); // Where main() gets the repository: GITHUB_REPOSITORY, resolved; unset means this file's own. @@ -5463,7 +5531,7 @@ export async function selfTest() { sizePrLeg.conclusion === 'not-applicable' && sizePrLeg.exitCode === EXIT_CLEAR && renderSizeVerdict(sizePrLeg) === '', ); let sizeReadsOnPr = 0; - const sizePrRun = await runSizeGuard({ + const sizePrRun = await runSizeGuard({ readCard: NO_CARD_READ, repo: REPO, event: EVENT_PULL_REQUEST, rows: [queuedRow(5)], @@ -5475,7 +5543,7 @@ export async function selfTest() { assert('and-makes-ZERO-pull-reads-there-measured-with-a-spy-that-THROWS', sizeReadsOnPr === 0 && sizePrRun.apiCalls === 0 && sizePrRun.conclusion === 'not-applicable'); // End to end through the orchestrator: one pull read per queued PR, the enumeration `queuedPullsInGroup`'s. const sizeReads = []; - const e2eSize = await runSizeGuard({ + const e2eSize = await runSizeGuard({ readCard: NO_CARD_READ, repo: REPO, event: EVENT_MERGE_GROUP, rows: [queuedRow(11), queuedRow(22), queuedRow(11)], @@ -5491,7 +5559,7 @@ export async function selfTest() { JSON.stringify({ reads: sizeReads, apiCalls: e2eSize.apiCalls, exit: e2eSize.exitCode }), ); let sizeUrl = ''; - const e2eReader = await runSizeGuard({ + const e2eReader = await runSizeGuard({ readCard: NO_CARD_READ, repo: REPO, event: EVENT_MERGE_GROUP, rows: [queuedRow(42)], @@ -5508,7 +5576,7 @@ export async function selfTest() { /\/repos\/o\/r\/pulls\/42$/.test(sizeUrl) && e2eReader.exitCode === EXIT_CLEAR && renderSizeVerdict(e2eReader).includes('12 changed line(s) (+10 / -2)'), sizeUrl, ); - const e2eSizeThrows = await runSizeGuard({ + const e2eSizeThrows = await runSizeGuard({ readCard: NO_CARD_READ, repo: REPO, event: EVENT_MERGE_GROUP, rows: [queuedRow(11)], @@ -5521,7 +5589,7 @@ export async function selfTest() { e2eSizeThrows.exitCode === EXIT_REFUSED_SIZE_UNREADABLE && /403/.test(renderSizeVerdict(e2eSizeThrows)) && /REFUSED/.test(renderSizeVerdict(e2eSizeThrows)), renderSizeVerdict(e2eSizeThrows), ); - const e2eNoPair = await runSizeGuard({ repo: REPO, event: EVENT_MERGE_GROUP, rows: [queuedRow(11)], fetchPull: async () => pull() }); + const e2eNoPair = await runSizeGuard({ readCard: NO_CARD_READ, repo: REPO, event: EVENT_MERGE_GROUP, rows: [queuedRow(11)], fetchPull: async () => pull() }); assert( '⛔ a-pull-object-with-no-pair-is-exit-9-too', e2eNoPair.exitCode === EXIT_REFUSED_SIZE_UNREADABLE && /no `additions` \/ `deletions` pair/.test(renderSizeVerdict(e2eNoPair)), @@ -5535,7 +5603,7 @@ export async function selfTest() { throw new Error('the governed leg must not read for an ungoverned diff'); }; const g18971 = await runGuard({ repo: REPO, event: EVENT_MERGE_GROUP, rows: pr18971, fetchReviews: explodeForSize, fetchPull: explodeForSize, fetchComments: explodeForSize }); - const s18971 = await runSizeGuard({ + const s18971 = await runSizeGuard({ readCard: NO_CARD_READ, repo: REPO, event: EVENT_MERGE_GROUP, rows: pr18971, @@ -5580,7 +5648,7 @@ export async function selfTest() { // code, already the top of the table. const bothRows = [row(9527, ['AGENTS.md', 'packages/x.ts'])]; const gBoth = await runGuard({ repo: REPO, event: EVENT_MERGE_GROUP, rows: bothRows, fetchReviews: async () => [], fetchPull: async () => pull(HEAD, { size: sizePair(LINE, 1) }), fetchComments: async () => [] }); - const sBoth = await runSizeGuard({ repo: REPO, event: EVENT_MERGE_GROUP, rows: bothRows, fetchPull: async () => pull(HEAD, { size: sizePair(LINE, 1) }) }); + const sBoth = await runSizeGuard({ readCard: NO_CARD_READ, repo: REPO, event: EVENT_MERGE_GROUP, rows: bothRows, fetchPull: async () => pull(HEAD, { size: sizePair(LINE, 1) }) }); assert( '⭐ governed-AND-oversized-prints-BOTH-limbs-and-exits-on-the-GOVERNED-code', gBoth.exitCode === EXIT_REFUSED_UNAPPROVED && sBoth.exitCode === EXIT_REFUSED_OVERSIZED && @@ -5600,7 +5668,7 @@ export async function selfTest() { // is handed to the size leg, which reads it — no second review read (the spy // throws) — and the group exits 0 on both limbs. let sizeReviewReadsReused = 0; - const sApprovedBig = await runSizeGuard({ + const sApprovedBig = await runSizeGuard({ readCard: NO_CARD_READ, repo: REPO, event: EVENT_MERGE_GROUP, rows: bothRows, @@ -5620,7 +5688,7 @@ export async function selfTest() { ); // The register's lift lifts a PATH, never the number: rows whose every path // the register lifted still pay the size — and with no approval, still refuse. - const liftedAll = await runSizeGuard({ + const liftedAll = await runSizeGuard({ readCard: NO_CARD_READ, repo: REPO, event: EVENT_MERGE_GROUP, rows: [{ sha: 'f'.repeat(40), subject: 'x (#77)', pr: 77, paths: [] }], @@ -5632,7 +5700,7 @@ export async function selfTest() { const bigUngoverned = (pr = 20125) => [{ sha: 'c'.repeat(40), subject: `feat!: retire the saved-report stack (#${pr})`, pr, paths: ['packages/x.ts', 'packages/y.ts'] }]; const PR20125_SHA = 'e4ead748' + '1'.repeat(32); const liftRun = (reviews, { size = sizePair(10764, 999, 'GET /repos/objectstack-ai/objectstack/pulls/20125'), sha = PR20125_SHA } = {}) => - runSizeGuard({ + runSizeGuard({ readCard: NO_CARD_READ, repo: REPO, event: EVENT_MERGE_GROUP, rows: bigUngoverned(), @@ -5687,7 +5755,7 @@ export async function selfTest() { /review list could NOT be read \(GET \/repos\/o\/r\/pulls\/20125\/reviews answered HTTP 403\) — fail closed, no lift/.test(renderSizeVerdict(reviewsThrow)), renderSizeVerdict(reviewsThrow), ); - const noReader = await runSizeGuard({ repo: REPO, event: EVENT_MERGE_GROUP, rows: bigUngoverned(), fetchPull: async () => pull(PR20125_SHA, { size: sizePair(LINE, 1) }) }); + const noReader = await runSizeGuard({ readCard: NO_CARD_READ, repo: REPO, event: EVENT_MERGE_GROUP, rows: bigUngoverned(), fetchPull: async () => pull(PR20125_SHA, { size: sizePair(LINE, 1) }) }); assert( '⛔ a-size-leg-run-with-NO-review-reader-at-all-fails-CLOSED-on-8-too', noReader.exitCode === EXIT_REFUSED_OVERSIZED && /no review reader was supplied/.test(renderSizeVerdict(noReader)), @@ -5784,6 +5852,56 @@ export async function selfTest() { assert('the-workflow-is-readable-for-the-size-scope-pin', false, String(error?.message ?? error).split('\n')[0]); } + // ── ⭐ the per-card count at the queue (ruling 7303003476) ───────────────── + // + // The size leg reads every queued pull's CARD total through `makeCardReader`: + // the recognisers' naming relation, the card timeline and each sibling read + // through the SAME pull reader. Two 2,000-line pulls on one card refuse in + // BOTH; an unread card total is `unreadable` (exit 9), never `within`. + battery('⭐ the per-card count at the queue (ruling 7303003476): a pull under the line refuses when its card totals more'); + const CARD = 77; + const cardRow = (number, body, add, extra = {}) => ({ number, state: 'open', merged_at: null, created_at: `2026-11-0${number % 9 + 1}T00:00:00Z`, additions: add, deletions: 0, body, head: { sha: 'c'.repeat(40), ref: 'x' }, ...extra }); + const cardRecognisers = async () => ({ available: true, countedCards: (p) => [...String(p?.body ?? '').matchAll(/(?:Fixes|Part of)\s+#(\d+)/g)].map((m) => Number(m[1])) }); + const cardFixture = (rows) => { + const reads = []; + const fetchCardPull = async (n) => { + reads.push(n); + const r = rows.find((x) => x.number === n); + if (!r) throw new Error(`GET /pulls/${n} answered HTTP 404`); + return { ...pull('c'.repeat(40), { body: r.body, size: sizePair(r.additions, 0) }), view: cardPullView(r) }; + }; + const fetchCardTimeline = async () => rows.map((r) => ({ event: 'cross-referenced', source: { issue: { number: r.number, pull_request: {}, repository: { full_name: 'o/r' } } } })); + return { reads, fetchPull: fetchCardPull, fetchTimeline: fetchCardTimeline, readCard: makeCardReader({ slug: 'o/r', fetchPull: fetchCardPull, fetchTimeline: fetchCardTimeline, loadRecognisers: cardRecognisers }) }; + }; + const twoOnOne = [cardRow(401, `Part of #${CARD}`, 2000), cardRow(402, `Fixes #${CARD}`, 2000)]; + const fxA = cardFixture(twoOnOne); + const splitRun = await runSizeGuard({ repo: REPO, event: EVENT_MERGE_GROUP, rows: [queuedRow(401), queuedRow(402)], fetchPull: fxA.fetchPull, fetchReviews: async () => [], fetchTimeline: async () => [], readCard: fxA.readCard }); + assert('⭐ the-split-case-two-2000-line-pulls-on-one-card-are-BOTH-oversized-at-the-queue-exit-8', + splitRun.exitCode === EXIT_REFUSED_OVERSIZED && splitRun.entries.every((e) => e.state === 'oversized' && e.verdict.size.exceedsBy === 'card'), JSON.stringify(splitRun.entries.map((e) => [e.pr, e.state, e.reason]))); + assert('and-the-log-names-the-card-its-total-and-that-the-CARD-put-it-over', (() => { const w = renderSizeVerdict(splitRun); return w.includes('card #77: 4000 changed line(s) across 2 pull(s)') && w.includes('OVER the line BY THE CARD') && w.includes("its CARD's pulls totalling more"); })(), renderSizeVerdict(splitRun)); + const aloneFx = cardFixture([cardRow(401, `Part of #${CARD}`, 2000)]); + const aloneRun = await runSizeGuard({ repo: REPO, event: EVENT_MERGE_GROUP, rows: [queuedRow(401)], fetchPull: aloneFx.fetchPull, readCard: aloneFx.readCard }); + assert('control: one-2000-line-pull-alone-on-its-card-is-within-and-the-group-clears', aloneRun.exitCode === EXIT_CLEAR && aloneRun.entries[0].state === 'within', JSON.stringify(aloneRun.entries)); + const closedFx = cardFixture([cardRow(401, `Part of #${CARD}`, 2000), cardRow(403, `Fixes #${CARD}`, 2000, { state: 'closed' })]); + assert('⛔ a-closed-unmerged-sibling-adds-nothing-and-a-merged-one-does', + (await runSizeGuard({ repo: REPO, event: EVENT_MERGE_GROUP, rows: [queuedRow(401)], fetchPull: closedFx.fetchPull, readCard: closedFx.readCard })).exitCode === EXIT_CLEAR && + (await runSizeGuard({ repo: REPO, event: EVENT_MERGE_GROUP, rows: [queuedRow(401)], fetchReviews: async () => [], fetchTimeline: async () => [], ...(() => { const f = cardFixture([cardRow(401, `Part of #${CARD}`, 2000), cardRow(403, `Fixes #${CARD}`, 2000, { state: 'closed', merged_at: '2026-11-02T00:00:00Z' })]); return { fetchPull: f.fetchPull, readCard: f.readCard }; })() })).exitCode === EXIT_REFUSED_OVERSIZED); + const brokenFx = cardFixture([cardRow(401, `Part of #${CARD}`, 2000)]); + const brokenRun = await runSizeGuard({ repo: REPO, event: EVENT_MERGE_GROUP, rows: [queuedRow(401)], fetchPull: brokenFx.fetchPull, readCard: makeCardReader({ slug: 'o/r', fetchPull: brokenFx.fetchPull, fetchTimeline: async () => { throw new Error('more than 1000 timeline events'); }, loadRecognisers: cardRecognisers }) }); + assert('⛔ an-UNREAD-card-total-is-read-as-OVER-the-line-oversized-exit-8-never-within-and-the-log-says-UNREAD', + brokenRun.exitCode === EXIT_REFUSED_OVERSIZED && brokenRun.entries[0].state === 'oversized' && brokenRun.entries[0].verdict.size.exceedsBy === 'card' && brokenRun.entries[0].verdict.size.card.measured === false && + renderSizeVerdict(brokenRun).includes("its CARD's total UNREAD") && renderSizeVerdict(brokenRun).includes('card total: UNREAD'), JSON.stringify(brokenRun.entries.map((e) => [e.state, e.reason]))); + const noReaderRun = await runSizeGuard({ repo: REPO, event: EVENT_MERGE_GROUP, rows: [queuedRow(401)], fetchPull: brokenFx.fetchPull }); + assert('⛔ a-size-leg-run-with-NO-card-reader-is-an-unread-total-too-oversized-fail-closed', noReaderRun.exitCode === EXIT_REFUSED_OVERSIZED && /no card reader/.test(noReaderRun.entries[0].verdict.size.card.reason), JSON.stringify(noReaderRun.entries.map((e) => [e.state, e.reason]))); + const brokenApproved = await runSizeGuard({ repo: REPO, event: EVENT_MERGE_GROUP, rows: [queuedRow(401)], fetchPull: brokenFx.fetchPull, readCard: makeCardReader({ slug: 'o/r', fetchPull: brokenFx.fetchPull, fetchTimeline: async () => { throw new Error('HTTP 502'); }, loadRecognisers: cardRecognisers }), fetchReviews: async () => [{ user: { login: GOVERNED_APPROVERS[0] }, state: 'APPROVED', commit_id: 'c'.repeat(40), submitted_at: '2026-11-03T00:00:00Z' }] }); + assert('⭐ an-unread-card-total-on-a-pull-with-an-AUTHORISED-approval-is-LIFTED-the-human-path-holds-and-the-group-clears', + brokenApproved.exitCode === EXIT_CLEAR && brokenApproved.entries[0].state === 'lifted', JSON.stringify(brokenApproved.entries.map((e) => [e.state, e.reason]))); + const noRelation = await makeCardReader({ slug: 'o/r', fetchPull: brokenFx.fetchPull, fetchTimeline: async () => [], loadRecognisers: async () => ({ available: false, reason: 'fixture' }) })(await brokenFx.fetchPull(401)); + assert('⛔ recognisers-that-did-not-load-are-an-unread-total-never-a-pull-naming-no-card', noRelation.measured === false && /naming relation did not load/.test(noRelation.reason), JSON.stringify(noRelation)); + assert('⭐ the-lift-still-lifts-a-card-limb-entry-an-authorized-approval-on-THAT-pull-clears-it', + (await runSizeGuard({ repo: REPO, event: EVENT_MERGE_GROUP, rows: [queuedRow(401)], fetchPull: fxA.fetchPull, readCard: fxA.readCard, fetchReviews: async () => [{ user: { login: GOVERNED_APPROVERS[0] }, state: 'APPROVED', commit_id: 'c'.repeat(40), submitted_at: '2026-11-03T00:00:00Z' }] })).entries[0].state === 'lifted'); + assert('the-pull-reader-carries-the-card-view-off-the-SAME-GET', (await makePullReader({ apiUrl: 'https://api.example', slug: 'o/r', token: null, fetchImpl: async () => ({ ok: true, json: async () => cardRow(9, 'Fixes #5', 3) }) })(9)).view?.body === 'Fixes #5'); + // ── ⭐ #19344: the remedy names a path the RULESET actually offers ──────── // // RECORDED, not live: this self-test is the required guard job's FIRST step, @@ -6850,19 +6968,19 @@ export async function selfTest() { // The SIZE limb follows the same predicate — through the sibling's lift, never one spelled here. const BIG = { additions: 6000, deletions: 1 }; - const bigEnqueued = await runSizeGuard({ repo: REPO, event: EVENT_MERGE_GROUP, rows: [row(18971, ['packages/x.ts'])], fetchPull: async () => pull(HEAD, { size: BIG }), fetchReviews: async () => [], fetchTimeline: timelineOf([added(GOVERNED_APPROVERS[0])]) }); + const bigEnqueued = await runSizeGuard({ readCard: NO_CARD_READ, repo: REPO, event: EVENT_MERGE_GROUP, rows: [row(18971, ['packages/x.ts'])], fetchPull: async () => pull(HEAD, { size: BIG }), fetchReviews: async () => [], fetchTimeline: timelineOf([added(GOVERNED_APPROVERS[0])]) }); const bigEnqueuedText = renderSizeVerdict(bigEnqueued); assert('⭐ an-oversized-PR-the-maintainer-ENQUEUED-is-LIFTED-and-the-log-names-the-enqueuer', bigEnqueued.exitCode === EXIT_CLEAR && bigEnqueued.entries[0].state === 'lifted' && bigEnqueued.apiCalls === 3 && bigEnqueuedText.includes(`LIFTED by the maintainer's own`) && bigEnqueuedText.includes(`${GOVERNED_APPROVERS[0]} (enqueued it at 2026-10-26T15:00:00Z)`), bigEnqueuedText); - const bigSeat = await runSizeGuard({ repo: REPO, event: EVENT_MERGE_GROUP, rows: [row(18971, ['packages/x.ts'])], fetchPull: async () => pull(HEAD, { size: BIG }), fetchReviews: async () => [], fetchTimeline: timelineOf([added(SEAT)]) }); + const bigSeat = await runSizeGuard({ readCard: NO_CARD_READ, repo: REPO, event: EVENT_MERGE_GROUP, rows: [row(18971, ['packages/x.ts'])], fetchPull: async () => pull(HEAD, { size: BIG }), fetchReviews: async () => [], fetchTimeline: timelineOf([added(SEAT)]) }); assert('⛔ an-oversized-PR-a-SEAT-enqueued-is-still-REFUSED-on-8-and-says-why', bigSeat.exitCode === EXIT_REFUSED_OVERSIZED && renderSizeVerdict(bigSeat).includes(`enqueued by ${SEAT}, outside GOVERNED_APPROVERS`), renderSizeVerdict(bigSeat)); // main()'s own wiring, reproduced: the governed leg's enqueue reading rides into the size leg and is NOT read twice. let timelineReads = 0; const countedTimeline = async () => { timelineReads += 1; return [added(GOVERNED_APPROVERS[0])]; }; const bigGovernedRows = [row(26066, ['AGENTS.md'])]; const bigGoverned = await runGuard({ repo: REPO, event: EVENT_MERGE_GROUP, rows: bigGovernedRows, fetchReviews: async () => [], fetchPull: async () => pull(HEAD, { size: BIG }), fetchTimeline: countedTimeline }); - const bigGovernedSize = await runSizeGuard({ + const bigGovernedSize = await runSizeGuard({ readCard: NO_CARD_READ, repo: REPO, event: EVENT_MERGE_GROUP, rows: bigGovernedRows, fetchPull: async () => pull(HEAD, { size: BIG }), fetchReviews: async () => [], fetchTimeline: countedTimeline, approvals: new Map(bigGoverned.entries.map((e) => [e.pr, e.enqueue === undefined ? e.approval : { ...e.approval, enqueue: e.enqueue }])), }); diff --git a/scripts/pm/dispatch-gates.mjs b/scripts/pm/dispatch-gates.mjs index be8840fe9ac..d0b68e4212f 100644 --- a/scripts/pm/dispatch-gates.mjs +++ b/scripts/pm/dispatch-gates.mjs @@ -14055,6 +14055,7 @@ export function changedLineLines(size) { `Changed lines — NOT MEASURED: a path list carries no diff to count. The human-merge threshold (${t},` + ' additions + deletions, generated files INCLUDED) is read off the worktree by this tool run with no paths,' + ' and at landing by `node scripts/pm/check-governed-merges.mjs --pr `.', + CARD_TOTAL_LINE, ]; } const reading = `Changed lines — ${s.changedLines} (+${s.additions} / -${s.deletions}; generated files INCLUDED) vs the human-merge threshold ${t}:`; @@ -14062,6 +14063,7 @@ export function changedLineLines(size) { return [ `${reading} under. Read off THIS worktree's diff against the merge base, not off the PR; the landing pre-check` + ' (`check-governed-merges.mjs --pr `) reads the PR\'s own number.', + CARD_TOTAL_LINE, ]; } return [ @@ -14071,9 +14073,20 @@ export function changedLineLines(size) { ' it, or arms auto-merge before that — ACCEPT on the card, `pm:awaiting-merge` on the PR, the final 维护者速读,' + ' review requested from GOVERNED_APPROVERS. The landing pre-check `check-governed-merges.mjs --pr ` reads the' + ' PR\'s own number.', + CARD_TOTAL_LINE, ]; } +/** + * Why this reading carries no CARD total (ruling 7303003476: the line is counted per card), printed on every + * branch above. This tool reads the worktree and no API, so the open and merged pulls naming the card are not + * read here; `check-governed-merges.mjs --pr` reads them at landing, and the queue guard before the merge. + */ +export const CARD_TOTAL_LINE = + 'Card total — NOT MEASURED here: this tool reads the worktree and no API. The line is counted per card (ruling' + + ' 7303003476): a diff under it is still over it when the open and merged pulls naming its card total more, and' + + ' then this PR too lands as a Tier H one does. `check-governed-merges.mjs --pr ` and the queue guard read that total.'; + // --------------------------------------------------------------------------- // The claim's `Container & model:` line — read against the ladder this file // derives, so the tier a seat DECLARES is compared to something diff --git a/scripts/pm/dispatch-gates.self-test.mjs b/scripts/pm/dispatch-gates.self-test.mjs index 94dbac62587..1c530511de5 100644 --- a/scripts/pm/dispatch-gates.self-test.mjs +++ b/scripts/pm/dispatch-gates.self-test.mjs @@ -12318,6 +12318,8 @@ export function selfTest({ tier = 'full' } = {}) { t('exactly at the threshold is under it — strictly greater, as the gate reads it', atLine.includes('under.') && !atLine.includes('HUMAN MERGE'), atLine); const noneLine = changedLineLines(null).join('\n'); t('an explicit path list is NOT MEASURED, said out loud, never a silent under', noneLine.includes('NOT MEASURED') && !noneLine.includes('under.') && noneLine.includes('--pr'), noneLine); + t('⭐ per card (ruling 7303003476): every branch says the card total is NOT read here, why, and who reads it — an under-line diff of an over-line card is still Tier H', + [overLine, atLine, noneLine].every((w) => w.includes('Card total — NOT MEASURED here') && w.includes('no API') && w.includes('--pr ') && w.includes('7303003476')), atLine); t('the threshold is read from the gate — no second copy here — and it is the ruled 3000', HUMAN_MERGE_LINE_THRESHOLD === 3000 && changedLineLines({ additions: 3001, deletions: 0 }).join('\n').includes('OVER')); t('a text buffer counts its lines, an unterminated last line included', lineCountOf(Buffer.from('a\nb\n')) === 2 && lineCountOf(Buffer.from('a\nb')) === 2 && lineCountOf(Buffer.alloc(0)) === 0); t('a buffer with a NUL in its first 8000 bytes is binary: null, which the caller counts as zero lines', lineCountOf(Buffer.from([0x61, 0, 0x62])) === null); diff --git a/scripts/pm/fleet-write/execute.mjs b/scripts/pm/fleet-write/execute.mjs index bddf22656f3..58a344d5e00 100644 --- a/scripts/pm/fleet-write/execute.mjs +++ b/scripts/pm/fleet-write/execute.mjs @@ -648,6 +648,8 @@ import { applyLowRiskArm, applyRuleChangeSplit, applyWorkflowSplit, + CARD_TIMELINE_PAGES, + cardPullView, fetchTimelineOver, GOVERNED_TIER_H, GOVERNED_TIER_S, @@ -662,6 +664,7 @@ import { pullChangesetReading, pullLowRiskReading, pullPathsFrom, + readCardSize, readWorkflowDiff, repoIdForSlug, RULE_CHANGE_RULING, @@ -1501,6 +1504,51 @@ async function readMergeQueue(repo, branch, api, t, query = MERGE_QUEUE_READ_QUE return { queue }; } +/** How many 100-event pages of a card's timeline the size fence's card reading walks — the guard's own `CARD_TIMELINE_PAGES`; a card still full on the last is unread. */ +export const ENQUEUE_FRONT_CARD_TIMELINE_PAGES = CARD_TIMELINE_PAGES; + +/** + * The size fence's per-card reading (ruling 7303003476, `readCardSize` in `check-governed-merges.mjs`): the cards the + * pull COUNTS toward through the queue guard's record recognisers (`countedCards`, the one naming relation), each + * card's whole timeline and each cross-referenced pull's own GET, all unpaced reads. Recognisers that did not load, a + * timeline still full on its last page, or a read that did not answer 200 are an unread total (`measured: false`), + * which the fence reads as over the line. Never throws. + */ +async function readEnqueueCard(payload, pull, api, t, loadRecognisers = loadRecordRecognisers) { + let recognisers; + try { + recognisers = await loadRecognisers(); + } catch (error) { + recognisers = { available: false, reason: String(error?.message ?? error).split('\n')[0] }; + } + if (recognisers?.available !== true || typeof recognisers.countedCards !== 'function') { + return { measured: false, reason: `the naming relation did not load (${recognisers?.reason ?? 'the recognisers carry no countedCards'})`, apiCalls: 0 }; + } + const self = cardPullView(pull); + return readCardSize({ + self, + named: recognisers.countedCards(self), + slug: payload.repo, + threshold: HUMAN_MERGE_LINE_THRESHOLD, + namesCard: (view, card) => recognisers.countedCards(view).includes(card), + fetchTimeline: async (card) => { + const events = []; + for (let page = 1; page <= ENQUEUE_FRONT_CARD_TIMELINE_PAGES; page++) { + const r = await rest(api, `/repos/${payload.repo}/issues/${card}/timeline?per_page=100&page=${page}`, {}, t); + if (r.status !== 200 || !Array.isArray(r.json)) throw new Error(`${r.call} -> HTTP ${r.status}`); + events.push(...r.json); + if (r.json.length < 100) return events; + } + throw new Error(`card #${card} has more than ${ENQUEUE_FRONT_CARD_TIMELINE_PAGES * 100} timeline events`); + }, + fetchPullView: async (n) => { + const r = await rest(api, `/repos/${payload.repo}/pulls/${n}`, {}, t); + if (r.status !== 200 || !r.json || typeof r.json !== 'object') throw new Error(`${r.call} -> HTTP ${r.status}`); + return cardPullView(r.json); + }, + }); +} + /** * The fences, AUTHORITATIVE (header: "The front-of-queue enqueue"): the pull's own GET, its whole file list (the * governed slice through the register) and its base's queue — the last three reads before the mutation — judged @@ -1519,10 +1567,15 @@ export async function enqueueFrontPreflight(req, payload, api, t) { if (base === null) return { fail: `pull #${number}'s base ref could not be read, so its queue was not judged — nothing sent` }; const q = await readMergeQueue(payload.repo, base, api, t); if (q.fail) return { fail: `${q.fail}, so its fences were not judged — nothing sent` }; - // The SIZE lift (header): read only for a pull over the line — its reviews, and the carrying comment when named. + // ⭐ The CARD total (ruling 7303003476): every open or merged pull naming this pull's card(s), read whole — an + // unread total is read as OVER the line, never as under it. + const card = await readEnqueueCard(payload, p.json, api, t); + // The SIZE lift (header): read only for a pull over the line — by its own number, its card's, or an unread card — + // its reviews, and the carrying comment when named. const lines = (p.json.additions ?? 0) + (p.json.deletions ?? 0); - const approval = Number.isInteger(p.json.additions) && Number.isInteger(p.json.deletions) && lines > HUMAN_MERGE_LINE_THRESHOLD ? await readSizeLift(req, payload, p.json, api, t) : null; - const failures = enqueueFrontFenceFailures({ pull: p.json, expectedHeadSha, governed, queue: q.queue, approval }); + const over = (Number.isInteger(p.json.additions) && Number.isInteger(p.json.deletions) && lines > HUMAN_MERGE_LINE_THRESHOLD) || card.measured !== true || card.exceeds === true; + const approval = over ? await readSizeLift(req, payload, p.json, api, t) : null; + const failures = enqueueFrontFenceFailures({ pull: p.json, expectedHeadSha, governed, queue: q.queue, approval, card }); if (failures.length) return { fail: `REFUSED at the relay's fence on pull #${number}, nothing sent — ${enqueueFrontFenceText(failures)}` }; return { pull: p.json, base, queue: q.queue }; } @@ -2926,10 +2979,10 @@ const SELF_TEST_BATTERIES = Object.freeze({ "the governed-review follow-up: after pr_ready alone — a pr_create summons NOBODY and never reads the pull's files, because a human is asked only at the seat's hand-off (pr_request_reviewers after ACCEPT + a same-head PASS); after pr_ready the pull's file list is read in full, a Tier H hit requests review from every GOVERNED_APPROVERS account not already requested, assigned or reviewed — the pull's own author assigned instead, never requested; a Tier S or ungoverned diff sends nothing and says so; a workflow-only pull in split.repos is judged by the queue guard's reading, merge base → head, and requests only when it says H or cannot be read; a skills-only pull in lowRisk.repos is judged by the low-risk arm's own reading — pull, file statuses, timeline, changesets and catalog modes, then the review record's `Security-touching:` line and the card's labels — and requests only when it says H or cannot be read; an unreadable or truncated list, an unreadable pull or review list, or a refused write is a FAILED action": 62, // 17 → 21 with the head fence: a stale head, the embedded copy never trusted, a run naming no pull, a pull unread. "the run_rerun_failed: the five fences judged HERE on the run and its pull, read immediately before ONE bodiless POST — the pull's current head by its own GET, never the run's embedded copy, and a run naming no pull refused by name; each refused with the POST not sent and accepted on the measured run; a run, pull, baseline or fence that fails is zero writes; the 201 confirmed only by reading attempt 2 back with its failed jobs queued or in progress, naming their job ids; attempt 2 never seen, a failed job completed, or a job list unread is FAILED; no annotation": 21, - "the pr_enqueue_front: the pull's own GET, its whole file list and its base's queue read immediately before ONE enqueuePullRequest mutation with jump true and the expected head — open, ready, its head, not Version Packages, no governed path, at most the human-merge line count, a queue read whole with no jumped entry; each fence refused with the mutation not sent; GraphQL errors FAILED naming the missing grant; the 200 confirmed only by reading the queue back with the pull jumped and nothing ahead; queued without the jump or behind another is FAILED, never re-sent; the queue read unpaced; no annotation": 20, + "the pr_enqueue_front: the pull's own GET, its whole file list and its base's queue read immediately before ONE enqueuePullRequest mutation with jump true and the expected head — open, ready, its head, not Version Packages, no governed path, at most the human-merge line count, a queue read whole with no jumped entry; each fence refused with the mutation not sent; GraphQL errors FAILED naming the missing grant; the 200 confirmed only by reading the queue back with the pull jumped and nothing ahead; queued without the jump or behind another is FAILED, never re-sent; the queue read unpaced; no annotation": 23, // 9 → 12 with a carrying comment that opens with a seat signature refused, its other way, and no reader carrying nothing; // the other way flipped (still 12) when a signature on ANY line refused the carry, not only the first. - "the pr_enqueue_front SIZE lift: a pull over the human-merge line is jumped only on an authorised APPROVED review on its current head, or an earlier one carried to the head by an authorised comment on the pull naming it — the reviews read only over the line, a full page or an unread list lifting nothing, a non-approver, an approval elsewhere, a comment naming another head or pull or holding a seat signature on any line refused with the mutation not sent": 14, + "the pr_enqueue_front SIZE lift: a pull over the human-merge line is jumped only on an authorised APPROVED review on its current head, or an earlier one carried to the head by an authorised comment on the pull naming it — the reviews read only over the line, a full page or an unread list lifting nothing, a non-approver, an approval elsewhere, a comment naming another head or pull or holding a seat signature on any line refused with the mutation not sent": 15, // 16 → 27 with seat-asks bound to the landing seat (another seat, the relay's own audit, no trailer, the pure match), // the pull read back open and unmerged (merged, closed, a late read, the pure reading) and the node id from the first read; // 27 → 28 with the second pull read one interval later, a merge that shows only there refused; @@ -3856,13 +3909,15 @@ export async function selfTest() { const after = queueOf([entry(PULL, 1, true), entry(3730, 2), entry(3732, 3)]); const enqueued = { status: 200, json: { data: { enqueuePullRequest: { mergeQueueEntry: entry(PULL, 1, true) } } } }; const stroke = base([{ op: 'pr_enqueue_front', pull: PULL, expected_head_sha: HEAD }]); - const happy = { ...allowed, [PULL_GET]: pullAt(), [FILES]: filesOf('apps/objectos/test/mcp-build-sample-cleanup.e2e.test.ts'), [GQL]: [before, enqueued, after] }; + // The card the pull names by its dev branch (ruling 7303003476): its timeline read whole, no sibling here. + const CARD_TL = `GET /repos/${REPO}/issues/3656/timeline`; + const happy = { ...allowed, [PULL_GET]: pullAt(), [FILES]: filesOf('apps/objectos/test/mcp-build-sample-cleanup.e2e.test.ts'), [GQL]: [before, enqueued, after], [CARD_TL]: { status: 200, json: [] } }; let clock = 0; const timing = { sleep: async (ms) => { clock += ms; }, now: () => clock }; const mutations = (seen) => seen.filter((s) => s.call === GQL && s.body?.query?.startsWith('mutation')); const ok = await run(stroke, happy, timing); - t('⭐ every fence holds: the sender gate, the pull, its files and its base queue — then the node id, ONE mutation, the queue read back; exit 0', [ok.exit, ok.seen.map((s) => s.call)], [EXIT_OK, [PERM, PULL_GET, FILES, GQL, PULL_GET, GQL, GQL]], ok.logs.join(' | ')); + t('⭐ every fence holds: the sender gate, the pull, its files and its base queue — then the node id, ONE mutation, the queue read back; exit 0', [ok.exit, ok.seen.map((s) => s.call)], [EXIT_OK, [PERM, PULL_GET, FILES, GQL, CARD_TL, PULL_GET, GQL, GQL]], ok.logs.join(' | ')); t('…the queue read names the pull\'s base, and the mutation sends jump true, the node id and the expected head', [ok.seen[3].body.variables, mutations(ok.seen).map((m) => [m.body.query.includes('jump: true'), m.body.query.includes('expectedHeadOid: $head'), m.body.variables])], [{ owner: REPO.split('/')[0], name: REPO.split('/')[1], branch: 'main' }, [[true, true, { id: 'PR_kwDOjump', head: HEAD }]]]); t('…the row lands on the read-back: the pull at the front, jumped, with the queue it read', [ok.rows[0]?.call, ok.rows[0]?.result], [`${GQL} enqueuePullRequest`, `#${PULL} at the front of the merge queue · position 1 · jump true · AWAITING_CHECKS · 3 entr(ies) queued`]); t('…no annotation, and only the mutation was paced as a write: the two queue reads are unpaced', [ok.annotations, ok.pace ? readFileSync(ok.pace.file, 'utf8').trim().split('\n').filter(Boolean).length : null], [[], 1]); @@ -3877,6 +3932,13 @@ export async function selfTest() { t('⛔ fence release, refused HERE: the Version Packages pull, by its changeset-release head and by its title', [await fenced({ [PULL_GET]: pullAt({ head: { sha: HEAD, ref: 'changeset-release/main' } }) }), await fenced({ [PULL_GET]: pullAt({ title: 'chore: version packages' }) })], [refused, refused]); t('⛔ fence governed, refused HERE: a workflow file and AGENTS.md (Tier H), a .claude/** file (Tier S) — the path named', [await fenced({ [FILES]: filesOf('src/a.ts', '.github/workflows/ci.yml') }), await fenced({ [FILES]: filesOf('AGENTS.md') }), await fenced({ [FILES]: filesOf('.claude/agents/os-dev.md') }), await named({ [FILES]: filesOf('.github/workflows/ci.yml') }, '1 governed path(s): .github/workflows/ci.yml')], [refused, refused, refused, true]); t('⛔ fence size, refused HERE: one line over the human-merge threshold; exactly at it passes', [await fenced({ [PULL_GET]: pullAt({ additions: 2990, deletions: 11 }) }), (await run(stroke, { ...happy, [PULL_GET]: pullAt({ additions: 2990, deletions: 10 }) }, timing)).exit], [refused, EXIT_OK]); + // ⭐ Per card (ruling 7303003476): a 46-line pull whose card already carries a merged 2,990-line sibling is over the line. + const SIB = 3601; + const sibling = { status: 200, json: { number: SIB, state: 'closed', merged_at: '2026-11-02T00:00:00Z', created_at: '2026-11-01T00:00:00Z', additions: 2990, deletions: 0, body: 'Part of #3656', head: { ref: 'claude/issue-3656-a' } } }; + const crossRef = { status: 200, json: [{ event: 'cross-referenced', source: { issue: { number: SIB, pull_request: {}, repository: { full_name: REPO } } } }] }; + t('⭐ fence size, refused HERE BY THE CARD: a 46-line pull whose card carries a merged 2,990-line sibling — the card total named', [await fenced({ [CARD_TL]: crossRef, [`GET /repos/${REPO}/pulls/${SIB}`]: sibling }), await named({ [CARD_TL]: crossRef, [`GET /repos/${REPO}/pulls/${SIB}`]: sibling }, '#3656 totals 3036 across 2 pull(s)')], [refused, true]); + t('control: the same sibling closed WITHOUT merging adds nothing — the jump goes through', (await run(stroke, { ...happy, [CARD_TL]: crossRef, [`GET /repos/${REPO}/pulls/${SIB}`]: { status: 200, json: { ...sibling.json, merged_at: null } } }, timing)).exit, EXIT_OK); + t('⛔ an UNREAD card total refuses the size fence, never reads as under the line', [await fenced({ [CARD_TL]: { status: 502, json: { message: 'Bad Gateway' } } }), await named({ [CARD_TL]: { status: 502, json: { message: 'Bad Gateway' } } }, 'the card total UNREAD')], [refused, true]); t('⛔ fence queue, refused HERE: a base with no merge queue, and an entry list read truncated', [await fenced({ [GQL]: { status: 200, json: { data: { repository: { mergeQueue: null } } } } }), await fenced({ [GQL]: queueOf([entry(3730, 1)], true) })], [refused, refused]); t('⛔ fence one-jump, refused HERE: another pull already jumped and still queued, and this pull already jumped — one per repository', [await fenced({ [GQL]: queueOf([entry(3730, 1, true), entry(PULL, 2)]) }), await fenced({ [GQL]: queueOf([entry(PULL, 1, true)]) }), await named({ [GQL]: queueOf([entry(3730, 1, true)]) }, 'jumped: #3730')], [refused, refused, true]); t('…a pull not yet queued may be jumped: an empty queue passes the fences', (await run(stroke, { ...happy, [GQL]: [queueOf([]), enqueued, queueOf([entry(PULL, 1, true)])] }, timing)).exit, EXIT_OK); @@ -3918,13 +3980,14 @@ export async function selfTest() { const COMMENT = `GET /repos/${REPO}/issues/comments/71`; const GQL = 'POST /graphql'; const big = { status: 200, json: { number: PULL, node_id: 'PR_kwDObig', state: 'open', draft: false, title: 'feat(ui): large', additions: 3300, deletions: 93, head: { sha: HEAD, ref: 'claude/issue-33181-x' }, base: { ref: 'main' } } }; + const BIG_CARD_TL = `GET /repos/${REPO}/issues/33181/timeline`; const entry = (number, position, jump = false) => ({ position, jump, state: 'AWAITING_CHECKS', pullRequest: { number } }); const queueOf = (nodes) => ({ status: 200, json: { data: { repository: { mergeQueue: { entries: { totalCount: nodes.length, pageInfo: { hasNextPage: false }, nodes } } } } } }); const enqueued = { status: 200, json: { data: { enqueuePullRequest: { mergeQueueEntry: entry(PULL, 1, true) } } } }; const review = (login, commit, state = 'APPROVED') => ({ id: 1, state, commit_id: commit, user: { login } }); const reviewsOf = (...list) => ({ status: 200, json: list }); const commentOf = (patch = {}) => ({ status: 200, json: { id: 71, user: { login: APPROVER }, issue_url: `https://api.github.com/repos/${REPO}/issues/${PULL}`, body: `The approval carries to ${HEAD.slice(0, 9)}.`, ...patch } }); - const happy = { ...allowed, [PULL_GET]: big, [FILES]: { status: 200, json: [{ filename: 'ui/src/a.ts' }] }, [REVIEWS]: reviewsOf(review(APPROVER, HEAD)), [GQL]: [queueOf([entry(3730, 1)]), enqueued, queueOf([entry(PULL, 1, true), entry(3730, 2)])] }; + const happy = { ...allowed, [PULL_GET]: big, [FILES]: { status: 200, json: [{ filename: 'ui/src/a.ts' }] }, [REVIEWS]: reviewsOf(review(APPROVER, HEAD)), [GQL]: [queueOf([entry(3730, 1)]), enqueued, queueOf([entry(PULL, 1, true), entry(3730, 2)])], [BIG_CARD_TL]: { status: 200, json: [] } }; const stroke = (extra = {}) => base([{ op: 'pr_enqueue_front', pull: PULL, expected_head_sha: HEAD, ...extra }]); let clock = 0; const timing = { sleep: async (ms) => { clock += ms; }, now: () => clock }; @@ -3936,7 +3999,11 @@ export async function selfTest() { const landed = [EXIT_OK, 1, 200]; const refused = [EXIT_ACTION_FAILED, 0, 'not sent']; const ok = await run(stroke(), happy, timing); - t('⭐ ON THE HEAD: an authorised APPROVED review whose commit is the current head lifts the line — the reviews read after the queue, the jump sent and read back', [ok.exit, ok.seen.map((x) => x.call)], [EXIT_OK, [PERM, PULL_GET, FILES, GQL, REVIEWS, PULL_GET, GQL, GQL]], ok.logs.join(' | ')); + t('⭐ ON THE HEAD: an authorised APPROVED review whose commit is the current head lifts the line — the reviews read after the queue, the jump sent and read back', [ok.exit, ok.seen.map((x) => x.call)], [EXIT_OK, [PERM, PULL_GET, FILES, GQL, BIG_CARD_TL, REVIEWS, PULL_GET, GQL, GQL]], ok.logs.join(' | ')); + // ⭐ An UNREAD card total is read as over the line (ruling 7303003476): a small pull whose card timeline 502s jumps + // on its authorised approval alone, and is refused without one. + const smallUnread = { [PULL_GET]: { status: 200, json: { ...big.json, additions: 40, deletions: 6 } }, [BIG_CARD_TL]: { status: 502, json: { message: 'Bad Gateway' } } }; + t('⭐ an UNREAD card total with an authorised approval on the head JUMPS — the lift holds the size fence; with no approval it is refused', [await verdict(smallUnread), (await verdict({ ...smallUnread, [REVIEWS]: reviewsOf() }))[1]], [landed, 0]); t('⛔ an authorised approval on an EARLIER commit with no approval_comment lifts nothing — refused naming the missing carry', [await verdict({ [REVIEWS]: reviewsOf(review(APPROVER, EARLIER)) }), (await run(stroke(), { ...happy, [REVIEWS]: reviewsOf(review(APPROVER, EARLIER)) })).rows[0]?.result.includes('no `approval_comment` carries it')], [refused, true]); t('⭐ CARRIED: an earlier authorised approval plus the approver\'s comment on this pull naming the head\'s prefix lifts it; the comment read by its own GET', [await verdict({ [REVIEWS]: reviewsOf(review(APPROVER, EARLIER)), [COMMENT]: commentOf() }, { approval_comment: 71 }), (await run(stroke({ approval_comment: 71 }), { ...happy, [REVIEWS]: reviewsOf(review(APPROVER, EARLIER)), [COMMENT]: commentOf() }, timing)).seen.some((x) => x.call === COMMENT)], [landed, true]); t('⛔ CARRIED, refused: a comment by a non-approver, on another pull, naming another head or too short a prefix, or unreadable', [ diff --git a/scripts/pm/fleet-write/ops.mjs b/scripts/pm/fleet-write/ops.mjs index 666872e57fe..e4cd7343ae3 100644 --- a/scripts/pm/fleet-write/ops.mjs +++ b/scripts/pm/fleet-write/ops.mjs @@ -1592,9 +1592,13 @@ export const ENQUEUE_FRONT_FENCES = Object.freeze([ }), Object.freeze({ fence: 'size', - wants: `at most ${HUMAN_MERGE_LINE_THRESHOLD} changed lines (additions + deletions), or a larger pull whose authorised approval stands on its current head or is carried to it by an authorised comment (\`approval_comment\`) — a larger pull lands the way a Tier H one does`, - reads: (c) => `${(c.pull?.additions ?? 0) + (c.pull?.deletions ?? 0)} changed line(s)${c.approval ? `, ${c.approval.reading}` : ''}`, - holds: (c) => Number.isInteger(c.pull?.additions) && Number.isInteger(c.pull?.deletions) && (c.pull.additions + c.pull.deletions <= HUMAN_MERGE_LINE_THRESHOLD || c.approval?.lifts === true), + wants: `at most ${HUMAN_MERGE_LINE_THRESHOLD} changed lines (additions + deletions) on the pull AND on its card — the open and merged pulls naming the card, epic/tracker cards exempt (ruling 7303003476), the card total read whole — or a larger pull, a larger card or an UNREAD card total whose pull's authorised approval stands on its current head or is carried to it by an authorised comment (\`approval_comment\`) — a larger one lands the way a Tier H one does`, + reads: (c) => `${(c.pull?.additions ?? 0) + (c.pull?.deletions ?? 0)} changed line(s)${enqueueFrontCardWords(c.card)}${c.approval ? `, ${c.approval.reading}` : ''}`, + holds: (c) => + Number.isInteger(c.pull?.additions) && + Number.isInteger(c.pull?.deletions) && + // An unread card total is read as OVER the line (never under it): it holds on the authorised approval alone. + ((c.pull.additions + c.pull.deletions <= HUMAN_MERGE_LINE_THRESHOLD && c.card?.measured === true && c.card.exceeds !== true) || c.approval?.lifts === true), }), Object.freeze({ fence: 'queue', @@ -1613,6 +1617,19 @@ export const ENQUEUE_FRONT_FENCES = Object.freeze([ }), ]); +/** + * The size fence's words for the CARD reading (`readCardSize` in `check-governed-merges.mjs`, ruling 7303003476): + * unread (read as over the line — ⛔ never under it — so only an authorised approval holds the fence), the cards + * over the line, or under. Pure. + */ +export function enqueueFrontCardWords(card) { + if (!card || card.measured !== true) return `, the card total UNREAD (${card?.reason ?? 'no card reading'}) and so read as over the line`; + if (!Array.isArray(card.cards) || card.cards.length === 0) return ', counting toward no card'; + const over = card.cards.filter((c) => c.exceeds); + if (over.length > 0) return `, its card${over.length > 1 ? 's' : ''} over the line: ${over.map((c) => `#${c.card} totals ${c.total} across ${c.counted.length} pull(s)`).join('; ')}`; + return `, its card total under the line (${card.cards.map((c) => `#${c.card} ${c.exempt ? 'exempt' : c.total}`).join(', ')})`; +} + /** The fences a context fails: `[{ fence, wants, got }]`, in `ENQUEUE_FRONT_FENCES` order; `[]` when all hold. Pure. */ export function enqueueFrontFenceFailures(ctx) { return ENQUEUE_FRONT_FENCES.filter((f) => !f.holds(ctx)).map((f) => ({ fence: f.fence, wants: f.wants, got: f.reads(ctx) ?? null })); diff --git a/scripts/pm/record-recognisers.mjs b/scripts/pm/record-recognisers.mjs index 4b24c739588..5870fa5ea6c 100644 --- a/scripts/pm/record-recognisers.mjs +++ b/scripts/pm/record-recognisers.mjs @@ -2379,6 +2379,26 @@ export function namedCardNumbers(pr) { return [...named].map(Number).filter((n) => Number.isInteger(n) && n > 0).sort((a, b) => a - b); } +/** + * The cards whose total a pull request COUNTS toward (ruling 7303003476 on #38296, the human-merge line per card): + * each closing keyword's target, each `Part of` target, and the card a protocol dev branch is named for — the + * card's option A pair plus the branch, which is how a dev's pull is made for its card. ⛔ NOT `Refs`: a pull that + * cites a card neither adds its size to that card's total nor inherits it, so a commonly cited card does not + * accumulate every pull that mentions it. Ascending numbers, each once. + * + * @param {object} pr — a REST pull row (or the guard's per-card view of one): `body`, and `head.ref` + * @returns {number[]} + */ +export function countedCardNumbers(pr) { + const body = String(pr?.body ?? ''); + const named = new Set([ + ...closingKeywordTargets(body).keys(), + ...partOfTargets(body), + ...[branchNameTarget(pr?.head?.ref)].filter((n) => n !== null && n !== undefined), + ]); + return [...named].map(Number).filter((n) => Number.isInteger(n) && n > 0).sort((a, b) => a - b); +} + /** * ③'s SQL push-down check, the one wording both printed shapes carry (the brief's ③ line and the * `--template` legend's ③ entry), read from `references/contract-review.md`'s ③ line and AGENTS.md @@ -2899,7 +2919,8 @@ const SELF_TEST_BATTERIES = Object.freeze({ // posted by an untrusted author not read — two pins, two cases. // Raised 19 → 22 with `namedCardNumbers`, every card a pull names: the low-risk arm reads the label on each. // Raised 22 → 23 with the unedited-paste pin: the shipped `Rule-change-verified: yes` lands nothing. - '#18701: ONE thread set -- what the template STATES is what the queue guard READS': 23, + // Raised 23 → 25 with `countedCardNumbers`, the per-card line's relation (ruling 7303003476): two pins. + '#18701: ONE thread set -- what the template STATES is what the queue guard READS': 25, 'the `Local-runs:` reading — `none` or ONE named probe, judged when present; an absent line is not re-judged': 12, // Raised 23 → 24 with ③'s SQL push-down check on every face's brief: one pin. 'the reviewer BRIEF template — the read-only shape a hand-written brief dropped, built in and printed': 24, @@ -4119,6 +4140,9 @@ export async function selfTest() { return deliveredCardNumber(partOf).card === 4444 && namedCardNumbers(partOf).join() === '4444,5555' && deliveredCardNumber(branch).card === 4444 && deliveryEvidence(branch, 5555) === null && namedCardNumbers(branch).join() === '4444,5555'; })()); t('namedCardNumbers names nothing a relation spelling does not: a bare mention, a spelling in a code span or a fence, and a branch outside the protocol shape name no card', namedCardNumbers(PIN_PULL('see #4444 and `Fixes #5555`\n```\nPart of #6666\n```\nRefs: #7777', 'feat/8888-x')).join() === '7777' && namedCardNumbers(PIN_PULL('nothing here')).length === 0 && namedCardNumbers(null).length === 0); + // `countedCardNumbers` -- the cards a pull's size counts toward (ruling 7303003476): the option A pair and the branch. + t('⭐ countedCardNumbers counts a closing keyword, a `Part of` and the dev branch -- and ⛔ NOT a `Refs`: a citation neither adds to a card nor inherits its total', countedCardNumbers(PIN_PULL('Fixes #4444\n\nPart of #5555\nRefs #3333 (item 2)', 'claude/issue-6666-x')).join() === '4444,5555,6666' && namedCardNumbers(PIN_PULL('Refs #3333')).join() === '3333' && countedCardNumbers(PIN_PULL('Refs #3333')).length === 0); + t('countedCardNumbers names nothing in a code span or fence, and reads the guard\'s per-card view (body + head.ref) as it reads a REST row', countedCardNumbers(PIN_PULL('`Fixes #5555`\n```\nPart of #6666\n```')).length === 0 && countedCardNumbers({ body: 'Part of #7', head: { ref: 'claude/issue-8-y' } }).join() === '7,8' && countedCardNumbers(null).length === 0); t('⛔ CONTROL: the ranking belongs to `deliveryEvidence` -- every grade it answers is ranked here, none invented', DELIVERY_EVIDENCE_PRECEDENCE.every((kind) => deliveryEvidenceNote(kind) !== 'evidence unread') && new Set(DELIVERY_EVIDENCE_PRECEDENCE).size === DELIVERY_EVIDENCE_PRECEDENCE.length); t('…and it is ranked in the order that function applies, measured pair by pair', DELIVERY_EVIDENCE_PRECEDENCE.indexOf(deliveryEvidence(PIN_PULL(`Fixes #1\nPart of #2`), '1')) < DELIVERY_EVIDENCE_PRECEDENCE.indexOf(deliveryEvidence(PIN_PULL(`Fixes #1\nPart of #2`), '2')) && DELIVERY_EVIDENCE_PRECEDENCE.indexOf('part-of') < DELIVERY_EVIDENCE_PRECEDENCE.indexOf('branch-name'));