From cee66270172f1342a563280dfcfb9aadfcf7e653 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 19:36:36 +0000 Subject: [PATCH 1/8] feat(pm): the contract-review record reading carries its Security-touching line The record reader (contractReviewRecordReading) gains securityTouching, the three-valued reading of the one Security-touching: line the low-risk skills arm will stand on: missing, read (no or yes), or unreadable with its reason. Exactly one bare line counts; a quoted, fenced, code-indented, repeated or near-miss line is unreadable, and nothing defaults to no. Claude-Session: https://claude.ai/code/session_01ADHkmR2U8dFkRvc5DvUz1W Co-authored-by: Claude --- scripts/pm/check-half-states.mjs | 82 ++++++++++++++++++++++++++++++-- 1 file changed, 79 insertions(+), 3 deletions(-) diff --git a/scripts/pm/check-half-states.mjs b/scripts/pm/check-half-states.mjs index ae1393b31c6..04fa4947e33 100644 --- a/scripts/pm/check-half-states.mjs +++ b/scripts/pm/check-half-states.mjs @@ -12955,6 +12955,9 @@ export function contractReviewVerdictLines(body) { * so the record fails CLOSED. * A delta record may also name what it closes by id alone * (`S1: closed.`), which mentions no grade. + * securityTouching the record's ONE `Security-touching:` line, three-valued + * (`contractReviewSecurityTouching` below) — the line the low-risk + * skills arm stands on, read by nobody else. * * Grammar measured on the records of PRs #33686, #33687, #33688 (both rounds), * #33711 (all three rounds), #33720, #33726 and #33736 (2026-11-15); nits are @@ -13005,7 +13008,71 @@ export function contractReviewRecordReading(body) { } else if (!CONTRACT_REVIEW_GRADE_NEGATED.test(line.slice(0, mention.index))) unreadable.push(line.trim()); } } - return { verdicts, failSpellings, findings: { open, unreadable: [...new Set(unreadable)] } }; + return { verdicts, failSpellings, findings: { open, unreadable: [...new Set(unreadable)] }, securityTouching: contractReviewSecurityTouching(text) }; +} + +/** + * The key and the two values of the record's ONE machine line the LOW-RISK SKILLS ARM reads + * (`lowRiskArmVerdict`, `check-governed-merges.mjs`). `Security-touching: no` is the reviewer's + * statement that no changed hunk teaches permission, sharing, credential, token, authentication + * or other security behaviour — the teaching a path's name and a label cannot show; `yes` says + * one does. The arm stands on `no` alone. + */ +export const CONTRACT_REVIEW_SECURITY_TOUCHING_KEY = 'Security-touching'; +export const CONTRACT_REVIEW_SECURITY_TOUCHING_VALUES = Object.freeze(['no', 'yes']); +// A DECLARATION line: the key at the line's lead — behind a heading mark, quote, bullet or emphasis, inside +// a code span, in any case, its two words joined by a hyphen, an underscore or blanks — then a colon. +const CONTRACT_REVIEW_SECURITY_TOUCHING_LINE = new RegExp(CONTRACT_REVIEW_LINE_LEAD + '`?[*_]{0,3}security[-_ \\t]*touching[*_`]{0,3}[ \\t]*[::]', 'i'); + +/** + * The record's `Security-touching:` line, read off the WHOLE comment like its `VERDICT:` lines: + * + * missing no declaration line at all — every record written before the line existed; + * read the one bare line, with its value (`no` or `yes`); + * unreadable anything else, with the reason. + * + * Every declaration line counts, fenced and quoted ones included, and exactly ONE may exist: + * outside any code fence (`FENCE_LINE`, `FENCE_CLOSE_LINE`) and any `>` quote, indented at most + * three spaces, and with its list bullet, bold and backticks stripped reading EXACTLY + * `Security-touching: no` or `Security-touching: yes`. So a second declaration (a quoted `no` + * beside the record's own `yes`), trailing words (`no — wording only`), another value, a + * near-miss key (`Security touching:`) and a fenced, quoted or code-indented line are each + * `unreadable` — the same strictness `readBareDeclaration` holds a PR body's `Clause-②:` line to. + * + * ⛔ Fail closed, in the one direction that matters: `missing`, `unreadable` and `yes` each + * keep the pull request at Tier H, and no reading here ever DEFAULTS to `no`. Pure. + */ +function contractReviewSecurityTouching(body) { + const key = CONTRACT_REVIEW_SECURITY_TOUCHING_KEY; + const hits = []; + let fence = null; // the OPEN fence — its character and run length — or null outside one + for (const line of String(body ?? '').split(/\r?\n/)) { + if (fence !== null) { + if (CONTRACT_REVIEW_SECURITY_TOUCHING_LINE.test(line)) hits.push({ line, fenced: true }); + const c = FENCE_CLOSE_LINE.exec(line); + if (c !== null && c[1][0] === fence.ch && c[1].length >= fence.len) fence = null; + continue; + } + const f = FENCE_LINE.exec(line); + if (f !== null) { + fence = { ch: f[1][0], len: f[1].length }; + continue; + } + if (CONTRACT_REVIEW_SECURITY_TOUCHING_LINE.test(line)) hits.push({ line, fenced: false }); + } + if (hits.length === 0) return { state: 'missing' }; + const unreadable = (reason) => ({ state: 'unreadable', reason }); + // A quoted record line is comment text: flattened (no backtick, pipe or angle bracket survives) and cut. + const quote = (line) => `\`${String(line).replace(/[`|<>\r\n]+/g, ' ').trim().slice(0, 80)}\``; + if (hits.length > 1) return unreadable(`it carries ${hits.length} \`${key}:\` lines, and a record states exactly one`); + const [{ line, fenced }] = hits; + if (fenced) return unreadable(`its one \`${key}:\` line sits inside a code fence`); + if (/^[ \t]*>/.test(line)) return unreadable(`its one \`${key}:\` line is a quote (${quote(line)})`); + if (/^(?: {4,}| *\t)/.test(line)) return unreadable(`its one \`${key}:\` line is indented as code (${quote(line)})`); + const bare = line.replace(/^[ \t]*(?:[-*+][ \t]+)?/, '').replace(/\*\*|`/g, '').replace(/[ \t]+/g, ' ').trim(); + const value = CONTRACT_REVIEW_SECURITY_TOUCHING_VALUES.find((v) => bare === `${key}: ${v}`); + if (value === undefined) return unreadable(`its \`${key}:\` line reads ${quote(line)}, not exactly ${CONTRACT_REVIEW_SECURITY_TOUCHING_VALUES.map((v) => `\`${key}: ${v}\``).join(' or ')}`); + return { state: 'read', value }; } // --------------------------------------------------------------------------- @@ -25567,7 +25634,9 @@ export const SELF_TEST_BATTERIES = Object.freeze({ // shadow a trusted FAIL, an approver's read, two lines and an inline word alone // no PASS, no binding UNREAD, the binding's four unloaded reasons and its clause // (two more, the real guard's predicate and set, run where the register loads). - 'H43 hand-off timing': 88, + // 88 → 93: the record's `Security-touching:` line, the low-risk skills arm's machine line — the bare + // readings, the MISSING record, the unreadable shapes, the fence and reason pins, and the constants. + 'H43 hand-off timing': 93, // Registered with the seat-patrol rows (#28642), pin just under the count: two // free readings, each with its firing controls and its out-of-scope arms inside. 'H70/H71 seat patrol': 30, @@ -33062,7 +33131,14 @@ async function selfTest() { t43('#33604 S2 (review 6891926185): heading-led key, table cell, words before the key, a dash, a bare `FAIL.` and a second heading read FAIL', ['### VERDICT: FAIL', '## Verdict: FAIL', '| Verdict | FAIL |', 'Overall verdict: FAIL', 'Verdict — FAIL', 'FAIL.', '**FAIL.**', '## Contract review — FAIL', '| Verdict | PASS |'].map((l) => read43(l).failSpellings.length).join(), '1,1,1,1,1,1,1,1,0'); t43('#33604 r3 (review 6892305129): the state word must end the finding — `closed in part`, `Closed PRs …`, `none of …` stay open; `closed here.`, a closed bold title then a sentence, `closed;` close', ['S1 (should-fix): closed in part, still open for X', '**S2 (should-fix) — Closed PRs are still read as merged.**', '- should-fix: none of S1, S2 is fixed', 'S1 (should-fix): closed here.', '- **S1 (should-fix): closed.** Every knock names a key.', 'S1 (should-fix): closed;'].map(grades43).join(), 'S1:should-fix|0,S2:should-fix|0,-:should-fix|0,|0,|0,|0'); t43('#33604 r3 N2: `Verdict: FAILED`, `Verdict is FAIL`, `Verdict (delta): FAIL`, `| FAIL | Verdict |`, `FAIL!` and a late FAIL in a heading tail read FAIL', ['Verdict: FAILED', 'Verdict is FAIL', 'Verdict (delta): FAIL', '| FAIL | Verdict |', 'FAIL!', '## Contract review — PASS withdrawn, FAIL', 'The verdict is PASS.'].map((l) => read43(l).failSpellings.length).join(), '1,1,1,1,1,1,0'); - t43('#33604 reading: no heading is no record (null); the template record reads one PASS, no FAIL, no grade', [contractReviewRecordReading('**VERDICT: PASS**'), JSON.stringify(contractReviewRecordReading(PASS43))].join(), ',{"verdicts":["PASS"],"failSpellings":[],"findings":{"open":[],"unreadable":[]}}'); + t43('#33604 reading: no heading is no record (null); the template record reads one PASS, no FAIL, no grade', [contractReviewRecordReading('**VERDICT: PASS**'), JSON.stringify(contractReviewRecordReading(PASS43))].join(), ',{"verdicts":["PASS"],"failSpellings":[],"findings":{"open":[],"unreadable":[]},"securityTouching":{"state":"missing"}}'); + // The record's `Security-touching:` line — the low-risk skills arm's machine line, three-valued and fail closed. + const st43 = (prose) => { const r = read43(prose).securityTouching; return r.state === 'read' ? `read:${r.value}` : r.state; }; + t43('Security-touching: the one bare line reads its value — `no`, `yes`, and behind a bullet, bold or a code span', ['Security-touching: no', 'Security-touching: yes', '- Security-touching: no', '**Security-touching:** no', '- **Security-touching**: `no`', '`Security-touching: no`', ' Security-touching: no'].map(st43).join(), 'read:no,read:yes,read:no,read:no,read:no,read:no,read:no'); + t43('⛔ Security-touching: a record with no such line reads MISSING, never `no` — every record written before the line existed, a mention in prose included', [st43('① Derived judgments: none.'), st43('The record carries no line; the seat reads `Security-touching: no` as the arm asks.'), contractReviewRecordReading(PASS43).securityTouching.state].join(), 'missing,missing,missing'); + t43('⛔ Security-touching: two lines, a quoted, fenced or code-indented line, trailing words, another value and a near-miss key are each UNREADABLE', ['Security-touching: no\nSecurity-touching: no', '> Security-touching: no\n\nSecurity-touching: yes', '> Security-touching: no', '```\nSecurity-touching: no\n```', '~~~text\nSecurity-touching: no', ' Security-touching: no', '\tSecurity-touching: no', 'Security-touching: no — wording only', 'Security-touching: none', 'Security-touching: No', 'Security-touching:', 'security-touching: no', 'Security touching: no', '### Security-touching: no', 'Security-touching:no'].map(st43).join(), Array(15).fill('unreadable').join()); + t43('⛔ Security-touching: a fenced `no` beside the record\'s own bare `yes` is two declarations (unreadable); a fence closed before the line leaves it read; the reasons name the shape', [st43('```\nSecurity-touching: no\n```\nSecurity-touching: yes'), st43('```\nsome code\n```\nSecurity-touching: no'), /2 `Security-touching:` lines/.test(read43('Security-touching: no\n> Security-touching: no').securityTouching.reason), /inside a code fence/.test(read43('```\nSecurity-touching: no\n```').securityTouching.reason), /is a quote/.test(read43('> Security-touching: no').securityTouching.reason), /not exactly `Security-touching: no` or `Security-touching: yes`/.test(read43('Security-touching: maybe').securityTouching.reason)].join(), 'unreadable,read:no,true,true,true,true'); + t43('Security-touching: the key and its two values are this file\'s constants, and the line is read above the heading too (the whole comment, like `VERDICT:`)', [CONTRACT_REVIEW_SECURITY_TOUCHING_KEY, CONTRACT_REVIEW_SECURITY_TOUCHING_VALUES.join('+'), Object.isFrozen(CONTRACT_REVIEW_SECURITY_TOUCHING_VALUES), contractReviewRecordReading(`Security-touching: no\n\n${PASS43}`).securityTouching.value, contractReviewRecordReading('Security-touching: no') === null].join(), 'Security-touching,no+yes,true,no,true'); t43('H43 verdict: latestContractReviewOnHead now carries the verdict beside id and sha', [latestContractReviewOnHead(rows43(ACCEPT43, PASS43), HEAD43)?.verdict, latestContractReviewOnHead(rows43(FAIL43), HEAD43)?.verdict, latestContractReviewOnHead(rows43(PASS43), '0123456789abcdef')].join(), 'PASS,FAIL,'); // The row and the probe, gated on the reading. t43('H43 row: ⛔ BEFORE the hand-off, nobody asked is NOT a half state — quiet', h43GovernedReviewRequestGap(h43pr(16), GOV43, APP43, [], BEFORE43), null); From a50cdaebf6276a36b9e460ae2314c5949916698a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 19:38:48 +0000 Subject: [PATCH 2/8] feat(pm): the record template prints the Security-touching line where an arm PR can sit record-recognisers --template carries Security-touching: yes after Scope: on the bare, rules and schema faces, and with --paths exactly when a hit sits under a low-risk row; the legend says who reads it and when no may be written. The brief hands the same duty on the same predicate. The shipped value is yes, so an unedited paste fails closed. Claude-Session: https://claude.ai/code/session_01ADHkmR2U8dFkRvc5DvUz1W Co-authored-by: Claude --- scripts/pm/record-recognisers.mjs | 80 +++++++++++++++++++++++++++++-- 1 file changed, 75 insertions(+), 5 deletions(-) diff --git a/scripts/pm/record-recognisers.mjs b/scripts/pm/record-recognisers.mjs index b9c6997d48e..4eae81dee3e 100644 --- a/scripts/pm/record-recognisers.mjs +++ b/scripts/pm/record-recognisers.mjs @@ -83,6 +83,8 @@ import { fileURLToPath } from 'node:url'; import { isEntrypoint } from '../invoked-as.mjs'; import { CONTRACT_REVIEW_HEADING_MARKER, + CONTRACT_REVIEW_SECURITY_TOUCHING_KEY, + CONTRACT_REVIEW_SECURITY_TOUCHING_VALUES, H51_SHA_MIN_HEX, branchNameTarget, closingKeywordTargets, @@ -102,6 +104,10 @@ import { // (#33501 for the low-risk skills arm, #33541 for every other leg), and, through the whole // reading, no FAIL spelled elsewhere and no open must-fix or should-fix (#33604). ⛔ Never a second parser. export { contractReviewRecordReading, contractReviewVerdictLines }; +// The record's `Security-touching:` line — the low-risk skills arm's machine line, read through the same +// reading (`securityTouching`). Its key and its two values are re-exported so the template below prints +// exactly what that reader takes, ⛔ never a second spelling. +export { CONTRACT_REVIEW_SECURITY_TOUCHING_KEY, CONTRACT_REVIEW_SECURITY_TOUCHING_VALUES }; // The tier `isModelIdentifierToken` refuses by VALUE. IMPORTED, never restated: // `dispatch-gates.mjs` is the one line in `scripts/pm/**` where the model id is // spelled as a value, and a second value site here is the drift that let a @@ -1776,6 +1782,28 @@ export const RECORD_SCOPE_PLACEHOLDERS = Object.freeze({ cited: 'CITED-FILE', }); +/** + * Does the record printed for this face carry the `Security-touching:` line — the ONE machine line the + * low-risk skills arm stands on (`lowRiskArmVerdict`, `check-governed-merges.mjs`)? With the `hits` + * known (`--paths`), exactly when one sits under a low-risk row (`lowRiskRowHit`, the register's own + * test); with none known, on every at-tier face a governed path can sit on — the bare template, the + * rules face and the schema face — since a record printed blind must not drop a line an arm PR lands + * on. ⛔ Not on the narrowing or the declaration face: neither holds a governed path. The brief hands + * the reviewer the duty on the same predicate, so the two printed shapes cannot disagree. Pure. + */ +export function recordCarriesSecurityTouching(face, tierName, scopeHits) { + if (tierName !== CONTRACT_REVIEW_TIER_NAME) return false; + if (scopeHits !== undefined) return lowRiskRowHit(scopeHits); + return face?.id !== 'narrowing'; +} + +/** + * The value the printed record ships on its `Security-touching:` line: `yes`. Like every placeholder + * above it PARSES through the reader that judges the real thing, and it fails closed — a record pasted + * with it left in keeps the pull request at Tier H, so `no` is only ever a reviewer's own statement. + */ +export const RECORD_SECURITY_TOUCHING_DEFAULT = CONTRACT_REVIEW_SECURITY_TOUCHING_VALUES[1]; + /** * The record itself — the lines a seat copies, and nothing else. * @@ -1816,6 +1844,11 @@ export const RECORD_SCOPE_PLACEHOLDERS = Object.freeze({ * The heading is prose to every reader in this file: the locator, the `Served-tier:` and head * readers are unchanged by it, which the self-test drives. * + * ⭐ `Security-touching:` rides the header block, after `Scope:`, where `recordCarriesSecurityTouching` + * says the record carries it: the low-risk skills arm reads it through `contractReviewRecordReading` + * and keeps the pull request at Tier H unless it reads `no`. It ships `yes` + * (`RECORD_SECURITY_TOUCHING_DEFAULT`), so an unedited paste fails closed. + * * @param {{headSha?: string, implementedBy?: string, reviewedBy?: string, tierName?: string, scopeHits?: string[], faceId?: string}} values * @returns {string[]} */ @@ -1838,6 +1871,7 @@ export function contractReviewRecordLines(values = {}) { `Head-sha: \`${headSha}\``, 'Local-runs: none', ...(tierName === CONTRACT_REVIEW_TIER_NAME ? [`Scope: ${scopeHits} + ${RECORD_SCOPE_PLACEHOLDERS.cited}`] : []), + ...(recordCarriesSecurityTouching(face, tierName, values.scopeHits) ? [`${CONTRACT_REVIEW_SECURITY_TOUCHING_KEY}: ${RECORD_SECURITY_TOUCHING_DEFAULT}`] : []), '', '### ① Derived judgments', '', @@ -2061,6 +2095,15 @@ export function contractReviewTemplateLines(values = {}) { ' named there; Tier H approval and the queue guard stay whole-PR. On the narrowing', ' face the floor is every path of the diff outside the prose faces: no path is a remainder,', ' and `+` names every file those hunks make a claim about, read in the cited code.', + ...(recordCarriesSecurityTouching(face, tierName, scopeHits) ? [ + ` · ${CONTRACT_REVIEW_SECURITY_TOUCHING_KEY} read by the low-risk skills arm alone (skill wording, add-only ADR notes): that arm`, + ' lands a PR on this record with no human approval, and only when this line reads `no`.', + ' Write `no` ONLY when no changed hunk teaches permission, sharing, credential, token,', + ' authentication or other security behaviour, whatever the path is called; else `yes`, and', + ' the seat adopting the record adds the `security` label. A missing line, `yes`, a second', + ' line, one that is quoted, fenced or code-indented, or anything after the value keeps the', + ` PR at Tier H. The template ships \`${RECORD_SECURITY_TOUCHING_DEFAULT}\`, so an unedited paste never lands on the arm.`, + ] : []), ' · ③ Boundary flags every dev flag and every `open_questions` entry answered, or escalated; and on', ' every face the SQL push-down check:', ...TEMPLATE_PUSH_DOWN_LINES, @@ -2250,15 +2293,24 @@ export function contractReviewBriefLines(values = {}) { // `--paths` the brief cannot know the hits, and the skill teaches the bare `--brief-template`, so every // at-tier brief over unknown paths carries the duty in its conditional form. const securityDuty = " behaviour the path name doesn't show, the record says so and the seat adopting the record adds the `security` label."; - const lowRiskLines = scopeHits !== undefined ? (lowRiskRowHit(scopeHits) ? [ + // WHERE the record says so: its `Security-touching:` line, which the arm reads and stands on at `no` alone. + // Printed on the predicate the record template prints the line on, so the brief never asks for a line the + // record does not carry. + const securityLine = [ + ` The record says so on its \`${CONTRACT_REVIEW_SECURITY_TOUCHING_KEY}:\` line, and the arm lands on \`no\` alone: write \`no\` ONLY when no changed`, + ' hunk teaches permission, sharing, credential, token, authentication or other security behaviour, else `yes`.', + ]; + const lowRiskLines = !recordCarriesSecurityTouching(face, tierName, scopeHits) ? [] : scopeHits !== undefined ? [ 'Security — a `hits` path sits on the low-risk skills arm: when the change teaches security, auth or permission', securityDuty, + ...securityLine, '', - ] : []) : atTier && face?.id !== 'narrowing' ? [ + ] : [ 'Security — if a `hits` path is under `skills/**` or `ui/skills/**` and the change teaches security, auth or permission', securityDuty, + ...securityLine, '', - ] : []; + ]; return [ 'record-recognisers --brief-template — the brief a seat hands its contract reviewer, copyable. The', "read-only shape is built in: keep every ⛔ line, they are the review's shape and not advice to it.", @@ -2459,7 +2511,10 @@ const SELF_TEST_BATTERIES = Object.freeze({ 'the `Served-tier:` reading — the tier that SERVED the record (#17915 · #18060 · #18174)': 27, '⭐ the 2026-09-20 ruling: a pure-regeneration head move KEEPS the record, decided on the COMMITTED trees': 22, // Raised 30 → 32 with ③'s SQL push-down check in the legend on every face, and its faceless-PR carrier: two pins. - '#18042: the copyable record TEMPLATE — the one machine-read artefact with nothing to copy': 32, + // Raised 32 → 38 with the `Security-touching:` line the low-risk skills arm reads: the record line and its + // shipped `yes`, the whole template read through the record reader, the `no` reading, the faces and hits it + // prints on, the one predicate, and the legend — six pins. + '#18042: the copyable record TEMPLATE — the one machine-read artefact with nothing to copy': 38, // Raised 17 → 19 by #33541: the template record's one `VERDICT:` line read PASS by the guard, and the same record // posted by an untrusted author not read — two pins, two cases. '#18701: ONE thread set -- what the template STATES is what the queue guard READS': 19, @@ -2468,7 +2523,8 @@ const SELF_TEST_BATTERIES = Object.freeze({ 'the reviewer BRIEF template — the read-only shape a hand-written brief dropped, built in and printed': 24, '⭐ B′ with C: the review tier FOLLOWS THE FACE that made it owed — exact, never a floor': 23, '⭐ B′ with C: a PROSE-ONLY head move keeps the record, decided on the COMMITTED trees like a regeneration': 6, - '⭐ letter C: the at-tier review of a mixed diff is SCOPED — `hits` plus what they claim, on the `Scope:` line': 22, + // Raised 22 → 24 with the brief's `Security-touching:` duty: where the record says so, and never on a brief whose record lacks the line. + '⭐ letter C: the at-tier review of a mixed diff is SCOPED — `hits` plus what they claim, on the `Scope:` line': 24, '⭐ letter B: a declared NARROWING is a face of its own at CONTRACT_REVIEW_TIER — keyed on the `Clause-②:` line, exact': 17, '⭐ the `Contract-review-handoff:` line — names the current head ⇒ the named review or sibling seat\'s review; head moved ⇒ stale; absent ⇒ the seat\'s own; `triage` unreadable': 17, // Raised 27 → 40 with the scenario table's seven admitted keys and the `seat-online` patrol field: one pin @@ -2784,6 +2840,9 @@ export async function selfTest() { t('⭐ the brief over a low-risk skills path hands the `security` label duty, unconditionally, on either catalog row and through the CLI — the record says so, the adopting seat labels', (() => { const own = ['skills/objectstack-data/SKILL.md', 'ui/skills/objectui-forms/SKILL.md']; return own.every((p) => { const b = contractReviewBriefLines({ paths: [p, ...DECL_PATHS] }).join('\n'); return says(b, SECURITY_DUTY) && says(b, 'sits on the low-risk skills arm') && !says(b, SECURITY_IF); }) && says(faceCli(['--brief-template', '--paths', own[0]]).stdout, "behaviour the path name doesn't show, the record says so") && !says(contractReviewBriefLines({ paths: [own[0]] }).join('\n'), 'reviewer adds'); })()); t('⭐ SF5: the bare `--brief-template` and `--face rules` brief — the spelling the skill teaches — carry the duty in its CONDITIONAL form', (() => { const forms = [contractReviewBriefLines(), contractReviewBriefLines({ face: 'rules' }), contractReviewBriefLines({ face: 'schema' })].map((b) => b.join('\n')); return forms.every((b) => says(b, SECURITY_IF) && says(b, SECURITY_DUTY)) && says(faceCli(['--brief-template']).stdout, SECURITY_IF) && says(faceCli(['--brief-template', '--face', 'rules']).stdout, SECURITY_IF); })()); t('⛔ …and a brief whose `hits` are known and off the arm carries none, nor does the declaration or the narrowing face', [contractReviewBriefLines({ paths: MIXED }), contractReviewBriefLines({ face: 'declaration' }), contractReviewBriefLines({ face: 'narrowing' })].every((b) => !says(b.join('\n'), SECURITY_DUTY))); + const SECURITY_LINE_DUTY = 'The record says so on its `Security-touching:` line, and the arm lands on `no` alone: write `no` ONLY when no changed'; + t('⭐ the brief names WHERE the record says so — its `Security-touching:` line, `no` only when no changed hunk teaches security behaviour — on every brief that hands the duty, the CLI included', [contractReviewBriefLines({ paths: ['skills/objectstack-data/SKILL.md'] }), contractReviewBriefLines(), contractReviewBriefLines({ face: 'rules' }), contractReviewBriefLines({ face: 'schema' })].every((b) => says(b.join('\n'), SECURITY_LINE_DUTY) && says(b.join('\n'), 'hunk teaches permission, sharing, credential, token, authentication or other security behaviour, else `yes`.')) && says(faceCli(['--brief-template', '--paths', 'skills/objectstack-data/SKILL.md']).stdout, SECURITY_LINE_DUTY)); + t('⛔ …and a brief never asks for a line its record does not carry: off the arm, on the narrowing face and on the declaration face neither names `Security-touching`', [{ paths: MIXED }, { face: 'declaration' }, { face: 'narrowing' }].every((v) => !says(contractReviewBriefLines(v).join('\n'), 'Security-touching') && !says(contractReviewTemplateLines(v).join('\n'), 'Security-touching')) && [{}, { face: 'rules' }, { paths: ['skills/objectstack-data/SKILL.md'] }].every((v) => says(contractReviewBriefLines(v).join('\n'), 'Security-touching') && says(fenced(contractReviewTemplateLines(v)), 'Security-touching: yes'))); t('⭐ `--template --paths` and `--brief-template --paths` print exactly the function output and exit 0', (() => { const a = faceCli(['--template', '--paths', ...MIXED]); const b = faceCli(['--brief-template', '--paths', ...MIXED]); return a.status === 0 && a.stdout === `${contractReviewTemplateLines({ paths: MIXED }).join('\n')}\n` && b.status === 0 && b.stdout === `${contractReviewBriefLines({ paths: MIXED }).join('\n')}\n`; })()); t('⛔ `--paths` naming no path, or beside `--face` in either order, is REFUSED with the usage, exit 1', [['--template', '--paths'], ['--template', '--paths', RULES_PATH, '--face', 'rules'], ['--brief-template', '--face', 'rules', '--paths', RULES_PATH], ['--template', '--paths', '']].every((args) => { const r = faceCli(args); return r.status === 1 && says(r.stderr, 'usage:'); })); t('…and the usage names the flag, the face it reads and the line it fills', ['--paths PATH...', '`reviewFace`', '`Scope:`'].every((s) => usageLines().join('\n').includes(s))); @@ -3274,6 +3333,17 @@ export async function selfTest() { t('⭐ the record carries `Local-runs: none` — the read-only shape, declared where the reader reads it', TPL_RECORD.includes('Local-runs: none') && readLocalRuns(TPL_RECORD).value === 'none' && localRunsStand(readLocalRuns(TPL_TEXT))); t('…and the notes explain both values and that an absent line is not re-judged', says(TPL_TEXT, 'probe — REASON') && says(TPL_TEXT, 'not re-judged')); t('the printed location is the ONE thread set\'s own words', says(TPL_TEXT, `ONE comment on ${REVIEW_OF_RECORD_LOCATION};`)); + // -- the `Security-touching:` line: the low-risk skills arm's machine line, printed where an arm PR can sit -- + const ST_LINE = (value) => `Security-touching: ${value}`; + const stOf = (text) => contractReviewRecordReading(text)?.securityTouching; + const ARM_PATHS = [['skills', 'objectstack-data', 'SKILL.md'].join('/'), ['ui', 'skills', 'objectui-forms', 'SKILL.md'].join('/'), ['docs', 'adr', '0001-x.md'].join('/')]; + const OFF_ARM_PATH = ['.claude', 'agents', 'os-dev.md'].join('/'); + t('⭐ the bare record carries ONE `Security-touching:` line, right after `Scope:`, and it ships `yes` — read by the fleet\'s record reader as `yes`, never as `no`', (() => { const rec = contractReviewRecordLines(); const i = rec.indexOf(ST_LINE('yes')); return i > 0 && rec[i - 1].startsWith('Scope: ') && rec[i + 1] === '' && rec.filter((l) => l.startsWith('Security-touching')).length === 1 && JSON.stringify(stOf(TPL_RECORD)) === '{"state":"read","value":"yes"}' && RECORD_SECURITY_TOUCHING_DEFAULT === 'yes'; })()); + t('⭐ the WHOLE printed template reads that one line too — the legend around the fence carries no second declaration, on any face that prints it', [{}, { face: 'rules' }, { face: 'schema' }, ...ARM_PATHS.map((path) => ({ paths: [path] }))].every((v) => JSON.stringify(stOf(contractReviewTemplateLines(v).join('\n'))) === '{"state":"read","value":"yes"}')); + t('…and a reviewer who writes `no` over it is read as `no` — the one value the arm stands on', JSON.stringify(stOf(TPL_RECORD.replace(ST_LINE('yes'), ST_LINE('no')))) === '{"state":"read","value":"no"}' && TPL_RECORD.includes(`\n${ST_LINE('yes')}\n`)); + t('⛔ the line prints exactly where an arm PR can sit: with the `hits` known, under a low-risk row (skills, ui/skills, an ADR) and nowhere else; with none known, on the bare, rules and schema faces — never the narrowing or declaration face', ARM_PATHS.every((path) => fenced(contractReviewTemplateLines({ paths: [path] })).includes(`\n${ST_LINE('yes')}\n`)) && !contractReviewTemplateLines({ paths: [OFF_ARM_PATH] }).join('\n').includes('Security-touching') && !contractReviewTemplateLines({ paths: MIXED }).join('\n').includes('Security-touching') && ['rules', 'schema'].every((id) => contractReviewRecordLines({ faceId: id }).includes(ST_LINE('yes'))) && ['narrowing', 'declaration'].every((id) => !contractReviewTemplateLines({ face: id }).join('\n').includes('Security-touching')) && !contractReviewRecordLines({ tierName: TIER_DEFAULT_NAME }).join('\n').includes('Security-touching')); + t('the predicate is ONE function over face, tier and hits — below tier never, a narrowing never, known hits by the register\'s own low-risk row test', recordCarriesSecurityTouching(null, CONTRACT_REVIEW_TIER_NAME, undefined) && !recordCarriesSecurityTouching(null, TIER_DEFAULT_NAME, undefined) && !recordCarriesSecurityTouching(reviewFaceById('narrowing'), CONTRACT_REVIEW_TIER_NAME, undefined) && recordCarriesSecurityTouching(reviewFaceById('rules'), CONTRACT_REVIEW_TIER_NAME, [ARM_PATHS[0]]) && !recordCarriesSecurityTouching(reviewFaceById('rules'), CONTRACT_REVIEW_TIER_NAME, [OFF_ARM_PATH]) && !recordCarriesSecurityTouching(null, TIER_DEFAULT_NAME, [ARM_PATHS[0]])); + t('the notes explain the line where the record carries it — who reads it, when `no` may be written, what keeps Tier H — and the key and values are the reader\'s own constants', ['· Security-touching read by the low-risk skills arm alone', 'only when this line reads `no`', 'Write `no` ONLY when no changed hunk teaches permission, sharing, credential, token,', 'adds the `security` label', 'PR at Tier H', 'The template ships `yes`'].every((frag) => says(TPL_TEXT, frag)) && CONTRACT_REVIEW_SECURITY_TOUCHING_KEY === 'Security-touching' && CONTRACT_REVIEW_SECURITY_TOUCHING_VALUES.join() === 'no,yes'); // -- item ④: the owner's full-review order rides THIS record as a fourth section ------------ const DJ = '### ④ Design judgment'; const headings = (lines) => lines.filter((line) => line.startsWith('### ')); From 6dc29c9f8614a42c54dcdaa4db6704f30e1ebeb4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 20:03:14 +0000 Subject: [PATCH 3/8] feat(pm): the low-risk skills arm reads the record's Security-touching line and the card's labels The arm gains a record stage, read last and fail closed: the contract-review record on the head must carry one bare `Security-touching: no`, and the card the pull request delivers must neither carry the `security` label nor have had it removed. A reading that hands no stage in is Tier H (`pending` once every pull-read condition holds); the queue leg, `--pr` and the post-merge sweep each read the stage through the guard's one reader and ask again. A favourable stand-in read never answers it. Claude-Session: https://claude.ai/code/session_01ADHkmR2U8dFkRvc5DvUz1W Co-authored-by: Claude --- scripts/pm/check-governed-merges.mjs | 502 ++++++++++++++++++++-- scripts/pm/check-governed-queue-guard.mjs | 490 +++++++++++++++++---- 2 files changed, 891 insertions(+), 101 deletions(-) diff --git a/scripts/pm/check-governed-merges.mjs b/scripts/pm/check-governed-merges.mjs index c6561b2affc..17c33debf07 100644 --- a/scripts/pm/check-governed-merges.mjs +++ b/scripts/pm/check-governed-merges.mjs @@ -503,12 +503,27 @@ * never removed one; and no catalog path names security, auth or permission * (`LOW_RISK_SECURITY_NAME`, any segment below the row, any case) — the label * OR the name sends the PR to H; security teaching the name cannot see is - * flagged in the contract review's record and labelled `security` by the - * seat adopting it (the reviewer brief says so); + * the reviewer's to state (the record stage below), and the seat adopting + * such a record adds the `security` label (the reviewer brief says so); * - the head lives in the base repository (`forkVerdict`); * - every catalog path is a MODIFIED regular file with the same mode at both ends * — an added, deleted, renamed or copied skill or eval, a symlink, a mode change - * or a status not read is H (`catalogFiles`). + * or a status not read is H (`catalogFiles`); + * - the RECORD STAGE, read last (`lowRiskRecordStageReasons`): the + * `## Contract review` record on this head carries, as a machine line, + * exactly ONE bare `Security-touching: no` (`contractReviewRecordReading`'s + * `securityTouching`, the fleet's one record reader) — the line absent, + * unreadable, doubled, quoted, fenced, `yes`, or the record absent, unsigned, + * unread or carried over a hop that moved catalog text is H; + * - and the CARD the pull request delivers was read and neither carries the + * `security` label nor ever had it removed (its labels and its timeline) — + * a card that cannot be derived or read is H. + * + * The record stage is a SECOND read (`recordStage`): a reading that hands none + * in is Tier H — `pending` when every condition above holds, and then the + * caller (the queue leg, the relay, `--pr`, the sweep) reads the record and the + * card and asks again. ⛔ No stand-in answers it: a favourable stand-in read + * (`armSettledWithoutUnread`) leaves it pending and settles nothing. * * Then the landing is Tier S's: a `## Contract review` record for the current * head at `CONTRACT_REVIEW_TIER` (the record recognisers' `rules` face — no @@ -1179,8 +1194,10 @@ const SELF_TEST_BATTERIES = Object.freeze({ 'the per-row repository scope (ruled B2, 2026-10-13)': 20, 'the nested `ui/` workspace rows, on the register (#25712)': 16, '⭐ the workflows split: Tier H by path or by C2 trigger, else Tier S (ruling record 6722205630)': 75, - '⚖️ the low-risk skills arm: skills wording on Clause-② no lands Tier S, everything else stays H (#33501)': 74, - '⚖️ #33603: the sweep lists a low-risk arm landing APART and judges it on a same-head at-tier PASS record': 51, + // 74 → 95 with the arm's record stage: sixteen pins on the two conjuncts and the stage's three states, five on `--pr`. + '⚖️ the low-risk skills arm: skills wording on Clause-② no lands Tier S, everything else stays H (#33501)': 95, + // 51 → 61 with the record stage as the sweep reads it at the landing: ten pins. + '⚖️ #33603: the sweep lists a low-risk arm landing APART and judges it on a same-head at-tier PASS record': 61, '⭐ the weekly audit card: every reading the job files on, both ways (#33814)': 54, '⚖️ #33539: the ADR leg of the low-risk arm — an add-only note lands Tier S, any other ADR change stays H': 52, }); @@ -2699,8 +2716,23 @@ export function lowRiskChangesetReasons(file) { * add, delete, rename, copy, symlink, mode change or unread row is H (ruling A); * - the labels were read and none is `security`, and the timeline was read and * never removed a `security` label; - * - the head lives in the base repository (no fork). + * - the head lives in the base repository (no fork); + * - the RECORD STAGE, the two conjuncts read off the review rather than the pull (`lowRiskRecordStageReasons`): + * the contract-review record on this head carries one bare `Security-touching: no` line + * (`reading.record`), and the card the PR delivers carries no `security` label, now or + * removed (`reading.cardLabels`). * ⛔ Fail closed: no reading, or one not measured, is Tier H with its reason. + * + * `recordStage` says how far the record stage got. The pull-read conjuncts cost the caller nothing + * more than the pull it already holds; the record stage costs two threads and the card, so a caller + * hands it in SECOND, and only when it can matter: + * `not-reached` a pull-read conjunct already gave a reason and no record-stage reading was handed + * in — Tier H on those reasons, nothing more to read; + * `pending` every pull-read conjunct holds and no record-stage reading was handed in — Tier H, + * with the one reason that says so. The caller reads the stage and asks again; + * `read` a record-stage reading was handed in and judged, each failure a reason. + * ⛔ `pending` is never Tier S, and nothing a caller leaves out is read as `no`: a stand-in for an + * unread input may answer a pull-read conjunct, never this stage. */ export function lowRiskArmVerdict(matched, repo, reading = null) { const rows = (Array.isArray(matched) ? matched : []).filter(Boolean); @@ -2710,6 +2742,7 @@ export function lowRiskArmVerdict(matched, repo, reading = null) { measured: false, reason: reading?.reason ?? 'no reading of the pull request was handed in — a path list alone cannot say what its body declares or which labels it carries', reasons: [], + recordStage: LOW_RISK_RECORD_STAGE.notReached, }; } const reasons = []; @@ -2802,7 +2835,91 @@ export function lowRiskArmVerdict(matched, repo, reading = null) { const fork = reading.fork; if (!fork || fork.measured !== true) reasons.push('its head repository was not read, so a fork cannot be ruled out'); else if (fork.isFork === true) reasons.push(`its head lives in a fork (${fork.headRepo ?? 'a deleted repository'})`); - return { tier: reasons.length === 0 ? GOVERNED_TIER_S : GOVERNED_TIER_H, measured: true, reason: null, reasons }; + // ── the RECORD STAGE, last: the review's own statement and the card's labels ── + // Judged whenever a reading of it was handed in. With none handed in it is consulted only when every + // pull-read conjunct above holds, and then it is the one reason left: Tier H until the caller reads it. + const handed = reading.record != null || reading.cardLabels != null; + let recordStage = LOW_RISK_RECORD_STAGE.notReached; + if (handed) { + recordStage = LOW_RISK_RECORD_STAGE.read; + reasons.push(...lowRiskRecordStageReasons(reading.record ?? null, reading.cardLabels ?? null)); + } else if (reasons.length === 0) { + recordStage = LOW_RISK_RECORD_STAGE.pending; + reasons.push(LOW_RISK_RECORD_STAGE_PENDING_REASON); + } + return { tier: reasons.length === 0 ? GOVERNED_TIER_S : GOVERNED_TIER_H, measured: true, reason: null, reasons, recordStage }; +} + +/** How far the arm's record stage got (`lowRiskArmVerdict`'s `recordStage`). */ +export const LOW_RISK_RECORD_STAGE = Object.freeze({ notReached: 'not-reached', pending: 'pending', read: 'read' }); + +/** + * The record's machine line the arm stands on, spelled as the arm's reasons print it. The key and the value are + * the record reader's own (`CONTRACT_REVIEW_SECURITY_TOUCHING_KEY` and its values, `check-half-states.mjs`): this + * file cannot import that one at module scope (see `proxyRearmPlan`), so the self-test holds the two together. + */ +export const LOW_RISK_RECORD_LINE = 'Security-touching: no'; + +/** The reason a `pending` record stage reads Tier H on: nothing of it was read. */ +export const LOW_RISK_RECORD_STAGE_PENDING_REASON = + `its contract-review record and the labels of its card were not read, so neither a \`${LOW_RISK_RECORD_LINE}\` line nor a card free of the \`security\` label is established`; + +/** + * Why the record stage keeps the arm at Tier H, or [] — the arm's last two conjuncts. Pure. + * + * `record` is the reading of the review of record on this head (the queue guard's `lowRiskRecordStage` + * builds it from the same threads its record leg reads): + * `{ measured: true, located: 'found' | 'unsigned' | 'absent', where, id, + * carried: null | { from, ok, reason }, securityTouching: { state, value?, reason? } }` + * or `{ measured: false, reason }`. The conjunct holds only for a record FOUND on this head — one + * carried from an older head only over hops that moved nothing the arm reads — whose + * `Security-touching:` line was READ and reads `no`. A record that is absent, unsigned, unread, + * carried over a hop that moved catalog text, or whose line is missing, unreadable or `yes`, is + * each a reason. + * + * `cardLabels` is the reading of the card the pull request delivers: + * `{ measured: true, card, labels: string[], timeline: { measured, reason, events } }` + * or `{ measured: false, reason }` — no derivable card included, since a label on a card nobody + * could name cannot be ruled out. The conjunct holds only when the labels were read and none is + * `security`, and the card's timeline was read and never removed one: the PR's own rule, on the card. + */ +export function lowRiskRecordStageReasons(record, cardLabels) { + return [...lowRiskRecordLineReasons(record), ...lowRiskCardLabelReasons(cardLabels)]; +} + +/** The record stage's first conjunct: the review of record on this head reads `Security-touching: no`. Pure. */ +function lowRiskRecordLineReasons(record) { + const key = LOW_RISK_RECORD_LINE.split(':')[0]; + if (!record || record.measured !== true) { + return [`its contract-review record was not read (${record?.reason ?? 'no reading'}), so no \`${LOW_RISK_RECORD_LINE}\` line is established`]; + } + if (record.located !== 'found') { + return [record.located === 'unsigned' + ? `its contract-review record on this head names no reviewer, so its \`${key}:\` line does not count` + : `no contract-review record names this head, so no \`${LOW_RISK_RECORD_LINE}\` line is established`]; + } + const reasons = []; + const which = `its contract-review record (${record.where ?? 'a'} comment ${record.id ?? '(no id)'})`; + const line = record.securityTouching; + if (record.carried && record.carried.ok !== true) reasons.push(`${which} ${record.carried.reason ?? 'was carried from an older head over hops that could not be read'}`); + if (!line || line.state === 'missing') reasons.push(`${which} carries no \`${key}:\` line`); + else if (line.state !== 'read') reasons.push(`the \`${key}:\` line of ${which} is unreadable: ${line.reason ?? 'no reason recorded'}`); + else if (line.value !== 'no') reasons.push(`${which} reads \`${key}: ${String(line.value)}\``); + return reasons; +} + +/** The record stage's second conjunct: the card the pull request delivers never carried `security`. Pure. */ +function lowRiskCardLabelReasons(cardLabels) { + if (!cardLabels || cardLabels.measured !== true || !Array.isArray(cardLabels.labels)) { + return [`the labels of its card were not read (${cardLabels?.reason ?? 'no reading'}), so a \`security\` label on the card cannot be ruled out`]; + } + const reasons = []; + const card = `its card #${cardLabels.card ?? '(no number)'}`; + if (cardLabels.labels.some((l) => String(l ?? '').toLowerCase() === 'security')) reasons.push(`${card} carries the \`security\` label`); + const timeline = cardLabels.timeline; + if (!timeline || timeline.measured !== true || !Array.isArray(timeline.events)) reasons.push(`the timeline of ${card} was not read (${timeline?.reason ?? 'no reading'}), so a removed \`security\` label cannot be ruled out`); + else if (timeline.events.some((e) => e?.event === 'unlabeled' && String(e?.label?.name ?? '').toLowerCase() === 'security')) reasons.push(`the timeline of ${card} shows the \`security\` label removed`); + return reasons; } /** @@ -2830,7 +2947,7 @@ export function renderLowRiskLines(matched) { ); } if (v.tier === GOVERNED_TIER_S) { - return ` ⚖️ low-risk skills arm (${LOW_RISK_ARM_RULING}): Tier S — modified skill files, add-only ADR notes and prose only, one bare \`Clause-②: no\` and \`Metadata-protocol: none\`, clean changesets, no \`security\` label ever and no catalog path named for it, no fork.\n`; + return ` ⚖️ low-risk skills arm (${LOW_RISK_ARM_RULING}): Tier S — modified skill files, add-only ADR notes and prose only, one bare \`Clause-②: no\` and \`Metadata-protocol: none\`, clean changesets, no \`security\` label ever on the PR or its card and no catalog path named for it, no fork, and a record on this head reading \`${LOW_RISK_RECORD_LINE}\`.\n`; } return ` ⚖️ low-risk skills arm (${LOW_RISK_ARM_RULING}): Tier H —\n${v.reasons.map((r) => ` - ${r}\n`).join('')}`; } @@ -4588,6 +4705,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, }), + // 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: { kind: 'pull', slug, @@ -4612,11 +4731,16 @@ export async function fetchPullFiles({ apiUrl, slug, pull, channels, fetchImpl = * read `null`, which the arm reads as H; a body that is not a string reads as * an empty body, which declares nothing and is H too. The fork predicate is * read off the same object; the timeline and the changesets arrive as their own - * readings, and one not handed in is NOT MEASURED, so H. + * readings, and one not handed in is NOT MEASURED, so H. The record stage + * (`record`, `cardLabels`) is the caller's second read: see `lowRiskArmVerdict`. */ -export function pullLowRiskReading(head, paths, { timeline = null, changesets = null, catalogFiles = null } = {}) { +export function pullLowRiskReading(head, paths, { timeline = null, changesets = null, catalogFiles = null, record = null, cardLabels = null } = {}) { const labels = Array.isArray(head?.labels) ? head.labels.map((l) => (typeof l === 'string' ? l : String(l?.name ?? ''))) : null; return { + // The record stage (`lowRiskRecordStageReasons`), carried only when a caller read it: left out, the arm + // answers `pending` once the pull-read conjuncts hold, and the caller reads the stage and asks again. + ...(record == null ? {} : { record }), + ...(cardLabels == null ? {} : { cardLabels }), measured: true, reason: null, paths: Array.isArray(paths) ? [...paths] : [], @@ -4723,6 +4847,42 @@ export async function fetchTimelineOver({ fetchImpl, url, channel, pageCap = PUL return { measured: true, reason: null, events }; } +/** + * `--pr`'s read of the arm's RECORD STAGE (`lowRiskArmVerdict`), taken SECOND and only when the first read left it + * `pending` — every pull-read condition holds — so no other `--pr` pays for it. ⭐ ONE reader: the queue guard's own + * `readLowRiskRecordStage` (the card it derives, the threads cut to trusted authors, `lowRiskRecordStage`, + * `readCardLabels`), loaded lazily (`loadArmReaders`), so `--pr` cannot read a record differently from the queue. + * `fetchers` are `{ fetchComments, fetchLabels, fetchTimeline }` over the channel that read the PR; `runGit` re-tests + * a carried record and is null when the PR is not in this checkout, which refuses the carry. + * ⛔ Readers that did not load are NOT MEASURED, so Tier H — never a stand-in and never `no`. + * Returns the reading with `record` and `cardLabels` added, or the reading AS IS when the stage is not pending. + */ +export async function pullRecordStage({ lowRisk, paths, repo, workflowDiff = null, pullHead, derivation, readers, fetchers = {}, runGit = null }) { + if (!lowRisk) return lowRisk; + const surfaces = applyLowRiskArm(applyWorkflowSplit(governedPathsIn(paths, repo), repo, workflowDiff), repo, lowRisk); + if (!surfaces.some((s) => s?.lowRiskVerdict?.recordStage === LOW_RISK_RECORD_STAGE.pending)) return lowRisk; + const loaded = typeof readers === 'function' ? await readers() : readers; + if (loaded?.available !== true) { + const reason = loaded?.reason ?? 'the queue guard readers were not loaded'; + return { ...lowRisk, record: { measured: false, reason }, cardLabels: { measured: false, reason: `not read: ${reason}` } }; + } + const built = typeof fetchers === 'function' ? fetchers(loaded.guard) : fetchers; + const stage = await loaded.guard.readLowRiskRecordStage({ + pr: derivation?.pull ?? pullHead?.number ?? null, + pull: pullHead ?? null, + headSha: derivation?.headSha ?? null, + paths, + repo, + runGit, + baseRef: derivation?.baseSha ?? null, + recognisers: loaded.recognisers, + fetchComments: built?.fetchComments ?? null, + fetchLabels: built?.fetchLabels ?? null, + fetchTimeline: built?.fetchTimeline ?? null, + }); + return { ...lowRisk, record: stage.record, cardLabels: stage.cardLabels }; +} + /** * `--pr`'s changeset reading for the arm: each `.changeset/*.md` the PR changes, * read at the PR's own head from THIS checkout. Anything short of that is NOT @@ -4765,7 +4925,7 @@ export function pullSizeFrom(head) { export const ARM_READER_SOURCE = './check-governed-queue-guard.mjs'; /** The guard exports the arm leg reads with. A missing one is NOT MEASURED, never a second parser here. */ -export const ARM_READER_EXPORTS = Object.freeze(['decomposeGovernedWork', 'readLowRiskTier', 'landsOnLowRiskArm', 'recordAuthorTrusted', 'ignoredAuthorLines', 'authorizedApprovalVerdict', 'enqueuerFromTimeline', 'authorizedEnqueueVerdict', 'loadRecordRecognisers', 'recordVerdict', 'lowRiskRecordVerdict', 'makePullReader', 'makeReviewReader', 'makeCommentReader', 'makeTimelineReader']); +export const ARM_READER_EXPORTS = Object.freeze(['decomposeGovernedWork', 'readLowRiskTier', 'landsOnLowRiskArm', 'recordAuthorTrusted', 'ignoredAuthorLines', 'authorizedApprovalVerdict', 'enqueuerFromTimeline', 'authorizedEnqueueVerdict', 'loadRecordRecognisers', 'recordVerdict', 'lowRiskRecordVerdict', 'lowRiskRecordStagePending', 'lowRiskRecordStage', 'readCardLabels', 'readLowRiskRecordStage', 'makePullReader', 'makeReviewReader', 'makeCommentReader', 'makeTimelineReader', 'makeLabelReader']); /** Load the guard's readers and the record recognisers once per run. Never throws: a failed load is the reason. */ export async function loadArmReaders(load = (specifier) => import(specifier)) { @@ -4801,9 +4961,18 @@ export async function loadArmReaders(load = (specifier) => import(specifier)) { * The carry test's `baseRef` is the landed commit's first parent (N6): between it and the merge group's base lie * only the squash commits of entries ahead in the same group, which no queued head contains, so `git merge-base` * of either base with a head names the same commit and the carry reads the same. - * States: `pass` (an arm landing on a same-head at-tier PASS record), `breach` (an arm landing without one, or - * whose pull did not land as this commit), `cleared` (the arm read S, but an authorized approval or enqueue - * cleared it first: the maintainer's merge), `tier-h` (the arm read H: the maintainer's merge), `not-measured` + * The arm's RECORD STAGE is read as the queue reads it, SECOND and only for an entry nothing else cleared: the first + * arm read leaves it pending (`lowRiskRecordStagePending`) when every pull-read condition holds, and a first read + * that is not pending is Tier H on a pull-read reason. Past the approval and enqueue legs, a record that stands and + * reads PASS must also carry the arm's line and the card must be free of the `security` label AS THEY STOOD AT THE + * LANDING: the line off the same as-landed rows (`lowRiskRecordStage`), the card's labels rebuilt from its timeline + * (`cardLabelsAsLanded`; `fetchers.fetchLabels` reads them, absent ⇒ `not-measured`). A stage that then reads Tier H + * is a `breach` flagged `stage: true` — the queue would have refused that landing — and a stage that could not be + * read is `not-measured`, ⛔ never `tier-h` and never a stand-in. + * States: `pass` (an arm landing on a same-head at-tier PASS record whose record stage holds), `breach` (an arm + * landing without one, on a record stage at Tier H, or whose pull did not land as this commit), `cleared` (the + * arm's pull-read conditions held, but an authorized approval or enqueue cleared it before the record was read: the + * maintainer's merge), `tier-h` (the arm read H on what the pull shows: the maintainer's merge), `not-measured` * (a read failed: listed with the maintainer's merges, and the sweep is INCOMPLETE). Never throws. */ export async function readArmLanding(entry, { paths, repo, readers, fetchers, runGit, attribution = null }) { @@ -4837,7 +5006,9 @@ export async function readArmLanding(entry, { paths, repo, readers, fetchers, ru } }; guard.readLowRiskTier(work, repo, head, { timeline: { measured: true, reason: null, events }, runGit: armGit }); - if (!guard.landsOnLowRiskArm(work)) { + // ⭐ The first read hands in no record stage, so it never reads Tier S: `pending` says every pull-read condition + // holds, and anything else is Tier H on what the pull shows — the branch below, unchanged by the record stage. + if (!guard.lowRiskRecordStagePending(work)) { const reasons = work.surfaces.find((s) => s?.lowRiskVerdict)?.lowRiskVerdict?.reasons ?? []; // #33765 N-b: an unread labels list is an unread input too, though no git read failed. const inputs = armUnreadInputs(gitFailures, pull.fork, runGit, pull.labels); @@ -4915,7 +5086,24 @@ export async function readArmLanding(entry, { paths, repo, readers, fetchers, ru if (record.state === 'unreadable') return unmeasured(record.reason); const found = { where: record.where ?? null, id: record.id ?? null, at: record.at ?? null, cardNote }; const ignored = guard.ignoredAuthorLines({ ignoredAuthors }).map((line) => line.trim()); - if (record.state === 'stands') return { state: 'pass', headSha, record: found, ...(ignored.length > 0 ? { ignored } : {}) }; + if (record.state === 'stands') { + // ⭐ The arm's record stage, as the queue read it: the line off the rows that existed, unedited, at the landing, + // and the card's labels as they stood then. ⛔ Anything unread is NOT MEASURED — never a stand-in, never `no`. + const stage = guard.lowRiskRecordStage({ pair, recognisers }); + if (stage.measured !== true) return unmeasured(`its record's \`${LOW_RISK_RECORD_LINE.split(':')[0]}:\` line could not be read (${stage.reason})`); + const carded = await guard.readCardLabels({ card, fetchLabels: fetchers.fetchLabels, fetchTimeline: fetchers.fetchTimeline }); + const named = card.card !== null && card.card !== undefined; + if (named && (carded.reading.measured !== true || carded.reading.timeline?.measured !== true)) { + return unmeasured(`the labels of its card #${card.card} could not be read as they stood at the landing (${carded.reading.reason ?? carded.reading.timeline?.reason ?? 'no reading'})`); + } + const cardLabels = named ? cardLabelsAsLanded(carded.reading, landed) : carded.reading; + guard.readLowRiskTier(work, repo, head, { timeline: { measured: true, reason: null, events }, runGit: armGit, record: stage, cardLabels }); + if (guard.landsOnLowRiskArm(work)) return { state: 'pass', headSha, record: found, ...(ignored.length > 0 ? { ignored } : {}) }; + // A git read that failed on this second pass is an unread input, not a reason the queue had. + if (gitFailures.length > 0) return unmeasured(`the low-risk arm could not re-read ${gitFailures.map((f) => `\`git ${(f.argv ?? []).slice(0, 2).join(' ')}\` (${f.why})`).join('; ')} for its record stage`); + const stageReasons = work.surfaces.find((s) => s?.lowRiskVerdict)?.lowRiskVerdict?.reasons ?? []; + return { state: 'breach', stage: true, headSha, reason: stageReasons.join('; ') || 'no reason recorded', record: found, ...(ignored.length > 0 ? { ignored } : {}) }; + } // N9, N10: the edit is named on every BREACH reason, and only for the row the record leg would have read. let edited = ''; if (editedAfter.size > 0) { @@ -4942,6 +5130,27 @@ export async function readArmLanding(entry, { paths, repo, readers, fetchers, ru return { state: 'breach', headSha, reason, record: found, ...(ignored.length > 0 ? { ignored } : {}) }; } +/** + * A card's labels as they stood when the commit landed, for the arm's record stage: the reading `readCardLabels` + * took NOW, rebuilt from the card's own timeline. Only `security` is rebuilt, the one label the arm reads: + * - its `labeled` / `unlabeled` events before the landing are kept as the timeline (so one removed before the + * landing reads as removed), and the newest of them says whether the card carried it at the landing; + * - with no such event before the landing, the card carried it then only if it carries it now and no `labeled` + * event at or after the landing explains that — a label with no event behind it is read as already there. + * An event with no readable time is read as before the landing: toward BREACH, never toward clean. Pure. + */ +export function cardLabelsAsLanded(reading, landed) { + const events = Array.isArray(reading?.timeline?.events) ? reading.timeline.events : []; + const isSecurity = (e) => (e?.event === 'labeled' || e?.event === 'unlabeled') && String(e?.label?.name ?? '').toLowerCase() === 'security'; + const after = (e) => Date.parse(e?.created_at ?? '') >= landed; + const prior = events.filter((e) => isSecurity(e) && !after(e)); + const now = (Array.isArray(reading?.labels) ? reading.labels : []).some((l) => String(l ?? '').toLowerCase() === 'security'); + const carried = prior.length > 0 + ? prior[prior.length - 1].event === 'labeled' + : now && !events.some((e) => isSecurity(e) && e.event === 'labeled' && after(e)); + return { ...reading, labels: carried ? ['security'] : [], timeline: { measured: true, reason: null, events: prior } }; +} + /** * The reviews as they stood when the commit landed (#33729 N8): a review GitHub now reads DISMISSED, whose * dismissal the timeline dates at or after the landing, is put back in the state the timeline's `review_dismissed` @@ -5020,6 +5229,9 @@ export function favourableArmGitRead(argv, paths) { * `favourableArmGitRead`, the fork predicate as no fork, the labels as none. The arm's verdict is a conjunction, * so if it still reads H, the reasons it gives come from measured inputs and settle Tier H: those reasons, or null * (a read with no such answer, a read that fails anew, or an arm that would read S), which stays NOT MEASURED. + * ⛔ The arm's record stage is never answered here: no stand-in record is handed in, so a re-read whose pull-read + * conditions all hold comes back `pending` — the arm WOULD go on to its record — and that is null, never a reason + * that settles Tier H and never a `Security-touching: no`. * Never throws. */ function armSettledWithoutUnread({ guard, entry, paths, repo, head, events, runGit, inputs }) { @@ -5047,7 +5259,7 @@ function armSettledWithoutUnread({ guard, entry, paths, repo, head, events, runG const fork = head.fork?.measured === true ? head.fork : { measured: true, isFork: false }; const labels = Array.isArray(head.labels) ? head.labels : []; guard.readLowRiskTier(work, repo, { ...head, fork, labels }, { timeline: { measured: true, reason: null, events }, runGit: git }); - if (guard.landsOnLowRiskArm(work) || armUnreadInputs(failures, fork, runGit, labels).length > 0) return null; + if (guard.landsOnLowRiskArm(work) || guard.lowRiskRecordStagePending(work) || armUnreadInputs(failures, fork, runGit, labels).length > 0) return null; const reasons = work.surfaces.find((s) => s?.lowRiskVerdict)?.lowRiskVerdict?.reasons ?? []; return reasons.length > 0 ? reasons : null; } catch { @@ -5062,8 +5274,9 @@ export function armCell(entry) { const head = a.headSha ? ` on head ${String(a.headSha).slice(0, 12)}` : ''; const ignored = (a.ignored ?? []).map((line) => `\n ${line}`).join(''); if (a.state === 'pass') return `\n ✅ low-risk arm landing${head}: same-head at-tier PASS record ${a.record?.where ?? ''} comment ${a.record?.id ?? '(no id)'}${ignored}`; + if (a.state === 'breach' && a.stage === true) return `\n ⛔ BREACH — low-risk arm landing${head} on a record stage that reads Tier H: ${a.reason}${ignored}`; if (a.state === 'breach') return `\n ⛔ BREACH — low-risk arm landing${head} WITHOUT a same-head at-tier PASS record: ${a.reason}${ignored}`; - if (a.state === 'cleared') return `\n low-risk arm: Tier S${head}, cleared by an authorized ${a.by === 'review' ? 'approval' : 'enqueue'} (${(a.who ?? []).join(', ')}) before the record leg — the maintainer's merge`; + if (a.state === 'cleared') return `\n low-risk arm: its pull-read conditions held${head}, cleared by an authorized ${a.by === 'review' ? 'approval' : 'enqueue'} (${(a.who ?? []).join(', ')}) before the record was read — the maintainer's merge`; if (a.state === 'not-measured') return `\n ⚠️ low-risk arm NOT MEASURED${head} — ${a.reason}; listed here, unjudged`; const reasons = a.reasons ?? []; const unread = (a.unread ?? []).length > 0 ? `; settled without the unread ${a.unread.join('; ')}` : ''; @@ -5328,7 +5541,7 @@ export function renderReport({ window, repos, scanned, entries, lookups, sweepCo (oversizedOnly.length > 0 ? ` and ${oversizedOnly.length} oversized landing(s) with no governed path` : '') + ` since ${window.requestedIso} ` + `across ${audited.length}/${repos.length} governed repo(s)\n` + - (armLandings.length > 0 ? ` of which ${armLandings.length} landed through the low-risk skills arm, ${breaches} of them ⛔ BREACH (no same-head at-tier PASS record)\n` : '') + + (armLandings.length > 0 ? ` of which ${armLandings.length} landed through the low-risk skills arm, ${breaches} of them ⛔ BREACH (no same-head at-tier PASS record, or a record stage at Tier H)\n` : '') + ` scanned ${scanned} mainline commit(s); ${lookups} API lookup(s).\n` + (sweepCode ? `${describeSweepCode(sweepCode)}\n` : '') + describeWindow(window); @@ -6131,7 +6344,25 @@ async function runPullMode(args) { catalogFiles: pullCatalogReading({ derivation: derived.derivation, statuses: derived.catalogStatuses, paths: derived.paths, sameCheckout: target.slug === selfSlug, run: (argv) => tryGit(root, argv) }), } : derived.lowRisk ?? null; - return await emitVerdict(derived.paths, args, derived.derivation, derived.size, { fork: derived.fork, checks: derived.checks }, repo, workflowDiff, lowRisk); + // ⭐ The arm's record stage: the readers load and the threads are read only when the stage is pending, over the + // channel that read the PR (a token rides only on the env-token channel, as the sweep's arm leg sends it). + const sameCheckout = target.slug === selfSlug; + const staged = await pullRecordStage({ + lowRisk, + paths: derived.paths, + repo, + workflowDiff, + pullHead: derived.pullHead, + derivation: derived.derivation, + readers: () => loadArmReaders(), + fetchers: (guard) => { + const token = derived.derivation.channel === 'env-token' ? process.env.GITHUB_TOKEN || process.env.GH_TOKEN || null : null; + const api = { ...apiContext(process.env), slug: target.slug, token }; + return { fetchComments: guard.makeCommentReader(api), fetchLabels: guard.makeLabelReader(api), fetchTimeline: guard.makeTimelineReader(api) }; + }, + runGit: sameCheckout ? (argv) => git(root, argv) : null, + }); + return await emitVerdict(derived.paths, args, derived.derivation, derived.size, { fork: derived.fork, checks: derived.checks }, repo, workflowDiff, staged); } /** @@ -6587,7 +6818,7 @@ async function main() { return read(n); }; const fetchers = armReaders.available - ? { fetchPull: counted(armReaders.guard.makePullReader(api)), fetchReviews: counted(armReaders.guard.makeReviewReader(api)), fetchTimeline: counted(armReaders.guard.makeTimelineReader(api)), fetchComments: counted(armReaders.guard.makeCommentReader(api)) } + ? { fetchPull: counted(armReaders.guard.makePullReader(api)), fetchReviews: counted(armReaders.guard.makeReviewReader(api)), fetchTimeline: counted(armReaders.guard.makeTimelineReader(api)), fetchComments: counted(armReaders.guard.makeCommentReader(api)), fetchLabels: counted(armReaders.guard.makeLabelReader(api)) } : null; const root = repoById.get(entry.repoId)?.path; entry.arm = await readArmLanding(entry, { paths: pathsBySha.get(entry.sha) ?? [], repo: entry.repoId, readers: armReaders, fetchers, runGit: (argv) => git(root, argv), attribution: entry.attribution ?? null }); @@ -7045,12 +7276,19 @@ async function selfTest() { // Every catalog path a MODIFIED regular file — the shape a wording PR has. const catFiles = (paths, status = 'modified', mode = '100644') => paths.filter((p) => /^(?:ui\/)?skills\//.test(p)).map((path) => ({ path, status, oldMode: mode, mode })); const csFiles = (paths, text = CS_TEXT) => paths.filter((p) => LOW_RISK_CHANGESET_PATH.test(p)).map((path) => ({ path, text })); + // The arm's RECORD STAGE, read and favourable: a record on this head whose one line reads `no`, and a card that + // never carried `security`. Every reading below carries it, so a row that pins Tier S pins it on the whole + // conjunction, and the record-stage rows further down each drop one piece. + const stageRecord = (over = {}) => ({ measured: true, reason: null, located: 'found', where: 'PR', id: 9001, carried: null, securityTouching: { state: 'read', value: 'no' }, ...over }); + const stageCard = (over = {}) => ({ measured: true, reason: null, card: 1, labels: [], timeline: { measured: true, reason: null, events: [] }, ...over }); const read = (paths, over = {}) => ({ measured: true, reason: null, paths, body: 'Fixes #1\n\nClause-②: no\nMetadata-protocol: none\n', labels: [], timeline: { measured: true, reason: null, events: [] }, fork: { measured: true, isFork: false, headRepo: 'o/r', baseRepo: 'o/r' }, changesets: { measured: true, reason: null, files: csFiles(paths) }, catalogFiles: { measured: true, reason: null, files: catFiles(paths) }, + record: stageRecord(), + cardLabels: stageCard(), ...over, }); const tier = (paths, reading, repo = REPO) => governedTierFor(paths, repo, GOVERNED_SURFACES, null, reading); @@ -7099,9 +7337,90 @@ async function selfTest() { assert('the-same-S-reading-moves-nothing-in-objectui-cloud-or-hotcrm', tier([SK, CS], read([SK, CS])) === GOVERNED_TIER_S && ['objectui', 'cloud', 'hotcrm'].every((r) => tier([SK, CS], read([SK, CS]), r) === GOVERNED_TIER_H)); assert('a-slice-with-no-catalog-row-is-returned-as-is-byte-identical', (() => { const m = governedPathsIn(['AGENTS.md', '.claude/x.md'], REPO); return applyLowRiskArm(m, REPO, read(['AGENTS.md', '.claude/x.md'])) === m && renderLowRiskLines(m) === ''; })() && tier(['.claude/agents/os-dev.md'], read(['.claude/agents/os-dev.md'])) === GOVERNED_TIER_S); + // ── The RECORD STAGE: the arm's last two conditions — the review's own `Security-touching: no` line and a card + // that never carried `security` — one row per piece. Every row holds the pull-read conditions fixed (`read`). + const staged = (over) => read([SK, CS], over); + const stageTier = (over) => tier([SK, CS], staged(over)); + const stageWhy = (over) => reasons([SK, CS], staged(over)); + const stageOf = (reading, paths = [SK, CS]) => lowRiskArmVerdict(governedPathsIn(paths, REPO), REPO, reading).recordStage; + const unstaged = (over = {}) => { const { record: _record, cardLabels: _cardLabels, ...rest } = staged(over); return rest; }; + const recordH = (record, re) => (stageTier({ record }) === GOVERNED_TIER_H && re.test(stageWhy({ record })) ? true : stageWhy({ record })); + const cardH = (cardLabels, re) => (stageTier({ cardLabels }) === GOVERNED_TIER_H && re.test(stageWhy({ cardLabels })) ? true : stageWhy({ cardLabels })); + assert('⭐ RECORD-STAGE-CONTROL a-record-on-this-head-reading-no-and-a-card-never-labelled-security-is-Tier-S-and-the-stage-says-read', + stageTier({}) === GOVERNED_TIER_S && stageOf(staged({})) === LOW_RISK_RECORD_STAGE.read && stageWhy({}) === '' && stageTier({ cardLabels: stageCard({ labels: ['docs', 'skip-changeset'], timeline: { measured: true, reason: null, events: [{ event: 'unlabeled', label: { name: 'docs' } }, { event: 'labeled', label: { name: 'docs' } }] } }) }) === GOVERNED_TIER_S, stageWhy({})); + assert('⛔ RECORD-LINE a-record-with-NO-Security-touching-line-is-Tier-H-and-the-reason-names-the-comment', + recordH(stageRecord({ securityTouching: { state: 'missing' } }), /^its contract-review record \(PR comment 9001\) carries no `Security-touching:` line$/) === true && + recordH(stageRecord({ securityTouching: null, where: 'card', id: 9002 }), /^its contract-review record \(card comment 9002\) carries no `Security-touching:` line$/) === true && + recordH(stageRecord({ securityTouching: undefined }), /carries no `Security-touching:` line/) === true); + assert('⛔ RECORD-LINE a-line-reading-yes-or-any-value-but-a-bare-no-is-Tier-H', + recordH(stageRecord({ securityTouching: { state: 'read', value: 'yes' } }), /reads `Security-touching: yes`$/) === true && + ['No', 'NO', ' no', 'none', '', null, undefined, false, 0].every((value) => recordH(stageRecord({ securityTouching: { state: 'read', value } }), /reads `Security-touching: /) === true)); + assert('⛔ RECORD-LINE an-unreadable-line-is-Tier-H-with-the-record-readers-own-reason', + recordH(stageRecord({ securityTouching: { state: 'unreadable', reason: 'it carries 2 `Security-touching:` lines, and a record states exactly one' } }), /the `Security-touching:` line of its contract-review record \(PR comment 9001\) is unreadable: it carries 2 /) === true && + recordH(stageRecord({ securityTouching: { state: 'unreadable' } }), /is unreadable: no reason recorded$/) === true); + assert('⛔ RECORD-LINE no-record-on-this-head-an-unsigned-one-or-one-that-was-not-read-is-Tier-H', + recordH(stageRecord({ located: 'absent', where: null, id: null, securityTouching: null }), /^no contract-review record names this head, so no `Security-touching: no` line is established$/) === true && + recordH(stageRecord({ located: 'unsigned' }), /names no reviewer, so its `Security-touching:` line does not count$/) === true && + recordH({ measured: false, reason: "PR #2's comment thread could not be read (HTTP 502)" }, /^its contract-review record was not read \(PR #2's comment thread could not be read \(HTTP 502\)\), so no `Security-touching: no` line is established$/) === true && + recordH(stageRecord({ located: 'unreadable' }), /no contract-review record names this head/) === true); + assert('⛔ RECORD-LINE a-record-CARRIED-over-hops-that-moved-what-the-arm-reads-is-Tier-H-and-one-carried-clean-stays-S', + recordH(stageRecord({ carried: { from: 'd'.repeat(40), ok: false, reason: 'was carried from `dddddddddddd` over hops that moved skills/a/SKILL.md, which the arm reads, after the review' } }), /\(PR comment 9001\) was carried from `dddddddddddd` over hops that moved skills\/a\/SKILL\.md/) === true && + recordH(stageRecord({ carried: { from: 'd'.repeat(40), ok: false } }), /over hops that could not be read$/) === true && + recordH(stageRecord({ carried: { from: 'd'.repeat(40) } }), /over hops that could not be read$/) === true && + stageTier({ record: stageRecord({ carried: { from: 'd'.repeat(40), ok: true, reason: null } }) }) === GOVERNED_TIER_S); + // ⛔ Fail closed on SHAPE: only a measured record FOUND on this head whose line was READ as exactly `no` passes, + // so no stand-in, partial or mistyped reading — whatever built it — can read `no`. + assert('⛔ RECORD-LINE no-reading-short-of-a-measured-found-record-whose-line-was-READ-as-no-passes-whatever-its-shape', + [true, 'no', {}, [], { measured: true }, { measured: 'true', located: 'found', securityTouching: { state: 'read', value: 'no' } }, { measured: true, located: 'found' }, + { measured: true, located: 'found', securityTouching: 'no' }, { measured: true, located: 'found', securityTouching: { value: 'no' } }, { measured: true, located: 'found', securityTouching: { state: 'read' } }, + { measured: true, located: 'Found', securityTouching: { state: 'read', value: 'no' } }, { measured: true, securityTouching: { state: 'read', value: 'no' } }, + { measured: true, located: 'found', securityTouching: { state: 'Read', value: 'no' } }].every((record) => stageTier({ record }) === GOVERNED_TIER_H)); + assert('⛔ CARD-LABEL a-card-carrying-the-security-label-in-any-case-is-Tier-H', + cardH(stageCard({ card: 69, labels: ['security'] }), /^its card #69 carries the `security` label$/) === true && + cardH(stageCard({ labels: ['docs', 'Security'] }), /its card #1 carries the `security` label/) === true && cardH(stageCard({ labels: ['SECURITY'] }), /carries the `security` label/) === true); + assert('⛔ CARD-LABEL a-security-label-REMOVED-from-the-card-is-Tier-H-though-its-labels-no-longer-show-it', + cardH(stageCard({ card: 69, timeline: { measured: true, reason: null, events: [{ event: 'labeled', label: { name: 'security' } }, { event: 'unlabeled', label: { name: 'Security' } }] } }), /^the timeline of its card #69 shows the `security` label removed$/) === true && + stageTier({ cardLabels: stageCard({ timeline: { measured: true, reason: null, events: [{ event: 'unlabeled', label: { name: 'security-review' } }, { event: 'closed', label: { name: 'security' } }] } }) }) === GOVERNED_TIER_S); + assert('⛔ CARD-LABEL labels-or-a-timeline-that-were-not-read-or-a-card-nobody-could-name-are-Tier-H', + cardH({ measured: false, reason: 'no card could be derived for it — the body names no card' }, /^the labels of its card were not read \(no card could be derived for it — the body names no card\), so a `security` label on the card cannot be ruled out$/) === true && + cardH({ measured: false, reason: "card #69's labels could not be read (HTTP 502)" }, /were not read \(card #69's labels could not be read \(HTTP 502\)\)/) === true && + cardH(stageCard({ labels: null }), /the labels of its card were not read \(no reading\)/) === true && cardH({}, /the labels of its card were not read/) === true && cardH(true, /the labels of its card were not read/) === true && + cardH(stageCard({ card: 69, timeline: { measured: false, reason: 'HTTP 502', events: null } }), /^the timeline of its card #69 was not read \(HTTP 502\), so a removed `security` label cannot be ruled out$/) === true && + cardH(stageCard({ timeline: null }), /the timeline of its card #1 was not read \(no reading\)/) === true && cardH(stageCard({ timeline: { measured: true, events: 'none' } }), /was not read/) === true); + // ⛔ PENDING: every pull-read condition holds and no record stage was handed in. Tier H on ONE reason, and the + // caller (the queue leg, the relay, `--pr`, the sweep) reads the stage and asks again. Never Tier S. + assert('⛔ RECORD-STAGE a-reading-with-no-record-stage-handed-in-is-Tier-H-PENDING-on-one-reason', + tier([SK, CS], unstaged()) === GOVERNED_TIER_H && stageOf(unstaged()) === LOW_RISK_RECORD_STAGE.pending && reasons([SK, CS], unstaged()) === LOW_RISK_RECORD_STAGE_PENDING_REASON && + LOW_RISK_RECORD_STAGE_PENDING_REASON.includes(`\`${LOW_RISK_RECORD_LINE}\``) && testVerdict([SK, CS], { repo: REPO, lowRisk: unstaged() }).tier === GOVERNED_TIER_H && + tier([SK, CS], { ...unstaged(), record: null, cardLabels: undefined }) === GOVERNED_TIER_H && stageOf({ ...unstaged(), record: null, cardLabels: undefined }) === LOW_RISK_RECORD_STAGE.pending, reasons([SK, CS], unstaged())); + assert('RECORD-STAGE a-pull-read-reason-leaves-the-stage-NOT-REACHED-with-no-pending-reason-and-an-unmeasured-reading-too', + stageOf(unstaged({ labels: ['security'] })) === LOW_RISK_RECORD_STAGE.notReached && !reasons([SK, CS], unstaged({ labels: ['security'] })).includes('contract-review record') && + stageOf(null) === LOW_RISK_RECORD_STAGE.notReached && stageOf({ measured: false, reason: 'x' }) === LOW_RISK_RECORD_STAGE.notReached && Object.isFrozen(LOW_RISK_RECORD_STAGE) && Object.values(LOW_RISK_RECORD_STAGE).join() === 'not-reached,pending,read'); + assert('⛔ RECORD-STAGE half-a-stage-is-a-stage-READ-and-the-half-not-handed-in-is-a-reason', + tier([SK, CS], { ...unstaged(), record: stageRecord() }) === GOVERNED_TIER_H && stageOf({ ...unstaged(), record: stageRecord() }) === LOW_RISK_RECORD_STAGE.read && /^the labels of its card were not read \(no reading\)/.test(reasons([SK, CS], { ...unstaged(), record: stageRecord() })) && + tier([SK, CS], { ...unstaged(), cardLabels: stageCard() }) === GOVERNED_TIER_H && stageOf({ ...unstaged(), cardLabels: stageCard() }) === LOW_RISK_RECORD_STAGE.read && /^its contract-review record was not read \(no reading\)/.test(reasons([SK, CS], { ...unstaged(), cardLabels: stageCard() }))); + assert('⛔ RECORD-STAGE a-stage-handed-in-is-judged-beside-the-pull-read-reasons-and-each-piece-prints-its-own', + (() => { const why = reasons([SK, CS], staged({ labels: ['security'], record: stageRecord({ securityTouching: { state: 'read', value: 'yes' } }), cardLabels: stageCard({ labels: ['security'], timeline: { measured: true, reason: null, events: [{ event: 'unlabeled', label: { name: 'security' } }] } }) })); + return /the PR carries the `security` label/.test(why) && /reads `Security-touching: yes`/.test(why) && /its card #1 carries the `security` label/.test(why) && /timeline of its card #1 shows the `security` label removed/.test(why) ? true : why; })() === true && + lowRiskRecordStageReasons(stageRecord(), stageCard()).length === 0 && lowRiskRecordStageReasons(null, null).length === 2); + // The line the arm prints is the record reader's own key and value — this file cannot import that one at + // module scope, so the two are held together here — and the reader's reading is the shape the arm reads. + { + const recognisers = await import('./record-recognisers.mjs'); + const line = (text) => recognisers.contractReviewRecordReading(`## Contract review\n\n${text}\n\n**VERDICT: PASS**\n`).securityTouching; + assert('the-line-the-arm-stands-on-is-the-record-readers-own-key-and-first-value-and-its-reading-is-the-shape-the-arm-reads', + LOW_RISK_RECORD_LINE === `${recognisers.CONTRACT_REVIEW_SECURITY_TOUCHING_KEY}: ${recognisers.CONTRACT_REVIEW_SECURITY_TOUCHING_VALUES[0]}` && + stageTier({ record: stageRecord({ securityTouching: line(LOW_RISK_RECORD_LINE) }) }) === GOVERNED_TIER_S && + stageTier({ record: stageRecord({ securityTouching: line('Security-touching: yes') }) }) === GOVERNED_TIER_H && + stageTier({ record: stageRecord({ securityTouching: line('Reviewed-by: `session_01SEAT`') }) }) === GOVERNED_TIER_H && + stageTier({ record: stageRecord({ securityTouching: line(`${LOW_RISK_RECORD_LINE}\n${LOW_RISK_RECORD_LINE}`) }) }) === GOVERNED_TIER_H && + stageTier({ record: stageRecord({ securityTouching: line(`> ${LOW_RISK_RECORD_LINE}`) }) }) === GOVERNED_TIER_H, JSON.stringify(line(LOW_RISK_RECORD_LINE))); + } + assert('the-Tier-S-words-name-the-record-line-and-the-card', (() => { const t = renderTestVerdict(testVerdict([SK, CS], { repo: REPO, lowRisk: read([SK, CS]) })); return t.includes(`a record on this head reading \`${LOW_RISK_RECORD_LINE}\``) && /no `security` label ever on the PR or its card/.test(t); })()); + // The H words name every reason; `--pr` reads the arm off the SAME pull object and file walk. assert('the-H-words-list-each-reason', (() => { const t = renderTestVerdict(testVerdict([SK, 'packages/core/src/x.ts'], { repo: REPO, lowRisk: read([SK, 'packages/core/src/x.ts'], { labels: ['security'] }) })); return /low-risk skills arm .*Tier H/.test(t) && /packages\/core/.test(t) && /`security` label/.test(t) && /landing tier: H/.test(t); })()); - const SAME = { head: { repo: { full_name: 'o/r' } }, base: { repo: { full_name: 'o/r' } } }; + const SAME = { head: { ref: 'claude/project-thread-x', repo: { full_name: 'o/r' } }, base: { repo: { full_name: 'o/r' } } }; const fromPull = pullLowRiskReading({ ...SAME, body: 'Clause-②: no', labels: [{ name: 'skip-changeset' }, { name: 'security' }] }, [SK]); assert('pullLowRiskReading-takes-body-label-names-the-whole-path-list-and-the-fork-predicate', fromPull.measured === true && fromPull.body === 'Clause-②: no' && fromPull.labels.join() === 'skip-changeset,security' && fromPull.paths.join() === SK && fromPull.fork.measured === true && fromPull.fork.isFork === false && pullLowRiskReading({}, [SK]).labels === null && pullLowRiskReading({ body: 7, labels: [] }, [SK]).body === '', JSON.stringify(fromPull)); assert('⛔ pullLowRiskReading-without-a-timeline-or-changesets-handed-in-reads-both-NOT-MEASURED-so-H', fromPull.timeline.measured === false && fromPull.changesets.measured === false && tier([SK, CS], pullLowRiskReading({ ...SAME, body: 'Clause-②: no\nMetadata-protocol: none', labels: [] }, [SK, CS])) === GOVERNED_TIER_H); @@ -7119,7 +7438,63 @@ async function selfTest() { }); const walked = await walk([SK, CS], []); const withCs = (r) => ({ ...r, changesets: { measured: true, reason: null, files: csFiles([SK, CS]) }, catalogFiles: { measured: true, reason: null, files: catFiles([SK]) } }); - assert('⭐ --pr-carries-the-arm-reading-off-the-same-GET-file-walk-and-timeline-and-with-its-changesets-read-it-answers-Tier-S', walked.ok === true && walked.lowRisk?.measured === true && walked.lowRisk.paths.join() === `${SK},${CS}` && walked.lowRisk.timeline.measured === true && urls.some((u) => /\/issues\/2\/timeline\?per_page=100$/.test(u)) && tier(walked.paths, withCs(walked.lowRisk)) === GOVERNED_TIER_S, JSON.stringify(walked.lowRisk ?? walked.reason)); + // The first read hands in no record stage, so with every pull-read condition holding `--pr` reads PENDING at + // Tier H; `pullRecordStage` then reads the stage through the queue guard's own reader (rows below). + assert('⭐ --pr-carries-the-arm-reading-off-the-same-GET-file-walk-and-timeline-and-with-its-changesets-read-its-record-stage-is-PENDING-at-Tier-H', walked.ok === true && walked.lowRisk?.measured === true && walked.lowRisk.paths.join() === `${SK},${CS}` && walked.lowRisk.timeline.measured === true && urls.some((u) => /\/issues\/2\/timeline\?per_page=100$/.test(u)) && + tier(walked.paths, withCs(walked.lowRisk)) === GOVERNED_TIER_H && stageOf(withCs(walked.lowRisk), walked.paths) === LOW_RISK_RECORD_STAGE.pending && + JSON.stringify(walked.pullHead) === JSON.stringify({ number: 2, body: 'Clause-②: no\nMetadata-protocol: none', head: { ref: 'claude/project-thread-x' } }), JSON.stringify(walked.lowRisk ?? walked.reason)); + { + const armReaders = await loadArmReaders(); + const PRHEAD = 'b'.repeat(40); + const RELAY_BOT = armReaders.recognisers?.trustedAuthors?.[0] ?? '(relay unread)'; + const { CONTRACT_REVIEW_TIER_NAME: AT_TIER } = await import('./record-recognisers.mjs'); + const review = (line = LOW_RISK_RECORD_LINE, over = {}) => ({ + id: 700, created_at: '2026-11-15T04:00:00Z', user: { login: RELAY_BOT }, + body: ['## Contract review', '', `Served-tier: \`${AT_TIER}\``, `Head-sha: \`${PRHEAD}\``, 'Reviewed-by: `session_01SEAT`', ...(line === null ? [] : [line]), '', '**VERDICT: PASS**'].join('\n'), ...over, + }); + const calls = []; + let loads = 0; + const stagePr = ({ rows = [review()], cardRows = [], labels = [], events = [], body = 'Fixes #69\n\nClause-②: no\nMetadata-protocol: none', rd = armReaders, reading = withCs(walked.lowRisk), throws = null, fetchers = undefined } = {}) => pullRecordStage({ + lowRisk: reading, paths: walked.paths, repo: REPO, pullHead: { number: 2, body, head: { ref: 'claude/project-thread-x' } }, derivation: { pull: 2, headSha: PRHEAD, baseSha: null }, + readers: () => { loads += 1; return rd; }, + fetchers: fetchers !== undefined ? fetchers : { + fetchComments: async (n) => { calls.push(`comments ${n}`); if (throws === 'comments') throw new Error('HTTP 502'); return n === 2 ? rows : n === 69 ? cardRows : []; }, + fetchLabels: async (n) => { calls.push(`labels ${n}`); if (throws === 'labels') throw new Error('HTTP 502'); return labels; }, + fetchTimeline: async (n) => { calls.push(`timeline ${n}`); if (throws === 'timeline') throw new Error('HTTP 502'); return events; }, + }, + }); + const prTier = async (over) => tier(walked.paths, await stagePr(over)); + const prH = async (over, re) => { const r = await stagePr(over); const why = reasons(walked.paths, r); return tier(walked.paths, r) === GOVERNED_TIER_H && re.test(why) ? true : why; }; + calls.length = 0; + const clean = await stagePr(); + assert('⭐ --pr-RECORD-STAGE a-record-on-the-head-reading-no-and-a-card-free-of-security-answers-Tier-S-off-both-threads-the-labels-and-the-card-timeline', + tier(walked.paths, clean) === GOVERNED_TIER_S && calls.join() === 'comments 2,comments 69,labels 69,timeline 69' && clean.record.located === 'found' && clean.record.where === 'PR' && clean.record.id === 700 && clean.cardLabels.card === 69 && + await prTier({ rows: [], cardRows: [review(LOW_RISK_RECORD_LINE, { id: 701 })] }) === GOVERNED_TIER_S, `${calls.join()} ${reasons(walked.paths, clean)}`); + assert('⛔ --pr-RECORD-LINE an-arm-PR-whose-record-LACKS-the-line-reads-Tier-H-and-so-does-yes-a-doubled-line-or-no-record', + await prH({ rows: [review(null)] }, /^its contract-review record \(PR comment 700\) carries no `Security-touching:` line$/) === true && + await prH({ rows: [review('Security-touching: yes')] }, /reads `Security-touching: yes`$/) === true && + await prH({ rows: [review(`${LOW_RISK_RECORD_LINE}\n${LOW_RISK_RECORD_LINE}`)] }, /is unreadable: it carries 2 `Security-touching:` lines/) === true && + await prH({ rows: [] }, /^no contract-review record names this head/) === true && + await prH({ rows: [review(LOW_RISK_RECORD_LINE, { user: { login: 'some-commenter' } })] }, /^no contract-review record names this head/) === true && + await prH({ rows: [review(), review(null, { id: 702, created_at: '2026-11-15T04:30:00Z' })] }, /\(PR comment 702\) carries no `Security-touching:` line/) === true); + assert('⛔ --pr-CARD-LABEL a-card-carrying-security-one-that-had-it-removed-or-a-PR-naming-no-card-reads-Tier-H', + await prH({ labels: ['docs', 'security'] }, /^its card #69 carries the `security` label$/) === true && + await prH({ events: [{ event: 'unlabeled', label: { name: 'security' } }] }, /^the timeline of its card #69 shows the `security` label removed$/) === true && + await prH({ body: 'Clause-②: no\nMetadata-protocol: none' }, /^the labels of its card were not read \(no card could be derived for it/) === true); + assert('⛔ --pr-RECORD-STAGE readers-that-did-not-load-or-any-read-that-threw-is-NOT-MEASURED-so-Tier-H', + await prH({ rd: { available: false, reason: 'no guard' } }, /its contract-review record was not read \(no guard\).*labels of its card were not read \(not read: no guard\)/) === true && + await prH({ rd: { ...armReaders, recognisers: { available: false, reason: 'recognisers did not load' } } }, /was not read \(recognisers did not load\)/) === true && + await prH({ throws: 'comments' }, /was not read \(PR #2's comment thread could not be read \(HTTP 502\)\)/) === true && + await prH({ throws: 'labels' }, /card #69's labels could not be read \(HTTP 502\)/) === true && + await prH({ throws: 'timeline' }, /the timeline of its card #69 was not read \(HTTP 502\)/) === true && + await prH({ fetchers: {} }, /no comment reader was supplied.*no label reader was supplied/) === true && await prH({ fetchers: null }, /no comment reader was supplied/) === true); + calls.length = 0; + loads = 0; + const labelled = withCs({ ...walked.lowRisk, labels: ['security'] }); + assert('--pr-reads-no-record-stage-and-loads-no-reader-unless-the-stage-is-pending', + (await stagePr({ reading: labelled })) === labelled && (await stagePr({ reading: null })) === null && (await stagePr({ reading: walked.lowRisk })) === walked.lowRisk && calls.length === 0 && loads === 0 && + (await stagePr()) !== withCs(walked.lowRisk) && loads === 1, `${calls.join()} loads=${loads}`); + } const removed = await walk([SK, CS], [{ event: 'labeled', label: { name: 'security' } }, { event: 'unlabeled', label: { name: 'security' } }]); assert('⛔ S1-a-security-label-REMOVED-in-the-timeline-the-pull-object-no-longer-shows-is-H', tier(removed.paths, withCs(removed.lowRisk)) === GOVERNED_TIER_H && /`security` label removed/.test(lowRiskArmVerdict(governedPathsIn(removed.paths, REPO), REPO, withCs(removed.lowRisk)).reasons.join())); const blind = await walk([SK, CS], 'fail'); @@ -9956,6 +10331,9 @@ async function selfTest() { fork: { measured: true, isFork: false, headRepo: 'o/r', baseRepo: 'o/r' }, changesets: { measured: true, reason: null, files: paths.filter((p) => LOW_RISK_CHANGESET_PATH.test(p)).map((path) => ({ path, text: CS_TEXT })) }, catalogFiles: { measured: true, reason: null, files: catalog }, + // The arm's record stage, read and favourable (the skills battery pins each piece of it). + record: { measured: true, reason: null, located: 'found', where: 'PR', id: 9001, carried: null, securityTouching: { state: 'read', value: 'no' } }, + cardLabels: { measured: true, reason: null, card: 1, labels: [], timeline: { measured: true, reason: null, events: [] } }, ...over, }); const tier = (paths, reading, repo = REPO) => governedTierFor(paths, repo, GOVERNED_SURFACES, null, reading); @@ -10156,19 +10534,23 @@ async function selfTest() { throw new Error(`fatal: unexpected git ${args.join(' ')}`); }; const RELAY = readers.recognisers?.trustedAuthors?.[0] ?? '(relay unread)'; - const record = ({ head = HEAD, tier = TIER_NAME, signed = true, verdict = '**VERDICT: PASS**', at = '2026-11-15T04:00:00Z', id = 900, by = RELAY } = {}) => ({ + // The record an arm landing stands on carries the arm's line (`line: null` leaves it out). + const record = ({ head = HEAD, tier = TIER_NAME, signed = true, verdict = '**VERDICT: PASS**', at = '2026-11-15T04:00:00Z', id = 900, by = RELAY, line = LOW_RISK_RECORD_LINE } = {}) => ({ id, created_at: at, user: { login: by }, - body: ['## Contract review', '', `Served-tier: \`${tier}\``, `Head-sha: \`${head}\``, ...(signed ? ['Reviewed-by: `session_01SEAT`'] : []), '', verdict].join('\n'), + body: ['## Contract review', '', `Served-tier: \`${tier}\``, `Head-sha: \`${head}\``, ...(signed ? ['Reviewed-by: `session_01SEAT`'] : []), ...(line === null ? [] : [line]), '', verdict].join('\n'), }); const entryOf = (paths = [SK, CS], size = null) => classifyCommit({ sha: LANDED, date: '2026-11-15T04:30:00Z', subject: 'docs(skills): wording (#70)' }, paths, OS, size); const LANDING = { mergedAt: MERGED_AT, mergeCommitSha: LANDED }; - const run = async ({ prRows = [record()], cardRows = [], pull = {}, throws = null, paths = [SK, CS], size = null, rd = readers, attribution = LANDING, reviews = [], events = [], git = runGit } = {}) => readArmLanding(entryOf(paths, size), { + // Card #69 as the label reader and the timeline reader answer it NOW: `cardLabels` its labels, `cardEvents` its + // timeline (`labelReader: false` hands the leg no label reader at all). + const run = async ({ prRows = [record()], cardRows = [], pull = {}, throws = null, paths = [SK, CS], size = null, rd = readers, attribution = LANDING, reviews = [], events = [], git = runGit, cardLabels = [], cardEvents = [], labelReader = true, seen = null } = {}) => readArmLanding(entryOf(paths, size), { paths, repo: 'objectstack', readers: rd, runGit: git, attribution, fetchers: { fetchPull: async () => { if (throws === 'pull') throw new Error('HTTP 502'); return { sha: HEAD, body: BODY, labels: [], fork: { measured: true, isFork: false, headRepo: 'o/r', baseRepo: 'o/r' }, headRef: 'claude/project-thread-x', ...pull }; }, fetchReviews: async () => { if (throws === 'reviews') throw new Error('HTTP 502'); return reviews; }, - fetchTimeline: async () => { if (throws === 'timeline') throw new Error('HTTP 502'); return events; }, + fetchTimeline: async (n) => { if (throws === 'timeline' || (throws === 'card-timeline' && n === 69)) throw new Error('HTTP 502'); return n === 69 ? cardEvents : events; }, fetchComments: async (n) => { if (throws === 'comments') throw new Error('HTTP 502'); return n === 70 ? prRows : n === 69 ? cardRows : []; }, + ...(labelReader ? { fetchLabels: async (n) => { seen?.push(n); if (throws === 'labels') throw new Error('HTTP 502'); return cardLabels; } } : {}), }, }); @@ -10228,6 +10610,72 @@ async function selfTest() { assert('no-catalog-row-or-no-PR-number-is-no-arm-reading', (await run({ paths: ['AGENTS.md'] })) === null && (await readArmLanding({ ...entryOf(), pr: null }, { paths: [SK], repo: 'objectstack', readers, fetchers: {}, runGit })) === null); + // The arm's RECORD STAGE, as the queue read it at the landing: a record that stands and reads PASS must also carry + // the arm's line, and the card must have been free of `security` THEN. A stage at Tier H is a BREACH flagged + // `stage` (the queue would have refused the landing); a piece that could not be read is NOT MEASURED. + const stageBreach = async (over, re) => { const v = await run(over); return v?.state === 'breach' && v.stage === true && re.test(v.reason) ? true : JSON.stringify(v); }; + const AT = (event, at, name = 'security') => ({ event, created_at: at, label: { name } }); + assert('⛔ RECORD-LINE an-arm-landing-on-a-PASS-record-with-NO-Security-touching-line-is-a-stage-BREACH-and-so-is-yes', + await stageBreach({ prRows: [record({ line: null })] }, /^its contract-review record \(PR comment 900\) carries no `Security-touching:` line$/) === true && + await stageBreach({ prRows: [record({ line: 'Security-touching: yes' })] }, /^its contract-review record \(PR comment 900\) reads `Security-touching: yes`$/) === true && + await stageBreach({ prRows: [record({ line: `- ${LOW_RISK_RECORD_LINE}\n- ${LOW_RISK_RECORD_LINE}` })] }, /is unreadable: it carries 2 `Security-touching:` lines/) === true && + await stageBreach({ prRows: [], cardRows: [record({ id: 901, line: null })] }, /^its contract-review record \(card comment 901\) carries no `Security-touching:` line$/) === true); + assert('⛔ CARD-LABEL a-card-carrying-security-AT-the-landing-is-a-stage-BREACH-whether-or-not-it-still-carries-it', + await stageBreach({ cardLabels: ['security'] }, /^its card #69 carries the `security` label$/) === true && + await stageBreach({ cardLabels: ['docs', 'Security'], cardEvents: [AT('labeled', '2026-11-15T03:00:00Z')] }, /^its card #69 carries the `security` label$/) === true && + await stageBreach({ cardLabels: [], cardEvents: [AT('labeled', '2026-11-15T03:00:00Z'), AT('unlabeled', '2026-11-15T06:00:00Z')] }, /^its card #69 carries the `security` label$/) === true); + assert('⛔ CARD-LABEL a-security-label-REMOVED-from-the-card-before-the-landing-is-a-stage-BREACH', + await stageBreach({ cardEvents: [AT('labeled', '2026-11-15T03:00:00Z'), AT('unlabeled', '2026-11-15T03:30:00Z')] }, /^the timeline of its card #69 shows the `security` label removed$/) === true && + await stageBreach({ cardEvents: [{ event: 'unlabeled', label: { name: 'security' } }] }, /shows the `security` label removed$/) === true); + assert('⭐ CARD-LABEL a-label-put-on-the-card-AFTER-the-landing-does-not-reach-back-the-queue-could-not-read-it', + (await run({ cardLabels: ['security'], cardEvents: [AT('labeled', '2026-11-15T06:00:00Z')] }))?.state === 'pass' && + (await run({ cardLabels: ['security'], cardEvents: [AT('labeled', MERGED_AT)] }))?.state === 'pass' && + (await run({ cardLabels: [], cardEvents: [AT('labeled', '2026-11-15T06:00:00Z'), AT('unlabeled', '2026-11-15T07:00:00Z')] }))?.state === 'pass' && + (await run({ cardLabels: ['docs'], cardEvents: [AT('labeled', '2026-11-15T03:00:00Z', 'docs'), AT('unlabeled', '2026-11-15T03:10:00Z', 'pm:queue')] }))?.state === 'pass'); + assert('⛔ CARD-LABEL a-landing-whose-PR-names-no-card-is-a-stage-BREACH-the-arm-reads-Tier-H-on-it', + await stageBreach({ pull: { body: 'Clause-②: no\nMetadata-protocol: none\n' } }, /^the labels of its card were not read \(no card could be derived for it/) === true); + assert('⛔ CARD-LABEL card-labels-or-a-card-timeline-that-could-not-be-read-are-NOT-MEASURED-never-PASS-and-never-a-BREACH', + await unmeasured({ throws: 'labels' }, /the labels of its card #69 could not be read as they stood at the landing \(card #69's labels could not be read \(HTTP 502\)\)/) === true && + await unmeasured({ throws: 'card-timeline' }, /the labels of its card #69 could not be read as they stood at the landing \(HTTP 502\)/) === true && + await unmeasured({ labelReader: false }, /no label reader was supplied to this leg/) === true); + assert('the-record-stage-is-read-only-on-a-record-that-stands-past-the-approval-and-enqueue-legs', await (async () => { + const seen = []; + await run({ seen, reviews: [APPROVED('os-zhuang')] }); + await run({ seen, events: QUEUED('os-zhuang') }); + await run({ seen, pull: { labels: ['security'] } }); + await run({ seen, prRows: [] }); + await run({ seen, prRows: [record({ verdict: '**VERDICT: FAIL**' })] }); + const before = seen.length; + await run({ seen }); + return before === 0 && seen.join() === '69' ? true : JSON.stringify(seen); + })() === true); + { + const landedAt = Date.parse(MERGED_AT); + const asLanded = (labels, events) => cardLabelsAsLanded({ measured: true, reason: null, card: 69, labels, timeline: { measured: true, reason: null, events } }, landedAt); + const onThenOffAfter = asLanded([], [AT('labeled', '2026-11-15T03:00:00Z'), AT('unlabeled', '2026-11-15T06:00:00Z')]); + const onThenOffBefore = asLanded([], [AT('labeled', '2026-11-15T03:00:00Z'), AT('unlabeled', '2026-11-15T03:30:00Z')]); + assert('cardLabelsAsLanded-rebuilds-the-security-label-from-the-card-timeline-and-reads-an-untimed-event-as-before-the-landing', + asLanded(['security'], []).labels.join() === 'security' && asLanded([], []).labels.length === 0 && asLanded(['docs', 'security'], []).labels.join() === 'security' && + asLanded(['security'], [AT('labeled', '2026-11-15T06:00:00Z')]).labels.length === 0 && asLanded(['security'], [AT('labeled', MERGED_AT)]).labels.length === 0 && + onThenOffAfter.labels.join() === 'security' && onThenOffAfter.timeline.events.length === 1 && onThenOffBefore.labels.length === 0 && onThenOffBefore.timeline.events.length === 2 && + asLanded([], [{ event: 'unlabeled', label: { name: 'security' } }]).timeline.events.length === 1 && asLanded([], [{ event: 'labeled', label: { name: 'Security' } }]).labels.join() === 'security' && + asLanded(['docs'], [AT('labeled', '2026-11-15T03:00:00Z', 'docs')]).timeline.events.length === 0 && onThenOffAfter.card === 69 && onThenOffAfter.measured === true && onThenOffAfter.timeline.measured === true, + JSON.stringify([onThenOffAfter, onThenOffBefore])); + } + assert('the-stage-BREACH-cell-names-the-record-stage-and-the-CLEARED-cell-claims-no-tier-the-record-stage-was-never-read', + armCell({ arm: { state: 'breach', stage: true, headSha: HEAD, reason: 'x' } }).endsWith('⛔ BREACH — low-risk arm landing on head bbbbbbbbbbbb on a record stage that reads Tier H: x') && + armCell({ arm: { state: 'breach', headSha: HEAD, reason: 'x' } }).endsWith('WITHOUT a same-head at-tier PASS record: x') && + (() => { const cell = armCell({ arm: { state: 'cleared', by: 'review', who: ['os-zhuang'], headSha: HEAD } }); return cell.includes('its pull-read conditions held on head bbbbbbbbbbbb, cleared by an authorized approval (os-zhuang) before the record was read') && !cell.includes('Tier S'); })()); + // ⛔ A favourable stand-in read never answers the record stage: an unread git input whose stand-in leaves every + // pull-read condition holding comes back PENDING, which settles nothing — NOT MEASURED, never `tier-h` on the + // pending reason and never a `Security-touching: no`. + assert('⛔ RECORD-STAGE a-favourable-stand-in-read-leaves-the-stage-PENDING-so-it-settles-nothing-and-never-reads-no', await (async () => { + const failing = (a) => { if (a[0] === 'diff-tree') throw new Error('fatal: bad object'); return runGit(a); }; + const withLine = await run({ git: failing }); + const without = await run({ git: failing, prRows: [record({ line: null })] }); + return withLine?.state === 'not-measured' && without?.state === 'not-measured' && !withLine.reason.includes('Security-touching') && /so its Tier H cannot say how the queue read it/.test(without.reason) ? true : JSON.stringify([withLine, without]); + })() === true); + // #33729 N5: a git read the arm needed that failed, or a fork predicate not measured, is NOT MEASURED, never Tier H. const gitWith = (over) => (args) => (over(args) ?? runGit(args)); assert('⛔ #33729-N5-an-unread-diff-tree-status-is-NOT-MEASURED-not-tier-h', await unmeasured({ git: gitWith((a) => { if (a[0] === 'diff-tree') throw new Error('fatal: bad object'); }) }, /could not read `git diff-tree.*bad object.*so its Tier H cannot say how the queue read it/) === true); diff --git a/scripts/pm/check-governed-queue-guard.mjs b/scripts/pm/check-governed-queue-guard.mjs index f177f1dfa42..736e5b3c388 100644 --- a/scripts/pm/check-governed-queue-guard.mjs +++ b/scripts/pm/check-governed-queue-guard.mjs @@ -355,10 +355,21 @@ * under the `adr` row that commit's full-context diff, which the register's * `addOnlyNoteReasons` reads add-only — the ADR leg, #33539) — through the * register's `governedTierFor`. An unread pull, - * timeline or changeset stays Tier H. An entry the arm puts at Tier S clears on + * timeline or changeset stays Tier H. That first read leaves the arm's RECORD + * STAGE pending (`lowRiskRecordStagePending`): an entry whose pull-read + * conditions all hold is still Tier H until the record leg below, on the + * threads it reads anyway, hands the arm the review's `Security-touching:` line + * (`lowRiskRecordStage`: the record on this head, read with the fleet's record + * reader) and the linked card's labels and timeline (`readCardLabels`), and + * `readLowRiskTier` reads the tier again. A record that is absent, unreadable or + * says anything but `Security-touching: no`, a `security` label on the card now + * or removed, or a card nobody could name, stays Tier H — and so does an entry + * an approval or an authorized enqueue already cleared, whose stage is never + * read. An entry the arm puts at Tier S clears on * a same-head record that READS PASS (`lowRiskRecordVerdict`), and a record * carried from an older head stands for it only when the hops moved no - * changeset and no catalog path. + * changeset and no catalog path (`lowRiskCarryRefusal`, one rule for the stage + * and the PASS). * * ⚖️ EVERY Tier S entry reads the record's VERDICT and its AUTHOR (card #33541; * AGENTS.md Prime Directive 14 lands Tier S on "a PASS verdict"): the record @@ -615,6 +626,7 @@ import { HUMAN_MERGE_LINE_THRESHOLD, LOW_RISK_ARM_RULING, LOW_RISK_CHANGESET_PATH, + LOW_RISK_RECORD_STAGE, SELF_REPO_ID, WORKFLOWS_PREFIX, addOnlyDiffArgv, @@ -691,8 +703,13 @@ const SELF_TEST_BATTERIES = Object.freeze({ '⭐ the 2026-10-26 ENQUEUE leg: an authorized enqueuer is the human review': 28, '⭐ the cheap early-warning leg: commits and trees, toolchain on demand': 20, '⭐ the workflows split at the queue (ruling record 6722205630)': 30, - '⚖️ the low-risk skills arm at the queue: body, labels and every path, read off the pull this leg holds (#33501)': 54, - '⚖️ the ADR leg at the queue: an add-only note clears on its PASS record, any other ADR change is H (#33539)': 12, + // Raised 54 → 72 with the arm's record stage: the record's `Security-touching:` line (control, absent line, `yes`, + // the unreadable shapes, newest-governs, the author binding, unsigned and unread, the card thread) and the linked + // card's `security` label (now, removed, unread, no card), the stage's cost, the unloaded recognisers, and the + // three builders — eighteen pins; 72 → 74 with the thread walk and the whole-stage reader `--pr` and the relay share. + '⚖️ the low-risk skills arm at the queue: body, labels and every path, read off the pull this leg holds (#33501)': 74, + // Raised 12 → 13 with the arm's record stage on the ADR leg: a record without the line, a `security`-labelled card. + '⚖️ the ADR leg at the queue: an add-only note clears on its PASS record, any other ADR change is H (#33539)': 13, }); // DELETING an entry silences that battery's floor exactly as effectively as @@ -2024,11 +2041,15 @@ export function renderGuardVerdict(verdict) { * untouched; `pull` null (its read failed) is an UNMEASURED reading, so the * entry stays Tier H with the reason printed, and so is a missing timeline, * fork reading, status reading or git reader. + * The arm's RECORD STAGE — `record` (`lowRiskRecordStage`) and `cardLabels` + * (`readCardLabels`) — is handed in on a SECOND call, by a caller that read it + * because the first call left the stage pending (`lowRiskRecordStagePending`): + * left out, an entry whose pull-read conditions all hold stays Tier H. * ⛔ The tier comes from the register's own `governedTierFor` and * `applyLowRiskArm` — no second predicate here. Mutates `entry` (its `surfaces` * and `tier`); returns it. */ -export function readLowRiskTier(entry, repo, pull, { timeline = null, runGit = null } = {}) { +export function readLowRiskTier(entry, repo, pull, { timeline = null, runGit = null, record = null, cardLabels = null } = {}) { if (!entry || !(entry.surfaces ?? []).some((s) => s?.lowRiskVerdict)) return entry; const refs = Array.isArray(entry.changesetRefs) ? entry.changesetRefs : []; const changesets = typeof runGit !== 'function' @@ -2056,6 +2077,8 @@ export function readLowRiskTier(entry, repo, pull, { timeline = null, runGit = n fork: pull.fork ?? null, timeline: timeline ?? { measured: false, reason: 'the timeline was not read', events: null }, changesets, + ...(record == null ? {} : { record }), + ...(cardLabels == null ? {} : { cardLabels }), } : { measured: false, reason: 'its pull request could not be read, so its body and labels are unknown' }; entry.surfaces = applyLowRiskArm(applyWorkflowSplit(governedPathsIn(entry.paths, repo), repo, entry.workflowDiff ?? null), repo, reading); @@ -2115,6 +2138,181 @@ export function landsOnLowRiskArm(entry) { return entry?.tier === TIER_S && (entry.surfaces ?? []).some((s) => s?.lowRiskVerdict?.tier === TIER_S); } +/** + * Do this entry's pull-read arm conditions all hold, with the arm's record stage still unread + * (`lowRiskArmVerdict`'s `recordStage: 'pending'`)? Such an entry is Tier H as it stands; the caller + * reads the record stage and calls `readLowRiskTier` again with it. + */ +export function lowRiskRecordStagePending(entry) { + return (entry?.surfaces ?? []).some((s) => s?.lowRiskVerdict?.recordStage === LOW_RISK_RECORD_STAGE.pending); +} + +/** + * Why a record CARRIED from an older head (the regeneration and prose-only hops) does not stand for + * the low-risk arm, as a predicate phrase (`was carried from …`), or null when it does. The hops + * (`git diff -z --name-only --no-renames ` through `pair.runGit`; a rename + * lists BOTH paths, so a skill moved out of the catalog counts) may touch no `.changeset/` path and no + * path under a low-risk row: a changeset, the body's partner, and catalog text such as a skill's + * `CHANGELOG.md` are prose faces the carry admits, yet they are exactly what the arm's tier — and the + * reviewer's `Security-touching:` statement — was read from. A diff that cannot be read refuses too. + * ONE rule for the record leg's PASS and the arm's record stage. Pure but for `runGit`. + */ +export function lowRiskCarryRefusal(carriedFrom, pair) { + const from = `\`${String(carriedFrom).slice(0, 12)}\``; + if (typeof pair?.runGit !== 'function' || !pair?.headSha) return `was carried from ${from} and this leg could not diff the hops`; + let moved; + try { + moved = String(pair.runGit(['diff', '-z', '--name-only', '--no-renames', carriedFrom, pair.headSha])).split('\0').filter(Boolean); + } catch (error) { + return `was carried from ${from} and the hops could not be diffed (${String(error?.message ?? error).split('\n')[0]})`; + } + const catalog = GOVERNED_SURFACES.filter((s) => s.lowRisk && s.prefix).map((s) => s.prefix); + const touched = moved.filter((p) => p.startsWith('.changeset/') || catalog.some((prefix) => p.startsWith(prefix))); + if (touched.length > 0) return `was carried from ${from} over hops that moved ${touched.slice(0, 3).join(', ')}${touched.length > 3 ? ` (+${touched.length - 3} more)` : ''}, which the arm reads, after the review`; + return null; +} + +/** + * The arm's reading of the review of record on this head — the `record` half of its record stage + * (`lowRiskRecordStageReasons`, the register). Built from the SAME threads and the SAME locator the + * record leg reads (`recognisers.locate`, rows already cut to trusted authors), and the line is read + * off the comment that locator chose with the fleet's one record reader (`recognisers.reading`, its + * `securityTouching`), ⛔ never a second parser: + * + * not measured the recognisers or the reader did not load, a thread or the head could not be + * read, or the chosen comment is not among the rows; + * absent no record names this head; + * found/unsigned the record, where it sits, its id, its line's reading, and — when it was carried + * from an older head — whether the carry stands for the arm (`lowRiskCarryRefusal`). + * + * ⛔ It decides nothing: the register's arm reads the object and gives the reasons. Pure but for + * `pair.runGit`. + */ +export function lowRiskRecordStage({ pair, recognisers }) { + const unmeasured = (reason) => ({ measured: false, reason }); + if (recognisers?.available !== true) return unmeasured(recognisers?.reason ?? 'the contract-review recognisers were not loaded'); + if (typeof recognisers.reading !== 'function') return unmeasured('the contract-review record reader was not loaded'); + const located = recognisers.locate(pair); + if (located.state === 'unreadable') return unmeasured(`${located.gaps.join(', ')} could not be read`); + if (located.state === 'absent') return { measured: true, reason: null, located: 'absent', where: null, id: null, carried: null, securityTouching: null }; + const rows = (recognisers.threads ?? []).flatMap((thread) => (Array.isArray(pair?.[thread.rows]) ? pair[thread.rows] : [])); + const comment = located.id === null || located.id === undefined ? null : rows.find((r) => r?.id === located.id) ?? null; + if (comment === null) return unmeasured('the record comment was not among the rows read, so its line is unknown'); + const why = located.carriedFrom ? lowRiskCarryRefusal(located.carriedFrom, pair) : null; + return { + measured: true, + reason: null, + located: located.state, + where: located.where ?? null, + id: located.id, + carried: located.carriedFrom ? { from: located.carriedFrom, ok: why === null, reason: why } : null, + securityTouching: recognisers.reading(comment.body)?.securityTouching ?? null, + }; +} + +/** + * The arm's reading of the CARD the pull request delivers — the `cardLabels` half of its record stage: + * the card's label names (`fetchLabels`) and its timeline (`fetchTimeline`, where a removed `security` + * label sits). `card` is `deliveredCardNumber`'s answer. No derivable card, no label reader or a label + * read that threw is NOT MEASURED; a timeline that could not be read is carried unmeasured inside a + * measured reading — each a reason in the arm, so Tier H. Returns `{ reading, apiCalls }`. Never throws. + */ +export async function readCardLabels({ card, fetchLabels = null, fetchTimeline = null }) { + const why = (error) => String(error?.message ?? error).split('\n')[0]; + if (!card || card.card === null || card.card === undefined) { + return { reading: { measured: false, reason: `no card could be derived for it — ${card?.reason ?? 'no card reading'}` }, apiCalls: 0 }; + } + if (typeof fetchLabels !== 'function') return { reading: { measured: false, reason: 'no label reader was supplied to this leg' }, apiCalls: 0 }; + let apiCalls = 1; + let labels; + try { + labels = await fetchLabels(card.card); + } catch (error) { + return { reading: { measured: false, reason: `card #${card.card}'s labels could not be read (${why(error)})` }, apiCalls }; + } + if (!Array.isArray(labels)) return { reading: { measured: false, reason: `card #${card.card}'s labels answered no list` }, apiCalls }; + let timeline = { measured: false, reason: 'no timeline reader was supplied to this leg', events: null }; + if (typeof fetchTimeline === 'function') { + apiCalls += 1; + try { + const events = await fetchTimeline(card.card); + timeline = Array.isArray(events) ? { measured: true, reason: null, events } : { measured: false, reason: 'the timeline answered no list', events: null }; + } catch (error) { + timeline = { measured: false, reason: why(error), events: null }; + } + } + return { reading: { measured: true, reason: null, card: card.card, labels: labels.map((l) => String(l ?? '')), timeline }, apiCalls }; +} + +/** + * The contract-review threads of one pair, read into it: one thread per entry of the shared set + * (`recognisers.threads` — the locations `--template` states), each cut to the authors this leg trusts + * (`recordAuthorTrusted`) BEFORE any reader sees it. A carrier the pair does not have (no card) holds + * no record: an empty list, never a gap. The first thread that cannot be read stops the walk and is + * named in `unreadable`. ONE walk for the queue's record leg, the arm's record stage, `--pr` and the + * relay. Mutates `pair`; returns `{ ignoredAuthors, unreadable, apiCalls }`. Never throws. + */ +export async function readRecordThreads({ pair, recognisers, fetchComments }) { + const ignoredAuthors = []; + let apiCalls = 0; + for (const thread of recognisers.threads) { + const number = pair[thread.number]; + if (number === null || number === undefined) { + // Not a gap: the pair has no such carrier at all, so that carrier + // holds no record. The caller's card note is what tells a reader which it was. + pair[thread.rows] = []; + continue; + } + try { + apiCalls += 1; + const read = await fetchComments(number); + // ⭐ The AUTHOR binding (#33541): a row its author does not earn is dropped HERE, before any + // reader sees the thread — ignored, never refused loudly; the count rides to the words. + if (Array.isArray(read)) { + const kept = read.filter((row) => recordAuthorTrusted(row, recognisers.trustedAuthors)); + for (const row of read) if (!kept.includes(row)) ignoredAuthors.push(String(row?.user?.login ?? '(unreadable author)')); + pair[thread.rows] = kept; + } else { + pair[thread.rows] = read; + } + } catch (error) { + return { ignoredAuthors, unreadable: `${thread.where} #${number}'s comment thread could not be read (${String(error?.message ?? error).split('\n')[0]})`, apiCalls }; + } + } + return { ignoredAuthors, unreadable: null, apiCalls }; +} + +/** + * The arm's whole RECORD STAGE for one pull request, for a caller that holds no thread yet (`--pr` + * and the relay; the queue leg reads the same pieces inline, beside its record leg): the card + * `recognisers.deliveredCard` derives from the pull object, the threads (`readRecordThreads`), then + * `lowRiskRecordStage` and `readCardLabels`. `pull` is the object `deliveredCard` reads (`number`, + * `body`, `head.ref`); `runGit` and `baseRef` are what a carried record is re-tested with, and one + * absent refuses the carry. ⛔ Anything that did not load or did not read is NOT MEASURED — recognisers + * that did not load, no comment reader, a thread that threw — which the arm reads as Tier H. + * Returns `{ record, cardLabels, card, apiCalls }`. Never throws. + */ +export async function readLowRiskRecordStage({ pr, pull, headSha, paths, repo, runGit = null, baseRef = null, recognisers, fetchComments = null, fetchLabels = null, fetchTimeline = null }) { + if (recognisers?.available !== true) { + return { + record: { measured: false, reason: recognisers?.reason ?? 'the contract-review recognisers were not loaded' }, + cardLabels: { measured: false, reason: 'not read: the contract-review recognisers, which name the card, did not load' }, + card: null, + apiCalls: 0, + }; + } + const card = pull + ? recognisers.deliveredCard(pull) + : { card: null, reason: 'its pull request row could not be read, so no card thread could be located for it' }; + const pair = { pr, card: card.card, headSha: headSha ?? null, runGit, baseRef, paths, repo }; + const threads = typeof fetchComments === 'function' + ? await readRecordThreads({ pair, recognisers, fetchComments }) + : { unreadable: 'no comment reader was supplied to this leg, so no thread was read', apiCalls: 0 }; + const record = threads.unreadable !== null ? { measured: false, reason: threads.unreadable } : lowRiskRecordStage({ pair, recognisers }); + const labelled = await readCardLabels({ card, fetchLabels, fetchTimeline }); + return { record, cardLabels: labelled.reading, card, apiCalls: threads.apiCalls + labelled.apiCalls }; +} + /** * The record leg's VERDICT, on every Tier S entry (card #33541; AGENTS.md * Prime Directive 14 lands Tier S on "a PASS verdict"): a record that STANDS @@ -2174,29 +2372,16 @@ export function recordPassVerdict(record, pair, recognisers) { * carry rule below, then `recordPassVerdict` like every other Tier S entry. * * ⛔ A record CARRIED from an older head (the regeneration and prose-only hops) - * stands for this arm only when nothing it reads moved after the PASS: the hops - * (`git diff -z --name-only --no-renames ` through - * `pair.runGit`; a rename lists BOTH paths, so a skill moved out of the catalog - * counts) - * may touch no `.changeset/` path and no path under a catalog row. A changeset, - * the body's partner, and catalog text such as a skill's `CHANGELOG.md` are - * prose faces the carry admits, yet they are exactly what the arm's tier was - * read from. A diff that cannot be read refuses too. Pure but for `runGit`. + * stands for this arm only when nothing it reads moved after the PASS + * (`lowRiskCarryRefusal`, the one carry rule this leg shares with the arm's + * record stage): the hops may touch no `.changeset/` path and no path under a + * catalog row, and a diff that cannot be read refuses too. Pure but for `runGit`. */ export function lowRiskRecordVerdict(record, pair, recognisers) { if (record?.state !== 'stands') return record; if (record.carriedFrom) { - const refuse = (why) => ({ ...record, state: 'not-pass', verdict: null, verdictReason: why }); - if (typeof pair?.runGit !== 'function' || !pair?.headSha) return refuse(`it was carried from \`${String(record.carriedFrom).slice(0, 12)}\` and this leg could not diff the hops`); - let moved; - try { - moved = String(pair.runGit(['diff', '-z', '--name-only', '--no-renames', record.carriedFrom, pair.headSha])).split('\0').filter(Boolean); - } catch (error) { - return refuse(`it was carried from \`${String(record.carriedFrom).slice(0, 12)}\` and the hops could not be diffed (${String(error?.message ?? error).split('\n')[0]})`); - } - const catalog = GOVERNED_SURFACES.filter((s) => s.lowRisk && s.prefix).map((s) => s.prefix); - const touched = moved.filter((p) => p.startsWith('.changeset/') || catalog.some((prefix) => p.startsWith(prefix))); - if (touched.length > 0) return refuse(`it was carried from \`${String(record.carriedFrom).slice(0, 12)}\` over hops that moved ${touched.slice(0, 3).join(', ')}${touched.length > 3 ? ` (+${touched.length - 3} more)` : ''}, which the arm reads, after the review`); + const why = lowRiskCarryRefusal(record.carriedFrom, pair); + if (why !== null) return { ...record, state: 'not-pass', verdict: null, verdictReason: `it ${why}` }; } return recordPassVerdict(record, pair, recognisers); } @@ -2215,7 +2400,7 @@ export function lowRiskRecordVerdict(record, pair, recognisers) { * still governs everything the verdict is derived FROM; it never governed * things the verdict merely mentions. */ -export async function runGuard({ event, repo, rows, fetchReviews, fetchPull, fetchComments, fetchTimeline = null, loadRecognisers = loadRecordRecognisers, lifted = [], runGit = null, baseRef = null }) { +export async function runGuard({ event, repo, rows, fetchReviews, fetchPull, fetchComments, fetchTimeline = null, fetchLabels = null, loadRecognisers = loadRecordRecognisers, lifted = [], runGit = null, baseRef = null }) { const { governed, unattributed } = decomposeGovernedWork(rows, assertGovernedRepo(repo, 'runGuard')); if (governed.length === 0 && unattributed.length === 0) { return guardVerdict({ event, repo, governed, unattributed, apiCalls: 0, lifted }); @@ -2307,7 +2492,12 @@ export async function runGuard({ event, repo, rows, fetchReviews, fetchPull, fet for (const entry of governed) readLowRiskTier(entry, repo, pulls.get(entry.pr) ?? null, { timeline: timelines.get(entry.pr) ?? null, runGit }); let recognisers = null; for (const entry of governed) { - if (entry.tier !== TIER_S) continue; + // ⭐ The arm's RECORD STAGE: an entry whose pull-read arm conditions all hold is Tier H until the + // review's `Security-touching:` line and the card's labels are read. They are read HERE, off the + // threads this leg reads anyway, and only for an entry nothing else cleared — so the stage is as + // MONOTONE and as FREE as the record leg it shares its threads with. + const pending = lowRiskRecordStagePending(entry); + if (entry.tier !== TIER_S && !pending) continue; if (approvals.get(entry.pr)?.state === 'approved') continue; if (enqueues.get(entry.pr)?.state === 'authorized') continue; if (recognisers === null) { @@ -2317,7 +2507,17 @@ export async function runGuard({ event, repo, rows, fetchReviews, fetchPull, fet recognisers = { available: false, reason: `the recogniser load threw: ${String(error?.message ?? error).split('\n')[0]}` }; } } + // The arm's second read of this entry's tier, with the record stage as far as it was read. + const readRecordStage = (record, cardLabels) => + readLowRiskTier(entry, repo, pulls.get(entry.pr) ?? null, { timeline: timelines.get(entry.pr) ?? null, runGit, record, cardLabels }); if (recognisers.available !== true) { + // ⛔ No recognisers, no record reading: the pending entry stays Tier H on that reason, and the + // record leg is never consulted for it. + if (pending) { + const unread = await readLowRiskRecordStage({ pr: entry.pr, pull: null, recognisers }); + readRecordStage(unread.record, unread.cardLabels); + continue; + } records.set(entry.pr, recordVerdict({ pair: null, recognisers })); continue; } @@ -2333,10 +2533,6 @@ export async function runGuard({ event, repo, rows, fetchReviews, fetchPull, fet card.card === null ? `⚠️ no card thread was searched — ${card.reason}` : `card #${card.card}, ${card.evidence}`; - // ⭐ ONE THREAD PER ENTRY IN THE SHARED SET, never a list spelled here: the - // locations this leg READS are the locations `--template` STATES, because - // both are this list. The cross-tool pin drives exactly this loop. - const numbers = { pr: entry.pr, card: card.card }; // ⭐ `runGit` and `baseRef` let the imported reader re-run the 纯重生成 // test on two COMMITTED trees when this head moved past its record — // the base being what separates the merge commit's carry-over from a hand @@ -2345,32 +2541,20 @@ export async function runGuard({ event, repo, rows, fetchReviews, fetchPull, fet // ⭐ `paths` and `repo` are what the record's tier is read from: the face the governed paths of // this entry put the review on (B′ with C) — the same committed-tree list this leg classified. const pair = { pr: entry.pr, card: card.card, headSha: heads.get(entry.pr) ?? null, runGit, baseRef, paths: entry.paths, repo }; - const ignoredAuthors = []; - let unreadable = null; - for (const thread of recognisers.threads) { - const number = numbers[thread.number]; - if (number === null || number === undefined) { - // Not a gap: the pair has no such carrier at all, so that carrier - // holds no record. `cardNote` is what tells a reader which it was. - pair[thread.rows] = []; - continue; - } - try { - apiCalls += 1; - const read = await fetchComments(number); - // ⭐ The AUTHOR binding (#33541): a row its author does not earn is dropped HERE, before any - // reader sees the thread — ignored, never refused loudly; the count rides to the words. - if (Array.isArray(read)) { - const kept = read.filter((row) => recordAuthorTrusted(row, recognisers.trustedAuthors)); - for (const row of read) if (!kept.includes(row)) ignoredAuthors.push(String(row?.user?.login ?? '(unreadable author)')); - pair[thread.rows] = kept; - } else { - pair[thread.rows] = read; - } - } catch (error) { - unreadable = `${thread.where} #${number}'s comment thread could not be read (${String(error?.message ?? error).split('\n')[0]})`; - break; - } + // ⭐ ONE THREAD PER ENTRY IN THE SHARED SET, never a list spelled here: the + // locations this leg READS are the locations `--template` STATES, because + // both are this list (`readRecordThreads`). The cross-tool pin drives exactly this walk. + const threads = await readRecordThreads({ pair, recognisers, fetchComments }); + apiCalls += threads.apiCalls; + const { ignoredAuthors, unreadable } = threads; + if (pending) { + // ⛔ A thread that could not be read is a record that was not read: NOT MEASURED, so Tier H. + const stage = unreadable !== null ? { measured: false, reason: unreadable } : lowRiskRecordStage({ pair, recognisers }); + const labelled = await readCardLabels({ card, fetchLabels, fetchTimeline }); + apiCalls += labelled.apiCalls; + readRecordStage(stage, labelled.reading); + // Tier H on the record stage: the entry needs the maintainer, and the record leg is never consulted. + if (entry.tier !== TIER_S) continue; } if (unreadable !== null) { records.set(entry.pr, { state: 'unreadable', reason: unreadable, cardNote }); @@ -3178,6 +3362,35 @@ export function makeTimelineReader({ apiUrl, slug, token, fetchImpl = fetch, per }; } +/** + * The label NAMES on an issue — the CARD a low-risk arm pull request delivers, whose `security` label + * keeps that pull request at Tier H (`readCardLabels`). + * + * Scope, measured the way the two readers above were: `GET /repos/{o}/{r}/issues/{n}/labels` answers + * `X-Accepted-GitHub-Permissions: issues=read; pull_requests=read` — alternative sets — so the workflow's + * existing `pull-requests: read` covers it and this leg widens NO scope. ⛔ Not `GET /issues/{n}`, whose + * labels field is the same list: that route answers `issues=read` ALONE, which the workflow does not hold. + * Measured 2026-11-15 against the live API on this repository, on an issue and on a pull request number. + * + * Throws on any non-2xx, a non-array body and a truncated list; the caller turns a throw into NOT MEASURED, + * which the arm reads as Tier H — never into an empty list, which would read as a card with no label. + */ +export function makeLabelReader({ apiUrl, slug, token, fetchImpl = fetch, perPage = 100, maxPages = 10 }) { + return async function fetchLabels(issue) { + const all = []; + for (let page = 1; page <= maxPages; page += 1) { + const url = `${apiUrl}/repos/${slug}/issues/${issue}/labels?per_page=${perPage}&page=${page}`; + const res = await fetchImpl(url, { headers: apiHeaders(token) }); + if (!res.ok) throw new Error(`GET /repos/${slug}/issues/${issue}/labels answered HTTP ${res.status}`); + const batch = await res.json(); + if (!Array.isArray(batch)) throw new Error(`the labels endpoint answered a non-array body for #${issue}`); + all.push(...batch.map((l) => String(l?.name ?? ''))); + if (batch.length < perPage) return all; + } + throw new Error(`#${issue} has more than ${perPage * maxPages} labels — refusing to judge a truncated list`); + }; +} + // ── CLI ───────────────────────────────────────────────────────────────────── /** @@ -3302,9 +3515,10 @@ async function main() { const fetchPull = makePullReader(reader); const fetchComments = makeCommentReader(reader); const fetchTimeline = makeTimelineReader(reader); + const fetchLabels = makeLabelReader(reader); const runGit = (args, input) => git(repoRoot, args, input); - const verdict = await runGuard({ event: context.event, repo, rows, fetchReviews, fetchPull, fetchComments, fetchTimeline, lifted, runGit, baseRef: context.baseSha ?? null }); + const verdict = await runGuard({ event: context.event, repo, rows, fetchReviews, fetchPull, fetchComments, fetchTimeline, fetchLabels, lifted, runGit, baseRef: context.baseSha ?? null }); // The SIZE leg (#19036): every queued pull request, through the same pull // reader the governed leg reads heads with. `merge_group` only, '' on the // other leg, so the `pull_request` output is byte-identical to what it was. @@ -5185,6 +5399,7 @@ export async function selfTest() { const REF_CARD = 69; let tierApiCalls = 0; let tierThreadsRead = []; + let tierLabelsRead = []; const tierRun = async ({ files = [REF_A], reviews = [], @@ -5206,16 +5421,22 @@ export async function selfTest() { extraRows = [], timeline = null, fork = SAME_REPO, + // The CARD's label names and timeline, read by the low-risk arm's record stage alone (`readCardLabels`): + // a list, `'throw'`, or `null` for no reader at all. + cardLabels = [], + cardTimeline = [], } = {}) => { tierApiCalls = 0; tierThreadsRead = []; + tierLabelsRead = []; return runGuard({ repo: REPO, event, rows: [{ ...row(pr, files, 'c'.repeat(40), `x (#${pr})`), ...(workflowDiff ? { workflowDiff } : {}) }, ...extraRows], fetchReviews: async () => { tierApiCalls += 1; return reviews; }, fetchPull: async () => { tierApiCalls += 1; if (headThrows) throw new Error('head unreadable'); return pull(head, { body: prBody, headRef: branch, labels, fork }); }, - ...(timeline === null ? {} : { fetchTimeline: async () => { if (timeline === 'throw') throw new Error('HTTP 403'); return timeline; } }), + ...(timeline === null ? {} : { fetchTimeline: async (n) => { if (n !== pr) tierApiCalls += 1; const read = n === pr ? timeline : cardTimeline; if (read === 'throw') throw new Error('HTTP 403'); return read; } }), + ...(cardLabels === null ? {} : { fetchLabels: async (n) => { tierApiCalls += 1; tierLabelsRead.push(n); if (cardLabels === 'throw') throw new Error('HTTP 403'); return cardLabels; } }), fetchComments: async (n) => { tierApiCalls += 1; tierThreadsRead.push(n); @@ -6098,7 +6319,11 @@ export async function selfTest() { } throw new Error(`fatal: path not in tree (${args.join(' ')})`); }; - const arm = { files: [SK, CS], prBody: LOW, comments: [recordComment()], timeline: [], runGit: csGit() }; + // ⭐ The arm's record carries the machine line the arm stands on: `Security-touching: no`. + const ST_NO = 'Security-touching: no'; + const armRecord = (over = {}) => recordComment({ ...over, prose: [ST_NO, ...(over.prose ?? [])] }); + const armOnOldHead = [armRecord({ sha: REF_OLD.slice(0, 12) }), REGEN_PROV]; + const arm = { files: [SK, CS], prBody: LOW, comments: [armRecord()], timeline: [], runGit: csGit() }; // The decomposition: a catalog entry is NOT MEASURED there (no row carries a body), and it keeps EVERY path of the PR. const split = decomposeGovernedWork([row(33501, [SK, CS, 'packages/spec/src/a.zod.ts'])], REPO).governed[0]; assert('the-decomposition-reads-a-catalog-entry-Tier-H-NOT-MEASURED-and-keeps-every-path', split.tier === TIER_H && split.surfaces[0].lowRiskVerdict?.measured === false && split.allPaths.join() === `${SK},${CS},packages/spec/src/a.zod.ts` && split.paths.join() === SK, JSON.stringify(split)); @@ -6112,22 +6337,134 @@ export async function selfTest() { const pass = await tierRun(arm); assert('⭐ a-pure-skills-PR-on-Clause-2-no-with-a-same-head-PASS-record-CLEARS-with-zero-approvals', pass.exitCode === EXIT_CLEAR && pass.conclusion === 'cleared' && pass.entries[0].tier === TIER_S && pass.entries[0].record.state === 'stands' && pass.entries[0].record.verdict === 'PASS', JSON.stringify(pass.entries[0])); assert('and-the-words-name-the-arm-its-ruling-and-the-PASS-it-read', /low-risk skills arm .*Tier S/.test(renderGuardVerdict(pass)) && renderGuardVerdict(pass).includes(LOW_RISK_ARM_RULING) && /READS PASS, and this one does/.test(renderGuardVerdict(pass)), renderGuardVerdict(pass)); + // ⛔ No record on this head is no `Security-touching: no` line: the arm's record stage reads Tier H, so the entry + // needs the maintainer and the record leg is never consulted (until this stage, such a PR read Tier S, refused + // on its absent record). const noRecord = await tierRun({ ...arm, comments: [] }); - assert('⛔ CONTROL: the-same-skills-PR-with-NO-record-is-REFUSED-Tier-S-without-its-record', noRecord.exitCode === EXIT_REFUSED_UNAPPROVED && noRecord.entries[0].tier === TIER_S && noRecord.entries[0].record.state === 'absent'); - const old = await tierRun({ ...arm, comments: [recordComment({ sha: REF_OLD.slice(0, 12) })] }); - assert('⛔ a-record-on-an-OLDER-head-is-REFUSED', old.exitCode === EXIT_REFUSED_UNAPPROVED && old.entries[0].record.state === 'absent'); + assert('⛔ CONTROL: the-same-skills-PR-with-NO-record-is-REFUSED-Tier-H-on-the-record-stage', noRecord.exitCode === EXIT_REFUSED_UNAPPROVED && noRecord.entries[0].tier === TIER_H && noRecord.entries[0].record === undefined && /no contract-review record names this head, so no `Security-touching: no` line is established/.test(renderGuardVerdict(noRecord)), renderGuardVerdict(noRecord)); + const old = await tierRun({ ...arm, comments: [armRecord({ sha: REF_OLD.slice(0, 12) })] }); + assert('⛔ a-record-on-an-OLDER-head-is-REFUSED-Tier-H-its-line-does-not-carry-forward', old.exitCode === EXIT_REFUSED_UNAPPROVED && old.entries[0].tier === TIER_H && old.entries[0].record === undefined && /no contract-review record names this head/.test(renderGuardVerdict(old))); + + // ── the arm's RECORD STAGE: the record's `Security-touching:` line, and the `security` label on the linked card ── + const stage = (v) => v.entries[0].surfaces.find((x) => x.lowRiskVerdict)?.lowRiskVerdict; + const stageH = (v, why) => v.exitCode === EXIT_REFUSED_UNAPPROVED && v.entries[0].tier === TIER_H && v.entries[0].record === undefined && stage(v).recordStage === 'read' && stage(v).reasons.length === 1 && why.test(stage(v).reasons[0]); + assert('⭐ RECORD-LINE-CONTROL: the-passing-arm-PR-was-read-through-the-record-stage-its-record-says-Security-touching-no', stage(pass).recordStage === 'read' && stage(pass).tier === TIER_S && stage(pass).reasons.length === 0 && pass.entries[0].record.id === 900); + const noLine = await tierRun({ ...arm, comments: [recordComment()] }); + assert('⛔ RECORD-LINE: an-arm-PR-whose-PASS-record-LACKS-the-line-reads-Tier-H-at-the-queue-refused-and-the-record-leg-is-never-consulted', stageH(noLine, /^its contract-review record \(PR comment 900\) carries no `Security-touching:` line$/) && /low-risk skills arm .*Tier H/.test(renderGuardVerdict(noLine)) && renderGuardVerdict(noLine).includes('carries no `Security-touching:` line'), renderGuardVerdict(noLine)); + const lineCase = async (prose, why) => stageH(await tierRun({ ...arm, comments: [recordComment({ prose })] }), why); + assert('⛔ RECORD-LINE: a-record-that-says-yes-reads-Tier-H', await lineCase(['Security-touching: yes'], /reads `Security-touching: yes`$/)); + assert('⛔ RECORD-LINE: a-quoted-no-two-lines-a-fenced-line-trailing-words-or-another-value-are-UNREADABLE-so-Tier-H', await lineCase(['> Security-touching: no'], /is unreadable: its one `Security-touching:` line is a quote/) && await lineCase(['Security-touching: no', '> Security-touching: yes'], /is unreadable: it carries 2 `Security-touching:` lines/) && await lineCase(['```', 'Security-touching: no', '```'], /is unreadable: its one `Security-touching:` line sits inside a code fence/) && await lineCase(['Security-touching: no — wording only'], /is unreadable: its `Security-touching:` line reads/) && await lineCase(['Security-touching: none'], /not exactly `Security-touching: no` or `Security-touching: yes`/)); + assert('⛔ RECORD-LINE: the-line-is-read-off-the-NEWEST-same-head-record-an-older-no-does-not-cover-a-newer-record-without-it', stageH(await tierRun({ ...arm, comments: [armRecord({ id: 901, at: '2026-09-13T12:00:00Z' }), recordComment({ id: 902, at: '2026-09-13T14:00:00Z' })] }), /\(PR comment 902\) carries no `Security-touching:` line/) && (await tierRun({ ...arm, comments: [recordComment({ id: 901, at: '2026-09-13T12:00:00Z' }), armRecord({ id: 902, at: '2026-09-13T14:00:00Z' })] })).exitCode === EXIT_CLEAR); + assert('⛔ RECORD-LINE: a-record-by-an-author-outside-the-relay-and-GOVERNED_APPROVERS-is-not-read-so-its-no-establishes-nothing', stageH(await tierRun({ ...arm, comments: [armRecord({ by: 'drive-by' })] }), /^no contract-review record names this head/)); + assert('⛔ RECORD-LINE: an-unsigned-record-and-an-unreadable-thread-are-Tier-H-too', stageH(await tierRun({ ...arm, comments: [armRecord({ signed: false })] }), /names no reviewer, so its `Security-touching:` line does not count/) && stageH(await tierRun({ ...arm, commentsThrow: true }), /^its contract-review record was not read \(PR #70's comment thread could not be read \(thread unreadable\)\)/)); + assert('RECORD-LINE: the-line-on-the-CARD-thread-record-counts-like-the-one-on-the-PR', (await tierRun({ ...arm, comments: [], cardComments: [armRecord()] })).exitCode === EXIT_CLEAR && stageH(await tierRun({ ...arm, comments: [], cardComments: [recordComment()] }), /\(card comment 900\) carries no `Security-touching:` line/)); + const cardLabelled = await tierRun({ ...arm, cardLabels: ['tooling', 'Security'] }); + assert('⛔ CARD-LABEL: the-security-label-on-the-LINKED-CARD-keeps-the-PR-Tier-H-though-the-PR-carries-none', stageH(cardLabelled, new RegExp(`^its card #${REF_CARD} carries the \`security\` label$`)) && tierLabelsRead.join() === String(REF_CARD), renderGuardVerdict(cardLabelled)); + assert('⭐ CARD-LABEL-CONTROL: other-labels-on-the-card-do-not', (await tierRun({ ...arm, cardLabels: ['tooling', 'priority:p2'] })).exitCode === EXIT_CLEAR); + assert('⛔ CARD-LABEL: a-security-label-REMOVED-on-the-card-timeline-keeps-it-Tier-H', stageH(await tierRun({ ...arm, cardTimeline: [{ event: 'labeled', label: { name: 'security' } }, { event: 'unlabeled', label: { name: 'security' } }] }), new RegExp(`^the timeline of its card #${REF_CARD} shows the \`security\` label removed$`))); + assert('⛔ CARD-LABEL: labels-that-threw-no-label-reader-or-a-card-timeline-that-threw-are-NOT-MEASURED-so-Tier-H', stageH(await tierRun({ ...arm, cardLabels: 'throw' }), /^the labels of its card were not read \(card #69's labels could not be read \(HTTP 403\)\)/) && stageH(await tierRun({ ...arm, cardLabels: null }), /^the labels of its card were not read \(no label reader was supplied to this leg\)/) && stageH(await tierRun({ ...arm, cardTimeline: 'throw' }), /^the timeline of its card #69 was not read \(HTTP 403\), so a removed `security` label cannot be ruled out$/)); + assert('⛔ CARD-LABEL: a-PR-that-names-NO-card-cannot-rule-the-label-out-Tier-H-with-no-label-read', stageH(await tierRun({ ...arm, prBody: 'Clause-②: no\nMetadata-protocol: none\n', branch: 'wording' }), /^the labels of its card were not read \(no card could be derived for it — /) && tierLabelsRead.length === 0); + assert('the-record-stage-costs-one-label-read-and-one-card-timeline-read-and-only-where-the-pull-read-conditions-all-hold', await (async () => { + await tierRun(arm); + const clean = [tierApiCalls, tierLabelsRead.join(), tierThreadsRead.join()]; + await tierRun({ ...arm, labels: ['security'] }); + const pullH = [tierLabelsRead.length, tierThreadsRead.length]; + await tierRun({ ...arm, reviews: [approvedAt(GOVERNED_APPROVERS[0], REF_HEAD)] }); + const approved = [tierLabelsRead.length, tierThreadsRead.length]; + // pull + reviews + PR thread + card thread + card labels + card timeline (the PR's own timeline is the enqueue leg's read). + return JSON.stringify(clean) === JSON.stringify([6, String(REF_CARD), `70,${REF_CARD}`]) && pullH.join() === '0,0' && approved.join() === '0,0'; + })()); + assert('⛔ a-recogniser-set-that-did-not-load-leaves-the-arm-entry-Tier-H-on-that-reason-with-no-thread-and-no-label-read', await (async () => { const v = await tierRun({ ...arm, recognisers: { available: false, reason: 'the recognisers would not load: boom' } }); return v.exitCode === EXIT_REFUSED_UNAPPROVED && v.entries[0].tier === TIER_H && v.entries[0].record === undefined && stage(v).recordStage === 'read' && /was not read \(the recognisers would not load: boom\)/.test(stage(v).reasons[0]) && tierThreadsRead.length === 0 && tierLabelsRead.length === 0; })()); + assert('lowRiskRecordStage-builds-the-reading-and-decides-nothing-absent-found-with-its-line-and-not-measured', (() => { + const pairOf = (rows) => ({ pr: 70, card: REF_CARD, headSha: REF_HEAD, paths: [SK], repo: REPO, prComments: rows, cardComments: [] }); + const found = lowRiskRecordStage({ pair: pairOf([armRecord()]), recognisers: live }); + const absent = lowRiskRecordStage({ pair: pairOf([]), recognisers: live }); + return JSON.stringify(found) === JSON.stringify({ measured: true, reason: null, located: 'found', where: 'PR', id: 900, carried: null, securityTouching: { state: 'read', value: 'no' } }) && + absent.measured === true && absent.located === 'absent' && absent.securityTouching === null && + lowRiskRecordStage({ pair: pairOf([armRecord()]), recognisers: { available: false, reason: 'x' } }).measured === false && + lowRiskRecordStage({ pair: pairOf([armRecord()]), recognisers: { ...live, reading: undefined } }).measured === false && + lowRiskRecordStage({ pair: { ...pairOf([armRecord()]), prComments: undefined }, recognisers: live }).measured === false && + lowRiskRecordStage({ pair: pairOf([recordComment()]), recognisers: live }).securityTouching.state === 'missing'; + })()); + assert('readCardLabels-never-throws-and-counts-its-reads-a-card-nobody-could-name-reads-nothing', await (async () => { + const none = await readCardLabels({ card: { card: null, reason: 'its body names no card' }, fetchLabels: async () => { throw new Error('must not be read'); } }); + const both = await readCardLabels({ card: { card: 69 }, fetchLabels: async () => ['a'], fetchTimeline: async () => [] }); + const noTimeline = await readCardLabels({ card: { card: 69 }, fetchLabels: async () => ['a'] }); + const notList = await readCardLabels({ card: { card: 69 }, fetchLabels: async () => ({}) }); + return none.apiCalls === 0 && none.reading.measured === false && /its body names no card/.test(none.reading.reason) && + both.apiCalls === 2 && JSON.stringify(both.reading) === JSON.stringify({ measured: true, reason: null, card: 69, labels: ['a'], timeline: { measured: true, reason: null, events: [] } }) && + noTimeline.apiCalls === 1 && noTimeline.reading.measured === true && noTimeline.reading.timeline.measured === false && + notList.reading.measured === false; + })()); + assert('makeLabelReader-reads-the-label-NAMES-off-the-issue-labels-route-and-throws-on-a-refusal', await (async () => { + const urls = []; + const respond = (b, ok = true, status = 200) => async (url) => { urls.push(url); return { ok, status, json: async () => b }; }; + const args = { apiUrl: 'https://api', slug: 'o/r', token: 't' }; + const names = await makeLabelReader({ ...args, fetchImpl: respond([{ name: 'security' }, { name: 'tooling' }]) })(69); + let refused = null; + try { await makeLabelReader({ ...args, fetchImpl: respond({ message: 'no' }, false, 403) })(69); } catch (error) { refused = String(error.message); } + let notList = null; + try { await makeLabelReader({ ...args, fetchImpl: respond({ labels: [] }) })(69); } catch (error) { notList = String(error.message); } + return names.join() === 'security,tooling' && urls[0] === 'https://api/repos/o/r/issues/69/labels?per_page=100&page=1' && /HTTP 403/.test(refused) && /non-array body/.test(notList); + })()); + assert('readRecordThreads-walks-the-shared-thread-set-once-cuts-each-thread-to-trusted-authors-and-names-the-first-that-threw', await (async () => { + const read = []; + const rows = { 70: [armRecord(), armRecord({ id: 901, by: 'some-commenter' })], [REF_CARD]: [armRecord({ id: 902 })] }; + const fetchComments = async (n) => { read.push(n); return rows[n] ?? []; }; + const both = { pr: 70, card: REF_CARD }; + const walked = await readRecordThreads({ pair: both, recognisers: live, fetchComments }); + const cardless = { pr: 70, card: null }; + const one = await readRecordThreads({ pair: cardless, recognisers: live, fetchComments }); + const thrown = await readRecordThreads({ pair: { pr: 70, card: REF_CARD }, recognisers: live, fetchComments: async (n) => { if (n === REF_CARD) throw new Error('HTTP 502'); return []; } }); + return walked.apiCalls === 2 && walked.unreadable === null && walked.ignoredAuthors.join() === 'some-commenter' && both.prComments.map((r) => r.id).join() === '900' && both.cardComments.map((r) => r.id).join() === '902' && read.slice(0, 2).join() === `70,${REF_CARD}` && + one.apiCalls === 1 && one.unreadable === null && Array.isArray(cardless.cardComments) && cardless.cardComments.length === 0 && + thrown.apiCalls === 2 && thrown.unreadable === `card #${REF_CARD}'s comment thread could not be read (HTTP 502)`; + })()); + // The whole stage for a caller that holds no thread yet — `--pr` and the relay read the arm through this. + assert('readLowRiskRecordStage-derives-the-card-reads-both-threads-the-labels-and-the-card-timeline-and-anything-unread-is-NOT-MEASURED', await (async () => { + const seen = []; + const pull = { number: 70, body: `Fixes #${REF_CARD}\n\nClause-②: no\nMetadata-protocol: none\n`, head: { ref: 'claude/project-thread-x' } }; + const stageOf = (over = {}) => readLowRiskRecordStage({ + pr: 70, pull, headSha: REF_HEAD, paths: [SK], repo: REPO, recognisers: live, + fetchComments: async (n) => { seen.push(`comments ${n}`); return n === 70 ? [armRecord()] : []; }, + fetchLabels: async (n) => { seen.push(`labels ${n}`); return ['tooling']; }, + fetchTimeline: async (n) => { seen.push(`timeline ${n}`); return []; }, + ...over, + }); + const clean = await stageOf(); + const order = seen.join(); + const noLine = await stageOf({ fetchComments: async (n) => (n === 70 ? [recordComment()] : []) }); + const untrusted = await stageOf({ fetchComments: async (n) => (n === 70 ? [armRecord({ by: 'some-commenter' })] : []) }); + const unloaded = await stageOf({ recognisers: { available: false, reason: 'the recognisers would not load: boom' } }); + const noReader = await stageOf({ fetchComments: null, fetchLabels: null }); + const thrown = await stageOf({ fetchComments: async () => { throw new Error('HTTP 502'); } }); + const cardless = await stageOf({ pull: { ...pull, body: 'Clause-②: no\nMetadata-protocol: none\n' } }); + const unreadPull = await stageOf({ pull: null }); + return order === `comments 70,comments ${REF_CARD},labels ${REF_CARD},timeline ${REF_CARD}` && clean.apiCalls === 4 && clean.card.card === REF_CARD && + JSON.stringify(clean.record) === JSON.stringify({ measured: true, reason: null, located: 'found', where: 'PR', id: 900, carried: null, securityTouching: { state: 'read', value: 'no' } }) && + JSON.stringify(clean.cardLabels) === JSON.stringify({ measured: true, reason: null, card: REF_CARD, labels: ['tooling'], timeline: { measured: true, reason: null, events: [] } }) && + noLine.record.securityTouching.state === 'missing' && untrusted.record.located === 'absent' && + unloaded.apiCalls === 0 && unloaded.record.measured === false && /would not load: boom/.test(unloaded.record.reason) && unloaded.cardLabels.measured === false && + noReader.record.measured === false && /no comment reader was supplied/.test(noReader.record.reason) && noReader.cardLabels.measured === false && /no label reader was supplied/.test(noReader.cardLabels.reason) && + thrown.record.measured === false && /PR #70's comment thread could not be read \(HTTP 502\)/.test(thrown.record.reason) && thrown.cardLabels.measured === true && + cardless.cardLabels.measured === false && /no card could be derived for it/.test(cardless.cardLabels.reason) && cardless.record.located === 'found' && cardless.apiCalls === 1 && + unreadPull.cardLabels.measured === false && /its pull request row could not be read/.test(unreadPull.cardLabels.reason); + })()); // ⛔ The verdict: the arm lands on a record that READS PASS, never on one that merely exists. - const failRecord = await tierRun({ ...arm, comments: [recordComment({ verdictWord: '**VERDICT: FAIL**' })] }); + const failRecord = await tierRun({ ...arm, comments: [armRecord({ verdictWord: '**VERDICT: FAIL**' })] }); assert('⛔ a-same-head-FAIL-record-is-REFUSED-on-the-arm', failRecord.exitCode === EXIT_REFUSED_UNAPPROVED && failRecord.entries[0].tier === TIER_S && failRecord.entries[0].record.state === 'not-pass' && failRecord.entries[0].record.verdict === 'FAIL' && /does not read PASS: it reads FAIL/.test(renderGuardVerdict(failRecord)), renderGuardVerdict(failRecord)); - const wordless = await tierRun({ ...arm, comments: [recordComment({ verdictWord: 'pending' })] }); + const wordless = await tierRun({ ...arm, comments: [armRecord({ verdictWord: 'pending' })] }); assert('⛔ a-same-head-record-with-NO-verdict-word-is-REFUSED-on-the-arm', wordless.exitCode === EXIT_REFUSED_UNAPPROVED && wordless.entries[0].record.state === 'not-pass' && /states no verdict/.test(renderGuardVerdict(wordless))); - const explicitPass = await tierRun({ ...arm, comments: [recordComment({ verdictWord: '**VERDICT: PASS**' })] }); + const explicitPass = await tierRun({ ...arm, comments: [armRecord({ verdictWord: '**VERDICT: PASS**' })] }); assert('the-template-VERDICT-PASS-line-clears-the-arm', explicitPass.exitCode === EXIT_CLEAR && explicitPass.entries[0].record.verdict === 'PASS'); - const newestFail = await tierRun({ ...arm, comments: [recordComment({ id: 901, at: '2026-09-13T12:00:00Z' }), recordComment({ id: 902, at: '2026-09-13T14:00:00Z', verdictWord: '**VERDICT: FAIL**' })] }); + const newestFail = await tierRun({ ...arm, comments: [armRecord({ id: 901, at: '2026-09-13T12:00:00Z' }), armRecord({ id: 902, at: '2026-09-13T14:00:00Z', verdictWord: '**VERDICT: FAIL**' })] }); assert('⛔ the-NEWEST-same-head-record-is-the-one-whose-verdict-is-read-an-older-PASS-does-not-clear-a-newer-FAIL', newestFail.exitCode === EXIT_REFUSED_UNAPPROVED && newestFail.entries[0].record.id === 902 && newestFail.entries[0].record.state === 'not-pass'); const noReader = await tierRun({ ...arm, recognisers: { ...live, reading: undefined } }); - assert('⛔ a-recogniser-set-without-the-verdict-reader-REFUSES-the-arm-fail-closed', noReader.exitCode === EXIT_REFUSED_UNAPPROVED && noReader.entries[0].record.state === 'not-pass' && /verdict reader was not loaded/.test(renderGuardVerdict(noReader))); + // The reader that reads the verdict is the reader that reads the arm's line: without it the arm's record stage is + // NOT MEASURED (Tier H, the record leg never consulted), and every other Tier S leg still refuses on the verdict. + const noReaderOther = await tierRun({ comments: [recordComment()], recognisers: { ...live, reading: undefined } }); + assert('⛔ a-recogniser-set-without-the-record-reader-REFUSES-fail-closed-the-arm-at-Tier-H-every-other-Tier-S-leg-on-its-verdict', noReader.exitCode === EXIT_REFUSED_UNAPPROVED && noReader.entries[0].tier === TIER_H && noReader.entries[0].record === undefined && /its contract-review record was not read \(the contract-review record reader was not loaded\)/.test(renderGuardVerdict(noReader)) && noReaderOther.exitCode === EXIT_REFUSED_UNAPPROVED && noReaderOther.entries[0].tier === TIER_S && noReaderOther.entries[0].record.state === 'not-pass' && /verdict reader was not loaded/.test(renderGuardVerdict(noReaderOther)), renderGuardVerdict(noReader)); assert('the-live-loader-reaches-the-fleet-record-reader-and-its-counting-form', typeof live.reading === 'function' && live.reading('## Contract review\n\n**VERDICT: FAIL**').verdicts.join() === 'FAIL' && live.verdict === undefined && live.verdictLines === undefined); assert('lowRiskRecordVerdict-passes-a-non-standing-record-through-and-reads-the-chosen-comment', (() => { const absent = { state: 'absent' }; @@ -6145,12 +6482,14 @@ export async function selfTest() { return tree(args.filter((a) => a !== '--no-renames')); }; }; - const carriedDocs = await tierRun({ ...arm, comments: onOldHead, runGit: armCarry('content/docs/guides/x.mdx\0'), baseRef: QBASE }); + const carriedDocs = await tierRun({ ...arm, comments: armOnOldHead, runGit: armCarry('content/docs/guides/x.mdx\0'), baseRef: QBASE }); assert('SF1-CONTROL-a-PASS-record-carried-over-a-docs-only-hop-still-clears-the-arm', carriedDocs.exitCode === EXIT_CLEAR && carriedDocs.entries[0].record.carriedHops === 1 && carriedDocs.entries[0].record.verdict === 'PASS', JSON.stringify(carriedDocs.entries[0].record)); - const carriedCs = await tierRun({ ...arm, comments: onOldHead, runGit: armCarry(`${CS}\0`), baseRef: QBASE }); - assert('⛔ SF1-a-record-carried-over-a-hop-that-rewrote-the-CHANGESET-is-refused-on-the-arm', carriedCs.exitCode === EXIT_REFUSED_UNAPPROVED && carriedCs.entries[0].record.state === 'not-pass' && /over hops that moved \.changeset\/33501-skills-wording\.md/.test(renderGuardVerdict(carriedCs)), JSON.stringify(carriedCs.entries[0].record)); - const carriedLog = await tierRun({ ...arm, comments: onOldHead, runGit: armCarry('skills/objectstack-data/CHANGELOG.md\0'), baseRef: QBASE }); - assert('⛔ SF1-a-record-carried-over-a-hop-that-moved-CATALOG-text-a-skill-CHANGELOG-is-refused-on-the-arm', carriedLog.exitCode === EXIT_REFUSED_UNAPPROVED && carriedLog.entries[0].record.state === 'not-pass' && /skills\/objectstack-data\/CHANGELOG\.md/.test(renderGuardVerdict(carriedLog)), JSON.stringify(carriedLog.entries[0].record)); + const carriedCs = await tierRun({ ...arm, comments: armOnOldHead, runGit: armCarry(`${CS}\0`), baseRef: QBASE }); + // The carry rule is ONE rule (`lowRiskCarryRefusal`): the arm's record stage applies it first, so a record carried + // over such a hop no longer establishes its `Security-touching: no` — Tier H, the record leg never consulted. + assert('⛔ SF1-a-record-carried-over-a-hop-that-rewrote-the-CHANGESET-is-refused-on-the-arm', carriedCs.exitCode === EXIT_REFUSED_UNAPPROVED && carriedCs.entries[0].tier === TIER_H && carriedCs.entries[0].record === undefined && /its contract-review record \(PR comment 900\) was carried from `[0-9a-f]{12}` over hops that moved \.changeset\/33501-skills-wording\.md/.test(renderGuardVerdict(carriedCs)), renderGuardVerdict(carriedCs)); + const carriedLog = await tierRun({ ...arm, comments: armOnOldHead, runGit: armCarry('skills/objectstack-data/CHANGELOG.md\0'), baseRef: QBASE }); + assert('⛔ SF1-a-record-carried-over-a-hop-that-moved-CATALOG-text-a-skill-CHANGELOG-is-refused-on-the-arm', carriedLog.exitCode === EXIT_REFUSED_UNAPPROVED && carriedLog.entries[0].tier === TIER_H && carriedLog.entries[0].record === undefined && /over hops that moved skills\/objectstack-data\/CHANGELOG\.md/.test(renderGuardVerdict(carriedLog)), renderGuardVerdict(carriedLog)); assert('⛔ SF1-a-carried-record-whose-hops-cannot-be-diffed-or-with-no-git-reader-is-refused', (() => { const carriedRec = { state: 'stands', id: 5, carriedFrom: REF_OLD, carriedHops: 1 }; const rows = { prComments: [{ id: 5, body: '## Contract review\n\n**VERDICT: PASS**' }], cardComments: [], headSha: REF_HEAD }; @@ -6294,7 +6633,8 @@ export async function selfTest() { } throw new Error(`fatal: unexpected read (${args.join(' ')})`); }; - const arm = { files: [ADR], prBody: LOW, comments: [recordComment()], timeline: [], runGit: adrGit() }; + // The ADR leg is the same arm: its record carries the arm's machine line, `Security-touching: no`. + const arm = { files: [ADR], prBody: LOW, comments: [recordComment({ prose: ['Security-touching: no'] })], timeline: [], runGit: adrGit() }; const hCase = async (over) => { const v = await tierRun({ ...arm, ...over }); return [v.exitCode, v.entries[0].tier, v.entries[0].record === undefined]; }; const H = JSON.stringify([EXIT_REFUSED_UNAPPROVED, TIER_H, true]); @@ -6302,7 +6642,9 @@ export async function selfTest() { const pass = await tierRun(arm); assert('⭐ ROW-1-an-add-only-ADR-note-with-a-same-head-PASS-record-CLEARS-at-the-queue-with-zero-approvals', pass.exitCode === EXIT_CLEAR && pass.entries[0].tier === TIER_S && pass.entries[0].record.verdict === 'PASS', renderGuardVerdict(pass)); const noRecord = await tierRun({ ...arm, comments: [] }); - assert('⛔ CONTROL: the-same-ADR-note-with-NO-record-is-REFUSED-Tier-S-without-its-record', noRecord.exitCode === EXIT_REFUSED_UNAPPROVED && noRecord.entries[0].tier === TIER_S && noRecord.entries[0].record.state === 'absent'); + // No record is no `Security-touching: no` line: Tier H on the arm's record stage (it read Tier S, refused on its absent record, before that stage). + assert('⛔ CONTROL: the-same-ADR-note-with-NO-record-is-REFUSED-Tier-H-on-the-record-stage', noRecord.exitCode === EXIT_REFUSED_UNAPPROVED && noRecord.entries[0].tier === TIER_H && noRecord.entries[0].record === undefined && /no contract-review record names this head/.test(renderGuardVerdict(noRecord))); + assert('⛔ RECORD-LINE: an-ADR-note-whose-PASS-record-lacks-the-Security-touching-line-reads-Tier-H-and-a-security-labelled-card-does-too', JSON.stringify(await hCase({ comments: [recordComment()] })) === H && JSON.stringify(await hCase({ cardLabels: ['security'] })) === H); // ⛔ ROWS 2–6, each WITH a valid PASS record: the record leg is never consulted. assert('⛔ ROW-2-a-removed-line-stays-H', JSON.stringify(await hCase({ runGit: adrGit(REMOVED) })) === H); assert('⛔ ROW-3-a-changed-or-added-Status-line-stays-H', JSON.stringify(await hCase({ runGit: adrGit(STATUS) })) === H); From 6afe4372cb4245661fd8b8d919bf538e40480f55 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 20:07:23 +0000 Subject: [PATCH 4/8] feat(pm): the relay's review plan reads the arm's record stage before it requests nobody After `pr_ready`, a skills-only pull whose pull-read arm conditions all hold is read a second time through the queue guard's one record-stage reader: the review of record's `Security-touching:` line and the labels of the card the pull delivers. A record that lacks the line, a labelled card or any read that fails keeps the pull at Tier H, and both approvers are requested as before. Claude-Session: https://claude.ai/code/session_01ADHkmR2U8dFkRvc5DvUz1W Co-authored-by: Claude --- scripts/pm/fleet-write/execute.mjs | 139 +++++++++++++++++++++++++---- 1 file changed, 123 insertions(+), 16 deletions(-) diff --git a/scripts/pm/fleet-write/execute.mjs b/scripts/pm/fleet-write/execute.mjs index b0efb759119..cf5826332c6 100644 --- a/scripts/pm/fleet-write/execute.mjs +++ b/scripts/pm/fleet-write/execute.mjs @@ -501,15 +501,22 @@ * token, and `pullChangesetReading` / `pullCatalogReading` from the checkout * once the compare answers the merge base and the head is fetched by sha at * depth `ahead_by + 1`), hands it to `governedReviewPlan`, and the arm's own - * `lowRiskArmVerdict` decides: Tier S requests nobody. ⛔ Fail closed: a + * `lowRiskArmVerdict` decides: Tier S requests nobody. When that reading leaves + * the arm's RECORD STAGE pending — every pull-read condition holds — the + * follow-up reads the stage too, through the queue guard's one reader + * (`readLowRiskRecordStage`: the card the pull delivers, both comment threads + * cut to trusted authors, the card's labels and its timeline), and asks the + * arm again. ⛔ Fail closed: a * condition broken (`Clause-②` not a bare `no`, a `security` label now or - * removed, a catalog path named for security, auth or permission, a catalog - * file added, deleted, renamed or not regular, a changeset releasing more than - * the skills catalog, a path off the allowlist), a reading not made (no - * checkout, an unread timeline, a refused compare, a head past - * `LOW_RISK_FETCH_DEPTH_CAP`, another repository, a failed fetch), a mixed - * pull or a repository outside `lowRisk.repos` requests exactly as the - * path-only plan, and the verdict row says why. + * removed, on the pull or on its card, a catalog path named for security, auth + * or permission, a catalog file added, deleted, renamed or not regular, a + * changeset releasing more than the skills catalog, a path off the allowlist, + * a contract-review record on the head that lacks one bare + * `Security-touching: no`), a reading not made (no checkout, an unread + * timeline, a refused compare, a head past `LOW_RISK_FETCH_DEPTH_CAP`, another + * repository, a failed fetch, an unread thread or label list, no derivable + * card), a mixed pull or a repository outside `lowRisk.repos` requests exactly + * as the path-only plan, and the verdict row says why. * * ## The step summary — what a person reads back * @@ -576,6 +583,8 @@ import { HUMAN_MERGE_LINE_THRESHOLD, landingTierOf, LOW_RISK_ARM_RULING, + LOW_RISK_RECORD_LINE, + LOW_RISK_RECORD_STAGE, pullCatalogReading, pullCatalogStatuses, pullChangesetReading, @@ -585,7 +594,16 @@ import { repoIdForSlug, slugFromRemote, } from '../check-governed-merges.mjs'; -import { authorizedApprovalVerdict, GOVERNED_APPROVERS, unreadableApproval } from '../check-governed-queue-guard.mjs'; +import { + authorizedApprovalVerdict, + GOVERNED_APPROVERS, + loadRecordRecognisers, + makeCommentReader, + makeLabelReader, + makeTimelineReader, + readLowRiskRecordStage, + unreadableApproval, +} from '../check-governed-queue-guard.mjs'; import { readSignatureLine } from '../check-half-states.mjs'; import { scrub } from '../fleet-token.mjs'; import { classifyHttp } from '../label-write.mjs'; @@ -1025,9 +1043,15 @@ export async function workflowReadingFor({ repo, paths, pr, api, t, git = null } * the merge base and how far the head is past it, and the head is fetched by sha at depth `ahead_by + 1`, so the * merge base `pullCatalogReading` computes here is in it. ⛔ Fail closed: no checkout, a refused compare, a head too * far past its base, another repository or a failed fetch leaves the changesets and catalog files NOT MEASURED, - * and an unread timeline is NOT MEASURED — each read by `lowRiskArmVerdict` as H. Never throws. + * and an unread timeline is NOT MEASURED — each read by `lowRiskArmVerdict` as H. + * The arm's RECORD STAGE is read SECOND, and only when that reading leaves it pending (every pull-read condition + * holds), so no other pull pays for it: the queue guard's `readLowRiskRecordStage`, imported, ⛔ no second reader, + * over the guard's own comment, label and timeline readers on the relay's token — the review of record's + * `Security-touching:` line and the labels of the card `pr` delivers. `loadRecognisers` is the seam for the + * contract-review recognisers; a load that fails, a thread or label list that does not read, or a pull that + * names no card is NOT MEASURED, so H. Never throws. */ -export async function lowRiskReadingFor({ repo, pull, paths, files, pr, api, t, git = null }) { +export async function lowRiskReadingFor({ repo, pull, paths, files, pr, api, t, git = null, loadRecognisers = loadRecordRecognisers }) { const token = t?.token ?? ''; const timeline = await fetchTimelineOver({ fetchImpl: t?.fetch ?? globalThis.fetch, @@ -1038,7 +1062,32 @@ export async function lowRiskReadingFor({ repo, pull, paths, files, pr, api, t, const unread = { measured: false, reason: checkout.reason, files: [] }; const changesets = checkout.run ? pullChangesetReading({ derivation: checkout.derivation, paths, sameCheckout: true, run: checkout.run }) : unread; const catalogFiles = checkout.run ? pullCatalogReading({ derivation: checkout.derivation, statuses: pullCatalogStatuses(files), paths, sameCheckout: true, run: checkout.run }) : unread; - return pullLowRiskReading(pr, paths, { timeline, changesets, catalogFiles }); + const first = pullLowRiskReading(pr, paths, { timeline, changesets, catalogFiles }); + const plan = governedReviewPlan({ paths, repo, lowRisk: first }); + if (plan.lowRiskVerdict?.recordStage !== LOW_RISK_RECORD_STAGE.pending) return first; + let recognisers; + try { + recognisers = await loadRecognisers(); + } catch (error) { + recognisers = { available: false, reason: `the recogniser load threw: ${String(error?.message ?? error).split('\n')[0]}` }; + } + const reader = { apiUrl: api, slug: repo, token, fetchImpl: t?.fetch ?? globalThis.fetch }; + const stage = await readLowRiskRecordStage({ + pr: pull, + pull: pr, + headSha: pr?.head?.sha ?? null, + paths, + repo: plan.repoId, + // A pending stage means the checkout read the changesets, so it holds the head and the merge base: a record + // carried from an older head is re-tested against them, and one the checkout cannot diff refuses the carry. + runGit: typeof git === 'function' ? git : null, + baseRef: checkout.derivation?.baseSha ?? null, + recognisers, + fetchComments: makeCommentReader(reader), + fetchLabels: makeLabelReader(reader), + fetchTimeline: makeTimelineReader(reader), + }); + return pullLowRiskReading(pr, paths, { timeline, changesets, catalogFiles, record: stage.record, cardLabels: stage.cardLabels }); } /** @@ -2552,7 +2601,9 @@ const SELF_TEST_BATTERIES = Object.freeze({ // six unreadable readings in one case, a mixed pull and an objectui workflow pull — every one but S requesting as the path-only plan. // 36 → 45 with the low-risk skills arm read on the relay: the plan with the arm (S and unread), seven H variants in one case, the // words, the readable gate, a Tier S skills pull requesting no one, three H readings, eight unreadable readings, a mixed pull and objectui. - "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 — 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": 45, + // 45 → 50 with the arm's record stage on the relay: nine H variants of the stage in one plan case, twelve in one run case (the record + // without its line first), the record on the card thread, the recogniser seam, and the stage's cost on a pull-read H. + "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": 50, // 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, @@ -2890,7 +2941,7 @@ export async function selfTest() { } // ── the governed-review follow-up ─────────────────────────────────────── - battery("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 — 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"); + battery("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"); { const PULLS = `POST /repos/${REPO}/pulls`; const N = 25050; @@ -3050,10 +3101,16 @@ export async function selfTest() { const [ARM_TIP, ARM_HEAD] = ['a', 'b'].map((c) => c.repeat(40)); const sameRepo = { repo: { full_name: REPO } }; const armPullJson = (over = {}) => ({ ...pullOf().json, body: LOW_BODY, labels: [], head: { sha: ARM_HEAD, ...sameRepo }, base: { sha: ARM_TIP, ref: 'main', ...sameRepo }, ...over }); + // The arm's record stage, read and favourable — a record on the head whose line reads `no`, a card never + // labelled `security` — unless a case overrides a half (`null` hands that half in unread: the arm's `pending`). + const stageRecord = (over = {}) => ({ measured: true, reason: null, located: 'found', where: 'PR', id: 900, carried: null, securityTouching: { state: 'read', value: 'no' }, ...over }); + const stageCard = (over = {}) => ({ measured: true, reason: null, card: 1, labels: [], timeline: { measured: true, reason: null, events: [] }, ...over }); const lowRead = (paths, over = {}) => pullLowRiskReading(armPullJson(over.pull ?? {}), paths, { timeline: { measured: true, reason: null, events: over.events ?? [] }, changesets: { measured: true, reason: null, files: paths.filter((p) => p.startsWith('.changeset/')).map((path) => ({ path, text: over.csText ?? CS_TEXT })) }, catalogFiles: { measured: true, reason: null, files: paths.filter((p) => p.startsWith('skills/')).map((path) => ({ path, status: over.status ?? 'modified', oldMode: '100644', mode: '100644' })) }, + record: over.record === undefined ? stageRecord() : over.record, + cardLabels: over.cardLabels === undefined ? stageCard() : over.cardLabels, }); const armPlan = (paths, reading) => governedReviewPlan({ paths, repo: REPO, lowRisk: reading }); t('⭐ the plan with the arm: a low-risk skills-wording pull read by the arm is Tier S and plans NO approver; no reading, or one not measured, keeps the path-only H and plans both', [armPlan([SK, CS], lowRead([SK, CS])), armPlan([SK, CS], null), armPlan([SK, CS], { measured: false, reason: 'x' }), armPlan([SK, CS], pullLowRiskReading(armPullJson(), [SK, CS]))].map((p) => [p.tier, p.toRequest]), [[GOVERNED_TIER_S, []], [GOVERNED_TIER_H, [A1, A2]], [GOVERNED_TIER_H, [A1, A2]], [GOVERNED_TIER_H, [A1, A2]]]); @@ -3068,6 +3125,18 @@ export async function selfTest() { 'a package path beside it': armPlan([SK, CS, 'packages/core/src/a.ts'], lowRead([SK, CS, 'packages/core/src/a.ts'])), }; t('⛔ the same pull with Clause-② yes, a security label (now or removed), a security-named catalog path, an added catalog file, a changeset releasing more than the skills catalog, or a package path beside it plans BOTH approvers', Object.entries(variants).map(([k, p]) => [k, p.tier, p.toRequest]), Object.keys(variants).map((k) => [k, GOVERNED_TIER_H, [A1, A2]]), Object.values(variants).map((p) => lowRiskReadingText(p)).join(' | ')); + const stageVariants = { + 'a record without the line': [armPlan([SK, CS], lowRead([SK, CS], { record: stageRecord({ securityTouching: { state: 'missing' } }) })), 'its contract-review record (PR comment 900) carries no `Security-touching:` line'], + 'a record reading yes': [armPlan([SK, CS], lowRead([SK, CS], { record: stageRecord({ securityTouching: { state: 'read', value: 'yes' } }) })), 'reads `Security-touching: yes`'], + 'a doubled line': [armPlan([SK, CS], lowRead([SK, CS], { record: stageRecord({ securityTouching: { state: 'unreadable', reason: 'it carries 2 `Security-touching:` lines, and a record states exactly one' } }) })), 'is unreadable: it carries 2'], + 'no record on the head': [armPlan([SK, CS], lowRead([SK, CS], { record: stageRecord({ located: 'absent', securityTouching: null }) })), 'no contract-review record names this head'], + 'a record not read': [armPlan([SK, CS], lowRead([SK, CS], { record: { measured: false, reason: 'HTTP 502' } })), 'its contract-review record was not read (HTTP 502)'], + 'a security label on the card': [armPlan([SK, CS], lowRead([SK, CS], { cardLabels: stageCard({ labels: ['security'] }) })), 'its card #1 carries the `security` label'], + 'a security label removed from the card': [armPlan([SK, CS], lowRead([SK, CS], { cardLabels: stageCard({ timeline: { measured: true, reason: null, events: [{ event: 'unlabeled', label: { name: 'security' } }] } }) })), 'the timeline of its card #1 shows the `security` label removed'], + 'a card nobody could name': [armPlan([SK, CS], lowRead([SK, CS], { cardLabels: { measured: false, reason: 'no card could be derived for it — its body names no card' } })), 'the labels of its card were not read (no card could be derived for it'], + 'the record stage not read at all': [armPlan([SK, CS], lowRead([SK, CS], { record: null, cardLabels: null })), 'its contract-review record and the labels of its card were not read'], + }; + t('⛔ the plan with the arm\'s record stage: a record that lacks the line, reads yes, doubles it, is absent or unread, a card carrying `security` or stripped of it, a card nobody could name, or a stage not read at all plans BOTH approvers, and the words name the reason', Object.entries(stageVariants).map(([k, [plan, why]]) => [k, plan.tier, plan.toRequest, lowRiskReadingText(plan).includes(why)]), Object.keys(stageVariants).map((k) => [k, GOVERNED_TIER_H, [A1, A2], true]), Object.values(stageVariants).map(([plan]) => lowRiskReadingText(plan)).join(' | ')); t('the arm words: Tier S names the ruling; Tier H lists every reason; no arm row adds nothing', [lowRiskReadingText(armPlan([SK, CS], lowRead([SK, CS]))), lowRiskReadingText(variants['a security label']).includes('the PR carries the `security` label'), lowRiskReadingText(governedReviewPlan({ paths: ['AGENTS.md'], repo: REPO }))], [` · low-risk skills arm read: Tier S (${LOW_RISK_ARM_RULING})`, true, '']); t('lowRiskArmReadable: catalog rows alone in objectstack are read; another row beside them, or a repository outside lowRisk.repos, is not — with the words why; a non-arm plan says nothing', [lowRiskArmReadable(governedReviewPlan({ paths: [SK, 'ui/skills/x/SKILL.md'], repo: REPO })), lowRiskArmReadable(governedReviewPlan({ paths: [SK, 'AGENTS.md'], repo: REPO })).read, lowRiskArmReadable(governedReviewPlan({ paths: [SK], repo: 'objectstack-ai/objectui' })).why, lowRiskArmReadable(governedReviewPlan({ paths: ['AGENTS.md'], repo: REPO }))], [{ read: true, why: null }, false, "objectui is not in the row's lowRisk.repos (objectstack), so the path-only tier stands", { read: false, why: null }]); @@ -3075,7 +3144,20 @@ export async function selfTest() { const ARM_COMPARE = `GET /repos/${REPO}/compare/${ARM_TIP}...${ARM_HEAD}`; const TIMELINE = `GET /repos/${REPO}/issues/${N}/timeline`; const armFiles = (...rows) => files(...rows.map((r) => (typeof r === 'string' ? { filename: r, status: 'modified' } : r))); - const armAnswers = (extra = {}) => ({ ...allowed, ...readied, [PULL]: { status: 200, json: armPullJson() }, [FILES]: armFiles(SK, CS), [TIMELINE]: { status: 200, json: [] }, [ARM_COMPARE]: { status: 200, json: { merge_base_commit: { sha: ARM_TIP }, ahead_by: 2 } }, [REVIEWS]: reviewsBy(), [REQUEST]: requestedAnswer([A1, A2]), ...extra }); + // The arm's record stage on the platform: the review of record on the pull's thread, by the relay's own login, + // and card #1 (the body's `Fixes #1`) with its thread, its labels and its timeline. + const armRecognisers = await loadRecordRecognisers(); + const { CONTRACT_REVIEW_TIER_NAME: AT_TIER } = await import('../record-recognisers.mjs'); + const reviewOfRecord = (line = LOW_RISK_RECORD_LINE, over = {}) => ({ + id: 900, created_at: '2026-11-15T04:00:00Z', user: { login: armRecognisers.trustedAuthors?.[0] ?? '(relay unread)' }, + body: ['## Contract review', '', `Served-tier: \`${AT_TIER}\``, `Head-sha: \`${ARM_HEAD}\``, 'Reviewed-by: `session_01SEAT`', ...(line === null ? [] : [line]), '', '**VERDICT: PASS**'].join('\n'), ...over, + }); + const THREAD = (n) => `GET /repos/${REPO}/issues/${n}/comments`; + const CARD_LABELS = `GET /repos/${REPO}/issues/1/labels`; + const CARD_TIMELINE = `GET /repos/${REPO}/issues/1/timeline`; + const STAGE_READS = [THREAD(N), THREAD(1), CARD_LABELS, CARD_TIMELINE]; + const stageAnswers = ({ rows = [reviewOfRecord()], cardRows = [], labels = [], events = [] } = {}) => ({ [THREAD(N)]: { status: 200, json: rows }, [THREAD(1)]: { status: 200, json: cardRows }, [CARD_LABELS]: { status: 200, json: labels.map((name) => ({ name })) }, [CARD_TIMELINE]: { status: 200, json: events } }); + const armAnswers = (extra = {}) => ({ ...allowed, ...readied, [PULL]: { status: 200, json: armPullJson() }, [FILES]: armFiles(SK, CS), [TIMELINE]: { status: 200, json: [] }, [ARM_COMPARE]: { status: 200, json: { merge_base_commit: { sha: ARM_TIP }, ahead_by: 2 } }, [REVIEWS]: reviewsBy(), [REQUEST]: requestedAnswer([A1, A2]), ...stageAnswers(), ...extra }); // The checkout: `fetched` once the fetch ran (or `present` from the start); the merge base answers ARM_TIP; modes and texts per commit. const armGit = (calls, { present = [ARM_TIP], fetchable = true, remote = `https://github.com/${REPO}`, throwOn = null, modes = {} } = {}) => { const held = new Set(present); @@ -3110,10 +3192,35 @@ export async function selfTest() { }; const lowCalls = []; const low = await run(ready(), armAnswers(), { git: armGit(lowCalls) }); - t('⭐ low-risk-skills-pull-requests-no-one: a skills-wording pull the arm reads as Tier S — the timeline and the compare read, the head fetched by sha at depth ahead_by + 1, NO reviews read, NO request, exit 0, the row naming the arm and its ruling', [low.exit, writes(low.seen).map((s) => s.call), low.seen.some((s) => s.call === REVIEWS), low.seen.filter((s) => s.call === TIMELINE).length, lowCalls.filter((c) => c.startsWith('fetch')), low.rows[1]?.result], [EXIT_OK, [GRAPHQL], false, 1, [`fetch --no-tags --depth=3 origin ${ARM_HEAD}`], `governed review: Tier S (\`skills/**\`×1) lands on a seat's review of record — no review requested · low-risk skills arm read: Tier S (${LOW_RISK_ARM_RULING})`], low.logs.join(' | ')); + t('⭐ low-risk-skills-pull-requests-no-one: a skills-wording pull the arm reads as Tier S — the timeline and the compare read, the head fetched by sha at depth ahead_by + 1, then the record stage read once (the pull\'s thread, the card\'s thread, its labels and its timeline, on the relay token), NO reviews read, NO request, exit 0, the row naming the arm and its ruling', [low.exit, writes(low.seen).map((s) => s.call), low.seen.some((s) => s.call === REVIEWS), low.seen.filter((s) => s.call === TIMELINE).length, low.seen.map((s) => s.call).filter((c) => STAGE_READS.includes(c)), low.seen.filter((s) => STAGE_READS.includes(s.call)).every((s) => s.auth === `Bearer ${TOKEN}`), lowCalls.filter((c) => c.startsWith('fetch')), low.rows[1]?.result], [EXIT_OK, [GRAPHQL], false, 1, STAGE_READS, true, [`fetch --no-tags --depth=3 origin ${ARM_HEAD}`], `governed review: Tier S (\`skills/**\`×1) lands on a seat's review of record — no review requested · low-risk skills arm read: Tier S (${LOW_RISK_ARM_RULING})`], low.logs.join(' | ')); + // ⛔ The record stage on the relay: an arm pull whose record lacks the line reads Tier H, and so does each other + // way the stage can fail — both approvers requested, as the path-only plan, the row naming the reason. + const stageRun = (stage, extra = {}) => run(ready(), armAnswers({ ...stageAnswers(stage), ...extra }), { git: armGit([]) }); + const stageH = { + 'a record that LACKS the line': [await stageRun({ rows: [reviewOfRecord(null)] }), 'its contract-review record (PR comment 900) carries no `Security-touching:` line'], + 'a record reading yes': [await stageRun({ rows: [reviewOfRecord('Security-touching: yes')] }), '(PR comment 900) reads `Security-touching: yes`'], + 'a record with the line twice': [await stageRun({ rows: [reviewOfRecord(`${LOW_RISK_RECORD_LINE}\n${LOW_RISK_RECORD_LINE}`)] }), 'is unreadable: it carries 2 `Security-touching:` lines'], + 'no record on the head': [await stageRun({ rows: [] }), 'no contract-review record names this head'], + 'a record by an author the leg does not trust': [await stageRun({ rows: [reviewOfRecord(LOW_RISK_RECORD_LINE, { user: { login: 'some-commenter' } })] }), 'no contract-review record names this head'], + 'a newer record on the head without the line': [await stageRun({ rows: [reviewOfRecord(), reviewOfRecord(null, { id: 901, created_at: '2026-11-15T04:30:00Z' })] }), '(PR comment 901) carries no `Security-touching:` line'], + 'a security label on the card': [await stageRun({ labels: ['tooling', 'security'] }), 'its card #1 carries the `security` label'], + 'a security label removed from the card': [await stageRun({ events: [{ event: 'labeled', label: { name: 'security' } }, { event: 'unlabeled', label: { name: 'security' } }] }), 'the timeline of its card #1 shows the `security` label removed'], + 'a pull that names no card': [await stageRun({}, { [PULL]: { status: 200, json: armPullJson({ body: 'Clause-②: no\nMetadata-protocol: none\n' }) } }), 'the labels of its card were not read (no card could be derived for it'], + 'a thread that does not read': [await stageRun({}, { [THREAD(N)]: { status: 502, json: { message: 'bad gateway' } } }), `its contract-review record was not read (PR #${N}'s comment thread could not be read`], + 'card labels that do not read': [await stageRun({}, { [CARD_LABELS]: { status: 403, json: { message: 'forbidden' } } }), "card #1's labels could not be read"], + 'a card timeline that does not read': [await stageRun({}, { [CARD_TIMELINE]: { status: 502, json: { message: 'bad gateway' } } }), 'the timeline of its card #1 was not read'], + }; + t('⛔ record-stage-skills-pull-requests: an arm pull whose record LACKS the `Security-touching:` line, reads yes, doubles it, is absent, is by an untrusted author or is shadowed by a newer one without it, whose card carries `security` or had it removed, that names no card, or whose thread, labels or card timeline do not read — each requests BOTH approvers, and its row says Tier H, fail closed, with the reason', Object.entries(stageH).map(([k, [r, why]]) => [k, r.exit, writes(r.seen).map((s) => s.call), r.rows[1]?.result.includes('low-risk skills arm read: Tier H, fail closed') && r.rows[1]?.result.includes(why)]), Object.keys(stageH).map((k) => [k, EXIT_OK, [GRAPHQL, REQUEST], true]), Object.values(stageH).map(([r]) => r.rows[1]?.result).join(' | ')); + const onCard = await stageRun({ rows: [], cardRows: [reviewOfRecord(LOW_RISK_RECORD_LINE, { id: 902 })] }); + t('⭐ the record on the CARD thread carries the line as well as one on the pull: Tier S, no request', [onCard.exit, writes(onCard.seen).map((s) => s.call), onCard.rows[1]?.result.endsWith(`low-risk skills arm read: Tier S (${LOW_RISK_ARM_RULING})`)], [EXIT_OK, [GRAPHQL], true], onCard.rows[1]?.result); + const stageFor = (loadRecognisers) => lowRiskReadingFor({ repo: REPO, pull: N, paths: [SK, CS], files: armFiles(SK, CS).json, pr: armPullJson(), api: 'https://api.github.test', t: { fetch: platform(armAnswers(), []), token: TOKEN }, git: armGit([]), ...(loadRecognisers ? { loadRecognisers } : {}) }); + const [stageLoaded, stageThrew, stageUnavailable] = [await stageFor(), await stageFor(async () => { throw new Error('ERR_MODULE_NOT_FOUND'); }), await stageFor(async () => ({ available: false, reason: 'the recognisers would not load' }))]; + t('⛔ lowRiskReadingFor: recognisers that load give the stage its two readings; a load that throws or answers unavailable is NOT MEASURED on both halves, never a pass', [[stageLoaded.record?.located, stageLoaded.record?.securityTouching, stageLoaded.cardLabels?.card, armPlan([SK, CS], stageLoaded).tier], [stageThrew.record, stageThrew.cardLabels?.measured, armPlan([SK, CS], stageThrew).tier], [stageUnavailable.record, armPlan([SK, CS], stageUnavailable).tier]], + [['found', { state: 'read', value: 'no' }, 1, GOVERNED_TIER_S], [{ measured: false, reason: 'the recogniser load threw: ERR_MODULE_NOT_FOUND' }, false, GOVERNED_TIER_H], [{ measured: false, reason: 'the recognisers would not load' }, GOVERNED_TIER_H]]); const secLabel = await run(ready(), armAnswers({ [PULL]: { status: 200, json: armPullJson({ labels: [{ name: 'security' }] }) } }), { git: armGit([]) }); const added = await run(ready(), armAnswers({ [FILES]: armFiles({ filename: SK, status: 'added' }, CS) }), { git: armGit([]) }); const symlinked = await run(ready(), armAnswers(), { git: armGit([], { modes: { [SK]: '120000' } }) }); + t('the record stage is read only when every pull-read condition holds: a pull the arm reads H on its own label, an added file or a symlink reads no thread and no card label', [secLabel, added, symlinked].map((r) => r.seen.filter((s) => STAGE_READS.includes(s.call)).length), [0, 0, 0]); t('⭐ h-reading-skills-pull-requests: the same pull with a security label, an added catalog file, or a catalog path turned symlink requests BOTH approvers, and its row names the reason', [[secLabel, 'the `security` label'], [added, 'added, deleted or renamed'], [symlinked, 'not a regular file at both ends']].map(([r, why]) => [r.exit, writes(r.seen).map((s) => s.call), r.rows[1]?.result.includes('low-risk skills arm read: Tier H, fail closed') && r.rows[1]?.result.includes(why)]), [0, 1, 2].map(() => [EXIT_OK, [GRAPHQL, REQUEST], true]), [secLabel, added, symlinked].map((r) => r.rows[1]?.result).join(' | ')); const armUnread = { 'no checkout': [await run(ready(), armAnswers()), 'no checkout was handed to this run'], From 9d26a6a2dcea1d7021695e795aa0a95f185e45f9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 20:08:59 +0000 Subject: [PATCH 5/8] docs(pm): the contract-review reference names the record's Security-touching line The line that pointed at `--template` for the independence pair now points there for the `Security-touching:` line the low-risk arm reads as well. Same line count; the pair's two key spellings stay in the review lane reference and in the template itself. Claude-Session: https://claude.ai/code/session_01ADHkmR2U8dFkRvc5DvUz1W Co-authored-by: Claude --- .claude/skills/pm-dispatch/references/contract-review.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.claude/skills/pm-dispatch/references/contract-review.md b/.claude/skills/pm-dispatch/references/contract-review.md index 59c12d25cd4..31053109682 100644 --- a/.claude/skills/pm-dispatch/references/contract-review.md +++ b/.claude/skills/pm-dispatch/references/contract-review.md @@ -43,7 +43,7 @@ - 另记作者:PR `user.login` 非 `objectstack-fleet[bot]` ⇒ ③ 注点名该 login(脱中继写),落地前读。 - ③ 恒查(席位自读同):SQL 可下推处新增 id 物化或应用内 join 而无因由 ⇒ 记发现(AGENTS.md)。 - 简报从 `record-recognisers.mjs --brief-template` 起稿:只读条款与输入集内建,⛔ 不删 ⛔ 行。 -- 独立性对:`Implemented-by:`/`Reviewed-by:` 取值同见 `--template`;子代理记采纳它的席位。 +- 独立性对与低风险臂读的 `Security-touching:` 行,取值同见 `--template`;子代理记采纳它的席位。 - ④ 恒由起草者之外的 agent 达档跑,起草已达档不免;喂入同上,⛔ 不喂起草者的结论。 - 卡线程隔离子代理照上落现 head 记录并贴简报 ⇒ 席核简报、`Scope:` 与独立性对后采纳, ACCEPT 点名其评论 id;`Scope:` 窄于 `hits` 不采纳;席的补缺记录只管缺口,⛔ 不单充 head 记录。 From 40aedc58bafa4e14350af419577cd51cd82b4023 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 20:25:00 +0000 Subject: [PATCH 6/8] feat(pm): the sweep reads the arm's record stage only for a landing whose own tree carries it The queue leg runs the register from the merge group's own tree, so the rule a queue applied to a landing is the one in the landed commit's tree. The post-merge sweep now asks that tree whether it declares the record stage before it reads the stage for the landing: an earlier landing is a pass on its record alone, as its queue read it, and a tree that cannot be read is not measured. Without this the first sweeps after the stage lands would read every earlier arm landing as a stage breach. Claude-Session: https://claude.ai/code/session_01ADHkmR2U8dFkRvc5DvUz1W Co-authored-by: Claude --- scripts/pm/check-governed-merges.mjs | 77 ++++++++++++++++++++++++++-- 1 file changed, 72 insertions(+), 5 deletions(-) diff --git a/scripts/pm/check-governed-merges.mjs b/scripts/pm/check-governed-merges.mjs index 99104a31b16..569427df4e1 100644 --- a/scripts/pm/check-governed-merges.mjs +++ b/scripts/pm/check-governed-merges.mjs @@ -551,7 +551,9 @@ * not move), and reads each one again with the queue guard's own arm and record * readers on the landed commit (`readArmLanding`): an arm landing is listed APART * from the maintainer's merges, a `pass` on a same-head at-tier PASS record that - * existed when it landed, a ⛔ `breach` without one; the arm's Tier H stays on + * existed when it landed, a ⛔ `breach` without one or on a record stage that + * read Tier H then (read only where the landed commit's own tree carries the + * stage, `armRecordStageBound`); the arm's Tier H stays on * the maintainer's list with its reasons, and so does an arm landing an * authorized approval or enqueue cleared first (the guard's own leg order); a * record counts only on a pull GitHub says landed AS this commit @@ -1196,8 +1198,8 @@ const SELF_TEST_BATTERIES = Object.freeze({ '⭐ the workflows split: Tier H by path or by C2 trigger, else Tier S (ruling record 6722205630)': 75, // 74 → 95 with the arm's record stage: sixteen pins on the two conjuncts and the stage's three states, five on `--pr`. '⚖️ the low-risk skills arm: skills wording on Clause-② no lands Tier S, everything else stays H (#33501)': 95, - // 51 → 61 with the record stage as the sweep reads it at the landing: ten pins. - '⚖️ #33603: the sweep lists a low-risk arm landing APART and judges it on a same-head at-tier PASS record': 61, + // 51 → 66 with the record stage as the sweep reads it at the landing: ten pins, and five on which landings it binds. + '⚖️ #33603: the sweep lists a low-risk arm landing APART and judges it on a same-head at-tier PASS record': 66, '⭐ the weekly audit card: every reading the job files on, both ways (#33814)': 54, '⚖️ #33539: the ADR leg of the low-risk arm — an add-only note lands Tier S, any other ADR change stays H': 52, }); @@ -4968,7 +4970,8 @@ export async function loadArmReaders(load = (specifier) => import(specifier)) { * LANDING: the line off the same as-landed rows (`lowRiskRecordStage`), the card's labels rebuilt from its timeline * (`cardLabelsAsLanded`; `fetchers.fetchLabels` reads them, absent ⇒ `not-measured`). A stage that then reads Tier H * is a `breach` flagged `stage: true` — the queue would have refused that landing — and a stage that could not be - * read is `not-measured`, ⛔ never `tier-h` and never a stand-in. + * read is `not-measured`, ⛔ never `tier-h` and never a stand-in. The stage is read only for a landing whose own tree + * carries it (`armRecordStageBound`): an earlier landing is a `pass` on its record alone, flagged `stageBound: false`. * States: `pass` (an arm landing on a same-head at-tier PASS record whose record stage holds), `breach` (an arm * landing without one, on a record stage at Tier H, or whose pull did not land as this commit), `cleared` (the * arm's pull-read conditions held, but an authorized approval or enqueue cleared it before the record was read: the @@ -5087,6 +5090,11 @@ export async function readArmLanding(entry, { paths, repo, readers, fetchers, ru const found = { where: record.where ?? null, id: record.id ?? null, at: record.at ?? null, cardNote }; const ignored = guard.ignoredAuthorLines({ ignoredAuthors }).map((line) => line.trim()); if (record.state === 'stands') { + // The stage binds a landing only when the queue that judged it ran it (`armRecordStageBound`): a landing whose + // own tree predates the stage stood on its record alone, as its queue read it, and nothing below is read for it. + const bound = armRecordStageBound(runGit, entry.sha); + if (bound === null) return unmeasured(`its landed tree's \`${ARM_RULE_PATH}\` could not be read, so whether the queue read the record stage for it is not known`); + if (bound === false) return { state: 'pass', headSha, record: found, stageBound: false, ...(ignored.length > 0 ? { ignored } : {}) }; // ⭐ The arm's record stage, as the queue read it: the line off the rows that existed, unedited, at the landing, // and the card's labels as they stood then. ⛔ Anything unread is NOT MEASURED — never a stand-in, never `no`. const stage = guard.lowRiskRecordStage({ pair, recognisers }); @@ -5130,6 +5138,31 @@ export async function readArmLanding(entry, { paths, repo, readers, fetchers, ru return { state: 'breach', headSha, reason, record: found, ...(ignored.length > 0 ? { ignored } : {}) }; } +/** This file, as a tree names it: where a landed commit keeps the rule its queue ran. */ +export const ARM_RULE_PATH = 'scripts/pm/check-governed-merges.mjs'; + +/** The record stage's own declaration, at a line start: a tree whose copy of this file has it ran the stage. */ +export const LOW_RISK_RECORD_STAGE_DECLARED = /^export const LOW_RISK_RECORD_STAGE = /m; + +/** + * Did the queue that judged this landing read the arm's record stage? The queue leg runs this file from the merge + * group's own tree (`governed-surface-guard.yml` checks out the `merge_group` ref itself), and a queue landing IS + * that merge-group commit, so the rule its queue applied is the one in the landed commit's tree: the stage bound the + * landing exactly when that tree's copy of this file declares it (`LOW_RISK_RECORD_STAGE_DECLARED`). + * ⛔ Without this read the first sweeps after the stage lands would read every earlier arm landing — whose record + * could not carry a line no template printed yet — as a stage BREACH, and file it as an incident. + * `true` bound, `false` the tree predates the stage, `null` the tree could not be read: NOT MEASURED, never a guess. + * `cat-file`, never `show`: `show` is the spelling the arm's own reads take (`ARM_CHANGESET_SHOW`), and this read + * is the sweep's, not the arm's — it is never stood in for and never counted among the arm's unread inputs. + */ +export function armRecordStageBound(runGit, sha) { + try { + return LOW_RISK_RECORD_STAGE_DECLARED.test(String(runGit(['cat-file', '-p', `${sha}:${ARM_RULE_PATH}`]))); + } catch { + return null; + } +} + /** * A card's labels as they stood when the commit landed, for the arm's record stage: the reading `readCardLabels` * took NOW, rebuilt from the card's own timeline. Only `security` is rebuilt, the one label the arm reads: @@ -5273,7 +5306,8 @@ export function armCell(entry) { if (!a) return ''; const head = a.headSha ? ` on head ${String(a.headSha).slice(0, 12)}` : ''; const ignored = (a.ignored ?? []).map((line) => `\n ${line}`).join(''); - if (a.state === 'pass') return `\n ✅ low-risk arm landing${head}: same-head at-tier PASS record ${a.record?.where ?? ''} comment ${a.record?.id ?? '(no id)'}${ignored}`; + const unbound = a.stageBound === false ? ' (its landed tree predates the record stage, so its queue read the record alone)' : ''; + if (a.state === 'pass') return `\n ✅ low-risk arm landing${head}: same-head at-tier PASS record ${a.record?.where ?? ''} comment ${a.record?.id ?? '(no id)'}${unbound}${ignored}`; if (a.state === 'breach' && a.stage === true) return `\n ⛔ BREACH — low-risk arm landing${head} on a record stage that reads Tier H: ${a.reason}${ignored}`; if (a.state === 'breach') return `\n ⛔ BREACH — low-risk arm landing${head} WITHOUT a same-head at-tier PASS record: ${a.reason}${ignored}`; if (a.state === 'cleared') return `\n low-risk arm: its pull-read conditions held${head}, cleared by an authorized ${a.by === 'review' ? 'approval' : 'enqueue'} (${(a.who ?? []).join(', ')}) before the record was read — the maintainer's merge`; @@ -10528,11 +10562,16 @@ async function selfTest() { const HEAD = 'b'.repeat(40); const BODY = 'Fixes #69\n\nClause-②: no\nMetadata-protocol: none\n'; const MERGED_AT = '2026-11-15T05:00:00Z'; + // This file as a landed tree holds it: with the record stage declared, and as it read before the stage. + const RULE_TREE = "/** the register */\nexport const LOW_RISK_RECORD_STAGE = Object.freeze({ pending: 'pending' });\n"; + const OLD_RULE_TREE = "/** the register, before the stage */\nexport function lowRiskArmVerdict() {}\n// 'export const LOW_RISK_RECORD_STAGE = ' only quoted\n"; // The landed commit as git answers the guard's readers: a MODIFIED skill and an added changeset. const runGit = (args) => { if (args[0] === 'diff-tree') return `:100644 100644 ${'1'.repeat(40)} ${'2'.repeat(40)} M\0${SK}\0:000000 100644 ${'0'.repeat(40)} ${'3'.repeat(40)} A\0${CS}\0`; if (args[0] === 'show' && args[1] === `${LANDED}:${CS}`) return CS_TEXT; if (args[0] === 'rev-parse') return `${'c'.repeat(40)}\n`; + // The landed tree's own copy of this file declares the record stage: its queue ran the stage. + if (args[0] === 'cat-file' && args[2] === `${LANDED}:${ARM_RULE_PATH}`) return RULE_TREE; throw new Error(`fatal: unexpected git ${args.join(' ')}`); }; const RELAY = readers.recognisers?.trustedAuthors?.[0] ?? '(relay unread)'; @@ -10678,6 +10717,34 @@ async function selfTest() { return withLine?.state === 'not-measured' && without?.state === 'not-measured' && !withLine.reason.includes('Security-touching') && /so its Tier H cannot say how the queue read it/.test(without.reason) ? true : JSON.stringify([withLine, without]); })() === true); + // The record stage binds a landing only when its own tree carries it: the queue leg runs this file from the merge + // group's tree, so a landing whose tree predates the stage stood on its record alone and is no BREACH of a rule + // that did not exist yet. ⛔ A tree that cannot be read is NOT MEASURED — never PASS on a guess, never a BREACH. + const treeGit = (text) => (a) => { if (a[0] !== 'cat-file') return runGit(a); if (text === null) throw new Error('fatal: path does not exist'); return text; }; + assert('⭐ RULE-AGE a-landing-whose-own-tree-predates-the-record-stage-is-PASS-on-its-record-alone-and-reads-no-card', await (async () => { + const seen = []; + const noLine = await run({ seen, git: treeGit(OLD_RULE_TREE), prRows: [record({ line: null })] }); + const labelled = await run({ seen, git: treeGit(OLD_RULE_TREE), cardLabels: ['security'] }); + const cell = armCell({ arm: noLine }); + return noLine?.state === 'pass' && noLine.stageBound === false && noLine.record.id === 900 && labelled?.state === 'pass' && labelled.stageBound === false && seen.length === 0 && + cell.includes('same-head at-tier PASS record PR comment 900 (its landed tree predates the record stage, so its queue read the record alone)') ? true : JSON.stringify([noLine, labelled, seen, cell]); + })() === true); + assert('⛔ RULE-AGE control-the-same-landings-on-a-tree-that-carries-the-stage-are-stage-BREACHES-and-a-bound-PASS-carries-no-flag', + await stageBreach({ git: treeGit(RULE_TREE), prRows: [record({ line: null })] }, /carries no `Security-touching:` line$/) === true && + await stageBreach({ git: treeGit(RULE_TREE), cardLabels: ['security'] }, /^its card #69 carries the `security` label$/) === true && + !('stageBound' in (await run({ git: treeGit(RULE_TREE) }))) && !armCell({ arm: pass }).includes('predates')); + assert('⛔ RULE-AGE a-landed-tree-that-cannot-be-read-is-NOT-MEASURED-never-PASS-and-never-a-BREACH', + await unmeasured({ git: treeGit(null) }, /^its landed tree's `scripts\/pm\/check-governed-merges\.mjs` could not be read, so whether the queue read the record stage for it is not known$/) === true && + await unmeasured({ git: treeGit(null), prRows: [record({ line: null })] }, /could not be read, so whether the queue read the record stage/) === true); + assert('⛔ RULE-AGE an-earlier-tree-excuses-only-the-record-stage-a-landing-with-no-record-is-still-a-BREACH', + await breach({ git: treeGit(OLD_RULE_TREE), prRows: [] }, /no `## Contract review` record on its head/) === true && + await breach({ git: treeGit(OLD_RULE_TREE), prRows: [record({ verdict: '**VERDICT: FAIL**' })] }, /does not read PASS/) === true && + await tierH({ git: treeGit(OLD_RULE_TREE), pull: { labels: ['security'] } }, /`security` label/) === true); + assert('⛔ RULE-AGE the-declaration-the-sweep-looks-for-is-this-files-own-and-a-quoted-copy-of-it-does-not-count', + LOW_RISK_RECORD_STAGE_DECLARED.test(readFileSync(scriptPath, 'utf8')) && scriptPath.replaceAll('\\', '/').endsWith(`/${ARM_RULE_PATH}`) && + armRecordStageBound(() => RULE_TREE, LANDED) === true && armRecordStageBound(() => OLD_RULE_TREE, LANDED) === false && armRecordStageBound(() => { throw new Error('x'); }, LANDED) === null && + (() => { const sent = []; armRecordStageBound((a) => { sent.push(a); return ''; }, LANDED); return JSON.stringify(sent) === JSON.stringify([['cat-file', '-p', `${LANDED}:${ARM_RULE_PATH}`]]); })()); + // #33729 N5: a git read the arm needed that failed, or a fork predicate not measured, is NOT MEASURED, never Tier H. const gitWith = (over) => (args) => (over(args) ?? runGit(args)); assert('⛔ #33729-N5-an-unread-diff-tree-status-is-NOT-MEASURED-not-tier-h', await unmeasured({ git: gitWith((a) => { if (a[0] === 'diff-tree') throw new Error('fatal: bad object'); }) }, /could not read `git diff-tree.*bad object.*so its Tier H cannot say how the queue read it/) === true); From e34225e64a034d6be6eac86fbced951620c6ec8c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 21:32:39 +0000 Subject: [PATCH 7/8] fix(pm): the low-risk arm reads the security label on every card a pull request names The arm's card conjunct read one card: the one the delivery relation answers with, the strongest evidence. A pull request that says `Fixes #A` and `Part of #B`, or `Fixes #A` on a branch named for card B, never had card B's `security` label or timeline read, so with the record line at `no` the arm read Tier S. `namedCardNumbers` (record-recognisers) lists every card a pull request names: closing-keyword targets, `Part of` targets, `Refs` targets and the card its branch is named for. `readCardLabels` reads the first card as before and every other one under `others`; the conjunct judges each, and a reading that does not say it read the others is a reason. More than eight other cards is Tier H with nothing more read. The queue guard, the relay, `--pr` and the post-merge sweep all go through the one reader; the sweep rebuilds each card as it stood at the landing, reads an unread card as NOT MEASURED and an over-limit landing as a stage BREACH. The record's `Security-touching:` line: a code span that holds the key (the spelling prose uses to mention the line) is unreadable; only the value may sit in a span. The template legend says so, and tells the seat to confirm a `yes` with the reviewer before labelling. Pins added for the sweep's two NOT MEASURED stage reads and for an arm entry an authorized enqueue or an approval cleared at the queue. Claude-Session: https://claude.ai/code/session_01ADHkmR2U8dFkRvc5DvUz1W Co-authored-by: Claude --- scripts/pm/check-governed-merges.mjs | 181 +++++++++++++++---- scripts/pm/check-governed-queue-guard.mjs | 207 ++++++++++++++++++---- scripts/pm/check-half-states.mjs | 27 ++- scripts/pm/fleet-write/execute.mjs | 31 +++- scripts/pm/record-recognisers.mjs | 54 +++++- 5 files changed, 408 insertions(+), 92 deletions(-) diff --git a/scripts/pm/check-governed-merges.mjs b/scripts/pm/check-governed-merges.mjs index 569427df4e1..0b0d6105553 100644 --- a/scripts/pm/check-governed-merges.mjs +++ b/scripts/pm/check-governed-merges.mjs @@ -515,9 +515,9 @@ * `securityTouching`, the fleet's one record reader) — the line absent, * unreadable, doubled, quoted, fenced, `yes`, or the record absent, unsigned, * unread or carried over a hop that moved catalog text is H; - * - and the CARD the pull request delivers was read and neither carries the + * - and EVERY card the pull request names was read and neither carries the * `security` label nor ever had it removed (its labels and its timeline) — - * a card that cannot be derived or read is H. + * no derivable card, or a named card that cannot be read, is H. * * The record stage is a SECOND read (`recordStage`): a reading that hands none * in is Tier H — `pending` when every condition above holds, and then the @@ -1196,10 +1196,13 @@ const SELF_TEST_BATTERIES = Object.freeze({ 'the per-row repository scope (ruled B2, 2026-10-13)': 20, 'the nested `ui/` workspace rows, on the register (#25712)': 16, '⭐ the workflows split: Tier H by path or by C2 trigger, else Tier S (ruling record 6722205630)': 75, - // 74 → 95 with the arm's record stage: sixteen pins on the two conjuncts and the stage's three states, five on `--pr`. - '⚖️ the low-risk skills arm: skills wording on Clause-② no lands Tier S, everything else stays H (#33501)': 95, - // 51 → 66 with the record stage as the sweep reads it at the landing: ten pins, and five on which landings it binds. - '⚖️ #33603: the sweep lists a low-risk arm landing APART and judges it on a same-head at-tier PASS record': 66, + // 74 → 95 with the arm's record stage: sixteen pins on the two conjuncts and the stage's three states, five on `--pr`; + // 95 → 100 with every other card the pull names (`others`): labelled, unread, not said to be read, each its own + // reason, and one on `--pr`. + '⚖️ the low-risk skills arm: skills wording on Clause-② no lands Tier S, everything else stays H (#33501)': 100, + // 51 → 66 with the record stage as the sweep reads it at the landing: ten pins, and five on which landings it binds; + // 66 → 71 with the other cards as they stood at the landing (four pins) and the stage's two NOT MEASURED reads. + '⚖️ #33603: the sweep lists a low-risk arm landing APART and judges it on a same-head at-tier PASS record': 71, '⭐ the weekly audit card: every reading the job files on, both ways (#33814)': 54, '⚖️ #33539: the ADR leg of the low-risk arm — an add-only note lands Tier S, any other ADR change stays H': 52, }); @@ -2721,7 +2724,7 @@ export function lowRiskChangesetReasons(file) { * - the head lives in the base repository (no fork); * - the RECORD STAGE, the two conjuncts read off the review rather than the pull (`lowRiskRecordStageReasons`): * the contract-review record on this head carries one bare `Security-touching: no` line - * (`reading.record`), and the card the PR delivers carries no `security` label, now or + * (`reading.record`), and no card the PR names carries a `security` label, now or * removed (`reading.cardLabels`). * ⛔ Fail closed: no reading, or one not measured, is Tier H with its reason. * @@ -2837,7 +2840,7 @@ export function lowRiskArmVerdict(matched, repo, reading = null) { const fork = reading.fork; if (!fork || fork.measured !== true) reasons.push('its head repository was not read, so a fork cannot be ruled out'); else if (fork.isFork === true) reasons.push(`its head lives in a fork (${fork.headRepo ?? 'a deleted repository'})`); - // ── the RECORD STAGE, last: the review's own statement and the card's labels ── + // ── the RECORD STAGE, last: the review's own statement and the labels of the cards it names ── // Judged whenever a reading of it was handed in. With none handed in it is consulted only when every // pull-read conjunct above holds, and then it is the one reason left: Tier H until the caller reads it. const handed = reading.record != null || reading.cardLabels != null; @@ -2879,11 +2882,12 @@ export const LOW_RISK_RECORD_STAGE_PENDING_REASON = * carried over a hop that moved catalog text, or whose line is missing, unreadable or `yes`, is * each a reason. * - * `cardLabels` is the reading of the card the pull request delivers: - * `{ measured: true, card, labels: string[], timeline: { measured, reason, events } }` + * `cardLabels` is the reading of the cards the pull request names — the one whose thread may carry + * its record on top, every other under `others`, each `{ measured, reason, card, labels, timeline }`: + * `{ measured: true, card, labels: string[], timeline: { measured, reason, events }, others: { measured, reason, cards } }` * or `{ measured: false, reason }` — no derivable card included, since a label on a card nobody - * could name cannot be ruled out. The conjunct holds only when the labels were read and none is - * `security`, and the card's timeline was read and never removed one: the PR's own rule, on the card. + * could name cannot be ruled out. The conjunct holds only when each card's labels were read and none is + * `security`, and its timeline was read and never removed one: the PR's own rule, on every card it names. */ export function lowRiskRecordStageReasons(record, cardLabels) { return [...lowRiskRecordLineReasons(record), ...lowRiskCardLabelReasons(cardLabels)]; @@ -2910,17 +2914,37 @@ function lowRiskRecordLineReasons(record) { return reasons; } -/** The record stage's second conjunct: the card the pull request delivers never carried `security`. Pure. */ +/** What ONE card's reading says against the arm: it carries `security`, had it removed, or its timeline is unread. Pure. */ +function cardLabelFacts(reading, card) { + const reasons = []; + if (reading.labels.some((l) => String(l ?? '').toLowerCase() === 'security')) reasons.push(`${card} carries the \`security\` label`); + const timeline = reading.timeline; + if (!timeline || timeline.measured !== true || !Array.isArray(timeline.events)) reasons.push(`the timeline of ${card} was not read (${timeline?.reason ?? 'no reading'}), so a removed \`security\` label cannot be ruled out`); + else if (timeline.events.some((e) => e?.event === 'unlabeled' && String(e?.label?.name ?? '').toLowerCase() === 'security')) reasons.push(`the timeline of ${card} shows the \`security\` label removed`); + return reasons; +} + +/** + * The record stage's second conjunct: NO card the pull request names ever carried `security` — the card + * whose thread may hold its record (the top of the reading) and every other card it names (`others`: a + * `Part of` beside a `Fixes`, a `Refs`, the card its branch is named for; `readCardLabels`, the queue + * guard). ⛔ A reading that does not say it read the others is a reason, never "it names no other". Pure. + */ function lowRiskCardLabelReasons(cardLabels) { if (!cardLabels || cardLabels.measured !== true || !Array.isArray(cardLabels.labels)) { return [`the labels of its card were not read (${cardLabels?.reason ?? 'no reading'}), so a \`security\` label on the card cannot be ruled out`]; } - const reasons = []; - const card = `its card #${cardLabels.card ?? '(no number)'}`; - if (cardLabels.labels.some((l) => String(l ?? '').toLowerCase() === 'security')) reasons.push(`${card} carries the \`security\` label`); - const timeline = cardLabels.timeline; - if (!timeline || timeline.measured !== true || !Array.isArray(timeline.events)) reasons.push(`the timeline of ${card} was not read (${timeline?.reason ?? 'no reading'}), so a removed \`security\` label cannot be ruled out`); - else if (timeline.events.some((e) => e?.event === 'unlabeled' && String(e?.label?.name ?? '').toLowerCase() === 'security')) reasons.push(`the timeline of ${card} shows the \`security\` label removed`); + const reasons = cardLabelFacts(cardLabels, `its card #${cardLabels.card ?? '(no number)'}`); + const others = cardLabels.others; + if (!others || others.measured !== true || !Array.isArray(others.cards)) { + reasons.push(`the other cards it names were not read (${others?.reason ?? 'no reading'}), so a \`security\` label on one of them cannot be ruled out`); + return reasons; + } + for (const other of others.cards) { + const card = `card #${other?.card ?? '(no number)'}, which it also names,`; + if (!other || other.measured !== true || !Array.isArray(other.labels)) reasons.push(`the labels of ${card} were not read (${other?.reason ?? 'no reading'}), so a \`security\` label on it cannot be ruled out`); + else reasons.push(...cardLabelFacts(other, card)); + } return reasons; } @@ -2949,7 +2973,7 @@ export function renderLowRiskLines(matched) { ); } if (v.tier === GOVERNED_TIER_S) { - return ` ⚖️ low-risk skills arm (${LOW_RISK_ARM_RULING}): Tier S — modified skill files, add-only ADR notes and prose only, one bare \`Clause-②: no\` and \`Metadata-protocol: none\`, clean changesets, no \`security\` label ever on the PR or its card and no catalog path named for it, no fork, and a record on this head reading \`${LOW_RISK_RECORD_LINE}\`.\n`; + return ` ⚖️ low-risk skills arm (${LOW_RISK_ARM_RULING}): Tier S — modified skill files, add-only ADR notes and prose only, one bare \`Clause-②: no\` and \`Metadata-protocol: none\`, clean changesets, no \`security\` label ever on the PR or a card it names and no catalog path named for it, no fork, and a record on this head reading \`${LOW_RISK_RECORD_LINE}\`.\n`; } return ` ⚖️ low-risk skills arm (${LOW_RISK_ARM_RULING}): Tier H —\n${v.reasons.map((r) => ` - ${r}\n`).join('')}`; } @@ -4927,7 +4951,7 @@ export function pullSizeFrom(head) { export const ARM_READER_SOURCE = './check-governed-queue-guard.mjs'; /** The guard exports the arm leg reads with. A missing one is NOT MEASURED, never a second parser here. */ -export const ARM_READER_EXPORTS = Object.freeze(['decomposeGovernedWork', 'readLowRiskTier', 'landsOnLowRiskArm', 'recordAuthorTrusted', 'ignoredAuthorLines', 'authorizedApprovalVerdict', 'enqueuerFromTimeline', 'authorizedEnqueueVerdict', 'loadRecordRecognisers', 'recordVerdict', 'lowRiskRecordVerdict', 'lowRiskRecordStagePending', 'lowRiskRecordStage', 'readCardLabels', 'readLowRiskRecordStage', 'makePullReader', 'makeReviewReader', 'makeCommentReader', 'makeTimelineReader', 'makeLabelReader']); +export const ARM_READER_EXPORTS = Object.freeze(['decomposeGovernedWork', 'readLowRiskTier', 'landsOnLowRiskArm', 'recordAuthorTrusted', 'ignoredAuthorLines', 'authorizedApprovalVerdict', 'enqueuerFromTimeline', 'authorizedEnqueueVerdict', 'loadRecordRecognisers', 'recordVerdict', 'lowRiskRecordVerdict', 'lowRiskRecordStagePending', 'lowRiskRecordStage', 'readCardLabels', 'namedCardsOf', 'readLowRiskRecordStage', 'makePullReader', 'makeReviewReader', 'makeCommentReader', 'makeTimelineReader', 'makeLabelReader']); /** Load the guard's readers and the record recognisers once per run. Never throws: a failed load is the reason. */ export async function loadArmReaders(load = (specifier) => import(specifier)) { @@ -4966,8 +4990,8 @@ export async function loadArmReaders(load = (specifier) => import(specifier)) { * The arm's RECORD STAGE is read as the queue reads it, SECOND and only for an entry nothing else cleared: the first * arm read leaves it pending (`lowRiskRecordStagePending`) when every pull-read condition holds, and a first read * that is not pending is Tier H on a pull-read reason. Past the approval and enqueue legs, a record that stands and - * reads PASS must also carry the arm's line and the card must be free of the `security` label AS THEY STOOD AT THE - * LANDING: the line off the same as-landed rows (`lowRiskRecordStage`), the card's labels rebuilt from its timeline + * reads PASS must also carry the arm's line and every card it names be free of the `security` label AS THEY STOOD AT + * THE LANDING: the line off the same as-landed rows (`lowRiskRecordStage`), each card's labels rebuilt from its timeline * (`cardLabelsAsLanded`; `fetchers.fetchLabels` reads them, absent ⇒ `not-measured`). A stage that then reads Tier H * is a `breach` flagged `stage: true` — the queue would have refused that landing — and a stage that could not be * read is `not-measured`, ⛔ never `tier-h` and never a stand-in. The stage is read only for a landing whose own tree @@ -5096,14 +5120,25 @@ export async function readArmLanding(entry, { paths, repo, readers, fetchers, ru if (bound === null) return unmeasured(`its landed tree's \`${ARM_RULE_PATH}\` could not be read, so whether the queue read the record stage for it is not known`); if (bound === false) return { state: 'pass', headSha, record: found, stageBound: false, ...(ignored.length > 0 ? { ignored } : {}) }; // ⭐ The arm's record stage, as the queue read it: the line off the rows that existed, unedited, at the landing, - // and the card's labels as they stood then. ⛔ Anything unread is NOT MEASURED — never a stand-in, never `no`. + // and the labels of every card it names as they stood then. ⛔ Anything unread is NOT MEASURED — never a stand-in, never `no`. const stage = guard.lowRiskRecordStage({ pair, recognisers }); if (stage.measured !== true) return unmeasured(`its record's \`${LOW_RISK_RECORD_LINE.split(':')[0]}:\` line could not be read (${stage.reason})`); - const carded = await guard.readCardLabels({ card, fetchLabels: fetchers.fetchLabels, fetchTimeline: fetchers.fetchTimeline }); + const carded = await guard.readCardLabels({ card, named: guard.namedCardsOf(recognisers, head), fetchLabels: fetchers.fetchLabels, fetchTimeline: fetchers.fetchTimeline }); const named = card.card !== null && card.card !== undefined; if (named && (carded.reading.measured !== true || carded.reading.timeline?.measured !== true)) { return unmeasured(`the labels of its card #${card.card} could not be read as they stood at the landing (${carded.reading.reason ?? carded.reading.timeline?.reason ?? 'no reading'})`); } + // Every other card the pull names is read the same way: one that was not read, or whose timeline was not, + // cannot be rebuilt as it stood at the landing — NOT MEASURED, never a BREACH on what it shows today. + // ⛔ More cards than the leg reads (`overLimit`) is no failed read: the queue counted the same names and + // refused the landing, so the conjunct below judges it — a stage BREACH. + const others = named ? carded.reading.others : null; + if (named && (!others || others.measured !== true || !Array.isArray(others.cards))) { + if (others?.overLimit !== true) return unmeasured(`the other cards it names could not be read as they stood at the landing (${others?.reason ?? 'no reading'})`); + } else if (named) { + const unread = others.cards.find((o) => o?.measured !== true || o?.timeline?.measured !== true); + if (unread) return unmeasured(`the labels of card #${unread?.card ?? '(no number)'}, which it also names, could not be read as they stood at the landing (${unread?.reason ?? unread?.timeline?.reason ?? 'no reading'})`); + } const cardLabels = named ? cardLabelsAsLanded(carded.reading, landed) : carded.reading; guard.readLowRiskTier(work, repo, head, { timeline: { measured: true, reason: null, events }, runGit: armGit, record: stage, cardLabels }); if (guard.landsOnLowRiskArm(work)) return { state: 'pass', headSha, record: found, ...(ignored.length > 0 ? { ignored } : {}) }; @@ -5170,9 +5205,18 @@ export function armRecordStageBound(runGit, sha) { * landing reads as removed), and the newest of them says whether the card carried it at the landing; * - with no such event before the landing, the card carried it then only if it carries it now and no `labeled` * event at or after the landing explains that — a label with no event behind it is read as already there. - * An event with no readable time is read as before the landing: toward BREACH, never toward clean. Pure. + * An event with no readable time is read as before the landing: toward BREACH, never toward clean. + * Every other card the pull names (`others`) is rebuilt by the same rule. Pure. */ export function cardLabelsAsLanded(reading, landed) { + const first = oneCardAsLanded(reading, landed); + const others = reading?.others; + // Every other card the pull names is rebuilt the same way; an `others` that was not read stays as it is. + return others?.measured === true && Array.isArray(others.cards) ? { ...first, others: { ...others, cards: others.cards.map((o) => (o?.measured === true ? oneCardAsLanded(o, landed) : o)) } } : first; +} + +/** One card's reading as it stood at the landing — `cardLabelsAsLanded`'s rule, for the first card and each other. Pure. */ +function oneCardAsLanded(reading, landed) { const events = Array.isArray(reading?.timeline?.events) ? reading.timeline.events : []; const isSecurity = (e) => (e?.event === 'labeled' || e?.event === 'unlabeled') && String(e?.label?.name ?? '').toLowerCase() === 'security'; const after = (e) => Date.parse(e?.created_at ?? '') >= landed; @@ -7314,7 +7358,8 @@ async function selfTest() { // never carried `security`. Every reading below carries it, so a row that pins Tier S pins it on the whole // conjunction, and the record-stage rows further down each drop one piece. const stageRecord = (over = {}) => ({ measured: true, reason: null, located: 'found', where: 'PR', id: 9001, carried: null, securityTouching: { state: 'read', value: 'no' }, ...over }); - const stageCard = (over = {}) => ({ measured: true, reason: null, card: 1, labels: [], timeline: { measured: true, reason: null, events: [] }, ...over }); + // `others`: every OTHER card the pull names, each read like the first; none here unless a row says so. + const stageCard = (over = {}) => ({ measured: true, reason: null, card: 1, labels: [], timeline: { measured: true, reason: null, events: [] }, others: { measured: true, reason: null, cards: [] }, ...over }); const read = (paths, over = {}) => ({ measured: true, reason: null, paths, body: 'Fixes #1\n\nClause-②: no\nMetadata-protocol: none\n', labels: [], timeline: { measured: true, reason: null, events: [] }, @@ -7421,6 +7466,25 @@ async function selfTest() { cardH(stageCard({ labels: null }), /the labels of its card were not read \(no reading\)/) === true && cardH({}, /the labels of its card were not read/) === true && cardH(true, /the labels of its card were not read/) === true && cardH(stageCard({ card: 69, timeline: { measured: false, reason: 'HTTP 502', events: null } }), /^the timeline of its card #69 was not read \(HTTP 502\), so a removed `security` label cannot be ruled out$/) === true && cardH(stageCard({ timeline: null }), /the timeline of its card #1 was not read \(no reading\)/) === true && cardH(stageCard({ timeline: { measured: true, events: 'none' } }), /was not read/) === true); + // ── EVERY card the pull request names (`others`, read by the queue guard's `readCardLabels`): a `security` + // label on a card it merely names beside the one that carries its record keeps the arm at Tier H too. + const otherCard = (over = {}) => ({ measured: true, reason: null, card: 71, labels: [], timeline: { measured: true, reason: null, events: [] }, ...over }); + const withOthers = (cards) => stageCard({ card: 69, others: { measured: true, reason: null, cards } }); + assert('⛔ NAMED-CARDS a-security-label-now-or-removed-on-ANOTHER-card-the-pull-names-is-Tier-H-and-the-reason-names-that-card', + cardH(withOthers([otherCard({ labels: ['docs', 'Security'] })]), /^card #71, which it also names, carries the `security` label$/) === true && + cardH(withOthers([otherCard(), otherCard({ card: 72, timeline: { measured: true, reason: null, events: [{ event: 'unlabeled', label: { name: 'SECURITY' } }] } })]), /^the timeline of card #72, which it also names, shows the `security` label removed$/) === true && + stageTier({ cardLabels: withOthers([otherCard({ labels: ['docs'] }), otherCard({ card: 72 })]) }) === GOVERNED_TIER_S); + assert('⛔ NAMED-CARDS another-card-whose-labels-or-timeline-were-not-read-is-Tier-H', + cardH(withOthers([{ measured: false, reason: "card #71's labels could not be read (HTTP 502)", card: 71 }]), /^the labels of card #71, which it also names, were not read \(card #71's labels could not be read \(HTTP 502\)\), so a `security` label on it cannot be ruled out$/) === true && + cardH(withOthers([otherCard({ timeline: { measured: false, reason: 'HTTP 403', events: null } })]), /^the timeline of card #71, which it also names, was not read \(HTTP 403\), so a removed `security` label cannot be ruled out$/) === true && + cardH(withOthers([null]), /^the labels of card #\(no number\), which it also names, were not read \(no reading\)/) === true && cardH(withOthers([otherCard({ labels: 'security' })]), /the labels of card #71, which it also names, were not read/) === true); + assert('⛔ NAMED-CARDS a-reading-that-does-not-say-it-read-the-other-cards-is-Tier-H-never-read-as-none-named', + cardH(stageCard({ others: undefined }), /^the other cards it names were not read \(no reading\), so a `security` label on one of them cannot be ruled out$/) === true && + cardH(stageCard({ others: { measured: false, reason: 'it names 9 more cards (#71, #72, #73, …), over the 8 this leg reads', cards: null } }), /^the other cards it names were not read \(it names 9 more cards \(#71, #72, #73, …\), over the 8 this leg reads\), so/) === true && + [{ measured: true, reason: null, cards: 'none' }, { measured: 'true', cards: [] }, { cards: [] }, [], true, null].every((others) => cardH(stageCard({ others }), /the other cards it names were not read/) === true)); + assert('⛔ NAMED-CARDS each-card-prints-its-own-reason-the-first-card-and-every-other', + (() => { const why = stageWhy({ cardLabels: stageCard({ card: 69, labels: ['security'], others: { measured: true, reason: null, cards: [otherCard({ labels: ['security'] }), otherCard({ card: 72, labels: ['security'] })] } }) }); + return why === 'its card #69 carries the `security` label | card #71, which it also names, carries the `security` label | card #72, which it also names, carries the `security` label' ? true : why; })() === true); // ⛔ PENDING: every pull-read condition holds and no record stage was handed in. Tier H on ONE reason, and the // caller (the queue leg, the relay, `--pr`, the sweep) reads the stage and asks again. Never Tier S. assert('⛔ RECORD-STAGE a-reading-with-no-record-stage-handed-in-is-Tier-H-PENDING-on-one-reason', @@ -7450,7 +7514,7 @@ async function selfTest() { stageTier({ record: stageRecord({ securityTouching: line(`${LOW_RISK_RECORD_LINE}\n${LOW_RISK_RECORD_LINE}`) }) }) === GOVERNED_TIER_H && stageTier({ record: stageRecord({ securityTouching: line(`> ${LOW_RISK_RECORD_LINE}`) }) }) === GOVERNED_TIER_H, JSON.stringify(line(LOW_RISK_RECORD_LINE))); } - assert('the-Tier-S-words-name-the-record-line-and-the-card', (() => { const t = renderTestVerdict(testVerdict([SK, CS], { repo: REPO, lowRisk: read([SK, CS]) })); return t.includes(`a record on this head reading \`${LOW_RISK_RECORD_LINE}\``) && /no `security` label ever on the PR or its card/.test(t); })()); + assert('the-Tier-S-words-name-the-record-line-and-the-card', (() => { const t = renderTestVerdict(testVerdict([SK, CS], { repo: REPO, lowRisk: read([SK, CS]) })); return t.includes(`a record on this head reading \`${LOW_RISK_RECORD_LINE}\``) && /no `security` label ever on the PR or a card it names/.test(t); })()); // The H words name every reason; `--pr` reads the arm off the SAME pull object and file walk. assert('the-H-words-list-each-reason', (() => { const t = renderTestVerdict(testVerdict([SK, 'packages/core/src/x.ts'], { repo: REPO, lowRisk: read([SK, 'packages/core/src/x.ts'], { labels: ['security'] }) })); return /low-risk skills arm .*Tier H/.test(t) && /packages\/core/.test(t) && /`security` label/.test(t) && /landing tier: H/.test(t); })()); @@ -7488,12 +7552,12 @@ async function selfTest() { }); const calls = []; let loads = 0; - const stagePr = ({ rows = [review()], cardRows = [], labels = [], events = [], body = 'Fixes #69\n\nClause-②: no\nMetadata-protocol: none', rd = armReaders, reading = withCs(walked.lowRisk), throws = null, fetchers = undefined } = {}) => pullRecordStage({ + const stagePr = ({ rows = [review()], cardRows = [], labels = [], labelsBy = {}, events = [], body = 'Fixes #69\n\nClause-②: no\nMetadata-protocol: none', rd = armReaders, reading = withCs(walked.lowRisk), throws = null, fetchers = undefined } = {}) => pullRecordStage({ lowRisk: reading, paths: walked.paths, repo: REPO, pullHead: { number: 2, body, head: { ref: 'claude/project-thread-x' } }, derivation: { pull: 2, headSha: PRHEAD, baseSha: null }, readers: () => { loads += 1; return rd; }, fetchers: fetchers !== undefined ? fetchers : { fetchComments: async (n) => { calls.push(`comments ${n}`); if (throws === 'comments') throw new Error('HTTP 502'); return n === 2 ? rows : n === 69 ? cardRows : []; }, - fetchLabels: async (n) => { calls.push(`labels ${n}`); if (throws === 'labels') throw new Error('HTTP 502'); return labels; }, + fetchLabels: async (n) => { calls.push(`labels ${n}`); if (throws === 'labels') throw new Error('HTTP 502'); return labelsBy[n] ?? labels; }, fetchTimeline: async (n) => { calls.push(`timeline ${n}`); if (throws === 'timeline') throw new Error('HTTP 502'); return events; }, }, }); @@ -7515,6 +7579,13 @@ async function selfTest() { await prH({ labels: ['docs', 'security'] }, /^its card #69 carries the `security` label$/) === true && await prH({ events: [{ event: 'unlabeled', label: { name: 'security' } }] }, /^the timeline of its card #69 shows the `security` label removed$/) === true && await prH({ body: 'Clause-②: no\nMetadata-protocol: none' }, /^the labels of its card were not read \(no card could be derived for it/) === true); + assert('⛔ --pr-NAMED-CARDS a-security-label-on-ANOTHER-card-the-PR-names-reads-Tier-H-with-both-cards-read-and-clears-when-that-card-is-clean', await (async () => { + const TWO = 'Fixes #69\n\nPart of #71\n\nClause-②: no\nMetadata-protocol: none'; + calls.length = 0; + const labelled = await prH({ body: TWO, labelsBy: { 71: ['docs', 'security'] } }, /^card #71, which it also names, carries the `security` label$/); + const read = calls.join(); + return labelled === true && read === 'comments 2,comments 69,labels 69,timeline 69,labels 71,timeline 71' && await prTier({ body: TWO }) === GOVERNED_TIER_S ? true : `${labelled} ${read}`; + })() === true); assert('⛔ --pr-RECORD-STAGE readers-that-did-not-load-or-any-read-that-threw-is-NOT-MEASURED-so-Tier-H', await prH({ rd: { available: false, reason: 'no guard' } }, /its contract-review record was not read \(no guard\).*labels of its card were not read \(not read: no guard\)/) === true && await prH({ rd: { ...armReaders, recognisers: { available: false, reason: 'recognisers did not load' } } }, /was not read \(recognisers did not load\)/) === true && @@ -10369,7 +10440,7 @@ async function selfTest() { catalogFiles: { measured: true, reason: null, files: catalog }, // The arm's record stage, read and favourable (the skills battery pins each piece of it). record: { measured: true, reason: null, located: 'found', where: 'PR', id: 9001, carried: null, securityTouching: { state: 'read', value: 'no' } }, - cardLabels: { measured: true, reason: null, card: 1, labels: [], timeline: { measured: true, reason: null, events: [] } }, + cardLabels: { measured: true, reason: null, card: 1, labels: [], timeline: { measured: true, reason: null, events: [] }, others: { measured: true, reason: null, cards: [] } }, ...over, }); const tier = (paths, reading, repo = REPO) => governedTierFor(paths, repo, GOVERNED_SURFACES, null, reading); @@ -10583,15 +10654,16 @@ async function selfTest() { const entryOf = (paths = [SK, CS], size = null) => classifyCommit({ sha: LANDED, date: '2026-11-15T04:30:00Z', subject: 'docs(skills): wording (#70)' }, paths, OS, size); const LANDING = { mergedAt: MERGED_AT, mergeCommitSha: LANDED }; // Card #69 as the label reader and the timeline reader answer it NOW: `cardLabels` its labels, `cardEvents` its - // timeline (`labelReader: false` hands the leg no label reader at all). - const run = async ({ prRows = [record()], cardRows = [], pull = {}, throws = null, paths = [SK, CS], size = null, rd = readers, attribution = LANDING, reviews = [], events = [], git = runGit, cardLabels = [], cardEvents = [], labelReader = true, seen = null } = {}) => readArmLanding(entryOf(paths, size), { + // timeline (`labelReader: false` hands the leg no label reader at all). Another card the pull names answers + // `cardLabelsBy[n]` and `cardEventsBy[n]` (`'throw'` throws), else no label and no event. + const run = async ({ prRows = [record()], cardRows = [], pull = {}, throws = null, paths = [SK, CS], size = null, rd = readers, attribution = LANDING, reviews = [], events = [], git = runGit, cardLabels = [], cardEvents = [], cardLabelsBy = {}, cardEventsBy = {}, labelReader = true, seen = null } = {}) => readArmLanding(entryOf(paths, size), { paths, repo: 'objectstack', readers: rd, runGit: git, attribution, fetchers: { fetchPull: async () => { if (throws === 'pull') throw new Error('HTTP 502'); return { sha: HEAD, body: BODY, labels: [], fork: { measured: true, isFork: false, headRepo: 'o/r', baseRepo: 'o/r' }, headRef: 'claude/project-thread-x', ...pull }; }, fetchReviews: async () => { if (throws === 'reviews') throw new Error('HTTP 502'); return reviews; }, - fetchTimeline: async (n) => { if (throws === 'timeline' || (throws === 'card-timeline' && n === 69)) throw new Error('HTTP 502'); return n === 69 ? cardEvents : events; }, + fetchTimeline: async (n) => { if (throws === 'timeline' || (throws === 'card-timeline' && n === 69) || cardEventsBy[n] === 'throw') throw new Error('HTTP 502'); return n === 69 ? cardEvents : n === 70 ? events : (cardEventsBy[n] ?? []); }, fetchComments: async (n) => { if (throws === 'comments') throw new Error('HTTP 502'); return n === 70 ? prRows : n === 69 ? cardRows : []; }, - ...(labelReader ? { fetchLabels: async (n) => { seen?.push(n); if (throws === 'labels') throw new Error('HTTP 502'); return cardLabels; } } : {}), + ...(labelReader ? { fetchLabels: async (n) => { seen?.push(n); if (throws === 'labels' || cardLabelsBy[n] === 'throw') throw new Error('HTTP 502'); return n === 69 ? cardLabels : (cardLabelsBy[n] ?? []); } } : {}), }, }); @@ -10679,6 +10751,45 @@ async function selfTest() { await unmeasured({ throws: 'labels' }, /the labels of its card #69 could not be read as they stood at the landing \(card #69's labels could not be read \(HTTP 502\)\)/) === true && await unmeasured({ throws: 'card-timeline' }, /the labels of its card #69 could not be read as they stood at the landing \(HTTP 502\)/) === true && await unmeasured({ labelReader: false }, /no label reader was supplied to this leg/) === true); + // Every OTHER card the pull names is read as it stood at the landing too: a `Part of` beside the `Fixes`, the card + // the branch is named for, a `Refs` — the cards the delivery relation does not answer with. + const ALSO = { pull: { body: `${BODY}\nPart of #71\n` } }; + const alsoCarries = /^card #71, which it also names, carries the `security` label$/; + assert('⛔ NAMED-CARDS another-card-the-pull-names-carrying-security-AT-the-landing-is-a-stage-BREACH-that-names-it', + await stageBreach({ ...ALSO, cardLabelsBy: { 71: ['security'] } }, alsoCarries) === true && + await stageBreach({ pull: { headRef: 'claude/issue-71-x' }, cardLabelsBy: { 71: ['docs', 'Security'] } }, alsoCarries) === true && + await stageBreach({ pull: { body: `${BODY}\nRefs #71\n` }, cardEventsBy: { 71: [AT('labeled', '2026-11-15T03:00:00Z'), AT('unlabeled', '2026-11-15T06:00:00Z')] } }, alsoCarries) === true && + await stageBreach({ ...ALSO, cardEventsBy: { 71: [AT('labeled', '2026-11-15T03:00:00Z'), AT('unlabeled', '2026-11-15T03:30:00Z')] } }, /^the timeline of card #71, which it also names, shows the `security` label removed$/) === true); + assert('⭐ NAMED-CARDS both-cards-clean-is-PASS-with-both-read-and-a-label-put-on-the-other-card-AFTER-the-landing-is-not-the-landing', await (async () => { + const seen = []; + const clean = await run({ ...ALSO, seen }); + const after = await run({ ...ALSO, cardLabelsBy: { 71: ['security'] }, cardEventsBy: { 71: [AT('labeled', '2026-11-15T06:00:00Z')] } }); + const onAndOffAfter = await run({ ...ALSO, cardEventsBy: { 71: [AT('labeled', '2026-11-15T06:00:00Z'), AT('unlabeled', '2026-11-15T07:00:00Z')] } }); + return clean?.state === 'pass' && seen.join() === '69,71' && after?.state === 'pass' && onAndOffAfter?.state === 'pass' ? true : JSON.stringify([clean, seen, after, onAndOffAfter]); + })() === true); + assert('⛔ NAMED-CARDS another-card-that-could-not-be-read-as-it-stood-is-NOT-MEASURED-never-PASS-and-never-a-BREACH', + await unmeasured({ ...ALSO, cardLabelsBy: { 71: 'throw' } }, /^the labels of card #71, which it also names, could not be read as they stood at the landing \(card #71's labels could not be read \(HTTP 502\)\)$/) === true && + await unmeasured({ ...ALSO, cardLabelsBy: { 71: ['security'] }, cardEventsBy: { 71: 'throw' } }, /^the labels of card #71, which it also names, could not be read as they stood at the landing \(HTTP 502\)$/) === true && + await unmeasured({ ...ALSO, rd: { ...readers, recognisers: { ...readers.recognisers, namedCards: undefined } } }, /^the other cards it names could not be read as they stood at the landing \(the cards the pull request names were not listed for this leg\)$/) === true); + assert('⛔ NAMED-CARDS a-landing-that-names-more-cards-than-the-leg-reads-is-a-stage-BREACH-not-a-failed-read-and-reads-only-its-first-card', await (async () => { + const seen = []; + const over = await stageBreach({ seen, pull: { body: `${BODY}\n${Array.from({ length: 9 }, (_, i) => `Part of #${71 + i}`).join('\n')}\n` } }, /^the other cards it names were not read \(it names 9 more cards \(#71, #72, #73, …\), over the 8 this leg reads\), so a `security` label on one of them cannot be ruled out$/); + return over === true && seen.join() === '69' ? true : `${over} ${seen.join()}`; + })() === true); + // ⛔ The two reads the stage itself can lose are NOT MEASURED, never a BREACH and never a PASS: a line the guard's + // stage reader could not read (defensive: a record that stands was read by the same recognisers, so only a guard + // that answers so reaches it), and a git read that answered the first arm read and failed the second. + assert('⛔ RECORD-STAGE a-stage-whose-line-could-not-be-read-and-a-git-read-that-failed-on-the-second-pass-are-NOT-MEASURED', await (async () => { + const seen = []; + const noReader = await run({ seen, rd: { ...readers, guard: { ...readers.guard, lowRiskRecordStage: () => ({ measured: false, reason: 'the record reader was not loaded' }) } }, cardLabels: ['security'] }); + // The rule-age read sits between the two arm reads, so a `diff-tree` after it is the second pass's. + const failsSecond = () => { let bound = false; return (a) => { if (a[0] === 'cat-file') bound = true; if (bound && a[0] === 'diff-tree') throw new Error('fatal: bad object'); return runGit(a); }; }; + const secondPass = await run({ git: failsSecond() }); + const secondPassNoLine = await run({ git: failsSecond(), prRows: [record({ line: null })] }); + return noReader?.state === 'not-measured' && noReader.reason === "its record's `Security-touching:` line could not be read (the record reader was not loaded)" && seen.length === 0 && + secondPass?.state === 'not-measured' && secondPass.reason === 'the low-risk arm could not re-read `git diff-tree -r` (fatal: bad object) for its record stage' && + secondPassNoLine?.state === 'not-measured' && secondPassNoLine.reason === secondPass.reason ? true : JSON.stringify([noReader, secondPass, secondPassNoLine, seen]); + })() === true); assert('the-record-stage-is-read-only-on-a-record-that-stands-past-the-approval-and-enqueue-legs', await (async () => { const seen = []; await run({ seen, reviews: [APPROVED('os-zhuang')] }); diff --git a/scripts/pm/check-governed-queue-guard.mjs b/scripts/pm/check-governed-queue-guard.mjs index 27fe7650ff4..1d0bc59aed1 100644 --- a/scripts/pm/check-governed-queue-guard.mjs +++ b/scripts/pm/check-governed-queue-guard.mjs @@ -360,9 +360,9 @@ * conditions all hold is still Tier H until the record leg below, on the * threads it reads anyway, hands the arm the review's `Security-touching:` line * (`lowRiskRecordStage`: the record on this head, read with the fleet's record - * reader) and the linked card's labels and timeline (`readCardLabels`), and + * reader) and the labels and timeline of EVERY card it names (`readCardLabels`), and * `readLowRiskTier` reads the tier again. A record that is absent, unreadable or - * says anything but `Security-touching: no`, a `security` label on the card now + * says anything but `Security-touching: no`, a `security` label on any such card now * or removed, or a card nobody could name, stays Tier H — and so does an entry * an approval or an authorized enqueue already cleared, whose stage is never * read. An entry the arm puts at Tier S clears on @@ -707,9 +707,13 @@ const SELF_TEST_BATTERIES = Object.freeze({ // the unreadable shapes, newest-governs, the author binding, unsigned and unread, the card thread) and the linked // card's `security` label (now, removed, unread, no card), the stage's cost, the unloaded recognisers, and the // three builders — eighteen pins; 72 → 74 with the thread walk and the whole-stage reader `--pr` and the relay share. - '⚖️ the low-risk skills arm at the queue: body, labels and every path, read off the pull this leg holds (#33501)': 74, - // Raised 12 → 13 with the arm's record stage on the ADR leg: a record without the line, a `security`-labelled card. - '⚖️ the ADR leg at the queue: an add-only note clears on its PASS record, any other ADR change is H (#33539)': 13, + // Raised 74 → 84 with every card the pull NAMES: `security` on the second card behind a `Part of`, a branch name + // and a `Refs`, their clean control, the first card beside a clean second, the second card unread, the limit, the + // reader's own walk, `namedCardsOf`, and the cleared entry that spends no stage read — ten pins. + '⚖️ the low-risk skills arm at the queue: body, labels and every path, read off the pull this leg holds (#33501)': 84, + // Raised 12 → 13 with the arm's record stage on the ADR leg: a record without the line, a `security`-labelled card; + // 13 → 14 with a second card the note names. + '⚖️ the ADR leg at the queue: an add-only note clears on its PASS record, any other ADR change is H (#33539)': 14, }); // DELETING an entry silences that battery's floor exactly as effectively as @@ -1030,6 +1034,8 @@ export async function loadRecordRecognisers(load = (specifier) => import(specifi const found = { locate: tier?.locateReviewOfRecord, 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, servedTierStands: tier?.servedTierStands, isModelIdentifierToken: tier?.isModelIdentifierToken, reviewFace: tier?.reviewFace, @@ -1042,7 +1048,7 @@ export async function loadRecordRecognisers(load = (specifier) => import(specifi trustedAuthors: recordTrustedAuthors(bot), }; const missing = [ - ...['locate', 'deliveredCard', 'servedTierStands', 'isModelIdentifierToken', 'reviewFace', 'reading'].filter((key) => typeof found[key] !== 'function'), + ...['locate', 'deliveredCard', 'namedCards', 'servedTierStands', 'isModelIdentifierToken', 'reviewFace', 'reading'].filter((key) => typeof found[key] !== 'function'), ...(found.trustedAuthors === null ? [`trustedAuthors (FLEET_BOT_LOGIN from ${RECOGNISER_SOURCES.author})`] : []), ...(Array.isArray(found.threads) && found.threads.length > 0 ? [] : ['threads']), ...(typeof found.location === 'string' && found.location.length > 0 ? [] : ['location']), @@ -2211,37 +2217,70 @@ export function lowRiskRecordStage({ pair, recognisers }) { } /** - * The arm's reading of the CARD the pull request delivers — the `cardLabels` half of its record stage: - * the card's label names (`fetchLabels`) and its timeline (`fetchTimeline`, where a removed `security` - * label sits). `card` is `deliveredCardNumber`'s answer. No derivable card, no label reader or a label - * read that threw is NOT MEASURED; a timeline that could not be read is carried unmeasured inside a - * measured reading — each a reason in the arm, so Tier H. Returns `{ reading, apiCalls }`. Never throws. + * How many cards BESIDE the one that carries its record a pull request may name and still be read on the arm. + * Each costs two reads in the merge group, so a body naming more is not read at all: Tier H. */ -export async function readCardLabels({ card, fetchLabels = null, fetchTimeline = null }) { +export const LOW_RISK_NAMED_CARD_LIMIT = 8; + +/** One card's label names and timeline, for `readCardLabels`. Returns `{ reading, apiCalls }`. Never throws. */ +async function readOneCardLabels(number, fetchLabels, fetchTimeline) { const why = (error) => String(error?.message ?? error).split('\n')[0]; - if (!card || card.card === null || card.card === undefined) { - return { reading: { measured: false, reason: `no card could be derived for it — ${card?.reason ?? 'no card reading'}` }, apiCalls: 0 }; - } - if (typeof fetchLabels !== 'function') return { reading: { measured: false, reason: 'no label reader was supplied to this leg' }, apiCalls: 0 }; let apiCalls = 1; let labels; try { - labels = await fetchLabels(card.card); + labels = await fetchLabels(number); } catch (error) { - return { reading: { measured: false, reason: `card #${card.card}'s labels could not be read (${why(error)})` }, apiCalls }; + return { reading: { measured: false, reason: `card #${number}'s labels could not be read (${why(error)})`, card: number }, apiCalls }; } - if (!Array.isArray(labels)) return { reading: { measured: false, reason: `card #${card.card}'s labels answered no list` }, apiCalls }; + if (!Array.isArray(labels)) return { reading: { measured: false, reason: `card #${number}'s labels answered no list`, card: number }, apiCalls }; let timeline = { measured: false, reason: 'no timeline reader was supplied to this leg', events: null }; if (typeof fetchTimeline === 'function') { apiCalls += 1; try { - const events = await fetchTimeline(card.card); + const events = await fetchTimeline(number); timeline = Array.isArray(events) ? { measured: true, reason: null, events } : { measured: false, reason: 'the timeline answered no list', events: null }; } catch (error) { timeline = { measured: false, reason: why(error), events: null }; } } - return { reading: { measured: true, reason: null, card: card.card, labels: labels.map((l) => String(l ?? '')), timeline }, apiCalls }; + return { reading: { measured: true, reason: null, card: number, labels: labels.map((l) => String(l ?? '')), timeline }, apiCalls }; +} + +/** + * The arm's reading of the CARDS the pull request names — the `cardLabels` half of its record stage: + * each card's label names (`fetchLabels`) and its timeline (`fetchTimeline`, where a removed `security` + * label sits). `card` is `deliveredCardNumber`'s answer, the ONE card whose thread may carry the record; + * `named` is `namedCardNumbers`' answer, EVERY card the pull names (a `Part of` beside a `Fixes`, a + * `Refs`, the card its branch is named for) — a `security` label on any of them keeps the arm at Tier H, + * so each is read, the first card at the top of the reading and the rest under `others`. + * No derivable card, no label reader or a label read that threw is NOT MEASURED; a timeline that could + * not be read is carried unmeasured inside a measured reading; `named` not handed in, or more than + * `LOW_RISK_NAMED_CARD_LIMIT` other cards (flagged `overLimit`: a fact of the pull, not a failed read), + * leaves `others` unmeasured with nothing read; one other card that could not be read is carried + * unmeasured in its place — each a reason in the arm, so Tier H. + * Returns `{ reading, apiCalls }`. Never throws. + */ +export async function readCardLabels({ card, named = null, fetchLabels = null, fetchTimeline = null }) { + if (!card || card.card === null || card.card === undefined) { + return { reading: { measured: false, reason: `no card could be derived for it — ${card?.reason ?? 'no card reading'}` }, apiCalls: 0 }; + } + if (typeof fetchLabels !== 'function') return { reading: { measured: false, reason: 'no label reader was supplied to this leg' }, apiCalls: 0 }; + const first = await readOneCardLabels(card.card, fetchLabels, fetchTimeline); + if (first.reading.measured !== true) return { reading: { measured: false, reason: first.reading.reason }, apiCalls: first.apiCalls }; + let apiCalls = first.apiCalls; + const withOthers = (others) => ({ reading: { ...first.reading, others }, apiCalls }); + if (!Array.isArray(named)) return withOthers({ measured: false, reason: 'the cards the pull request names were not listed for this leg', cards: null }); + const rest = [...new Set(named.map(Number))].filter((n) => Number.isInteger(n) && n > 0 && n !== Number(card.card)).sort((a, b) => a - b); + if (rest.length > LOW_RISK_NAMED_CARD_LIMIT) { + return withOthers({ measured: false, reason: `it names ${rest.length} more cards (${rest.slice(0, 3).map((n) => `#${n}`).join(', ')}, …), over the ${LOW_RISK_NAMED_CARD_LIMIT} this leg reads`, cards: null, overLimit: true }); + } + const cards = []; + for (const number of rest) { + const one = await readOneCardLabels(number, fetchLabels, fetchTimeline); + apiCalls += one.apiCalls; + cards.push(one.reading); + } + return withOthers({ measured: true, reason: null, cards }); } /** @@ -2282,14 +2321,26 @@ export async function readRecordThreads({ pair, recognisers, fetchComments }) { return { ignoredAuthors, unreadable: null, apiCalls }; } +/** + * Every card the pull names, as the arm's card conjunct reads them (`recognisers.namedCards`), or null when + * the recogniser set does not carry that reader or there is no pull row: `readCardLabels` reads null as + * NOT MEASURED, ⛔ never as "names no other card". Pure. + */ +export function namedCardsOf(recognisers, pull) { + if (typeof recognisers?.namedCards !== 'function' || !pull) return null; + const named = recognisers.namedCards(pull); + return Array.isArray(named) ? named : null; +} + /** * The arm's whole RECORD STAGE for one pull request, for a caller that holds no thread yet (`--pr` * and the relay; the queue leg reads the same pieces inline, beside its record leg): the card * `recognisers.deliveredCard` derives from the pull object, the threads (`readRecordThreads`), then - * `lowRiskRecordStage` and `readCardLabels`. `pull` is the object `deliveredCard` reads (`number`, - * `body`, `head.ref`); `runGit` and `baseRef` are what a carried record is re-tested with, and one - * absent refuses the carry. ⛔ Anything that did not load or did not read is NOT MEASURED — recognisers - * that did not load, no comment reader, a thread that threw — which the arm reads as Tier H. + * `lowRiskRecordStage` and `readCardLabels` over every card `recognisers.namedCards` lists. `pull` is + * the object both read (`number`, `body`, `head.ref`); `runGit` and `baseRef` are what a carried + * record is re-tested with, and one absent refuses the carry. ⛔ Anything that did not load or did + * not read is NOT MEASURED — recognisers that did not load, no comment reader, a thread that threw — + * which the arm reads as Tier H. * Returns `{ record, cardLabels, card, apiCalls }`. Never throws. */ export async function readLowRiskRecordStage({ pr, pull, headSha, paths, repo, runGit = null, baseRef = null, recognisers, fetchComments = null, fetchLabels = null, fetchTimeline = null }) { @@ -2309,7 +2360,7 @@ export async function readLowRiskRecordStage({ pr, pull, headSha, paths, repo, r ? await readRecordThreads({ pair, recognisers, fetchComments }) : { unreadable: 'no comment reader was supplied to this leg, so no thread was read', apiCalls: 0 }; const record = threads.unreadable !== null ? { measured: false, reason: threads.unreadable } : lowRiskRecordStage({ pair, recognisers }); - const labelled = await readCardLabels({ card, fetchLabels, fetchTimeline }); + const labelled = await readCardLabels({ card, named: namedCardsOf(recognisers, pull), fetchLabels, fetchTimeline }); return { record, cardLabels: labelled.reading, card, apiCalls: threads.apiCalls + labelled.apiCalls }; } @@ -2550,7 +2601,8 @@ export async function runGuard({ event, repo, rows, fetchReviews, fetchPull, fet if (pending) { // ⛔ A thread that could not be read is a record that was not read: NOT MEASURED, so Tier H. const stage = unreadable !== null ? { measured: false, reason: unreadable } : lowRiskRecordStage({ pair, recognisers }); - const labelled = await readCardLabels({ card, fetchLabels, fetchTimeline }); + // Every card the pull names, not only the one whose thread may carry the record. + const labelled = await readCardLabels({ card, named: namedCardsOf(recognisers, pull), fetchLabels, fetchTimeline }); apiCalls += labelled.apiCalls; readRecordStage(stage, labelled.reading); // Tier H on the record stage: the entry needs the maintainer, and the record leg is never consulted. @@ -3363,7 +3415,7 @@ export function makeTimelineReader({ apiUrl, slug, token, fetchImpl = fetch, per } /** - * The label NAMES on an issue — the CARD a low-risk arm pull request delivers, whose `security` label + * The label NAMES on an issue — a CARD a low-risk arm pull request names, whose `security` label * keeps that pull request at Tier H (`readCardLabels`). * * Scope, measured the way the two readers above were: `GET /repos/{o}/{r}/issues/{n}/labels` answers @@ -5425,6 +5477,9 @@ export async function selfTest() { // a list, `'throw'`, or `null` for no reader at all. cardLabels = [], cardTimeline = [], + // Per-card answers for a pull that names more than one card: `{ [number]: list | 'throw' }`, over the two above. + cardLabelsBy = {}, + cardTimelineBy = {}, } = {}) => { tierApiCalls = 0; tierThreadsRead = []; @@ -5435,8 +5490,8 @@ export async function selfTest() { rows: [{ ...row(pr, files, 'c'.repeat(40), `x (#${pr})`), ...(workflowDiff ? { workflowDiff } : {}) }, ...extraRows], fetchReviews: async () => { tierApiCalls += 1; return reviews; }, fetchPull: async () => { tierApiCalls += 1; if (headThrows) throw new Error('head unreadable'); return pull(head, { body: prBody, headRef: branch, labels, fork }); }, - ...(timeline === null ? {} : { fetchTimeline: async (n) => { if (n !== pr) tierApiCalls += 1; const read = n === pr ? timeline : cardTimeline; if (read === 'throw') throw new Error('HTTP 403'); return read; } }), - ...(cardLabels === null ? {} : { fetchLabels: async (n) => { tierApiCalls += 1; tierLabelsRead.push(n); if (cardLabels === 'throw') throw new Error('HTTP 403'); return cardLabels; } }), + ...(timeline === null ? {} : { fetchTimeline: async (n) => { if (n !== pr) tierApiCalls += 1; const read = n === pr ? timeline : (cardTimelineBy[n] ?? cardTimeline); if (read === 'throw') throw new Error('HTTP 403'); return read; } }), + ...(cardLabels === null ? {} : { fetchLabels: async (n) => { tierApiCalls += 1; tierLabelsRead.push(n); const read = cardLabelsBy[n] ?? cardLabels; if (read === 'throw') throw new Error('HTTP 403'); return read; } }), fetchComments: async (n) => { tierApiCalls += 1; tierThreadsRead.push(n); @@ -6345,7 +6400,7 @@ export async function selfTest() { const old = await tierRun({ ...arm, comments: [armRecord({ sha: REF_OLD.slice(0, 12) })] }); assert('⛔ a-record-on-an-OLDER-head-is-REFUSED-Tier-H-its-line-does-not-carry-forward', old.exitCode === EXIT_REFUSED_UNAPPROVED && old.entries[0].tier === TIER_H && old.entries[0].record === undefined && /no contract-review record names this head/.test(renderGuardVerdict(old))); - // ── the arm's RECORD STAGE: the record's `Security-touching:` line, and the `security` label on the linked card ── + // ── the arm's RECORD STAGE: the record's `Security-touching:` line, and the `security` label on a card it names ── const stage = (v) => v.entries[0].surfaces.find((x) => x.lowRiskVerdict)?.lowRiskVerdict; const stageH = (v, why) => v.exitCode === EXIT_REFUSED_UNAPPROVED && v.entries[0].tier === TIER_H && v.entries[0].record === undefined && stage(v).recordStage === 'read' && stage(v).reasons.length === 1 && why.test(stage(v).reasons[0]); assert('⭐ RECORD-LINE-CONTROL: the-passing-arm-PR-was-read-through-the-record-stage-its-record-says-Security-touching-no', stage(pass).recordStage === 'read' && stage(pass).tier === TIER_S && stage(pass).reasons.length === 0 && pass.entries[0].record.id === 900); @@ -6364,6 +6419,57 @@ export async function selfTest() { assert('⛔ CARD-LABEL: a-security-label-REMOVED-on-the-card-timeline-keeps-it-Tier-H', stageH(await tierRun({ ...arm, cardTimeline: [{ event: 'labeled', label: { name: 'security' } }, { event: 'unlabeled', label: { name: 'security' } }] }), new RegExp(`^the timeline of its card #${REF_CARD} shows the \`security\` label removed$`))); assert('⛔ CARD-LABEL: labels-that-threw-no-label-reader-or-a-card-timeline-that-threw-are-NOT-MEASURED-so-Tier-H', stageH(await tierRun({ ...arm, cardLabels: 'throw' }), /^the labels of its card were not read \(card #69's labels could not be read \(HTTP 403\)\)/) && stageH(await tierRun({ ...arm, cardLabels: null }), /^the labels of its card were not read \(no label reader was supplied to this leg\)/) && stageH(await tierRun({ ...arm, cardTimeline: 'throw' }), /^the timeline of its card #69 was not read \(HTTP 403\), so a removed `security` label cannot be ruled out$/)); assert('⛔ CARD-LABEL: a-PR-that-names-NO-card-cannot-rule-the-label-out-Tier-H-with-no-label-read', stageH(await tierRun({ ...arm, prBody: 'Clause-②: no\nMetadata-protocol: none\n', branch: 'wording' }), /^the labels of its card were not read \(no card could be derived for it — /) && tierLabelsRead.length === 0); + // ── EVERY card the pull request NAMES is read (`namedCardNumbers`), not only the one whose thread may carry its + // record: a `Part of` beside a `Fixes`, a `Refs`, the card the branch is named for — two cards at different + // strengths, where the delivery relation answers with the stronger one alone. + const ALSO = 71; + const alsoLabelled = { cardLabelsBy: { [ALSO]: ['tooling', 'Security'] } }; + const partOfTwo = { ...arm, prBody: `${LOW}\nPart of #${ALSO}\n` }; + const branchTwo = { ...arm, branch: `claude/issue-${ALSO}-x` }; + const refsTwo = { ...arm, prBody: `${LOW}\nRefs #${ALSO}\n` }; + const alsoCarries = new RegExp(`^card #${ALSO}, which it also names, carries the \`security\` label$`); + const bothRead = () => tierLabelsRead.join() === `${REF_CARD},${ALSO}`; + assert('⛔ NAMED-CARDS: Fixes-A-plus-Part-of-B-with-security-on-B-reads-Tier-H-naming-card-B', stageH(await tierRun({ ...partOfTwo, ...alsoLabelled }), alsoCarries) && bothRead(), tierLabelsRead.join()); + assert('⛔ NAMED-CARDS: Fixes-A-on-a-branch-named-for-B-with-security-on-B-reads-Tier-H-naming-card-B', stageH(await tierRun({ ...branchTwo, ...alsoLabelled }), alsoCarries) && bothRead(), tierLabelsRead.join()); + assert('⛔ NAMED-CARDS: Fixes-A-plus-Refs-B-with-security-on-B-reads-Tier-H-naming-card-B', stageH(await tierRun({ ...refsTwo, ...alsoLabelled }), alsoCarries) && bothRead(), tierLabelsRead.join()); + assert('⭐ NAMED-CARDS-CONTROL: the-same-three-pulls-with-BOTH-cards-clean-CLEAR-and-the-second-card-costs-two-more-reads', await (async () => { + const cleared = []; + for (const shape of [partOfTwo, branchTwo, refsTwo]) { + const v = await tierRun(shape); + // pull + reviews + PR thread + card thread + two cards' labels and timelines. + cleared.push(v.exitCode === EXIT_CLEAR && stage(v).tier === TIER_S && stage(v).reasons.length === 0 && bothRead() && tierApiCalls === 8 && tierThreadsRead.join() === `70,${REF_CARD}`); + } + return cleared.join() === 'true,true,true'; + })()); + assert('⛔ NAMED-CARDS: the-label-on-the-card-that-carries-the-record-still-reads-Tier-H-beside-a-clean-second-card', stageH(await tierRun({ ...partOfTwo, cardLabelsBy: { [REF_CARD]: ['security'] } }), new RegExp(`^its card #${REF_CARD} carries the \`security\` label$`)) && bothRead()); + assert('⛔ NAMED-CARDS: a-second-card-whose-labels-or-timeline-could-not-be-read-or-whose-timeline-shows-the-label-removed-is-Tier-H', + stageH(await tierRun({ ...partOfTwo, cardLabelsBy: { [ALSO]: 'throw' } }), /^the labels of card #71, which it also names, were not read \(card #71's labels could not be read \(HTTP 403\)\), so a `security` label on it cannot be ruled out$/) && + stageH(await tierRun({ ...branchTwo, cardTimelineBy: { [ALSO]: 'throw' } }), /^the timeline of card #71, which it also names, was not read \(HTTP 403\), so a removed `security` label cannot be ruled out$/) && + stageH(await tierRun({ ...refsTwo, cardTimelineBy: { [ALSO]: [{ event: 'labeled', label: { name: 'security' } }, { event: 'unlabeled', label: { name: 'Security' } }] } }), /^the timeline of card #71, which it also names, shows the `security` label removed$/)); + assert('⛔ NAMED-CARDS: a-pull-that-names-more-cards-than-the-leg-reads-is-Tier-H-with-only-its-first-card-read-and-one-fewer-clears', await (async () => { + const lines = Array.from({ length: LOW_RISK_NAMED_CARD_LIMIT + 1 }, (_, i) => `Part of #${ALSO + i}`); + const over = await tierRun({ ...arm, prBody: `${LOW}\n${lines.join('\n')}\n` }); + const overRead = tierLabelsRead.join(); + const atLimit = await tierRun({ ...arm, prBody: `${LOW}\n${lines.slice(1).join('\n')}\n` }); + return stageH(over, /^the other cards it names were not read \(it names 9 more cards \(#71, #72, #73, …\), over the 8 this leg reads\), so a `security` label on one of them cannot be ruled out$/) && overRead === String(REF_CARD) && + atLimit.exitCode === EXIT_CLEAR && tierLabelsRead.length === LOW_RISK_NAMED_CARD_LIMIT + 1 && tierLabelsRead[0] === REF_CARD; + })()); + // ⛔ An entry something else already cleared never reaches the stage: no thread and no label is read for it, and it + // stays Tier H — cleared by the human leg, never by the arm. An authorized ENQUEUE leaves it `pending` on the one + // reason that says nothing of the stage was read; an APPROVAL clears before the timeline is read at all, so the + // arm stops one conjunct earlier (`not-reached`) on the unread timeline. + assert('⛔ an-arm-entry-an-authorized-enqueue-or-an-approval-CLEARED-spends-no-stage-read-and-stays-Tier-H-on-the-reason-that-says-what-was-not-read', await (async () => { + const cleared = async (over) => { + const v = await tierRun({ ...partOfTwo, ...alsoLabelled, ...over }); + const read = stage(v); + return v.exitCode === EXIT_CLEAR && v.entries[0].tier === TIER_H && v.entries[0].record === undefined && read.reasons.length === 1 && + tierLabelsRead.length === 0 && tierThreadsRead.length === 0 && renderGuardVerdict(v).includes(`- ${read.reasons[0]}`) ? `${read.recordStage}: ${read.reasons[0]}` : `✗ ${JSON.stringify(read)}`; + }; + const enqueued = await cleared({ timeline: [added(GOVERNED_APPROVERS[0])] }); + const approved = await cleared({ reviews: [approvedAt(GOVERNED_APPROVERS[0], REF_HEAD)] }); + return enqueued === 'pending: its contract-review record and the labels of its card were not read, so neither a `Security-touching: no` line nor a card free of the `security` label is established' && + approved === 'not-reached: its timeline was not read (the timeline was not read), so a removed `security` label cannot be ruled out'; + })()); assert('the-record-stage-costs-one-label-read-and-one-card-timeline-read-and-only-where-the-pull-read-conditions-all-hold', await (async () => { await tierRun(arm); const clean = [tierApiCalls, tierLabelsRead.join(), tierThreadsRead.join()]; @@ -6388,13 +6494,39 @@ export async function selfTest() { })()); assert('readCardLabels-never-throws-and-counts-its-reads-a-card-nobody-could-name-reads-nothing', await (async () => { const none = await readCardLabels({ card: { card: null, reason: 'its body names no card' }, fetchLabels: async () => { throw new Error('must not be read'); } }); - const both = await readCardLabels({ card: { card: 69 }, fetchLabels: async () => ['a'], fetchTimeline: async () => [] }); - const noTimeline = await readCardLabels({ card: { card: 69 }, fetchLabels: async () => ['a'] }); - const notList = await readCardLabels({ card: { card: 69 }, fetchLabels: async () => ({}) }); + const both = await readCardLabels({ card: { card: 69 }, named: [69], fetchLabels: async () => ['a'], fetchTimeline: async () => [] }); + const noTimeline = await readCardLabels({ card: { card: 69 }, named: [69], fetchLabels: async () => ['a'] }); + const notList = await readCardLabels({ card: { card: 69 }, named: [69], fetchLabels: async () => ({}) }); + // ⛔ The cards the pull names were not handed in: the first card is read, `others` says it was not — never "none". + const unlisted = await readCardLabels({ card: { card: 69 }, fetchLabels: async () => ['a'], fetchTimeline: async () => [] }); return none.apiCalls === 0 && none.reading.measured === false && /its body names no card/.test(none.reading.reason) && - both.apiCalls === 2 && JSON.stringify(both.reading) === JSON.stringify({ measured: true, reason: null, card: 69, labels: ['a'], timeline: { measured: true, reason: null, events: [] } }) && + both.apiCalls === 2 && JSON.stringify(both.reading) === JSON.stringify({ measured: true, reason: null, card: 69, labels: ['a'], timeline: { measured: true, reason: null, events: [] }, others: { measured: true, reason: null, cards: [] } }) && noTimeline.apiCalls === 1 && noTimeline.reading.measured === true && noTimeline.reading.timeline.measured === false && - notList.reading.measured === false; + notList.reading.measured === false && notList.reading.others === undefined && + unlisted.apiCalls === 2 && unlisted.reading.measured === true && JSON.stringify(unlisted.reading.others) === JSON.stringify({ measured: false, reason: 'the cards the pull request names were not listed for this leg', cards: null }) && !('overLimit' in unlisted.reading.others); + })()); + assert('⛔ readCardLabels-reads-EVERY-named-card-once-in-ascending-order-after-the-first-and-carries-an-unread-one-in-its-place', await (async () => { + const read = []; + const labelsOf = { 69: ['a'], 70: ['security'], 72: 'throw' }; + const fetchLabels = async (n) => { read.push(`labels ${n}`); if (labelsOf[n] === 'throw') throw new Error('HTTP 502'); return labelsOf[n] ?? []; }; + const fetchTimeline = async (n) => { read.push(`timeline ${n}`); if (n === 71) throw new Error('HTTP 403'); return []; }; + const all = await readCardLabels({ card: { card: 70 }, named: [72, 69, 70, 71, 69, '71', 0, -3, 1.5, 'x'], fetchLabels, fetchTimeline }); + const others = all.reading.others; + const over = await readCardLabels({ card: { card: 1 }, named: Array.from({ length: LOW_RISK_NAMED_CARD_LIMIT + 2 }, (_, i) => i + 1), fetchLabels: async () => [], fetchTimeline: async () => [] }); + const atLimit = await readCardLabels({ card: { card: 1 }, named: Array.from({ length: LOW_RISK_NAMED_CARD_LIMIT + 1 }, (_, i) => i + 1), fetchLabels: async () => [], fetchTimeline: async () => [] }); + return read.join() === 'labels 70,timeline 70,labels 69,timeline 69,labels 71,timeline 71,labels 72' && all.apiCalls === 7 && + all.reading.card === 70 && all.reading.labels.join() === 'security' && others.measured === true && others.cards.map((c) => c.card).join() === '69,71,72' && + others.cards[0].measured === true && others.cards[0].labels.join() === 'a' && others.cards[0].timeline.measured === true && + others.cards[1].measured === true && others.cards[1].timeline.measured === false && others.cards[1].timeline.reason === 'HTTP 403' && + others.cards[2].measured === false && others.cards[2].reason === "card #72's labels could not be read (HTTP 502)" && + over.apiCalls === 2 && over.reading.others.measured === false && over.reading.others.cards === null && over.reading.others.overLimit === true && /^it names 9 more cards \(#2, #3, #4, …\), over the 8 this leg reads$/.test(over.reading.others.reason) && + atLimit.apiCalls === 2 * (LOW_RISK_NAMED_CARD_LIMIT + 1) && atLimit.reading.others.measured === true && atLimit.reading.others.cards.length === LOW_RISK_NAMED_CARD_LIMIT; + })()); + assert('namedCardsOf-lists-the-cards-through-the-recogniser-set-and-answers-null-never-an-empty-list-where-it-cannot', (() => { + const pull = { number: 70, body: 'Fixes #69\n\nPart of #71', head: { ref: 'claude/issue-73-x' } }; + return namedCardsOf(live, pull).join() === '69,71,73' && namedCardsOf(live, { number: 70, body: 'wording', head: { ref: 'wording' } }).join() === '' && + namedCardsOf(live, null) === null && namedCardsOf({ ...live, namedCards: undefined }, pull) === null && namedCardsOf({ available: false, reason: 'x' }, pull) === null && + namedCardsOf({ ...live, namedCards: () => 'none' }, pull) === null; })()); assert('makeLabelReader-reads-the-label-NAMES-off-the-issue-labels-route-and-throws-on-a-refusal', await (async () => { const urls = []; @@ -6442,7 +6574,7 @@ export async function selfTest() { const unreadPull = await stageOf({ pull: null }); return order === `comments 70,comments ${REF_CARD},labels ${REF_CARD},timeline ${REF_CARD}` && clean.apiCalls === 4 && clean.card.card === REF_CARD && JSON.stringify(clean.record) === JSON.stringify({ measured: true, reason: null, located: 'found', where: 'PR', id: 900, carried: null, securityTouching: { state: 'read', value: 'no' } }) && - JSON.stringify(clean.cardLabels) === JSON.stringify({ measured: true, reason: null, card: REF_CARD, labels: ['tooling'], timeline: { measured: true, reason: null, events: [] } }) && + JSON.stringify(clean.cardLabels) === JSON.stringify({ measured: true, reason: null, card: REF_CARD, labels: ['tooling'], timeline: { measured: true, reason: null, events: [] }, others: { measured: true, reason: null, cards: [] } }) && noLine.record.securityTouching.state === 'missing' && untrusted.record.located === 'absent' && unloaded.apiCalls === 0 && unloaded.record.measured === false && /would not load: boom/.test(unloaded.record.reason) && unloaded.cardLabels.measured === false && noReader.record.measured === false && /no comment reader was supplied/.test(noReader.record.reason) && noReader.cardLabels.measured === false && /no label reader was supplied/.test(noReader.cardLabels.reason) && @@ -6645,6 +6777,7 @@ export async function selfTest() { // No record is no `Security-touching: no` line: Tier H on the arm's record stage (it read Tier S, refused on its absent record, before that stage). assert('⛔ CONTROL: the-same-ADR-note-with-NO-record-is-REFUSED-Tier-H-on-the-record-stage', noRecord.exitCode === EXIT_REFUSED_UNAPPROVED && noRecord.entries[0].tier === TIER_H && noRecord.entries[0].record === undefined && /no contract-review record names this head/.test(renderGuardVerdict(noRecord))); assert('⛔ RECORD-LINE: an-ADR-note-whose-PASS-record-lacks-the-Security-touching-line-reads-Tier-H-and-a-security-labelled-card-does-too', JSON.stringify(await hCase({ comments: [recordComment()] })) === H && JSON.stringify(await hCase({ cardLabels: ['security'] })) === H); + assert('⛔ NAMED-CARDS: an-ADR-note-that-also-names-a-security-labelled-card-reads-Tier-H-and-clears-when-that-card-is-clean', JSON.stringify(await hCase({ prBody: `${LOW}\nPart of #71\n`, cardLabelsBy: { 71: ['security'] } })) === H && tierLabelsRead.join() === `${REF_CARD},71` && (await tierRun({ ...arm, prBody: `${LOW}\nPart of #71\n` })).exitCode === EXIT_CLEAR); // ⛔ ROWS 2–6, each WITH a valid PASS record: the record leg is never consulted. assert('⛔ ROW-2-a-removed-line-stays-H', JSON.stringify(await hCase({ runGit: adrGit(REMOVED) })) === H); assert('⛔ ROW-3-a-changed-or-added-Status-line-stays-H', JSON.stringify(await hCase({ runGit: adrGit(STATUS) })) === H); diff --git a/scripts/pm/check-half-states.mjs b/scripts/pm/check-half-states.mjs index 04fa4947e33..dd0712442fb 100644 --- a/scripts/pm/check-half-states.mjs +++ b/scripts/pm/check-half-states.mjs @@ -13033,11 +13033,15 @@ const CONTRACT_REVIEW_SECURITY_TOUCHING_LINE = new RegExp(CONTRACT_REVIEW_LINE_L * * Every declaration line counts, fenced and quoted ones included, and exactly ONE may exist: * outside any code fence (`FENCE_LINE`, `FENCE_CLOSE_LINE`) and any `>` quote, indented at most - * three spaces, and with its list bullet, bold and backticks stripped reading EXACTLY - * `Security-touching: no` or `Security-touching: yes`. So a second declaration (a quoted `no` - * beside the record's own `yes`), trailing words (`no — wording only`), another value, a - * near-miss key (`Security touching:`) and a fenced, quoted or code-indented line are each - * `unreadable` — the same strictness `readBareDeclaration` holds a PR body's `Clause-②:` line to. + * three spaces, and with its list bullet, bold and a code span around the VALUE stripped reading + * EXACTLY `Security-touching: no` or `Security-touching: yes`. So a second declaration (a quoted + * `no` beside the record's own `yes`), trailing words (`no — wording only`), another value, a + * near-miss key (`Security touching:`), a fenced, quoted or code-indented line and a code span + * holding the KEY (the spelling that mentions the line) are each `unreadable` — the same + * strictness `readBareDeclaration` holds a PR body's `Clause-②:` line to. + * ⚠️ Not read: whether GitHub RENDERS the line. A bare line inside an HTML comment, a `pre` element + * or a code span opened on an earlier line is hidden or shown as code there and still reads here; + * only an author the guard trusts can write a record, so the reader is not widened into a renderer. * * ⛔ Fail closed, in the one direction that matters: `missing`, `unreadable` and `yes` each * keep the pull request at Tier H, and no reading here ever DEFAULTS to `no`. Pure. @@ -13069,7 +13073,12 @@ function contractReviewSecurityTouching(body) { if (fenced) return unreadable(`its one \`${key}:\` line sits inside a code fence`); if (/^[ \t]*>/.test(line)) return unreadable(`its one \`${key}:\` line is a quote (${quote(line)})`); if (/^(?: {4,}| *\t)/.test(line)) return unreadable(`its one \`${key}:\` line is indented as code (${quote(line)})`); - const bare = line.replace(/^[ \t]*(?:[-*+][ \t]+)?/, '').replace(/\*\*|`/g, '').replace(/[ \t]+/g, ' ').trim(); + const stated = line.replace(/^[ \t]*(?:[-*+][ \t]+)?/, '').replace(/\*\*/g, ''); + // A code span that holds the KEY is how the line is MENTIONED — the template's legend, the review brief and every + // reason the arm prints spell it so — and a record that only mentions the line states nothing. The value alone + // may sit in a span (`Head-sha:` refuses a span holding its key the same way). + if (/^[^::]*`/.test(stated)) return unreadable(`its one \`${key}:\` line holds the key inside a code span (${quote(line)}), which mentions the line and states nothing`); + const bare = stated.replace(/`/g, '').replace(/[ \t]+/g, ' ').trim(); const value = CONTRACT_REVIEW_SECURITY_TOUCHING_VALUES.find((v) => bare === `${key}: ${v}`); if (value === undefined) return unreadable(`its \`${key}:\` line reads ${quote(line)}, not exactly ${CONTRACT_REVIEW_SECURITY_TOUCHING_VALUES.map((v) => `\`${key}: ${v}\``).join(' or ')}`); return { state: 'read', value }; @@ -25636,7 +25645,8 @@ export const SELF_TEST_BATTERIES = Object.freeze({ // (two more, the real guard's predicate and set, run where the register loads). // 88 → 93: the record's `Security-touching:` line, the low-risk skills arm's machine line — the bare // readings, the MISSING record, the unreadable shapes, the fence and reason pins, and the constants. - 'H43 hand-off timing': 93, + // 93 → 94: a code span holding the KEY mentions the line and is unreadable; only the value may sit in one. + 'H43 hand-off timing': 94, // Registered with the seat-patrol rows (#28642), pin just under the count: two // free readings, each with its firing controls and its out-of-scope arms inside. 'H70/H71 seat patrol': 30, @@ -33134,7 +33144,8 @@ async function selfTest() { t43('#33604 reading: no heading is no record (null); the template record reads one PASS, no FAIL, no grade', [contractReviewRecordReading('**VERDICT: PASS**'), JSON.stringify(contractReviewRecordReading(PASS43))].join(), ',{"verdicts":["PASS"],"failSpellings":[],"findings":{"open":[],"unreadable":[]},"securityTouching":{"state":"missing"}}'); // The record's `Security-touching:` line — the low-risk skills arm's machine line, three-valued and fail closed. const st43 = (prose) => { const r = read43(prose).securityTouching; return r.state === 'read' ? `read:${r.value}` : r.state; }; - t43('Security-touching: the one bare line reads its value — `no`, `yes`, and behind a bullet, bold or a code span', ['Security-touching: no', 'Security-touching: yes', '- Security-touching: no', '**Security-touching:** no', '- **Security-touching**: `no`', '`Security-touching: no`', ' Security-touching: no'].map(st43).join(), 'read:no,read:yes,read:no,read:no,read:no,read:no,read:no'); + t43('Security-touching: the one bare line reads its value — `no`, `yes`, and behind a bullet, bold, or with the VALUE alone in a code span', ['Security-touching: no', 'Security-touching: yes', '- Security-touching: no', '**Security-touching:** no', '- **Security-touching**: `no`', 'Security-touching: `yes`', ' Security-touching: no'].map(st43).join(), 'read:no,read:yes,read:no,read:no,read:no,read:yes,read:no'); + t43('⛔ Security-touching: a code span that holds the KEY mentions the line and states nothing — UNREADABLE, never `no`, and the reason says so', [...['`Security-touching: no`', '- `Security-touching: no`', '`Security-touching:` no', '`Security-touching`: no', '**`Security-touching: no`**', '`Security-touching: yes`'].map(st43), /holds the key inside a code span \(`Security-touching: no`\), which mentions the line and states nothing$/.test(read43('`Security-touching: no`').securityTouching.reason)].join(), `${Array(6).fill('unreadable').join()},true`); t43('⛔ Security-touching: a record with no such line reads MISSING, never `no` — every record written before the line existed, a mention in prose included', [st43('① Derived judgments: none.'), st43('The record carries no line; the seat reads `Security-touching: no` as the arm asks.'), contractReviewRecordReading(PASS43).securityTouching.state].join(), 'missing,missing,missing'); t43('⛔ Security-touching: two lines, a quoted, fenced or code-indented line, trailing words, another value and a near-miss key are each UNREADABLE', ['Security-touching: no\nSecurity-touching: no', '> Security-touching: no\n\nSecurity-touching: yes', '> Security-touching: no', '```\nSecurity-touching: no\n```', '~~~text\nSecurity-touching: no', ' Security-touching: no', '\tSecurity-touching: no', 'Security-touching: no — wording only', 'Security-touching: none', 'Security-touching: No', 'Security-touching:', 'security-touching: no', 'Security touching: no', '### Security-touching: no', 'Security-touching:no'].map(st43).join(), Array(15).fill('unreadable').join()); t43('⛔ Security-touching: a fenced `no` beside the record\'s own bare `yes` is two declarations (unreadable); a fence closed before the line leaves it read; the reasons name the shape', [st43('```\nSecurity-touching: no\n```\nSecurity-touching: yes'), st43('```\nsome code\n```\nSecurity-touching: no'), /2 `Security-touching:` lines/.test(read43('Security-touching: no\n> Security-touching: no').securityTouching.reason), /inside a code fence/.test(read43('```\nSecurity-touching: no\n```').securityTouching.reason), /is a quote/.test(read43('> Security-touching: no').securityTouching.reason), /not exactly `Security-touching: no` or `Security-touching: yes`/.test(read43('Security-touching: maybe').securityTouching.reason)].join(), 'unreadable,read:no,true,true,true,true'); diff --git a/scripts/pm/fleet-write/execute.mjs b/scripts/pm/fleet-write/execute.mjs index cf5826332c6..1baf8139d08 100644 --- a/scripts/pm/fleet-write/execute.mjs +++ b/scripts/pm/fleet-write/execute.mjs @@ -505,10 +505,10 @@ * the arm's RECORD STAGE pending — every pull-read condition holds — the * follow-up reads the stage too, through the queue guard's one reader * (`readLowRiskRecordStage`: the card the pull delivers, both comment threads - * cut to trusted authors, the card's labels and its timeline), and asks the - * arm again. ⛔ Fail closed: a + * cut to trusted authors, the labels and timeline of every card it names), and + * asks the arm again. ⛔ Fail closed: a * condition broken (`Clause-②` not a bare `no`, a `security` label now or - * removed, on the pull or on its card, a catalog path named for security, auth + * removed, on the pull or on a card it names, a catalog path named for security, auth * or permission, a catalog file added, deleted, renamed or not regular, a * changeset releasing more than the skills catalog, a path off the allowlist, * a contract-review record on the head that lacks one bare @@ -1047,7 +1047,7 @@ export async function workflowReadingFor({ repo, paths, pr, api, t, git = null } * The arm's RECORD STAGE is read SECOND, and only when that reading leaves it pending (every pull-read condition * holds), so no other pull pays for it: the queue guard's `readLowRiskRecordStage`, imported, ⛔ no second reader, * over the guard's own comment, label and timeline readers on the relay's token — the review of record's - * `Security-touching:` line and the labels of the card `pr` delivers. `loadRecognisers` is the seam for the + * `Security-touching:` line and the labels of every card `pr` names. `loadRecognisers` is the seam for the * contract-review recognisers; a load that fails, a thread or label list that does not read, or a pull that * names no card is NOT MEASURED, so H. Never throws. */ @@ -2603,7 +2603,8 @@ const SELF_TEST_BATTERIES = Object.freeze({ // words, the readable gate, a Tier S skills pull requesting no one, three H readings, eight unreadable readings, a mixed pull and objectui. // 45 → 50 with the arm's record stage on the relay: nine H variants of the stage in one plan case, twelve in one run case (the record // without its line first), the record on the card thread, the recogniser seam, and the stage's cost on a pull-read H. - "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": 50, + // 50 → 52 with every card the pull names: five H variants of a second card in one run case, and its clean control. + "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": 52, // 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, @@ -3104,7 +3105,7 @@ export async function selfTest() { // The arm's record stage, read and favourable — a record on the head whose line reads `no`, a card never // labelled `security` — unless a case overrides a half (`null` hands that half in unread: the arm's `pending`). const stageRecord = (over = {}) => ({ measured: true, reason: null, located: 'found', where: 'PR', id: 900, carried: null, securityTouching: { state: 'read', value: 'no' }, ...over }); - const stageCard = (over = {}) => ({ measured: true, reason: null, card: 1, labels: [], timeline: { measured: true, reason: null, events: [] }, ...over }); + const stageCard = (over = {}) => ({ measured: true, reason: null, card: 1, labels: [], timeline: { measured: true, reason: null, events: [] }, others: { measured: true, reason: null, cards: [] }, ...over }); const lowRead = (paths, over = {}) => pullLowRiskReading(armPullJson(over.pull ?? {}), paths, { timeline: { measured: true, reason: null, events: over.events ?? [] }, changesets: { measured: true, reason: null, files: paths.filter((p) => p.startsWith('.changeset/')).map((path) => ({ path, text: over.csText ?? CS_TEXT })) }, @@ -3211,6 +3212,24 @@ export async function selfTest() { 'a card timeline that does not read': [await stageRun({}, { [CARD_TIMELINE]: { status: 502, json: { message: 'bad gateway' } } }), 'the timeline of its card #1 was not read'], }; t('⛔ record-stage-skills-pull-requests: an arm pull whose record LACKS the `Security-touching:` line, reads yes, doubles it, is absent, is by an untrusted author or is shadowed by a newer one without it, whose card carries `security` or had it removed, that names no card, or whose thread, labels or card timeline do not read — each requests BOTH approvers, and its row says Tier H, fail closed, with the reason', Object.entries(stageH).map(([k, [r, why]]) => [k, r.exit, writes(r.seen).map((s) => s.call), r.rows[1]?.result.includes('low-risk skills arm read: Tier H, fail closed') && r.rows[1]?.result.includes(why)]), Object.keys(stageH).map((k) => [k, EXIT_OK, [GRAPHQL, REQUEST], true]), Object.values(stageH).map(([r]) => r.rows[1]?.result).join(' | ')); + // ⛔ Every card the pull NAMES is read on the relay too — a `Part of` beside the `Fixes`, the card the branch is + // named for — not only the one whose thread may carry its record. + const ALSO = 7; + const [ALSO_LABELS, ALSO_TIMELINE] = ['labels', 'timeline'].map((leaf) => `GET /repos/${REPO}/issues/${ALSO}/${leaf}`); + const alsoCard = (labels = [], events = []) => ({ [ALSO_LABELS]: { status: 200, json: labels.map((name) => ({ name })) }, [ALSO_TIMELINE]: { status: 200, json: events } }); + const partOfPull = { [PULL]: { status: 200, json: armPullJson({ body: `Fixes #1\n\nPart of #${ALSO}\n\nClause-②: no\nMetadata-protocol: none\n` }) } }; + const branchPull = { [PULL]: { status: 200, json: armPullJson({ head: { sha: ARM_HEAD, ref: `claude/issue-${ALSO}-x`, ...sameRepo } }) } }; + const alsoCarries = `card #${ALSO}, which it also names, carries the \`security\` label`; + const namedH = { + 'a security label on the card a Part of names': [await stageRun({}, { ...partOfPull, ...alsoCard(['security']) }), alsoCarries], + 'a security label on the card the branch is named for': [await stageRun({}, { ...branchPull, ...alsoCard(['tooling', 'Security']) }), alsoCarries], + 'a security label removed from that card': [await stageRun({}, { ...partOfPull, ...alsoCard([], [{ event: 'labeled', label: { name: 'security' } }, { event: 'unlabeled', label: { name: 'security' } }]) }), `the timeline of card #${ALSO}, which it also names, shows the \`security\` label removed`], + 'labels of that card that do not read': [await stageRun({}, { ...partOfPull, ...alsoCard(), [ALSO_LABELS]: { status: 403, json: { message: 'forbidden' } } }), `the labels of card #${ALSO}, which it also names, were not read (card #${ALSO}'s labels could not be read`], + 'a timeline of that card that does not read': [await stageRun({}, { ...branchPull, ...alsoCard(), [ALSO_TIMELINE]: { status: 502, json: { message: 'bad gateway' } } }), `the timeline of card #${ALSO}, which it also names, was not read`], + }; + t('⛔ named-cards-skills-pull-requests: an arm pull that ALSO names a card — by a `Part of` or by its branch — which carries `security`, had it removed, or whose labels or timeline do not read, requests BOTH approvers, and its row says Tier H, fail closed, naming that card', Object.entries(namedH).map(([k, [r, why]]) => [k, r.exit, writes(r.seen).map((s) => s.call), r.rows[1]?.result.includes('low-risk skills arm read: Tier H, fail closed') && r.rows[1]?.result.includes(why)]), Object.keys(namedH).map((k) => [k, EXIT_OK, [GRAPHQL, REQUEST], true]), Object.values(namedH).map(([r]) => r.rows[1]?.result).join(' | ')); + const twoClean = [await stageRun({}, { ...partOfPull, ...alsoCard() }), await stageRun({}, { ...branchPull, ...alsoCard() })]; + t('⭐ CONTROL: the same two pulls with BOTH cards clean are Tier S with no request, and the second card cost its labels and its timeline after the first', twoClean.map((r) => [r.exit, writes(r.seen).map((s) => s.call), r.rows[1]?.result.endsWith(`low-risk skills arm read: Tier S (${LOW_RISK_ARM_RULING})`), r.seen.map((s) => s.call).filter((c) => [...STAGE_READS, ALSO_LABELS, ALSO_TIMELINE].includes(c))]), twoClean.map(() => [EXIT_OK, [GRAPHQL], true, [...STAGE_READS, ALSO_LABELS, ALSO_TIMELINE]]), twoClean.map((r) => r.rows[1]?.result).join(' | ')); const onCard = await stageRun({ rows: [], cardRows: [reviewOfRecord(LOW_RISK_RECORD_LINE, { id: 902 })] }); t('⭐ the record on the CARD thread carries the line as well as one on the pull: Tier S, no request', [onCard.exit, writes(onCard.seen).map((s) => s.call), onCard.rows[1]?.result.endsWith(`low-risk skills arm read: Tier S (${LOW_RISK_ARM_RULING})`)], [EXIT_OK, [GRAPHQL], true], onCard.rows[1]?.result); const stageFor = (loadRecognisers) => lowRiskReadingFor({ repo: REPO, pull: N, paths: [SK, CS], files: armFiles(SK, CS).json, pr: armPullJson(), api: 'https://api.github.test', t: { fetch: platform(armAnswers(), []), token: TOKEN }, git: armGit([]), ...(loadRecognisers ? { loadRecognisers } : {}) }); diff --git a/scripts/pm/record-recognisers.mjs b/scripts/pm/record-recognisers.mjs index dff792a3cad..8e7ebdccb74 100644 --- a/scripts/pm/record-recognisers.mjs +++ b/scripts/pm/record-recognisers.mjs @@ -99,6 +99,7 @@ import { latestMarkedComment, partOfTargets, readSignatureLine, + refsTargets, SEAT_SIGNATURE_SESSION_SOURCE, stripSignatureLine, } from './check-half-states.mjs'; @@ -2024,6 +2025,37 @@ export function deliveredCardNumber(pr) { return { card: strongest[0].card, evidence: strongest[0].evidence }; } +/** + * EVERY card a pull request NAMES through a channel the card relations read, as numbers in ascending + * order: each closing keyword's target, each `Part of` target (at the declaration position or inline), + * each `Refs` target, and the card a protocol dev branch is named for — the branch whether or not the + * body declares another card. + * + * ⭐ WIDER than `deliveredCardNumber` on purpose, and for ONE reader: the low-risk skills arm's card + * conjunct (`readCardLabels`, the queue guard), which lands no pull request while ANY card it names + * carries the `security` label. `deliveredCardNumber` answers which ONE thread may hold the record — the + * strongest evidence — so beside a `Fixes #A`, a `Part of #B` or a branch named for #B leaves #B unread + * there. A label is not a thread: one card read too many costs two reads and fails closed, one read too + * few lands security teaching with no human approval. + * + * ⛔ NOT a delivery relation: nothing here says the pull request delivers these cards (`deliveryEvidence` + * rejects a branch name once the body speaks, and never reads `Refs`), and no reader may search these + * threads for a record. A number mentioned in prose with none of the four spellings is not named. + * + * @param {object} pr — a REST pull row: `body`, and `head.ref` for the branch + * @returns {number[]} + */ +export function namedCardNumbers(pr) { + const body = String(pr?.body ?? ''); + const named = new Set([ + ...closingKeywordTargets(body).keys(), + ...partOfTargets(body), + ...refsTargets(body).keys(), + ...[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 @@ -2113,10 +2145,10 @@ export function contractReviewTemplateLines(values = {}) { ` · ${CONTRACT_REVIEW_SECURITY_TOUCHING_KEY} read by the low-risk skills arm alone (skill wording, add-only ADR notes): that arm`, ' lands a PR on this record with no human approval, and only when this line reads `no`.', ' Write `no` ONLY when no changed hunk teaches permission, sharing, credential, token,', - ' authentication or other security behaviour, whatever the path is called; else `yes`, and', - ' the seat adopting the record adds the `security` label. A missing line, `yes`, a second', - ' line, one that is quoted, fenced or code-indented, or anything after the value keeps the', - ` PR at Tier H. The template ships \`${RECORD_SECURITY_TOUCHING_DEFAULT}\`, so an unedited paste never lands on the arm.`, + ' authentication or other security behaviour, whatever the path is called; else `yes`. A missing', + ' line, `yes`, a second line, the key inside a code span, a quoted, fenced or code-indented line,', + ` or anything after the value keeps the PR at Tier H. The template ships \`${RECORD_SECURITY_TOUCHING_DEFAULT}\`, so an unedited paste`, + ' never lands on the arm: the seat adds the `security` label only once the reviewer confirms a `yes` was meant.', ] : []), ' · ③ Boundary flags every dev flag and every `open_questions` entry answered, or escalated; and on', ' every face the SQL push-down check:', @@ -2531,7 +2563,8 @@ const SELF_TEST_BATTERIES = Object.freeze({ '#18042: the copyable record TEMPLATE — the one machine-read artefact with nothing to copy': 38, // Raised 17 → 19 by #33541: the template record's one `VERDICT:` line read PASS by the guard, and the same record // posted by an untrusted author not read — two pins, two cases. - '#18701: ONE thread set -- what the template STATES is what the queue guard READS': 19, + // Raised 19 → 22 with `namedCardNumbers`, every card a pull names: the low-risk arm reads the label on each. + '#18701: ONE thread set -- what the template STATES is what the queue guard READS': 22, '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, @@ -3391,7 +3424,7 @@ export async function selfTest() { t('…and a reviewer who writes `no` over it is read as `no` — the one value the arm stands on', JSON.stringify(stOf(TPL_RECORD.replace(ST_LINE('yes'), ST_LINE('no')))) === '{"state":"read","value":"no"}' && TPL_RECORD.includes(`\n${ST_LINE('yes')}\n`)); t('⛔ the line prints exactly where an arm PR can sit: with the `hits` known, under a low-risk row (skills, ui/skills, an ADR) and nowhere else; with none known, on the bare, rules and schema faces — never the narrowing or declaration face', ARM_PATHS.every((path) => fenced(contractReviewTemplateLines({ paths: [path] })).includes(`\n${ST_LINE('yes')}\n`)) && !contractReviewTemplateLines({ paths: [OFF_ARM_PATH] }).join('\n').includes('Security-touching') && !contractReviewTemplateLines({ paths: MIXED }).join('\n').includes('Security-touching') && ['rules', 'schema'].every((id) => contractReviewRecordLines({ faceId: id }).includes(ST_LINE('yes'))) && ['narrowing', 'declaration'].every((id) => !contractReviewTemplateLines({ face: id }).join('\n').includes('Security-touching')) && !contractReviewRecordLines({ tierName: TIER_DEFAULT_NAME }).join('\n').includes('Security-touching')); t('the predicate is ONE function over face, tier and hits — below tier never, a narrowing never, known hits by the register\'s own low-risk row test', recordCarriesSecurityTouching(null, CONTRACT_REVIEW_TIER_NAME, undefined) && !recordCarriesSecurityTouching(null, TIER_DEFAULT_NAME, undefined) && !recordCarriesSecurityTouching(reviewFaceById('narrowing'), CONTRACT_REVIEW_TIER_NAME, undefined) && recordCarriesSecurityTouching(reviewFaceById('rules'), CONTRACT_REVIEW_TIER_NAME, [ARM_PATHS[0]]) && !recordCarriesSecurityTouching(reviewFaceById('rules'), CONTRACT_REVIEW_TIER_NAME, [OFF_ARM_PATH]) && !recordCarriesSecurityTouching(null, TIER_DEFAULT_NAME, [ARM_PATHS[0]])); - t('the notes explain the line where the record carries it — who reads it, when `no` may be written, what keeps Tier H — and the key and values are the reader\'s own constants', ['· Security-touching read by the low-risk skills arm alone', 'only when this line reads `no`', 'Write `no` ONLY when no changed hunk teaches permission, sharing, credential, token,', 'adds the `security` label', 'PR at Tier H', 'The template ships `yes`'].every((frag) => says(TPL_TEXT, frag)) && CONTRACT_REVIEW_SECURITY_TOUCHING_KEY === 'Security-touching' && CONTRACT_REVIEW_SECURITY_TOUCHING_VALUES.join() === 'no,yes'); + t('the notes explain the line where the record carries it — who reads it, when `no` may be written, what keeps Tier H — and the key and values are the reader\'s own constants', ['· Security-touching read by the low-risk skills arm alone', 'only when this line reads `no`', 'Write `no` ONLY when no changed hunk teaches permission, sharing, credential, token,', 'the key inside a code span', 'keeps the PR at Tier H', 'The template ships `yes`', 'adds the `security` label only once the reviewer confirms a `yes` was meant'].every((frag) => says(TPL_TEXT, frag)) && CONTRACT_REVIEW_SECURITY_TOUCHING_KEY === 'Security-touching' && CONTRACT_REVIEW_SECURITY_TOUCHING_VALUES.join() === 'no,yes'); // -- item ④: the owner's full-review order rides THIS record as a fourth section ------------ const DJ = '### ④ Design judgment'; const headings = (lines) => lines.filter((line) => line.startsWith('### ')); @@ -3562,6 +3595,15 @@ export async function selfTest() { t('⛔ a body naming NO card yields no card and a reason, never a guess', (() => { const r = deliveredCardNumber(PIN_PULL('nothing here')); return r.card === null && r.reason.includes('names no card'); })()); t('⛔ two cards at the SAME strength yield NEITHER, and the reason names both', (() => { const r = deliveredCardNumber(PIN_PULL('Fixes #4444\nFixes #5555')); return r.card === null && r.reason.includes('#4444') && r.reason.includes('#5555'); })()); t('…while a STRONGER grade still decides, so a stray `Part of` beside a keyword is not a tie', deliveredCardNumber(PIN_PULL(`Fixes #${PIN_CARD}\n\npart of #4444 already landed`)).card === PIN_CARD); + // `namedCardNumbers` -- every card the pull names, for the low-risk arm's label read: wider than the one + // card above, because a `security` label on ANY of them keeps the arm at Tier H. + t('⭐ namedCardNumbers lists EVERY card a pull names -- a closing keyword, a `Part of` (declared or inline), a `Refs`, and its branch -- ascending, once each', namedCardNumbers(PIN_PULL('Fixes #4444\n\nPart of #5555\nRefs #3333 (item 2)\nthis is part of #2222 too\ncloses #4444', 'claude/issue-6666-x')).join() === '2222,3333,4444,5555,6666'); + t('⛔ namedCardNumbers keeps the card the WEAKER evidence names: a `Part of` beside a keyword, and a branch named for another card once the body speaks -- the two `deliveredCardNumber` drops', (() => { + const partOf = PIN_PULL('Fixes #4444\nPart of #5555'); + const branch = PIN_PULL('Fixes #4444', 'claude/issue-5555-x'); + 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); 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')); From 26f909c430e6486a7370593cdd122ac80c5e4b2f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 22:22:50 +0000 Subject: [PATCH 8/8] fix(pm): the timeline reader follows the Link header past a short page The low-risk arm reads a removed `security` label off a card's timeline through `makeTimelineReader`, which ended its walk at the first page shorter than `per_page`. A short page that was not the last would have ended the walk early and read "never removed". The walk now ends on a short page only when the answer's `Link` header names no next page; an answer with no such header reads as before, and a next page named on every answer throws at the page limit. Whether the route answers a short page that is not the last was not measured. The line reader's docblock names one more shape it does not judge: a bare line directly under a quoted line is rendered inside that quote and still reads. The `H43 hand-off timing` floor moves 94 to 103 for the nine verdict-reader rows the merge brought in with no pin of their own; the battery registers 126 cases. The enqueue-leg floor moves 28 to 30 with the two new reader rows. Claude-Session: https://claude.ai/code/session_01ADHkmR2U8dFkRvc5DvUz1W Co-authored-by: Claude --- scripts/pm/check-governed-queue-guard.mjs | 20 ++++++++++++++++++-- scripts/pm/check-half-states.mjs | 9 ++++++--- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/scripts/pm/check-governed-queue-guard.mjs b/scripts/pm/check-governed-queue-guard.mjs index 9f44357621e..ab44a57da14 100644 --- a/scripts/pm/check-governed-queue-guard.mjs +++ b/scripts/pm/check-governed-queue-guard.mjs @@ -700,7 +700,9 @@ const SELF_TEST_BATTERIES = Object.freeze({ 'the per-row repository scope (ruling B2, 2026-10-13)': 14, '⭐ B′ with C: the record stands at the tier its FACE maps to, read off the committed paths': 8, 'the CODEOWNERS mirror: every Tier H register row routes to every GOVERNED_APPROVERS account, nothing else is routed, and the file says so': 12, - '⭐ the 2026-10-26 ENQUEUE leg: an authorized enqueuer is the human review': 28, + // Raised 28 → 30 with the timeline reader's `Link` header: a short page that names a next page is followed, and + // a next page named on every answer throws at the page limit. + '⭐ the 2026-10-26 ENQUEUE leg: an authorized enqueuer is the human review': 30, '⭐ the cheap early-warning leg: commits and trees, toolchain on demand': 20, '⭐ the workflows split at the queue (ruling record 6722205630)': 30, // Raised 54 → 72 with the arm's record stage: the record's `Security-touching:` line (control, absent line, `yes`, @@ -3397,6 +3399,12 @@ export function makeCommentReader({ apiUrl, slug, token, fetchImpl = fetch, perP * timeline is oldest-first, so the event this leg reads is on the LAST page. A * list cut at `maxPages` would answer an older enqueue as the newest, so it * throws instead — the caller turns that into UNDETERMINED, never a pass. + * + * ⚠️ A SHORT page ends the walk only when the answer names no next page. The arm reads a REMOVED + * label off a card's timeline with this reader, and a walk that stopped at a short page that was not + * the last would read "never removed". Whether this route ever answers such a page is NOT MEASURED; + * the `Link` header's `rel="next"` settles it either way, and an answer with no such header reads as + * it always did. */ export function makeTimelineReader({ apiUrl, slug, token, fetchImpl = fetch, perPage = 100, maxPages = 10 }) { return async function fetchTimeline(pull) { @@ -3408,7 +3416,8 @@ export function makeTimelineReader({ apiUrl, slug, token, fetchImpl = fetch, per const batch = await res.json(); if (!Array.isArray(batch)) throw new Error(`the timeline endpoint answered a non-array body for #${pull}`); all.push(...batch); - if (batch.length < perPage) return all; + const namesNextPage = /<[^>]*>[ \t]*;[ \t]*rel="?next"?/i.test(String(res.headers?.get?.('link') ?? '')); + if (batch.length < perPage && !namesNextPage) return all; } throw new Error(`#${pull} has more than ${perPage * maxPages} timeline events — the newest is on a page this read never reached`); }; @@ -6204,6 +6213,13 @@ export async function selfTest() { const fakeFetch = (pages) => async (url) => { urls.push(url); const page = Number(new URL(url).searchParams.get('page')); return { ok: true, status: 200, json: async () => pages[page - 1] ?? [] }; }; const twoPages = await makeTimelineReader({ apiUrl: 'https://api.example', slug: 'o/r', token: null, fetchImpl: fakeFetch([[added(SEAT), removed()], [added(GOVERNED_APPROVERS[0])]]), perPage: 2 })(9); assert('the-timeline-reader-walks-to-the-short-page-on-the-issues-timeline-route', twoPages.length === 3 && urls[0] === 'https://api.example/repos/o/r/issues/9/timeline?per_page=2&page=1' && enqueuerFromTimeline(twoPages).login === GOVERNED_APPROVERS[0], JSON.stringify(urls)); + // ⛔ A short page that is not the last: the answer's `Link` header names the next page, and the walk follows it. + const linked = (pages, next) => async (url) => { const page = Number(new URL(url).searchParams.get('page')); return { ok: true, status: 200, headers: { get: (name) => (name.toLowerCase() === 'link' && next(page) ? `<${url.replace(/page=\d+$/, `page=${page + 1}`)}>; rel="next", <${url}>; rel="last"` : null) }, json: async () => pages[page - 1] ?? [] }; }; + const shortThenMore = await makeTimelineReader({ apiUrl: 'https://api.example', slug: 'o/r', token: null, fetchImpl: linked([[added(SEAT)], [added(GOVERNED_APPROVERS[0])]], (page) => page === 1), perPage: 2 })(9); + const shortAndLast = await makeTimelineReader({ apiUrl: 'https://api.example', slug: 'o/r', token: null, fetchImpl: linked([[added(SEAT)], [added(GOVERNED_APPROVERS[0])]], () => false), perPage: 2 })(9); + assert('⛔ a-SHORT-page-whose-answer-names-a-next-page-is-NOT-the-last-the-walk-follows-the-Link-header', shortThenMore.length === 2 && enqueuerFromTimeline(shortThenMore).login === GOVERNED_APPROVERS[0] && shortAndLast.length === 1 && enqueuerFromTimeline(shortAndLast).login === SEAT, `${shortThenMore.length} then ${shortAndLast.length}`); + const neverEnds = await makeTimelineReader({ apiUrl: 'https://api.example', slug: 'o/r', token: null, fetchImpl: linked([[added(SEAT)]], () => true), perPage: 2, maxPages: 3 })(9).then(() => null, (error) => error); + assert('⛔ a-next-page-named-on-every-answer-THROWS-at-the-page-limit-never-an-early-answer', neverEnds instanceof Error && /never reached/.test(neverEnds.message), String(neverEnds?.message)); const truncated = await makeTimelineReader({ apiUrl: 'https://api.example', slug: 'o/r', token: null, fetchImpl: fakeFetch([[removed()], [added(GOVERNED_APPROVERS[0])]]), perPage: 1, maxPages: 1 })(9).then(() => null, (error) => error); assert('⛔ a-TRUNCATED-timeline-THROWS-rather-than-answering-an-older-add-as-the-newest', truncated instanceof Error && /never reached/.test(truncated.message), String(truncated?.message)); const denied = await makeTimelineReader({ apiUrl: 'https://api.example', slug: 'o/r', token: null, fetchImpl: async () => ({ ok: false, status: 403, json: async () => ({}) }) })(9).then(() => null, (error) => error); diff --git a/scripts/pm/check-half-states.mjs b/scripts/pm/check-half-states.mjs index 310a633dc46..d2d7ba432a3 100644 --- a/scripts/pm/check-half-states.mjs +++ b/scripts/pm/check-half-states.mjs @@ -13102,8 +13102,9 @@ const CONTRACT_REVIEW_SECURITY_TOUCHING_LINE = new RegExp(CONTRACT_REVIEW_LINE_L * holding the KEY (the spelling that mentions the line) are each `unreadable` — the same * strictness `readBareDeclaration` holds a PR body's `Clause-②:` line to. * ⚠️ Not read: whether GitHub RENDERS the line. A bare line inside an HTML comment, a `pre` element - * or a code span opened on an earlier line is hidden or shown as code there and still reads here; - * only an author the guard trusts can write a record, so the reader is not widened into a renderer. + * or a code span opened on an earlier line is hidden or shown as code there, and a bare line directly + * under a quoted line, with no blank line between, is rendered inside that quote; each still reads + * here. Only an author the guard trusts can write a record, so the reader is not widened into a renderer. * * ⛔ Fail closed, in the one direction that matters: `missing`, `unreadable` and `yes` each * keep the pull request at Tier H, and no reading here ever DEFAULTS to `no`. Pure. @@ -25708,7 +25709,9 @@ export const SELF_TEST_BATTERIES = Object.freeze({ // 88 → 93: the record's `Security-touching:` line, the low-risk skills arm's machine line — the bare // readings, the MISSING record, the unreadable shapes, the fence and reason pins, and the constants. // 93 → 94: a code span holding the KEY mentions the line and is unreadable; only the value may sit in one. - 'H43 hand-off timing': 94, + // 94 → 103: the nine verdict-reader rows that landed with no pin of their own — the closed finding that + // must END, the FAIL spellings, the fail-safe idiom. The battery registers 126 cases beside these rows. + 'H43 hand-off timing': 103, // Registered with the seat-patrol rows (#28642), pin just under the count: two // free readings, each with its firing controls and its out-of-scope arms inside. 'H70/H71 seat patrol': 30,