From dade7cacf16c0605f766fcb059288348304b89b2 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Sat, 28 Nov 2026 06:12:04 -0500 Subject: [PATCH] Stop mistaking ordinary text for Capy ids and check every part of a public PR body (GST-4105) (#4872) On public repositories, `/gstack-ship` no longer refuses or rewrites ordinary text such as `SHA-256:abc` or `test/jam_fix.ts` as if it were a Capy id, and it now checks every part of the PR body it posts. Why: these are the follow-ups #4868 left open. It made public PR bodies safe but caught too much and left a few corners unchecked. Nothing to do: private repositories keep working with PR bodies written before #4868. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/specialist-batched#1 reader=security Review-Finding: p2/outside-voice#1 reader=outside-voice Review-Finding: p2/outside-voice#2 reader=outside-voice Review-Finding: p2/outside-voice#3 reader=outside-voice Review-Finding: p2/outside-voice#4 reader=outside-voice Review-Finding: p2/adversarial-native#1 reader=adversarial-native --- bin/gstack-ship-receipt | 59 +++-- changelog.d/capy-public-pr-body-follow-ups.md | 4 + docs/troubleshooting.md | 57 ++++- lib/gate-dispositions.ts | 18 +- lib/pr-review-history.ts | 7 +- lib/ruled-notes.ts | 13 +- test/ship-receipt-public-safe.test.ts | 221 +++++++++++++++++- 7 files changed, 341 insertions(+), 38 deletions(-) create mode 100644 changelog.d/capy-public-pr-body-follow-ups.md diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receipt index f51702566..482a7ac35 100755 --- a/bin/gstack-ship-receipt +++ b/bin/gstack-ship-receipt @@ -53,7 +53,7 @@ import { approvalForReceipt } from '../lib/approval-citations'; import { CARRY_NAMED_PATHS, bindReceipt, carryReceipt, recheckCarried, classifyCarryPath, computeCensus, extractReceipt, landedStackParent, missingIssueLines, orderReceipt, parseReviewLoop, placeReceipt, planCarry, planTreeCarry, - publicReceiptLeaks, RUNS_FENCE, receiptIssuesFrom, receiptRuns, receiptSummaryLine, renderCensus, renderReceiptBlock, runId, unruledOpenBlockers, validateReceipt, type CensusPr, + publicReceiptLeaks, RUNS_FENCE, receiptIssuesFrom, receiptRuns, receiptSummaryLine, renderCensus, renderReceiptBlock, runId, sameRun, unruledOpenBlockers, validateReceipt, type CensusPr, } from '../lib/ship-receipt'; import { checkDocsCaps, docsCapLine, docsExceptionLine, parseReceiptDocs } from '../lib/ship-receipt-docs'; import { absorbedByBase, comparePath, contextPacket, PACKET_SECTION_CAP, readScopedReview, touchedPaths } from '../lib/ship-patch'; @@ -63,7 +63,7 @@ import { RISK_CLASSES, type RiskClass } from '../lib/review-risk'; import { checkReceiptProse, proseLine } from '../lib/ship-receipt-prose'; import { resolveStateRoot } from '../lib/state-root'; import { readPause, receiptBaseRed } from '../lib/base-red'; -import { bodyLineText, bodyListsLine, INTERNAL_ID, keepsInternalIds, publicRuledNote, readRuledNotes, redactInternalIds, repoRuledNotes, ruledNoteText } from '../lib/ruled-notes'; +import { bodyLineText, bodyListsLine, INTERNAL_ID, keepsInternalIds, publicRuledNote, readRuledNotes, redactInternalIds, RELAYED_REF, repoRuledNotes, ruledNoteText } from '../lib/ruled-notes'; import { renderMode, repoVisibility } from '../lib/approval-record'; import { appliedGateDispositions, gateDispositionText, publicGateDisposition } from '../lib/gate-dispositions'; import { securityFingerprints } from '../lib/security-findings'; @@ -308,8 +308,8 @@ async function cmdWrite(rest: string[], json: boolean): Promise { const ruledNotes = repoRuledNotes(readRuledNotes(repoRoot), repoRoot, process.env, flag(rest, '--repo')); const unlisted = bodyFile ? ruledNotes.map(n => `Ruled note: ${ruledNoteText(n)}`).find(l => !bodyListsLine(bodyText, l)) : undefined; if (unlisted) { process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_INVALID', `${bodyFile} does not list ruled note ${JSON.stringify(unlisted)} (gstack-approvals rulings prints each line the body carries); nothing written`) + '\n'); return EXIT.fail; } - const relayed = bodyFile ? bodyText.split(/\r?\n/).map(bodyLineText).filter(l => l.startsWith('Ruled note: ') && INTERNAL_ID.test(l)).join('\n') : ''; - if (relayed && !keepsInternalIds(relayed, repoRoot, process.env, flag(rest, '--repo'))) { process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_INVALID', `${bodyFile} has a Ruled note line that names a Capy thread or message id, and gh does not report this repository private: a PR body is public, so list the lines gstack-approvals rulings prints now, which say relayed from a private message; nothing written`) + '\n'); return EXIT.fail; } + const relayed = bodyFile ? bodyText.split(/\r?\n/).map(bodyLineText).some(l => l.startsWith('Ruled note: ') && (INTERNAL_ID.test(l) || RELAYED_REF.test(l))) : false; + if (relayed && renderMode(repoVisibility(repoRoot, process.env, flag(rest, '--repo')), false) !== 'full') { process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_INVALID', `${bodyFile} has a Ruled note line that names a Capy thread or message id or relays from a ref other than a private message, and gh does not report this repository private: a PR body is public, so list the lines gstack-approvals rulings prints now, which say relayed from a private message; nothing written`) + '\n'); return EXIT.fail; } let gateDispositions: ReturnType['applied']; try { gateDispositions = appliedGateDispositions(repoRoot, { pin: 'HEAD' }).applied; } catch (e: any) { process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_INVALID', `the owner gate dispositions at HEAD cannot be derived (${e.message}); the receipt always records them, so an unreadable approval store or a git error writes nothing`) + '\n'); return EXIT.fail; } @@ -434,8 +434,6 @@ async function cmdWrite(rest: string[], json: boolean): Promise { return EXIT.fail; } const block = renderReceiptBlock(receipt); - const out = flag(rest, '--out'); - if (out) fs.writeFileSync(out, block); const closed = [...(receipt.cleared_by_trailer ?? []).map(t => `Closed by fix ${t.commit.slice(0, 12)}: ${t.id} (a later full review at ${t.review.slice(0, 12)} read it clean)`)]; if (body) { let text = fs.existsSync(body) ? fs.readFileSync(body, 'utf8') : ''; @@ -449,8 +447,17 @@ async function cmdWrite(rest: string[], json: boolean): Promise { } const notes = splitAgentNotes(text).notes ?? ''; const lines = closed.filter(l => !notes.includes(l)); - fs.writeFileSync(body, placeReceipt(lines.length ? withAgentNotes(text, [notes.trim(), ...lines].filter(Boolean).join('\n\n')) : text, receipt)); + const next = placeReceipt(lines.length ? withAgentNotes(text, [notes.trim(), ...lines].filter(Boolean).join('\n\n')) : text, receipt); + const runLeaks = runsBlockLeaks(next); + const runVisibility = runLeaks.length ? repoVisibility(repoRoot, process.env, flag(rest, '--repo')) : 'private'; + if (renderMode(runVisibility, false) !== 'full') { + process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_INVALID', `${body}'s runs block holds ${runLeaks.join(', ')}, and the repository's visibility is ${runVisibility}, not private: a PR body is public, so take the home path or Capy thread or message id out of that entry of the ${RUNS_FENCE} block; nothing written`) + '\n'); + return EXIT.fail; + } + fs.writeFileSync(body, next); } + const out = flag(rest, '--out'); + if (out) fs.writeFileSync(out, block); process.stderr.write(receiptSummaryLine(receipt) + '\n'); process.stdout.write(json ? JSON.stringify(receipt) + '\n' : block); return EXIT.ok; @@ -877,12 +884,12 @@ function cmdCarry(rest: string[], json: boolean): number { const carried = carryReceipt(rebound, head, plan.carry, { tree: headTree, fromTree, productPatchId: headPatch }); const errors = validateReceipt(carried); if (errors.length) return refused('RECEIPT_CARRY_REFUSED', `the carried receipt does not validate: ${errors[0]!.message} at ${errors[0]!.path}`); - const leaks = publicReceiptLeaks(carried); + const newBody = placeReceipt(body, carried); + const leaks = [...publicReceiptLeaks(carried), ...runsBlockLeaks(newBody)]; const visibility = leaks.length ? repoVisibility(repoRoot, process.env, flag(rest, '--repo')) : 'private'; - if (renderMode(visibility, false) !== 'full') return refused('RECEIPT_CARRY_REFUSED', `the carried receipt holds ${leaks.join(', ')} from an earlier write, and the repository's visibility is ${visibility}, not private: a PR body is public, so run /gstack-ship on ${head.slice(0, 12)} for a fresh receipt`); + if (renderMode(visibility, false) !== 'full') return refused('RECEIPT_CARRY_REFUSED', `the carried receipt or the body's runs block holds ${leaks.join(', ')} from an earlier write, and the repository's visibility is ${visibility}, not private: a PR body is public, so take it out of the runs block entry, or run /gstack-ship on ${head.slice(0, 12)} for a fresh receipt`); const targetedVerdict = receiptTargetedAtHead(repoRoot, baseRef, carried, head); if (!targetedVerdict.ok) return refused('RECEIPT_CARRY_REFUSED', `${targetedVerdict.line}: ${targetedVerdict.message}, so the queue refuses it too (#3859); run /gstack-ship on ${head.slice(0, 12)}`); - const newBody = placeReceipt(body, carried); const line = receiptSummaryLine(carried); if (scopedDryRun) return refused('RECEIPT_CARRY_SCOPED_REVIEW', scopedDryRun); if (rest.includes('--dry-run')) { @@ -977,23 +984,29 @@ function readBody(rest: string[]): { ok: true; body: string; pr?: string } | { o /** --run as receipts store it: the run dir's name, never its path (lib/ship-receipt.ts runId, GST-1955). */ const runFlag = (rest: string[]) => { const r = flag(rest, '--run'); return r === undefined ? undefined : runId(r); }; +/** publicReceiptLeaks over the runs block a body renders, abandon's who and why included (GST-4105): write, carry and abandon post it whole. */ +const runsBlockLeaks = (body: string) => publicReceiptLeaks({ [RUNS_FENCE]: receiptRuns(body) }); /** - * Why PR `pr` is not this checkout's PR, or null when it is (CAPY-1 qm#3983): its head must be this checkout's branch on the repository - * origin pushes to, since a fork's PR from a branch of the same name has the same headRefName. + * Why PR `pr` is not this checkout's open PR, or null when it is (CAPY-1 qm#3983): its head must be this checkout's branch on the + * repository the branch pushes to (its branch..pushRemote, else remote.pushDefault, else origin, at that remote's pushurl or + * url: a contributor's origin is often upstream and their fork another remote), since a fork's PR from a branch of the same name has the same headRefName; and it must be + * open, since a merged or closed PR's body is a record (GST-4105). */ function prOffBranch(rest: string[], pr: string): string | null { const branch = git(['branch', '--show-current']), repo = flag(rest, '--repo'); if (!branch) return `this checkout has no branch, so PR #${pr} cannot be matched to it`; - const origin = /([^/:]+)\/([^/]+?)(?:\.git)?\/*$/.exec(git(['config', '--get', 'remote.origin.url']) ?? ''); - if (!origin) return `this checkout has no origin repository, so PR #${pr} cannot be matched to it`; - const r = gh(['pr', 'view', pr, ...(repo ? ['--repo', repo] : []), '--json', 'headRefName,headRepository,headRepositoryOwner']); - let v: { headRefName?: unknown; headRepository?: { name?: unknown }; headRepositoryOwner?: { login?: unknown } } = {}; + const remote = git(['config', '--get', `branch.${branch}.pushRemote`]) || git(['config', '--get', 'remote.pushDefault']) || 'origin'; + const pushTo = /([^/:]+)\/([^/]+?)(?:\.git)?\/*$/.exec(git(['config', '--get', `remote.${remote}.pushurl`]) || git(['config', '--get', `remote.${remote}.url`]) || ''); + if (!pushTo) return `this checkout's push remote ${remote} names no repository, so PR #${pr} cannot be matched to it`; + const r = gh(['pr', 'view', pr, ...(repo ? ['--repo', repo] : []), '--json', 'headRefName,headRepository,headRepositoryOwner,state']); + let v: { headRefName?: unknown; headRepository?: { name?: unknown }; headRepositoryOwner?: { login?: unknown }; state?: unknown } = {}; try { v = JSON.parse(r.out) ?? {}; } catch { v = {}; } const owner = v.headRepositoryOwner?.login, name = v.headRepository?.name; if (!r.ok || typeof v.headRefName !== 'string' || typeof owner !== 'string' || typeof name !== 'string') return `gh pr view ${pr} did not name its head branch and repository${r.ok ? '' : ` (${r.err.split('\n')[0]})`}`; - if (`${owner}/${name}`.toLowerCase() !== `${origin[1]}/${origin[2]}`.toLowerCase()) return `PR #${pr}'s head is on ${owner}/${name}, not this checkout's origin ${origin[1]}/${origin[2]}`; - return v.headRefName === branch ? null : `PR #${pr}'s head branch is ${v.headRefName}, not this checkout's ${branch}`; + if (`${owner}/${name}`.toLowerCase() !== `${pushTo[1]}/${pushTo[2]}`.toLowerCase()) return `PR #${pr}'s head is on ${owner}/${name}, not this checkout's ${remote === 'origin' ? 'origin' : `push remote ${remote}`} ${pushTo[1]}/${pushTo[2]}`; + if (v.headRefName !== branch) return `PR #${pr}'s head branch is ${v.headRefName}, not this checkout's ${branch}`; + return v.state === 'OPEN' ? null : `PR #${pr} is ${typeof v.state === 'string' ? v.state.toLowerCase() : 'in a state gh pr view did not name'}, not open`; } /** Write the body back: to --body, to a HOST_PUBLISH hand-off on Capy (GST-3183), else through gh pr edit. */ @@ -1093,10 +1106,16 @@ function cmdAbandoned(rest: string[]): number { const head = git(['rev-parse', 'HEAD'])?.toLowerCase(); if (!head) { process.stderr.write('gstack-ship-receipt abandoned: cannot resolve HEAD\n'); return EXIT.usage; } const wrongPr = read.pr ? prOffBranch(rest, read.pr) : null; - if (wrongPr) { process.stderr.write(`gstack-ship-receipt abandoned: ${wrongPr}: abandon marks only the PR this checkout's branch opened, so pass that PR's number; not marked\n`); return EXIT.refused; } + if (wrongPr) { process.stderr.write(`gstack-ship-receipt abandoned: ${wrongPr}: abandon marks only the open PR this checkout's branch opened, so pass that PR's number; not marked\n`); return EXIT.refused; } + if (read.pr && ![...receiptRuns(read.body).map(e => e.run), extractReceipt(read.body).receipt?.run].some(r => sameRun(r, run))) { process.stderr.write(`gstack-ship-receipt abandoned: PR #${read.pr}'s body records no entry for run ${run} (a stub, stop record or receipt), so the run is not this PR's; pass the PR the run wrote to, or --body for a body you hold; not marked\n`); return EXIT.refused; } const safe = keepsInternalIds(`${by} ${reason}`, process.cwd(), process.env, flag(rest, '--repo')); if (!safe) process.stderr.write('RUN_ABANDON_REDACTED: --by or --reason named a Capy thread or message id, and gh does not report this repository private, so the PR body says a private message in its place\n'); - const err = postBody(rest, read.pr, placeRunEntry(read.body, abandonMarker({ head, run, by: safe ? by : redactInternalIds(by), reason: safe ? reason : redactInternalIds(reason) }))); + const marker = abandonMarker({ head, run, by: safe ? by : redactInternalIds(by), reason: safe ? reason : redactInternalIds(reason) }); + const next = placeRunEntry(read.body, marker); + const leaks = [...publicReceiptLeaks({ abandon: marker }), ...runsBlockLeaks(next)]; + const visibility = leaks.length ? repoVisibility(process.cwd(), process.env, flag(rest, '--repo')) : 'private'; + if (renderMode(visibility, false) !== 'full') { process.stderr.write(`gstack-ship-receipt abandoned: the runs block would hold ${leaks.join(', ')}, and the repository's visibility is ${visibility}, not private: a PR body is public, so keep home paths out of --by and --reason and take any out of the body's earlier entries; not marked\n`); return EXIT.refused; } + const err = postBody(rest, read.pr, next); if (err) { process.stderr.write(`gstack-ship-receipt abandoned: ${err}; not marked\n`); return EXIT.fail; } process.stdout.write(`RUN_ABANDON_MARK: run=${run} head=${head.slice(0, 12)}\n`); return EXIT.ok; diff --git a/changelog.d/capy-public-pr-body-follow-ups.md b/changelog.d/capy-public-pr-body-follow-ups.md new file mode 100644 index 000000000..1b41cfb80 --- /dev/null +++ b/changelog.d/capy-public-pr-body-follow-ups.md @@ -0,0 +1,4 @@ +--- +important: security +--- +**`/gstack-ship` stops mistaking ordinary text for Capy ids, and checks every part of a public PR body it posts.** Text such as `SHA-256:abc`, `UTF-8:x`, `PR-12:fix` or a file named `test/jam_fix.ts` was refused or replaced by "a private message" on public repositories; now only real Capy ids (`jam_`, `icm_`, `iev_`) and relay refs whose message part is a Capy id or a timestamp count, and a relayed ruling still reads "relayed from a private message" whatever its ref looks like. On a public repository, `gstack-ship-receipt` write, carry and abandoned now also refuse a home folder path or Capy id in the earlier-runs block and abandon reasons, not only in the receipt. `gstack-ship-receipt abandoned --pr` marks only an open PR that records the run, and reads the repository the branch pushes to (its `pushRemote` or `remote.pushDefault`, else `origin`, at that remote's push URL), so contributors whose `origin` is upstream can use it once one of those names their fork. On private repositories, the merge check again accepts a `Gate disposition:` line written before ids were redacted, and a hand-edited earlier-runs entry with a non-text run no longer crashes the round count. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index bf3fe9c7d..71238b315 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -4027,9 +4027,24 @@ It also refuses a body that names a raw security finding fingerprint, such as and `gstack-post` refuses to send such text, exit 1: a PR body and every GitHub post are public, so a security finding appears only in the redacted form gstack renders ([security findings stay private](ship-policy.md#security-findings-stay-private)). + +On a repository `gh` does not report private (public, or visibility it cannot +read), write also refuses, writing nothing, when the receipt or the body's +```` ```gstack-receipt-runs ```` block (earlier runs, stop records and abandon +entries, with their who and why) holds a home folder path (`/home//`, +`/Users//`, `/root/`, `C:\Users\`) or a Capy thread or message id +(`jam_…`, `icm_…`, `iev_…`, or a relay ref like `GSTA-36:icm_…` or +`GSTA-36:2026-11-28T09:28Z`), and when a `Ruled note: …` line still says +`relayed from` anything but `a private message`. The refusal names the field +(`thread`, `gstack-receipt-runs[0].reason`), never the value. Text that only +looks like a ref, such as `SHA-256:abc`, `UTF-8:x` or `PR-12:fix`, and file +names such as `test/jam_fix.ts`, are not refused. **Fix.** Regenerate it with `gstack-ship-receipt write`; never hand-edit the -block. For a missing body line, add the line the refusal quotes to the body and +block. For a public-repo refusal, pass `--run `, leave +`--thread` out, list the `Ruled note: …` lines `gstack-approvals rulings` +prints now, and delete the path or id from the runs block entry the refusal +names. For a missing body line, add the line the refusal quotes to the body and write again. For a security fingerprint, replace the text that names it with the line `gstack-approvals rulings`, `gstack-approvals dispositions` or `gstack-review-scope render` prints, keep the details in your private report, @@ -7612,7 +7627,10 @@ not the checked-out HEAD, or the receipt records `gstack_version` without `review_depth` ([ship-policy.md](ship-policy.md#ship-receipt)). It refuses, too, when HEAD needs a targeted class (money, gate, auth, secret) that the receipt's `review_targeted` does not cover with a done pass, since the queue would refuse -that receipt. The receipt in +that receipt. On a repository `gh` does not report private, it refuses when the +carried receipt or the body's runs block still holds a home folder path or a +Capy thread or message id from an earlier write +([public repositories](#receipt-public-repo)). The receipt in the body is unchanged and still names the old head, so `gstack-ship-queue ready` refuses `QUEUE_RECEIPT_STALE`. @@ -7622,7 +7640,9 @@ already rewritten and the receipt predates `head_tree`, run /gstack-ship on the head; next time merge the base in instead of rebasing. For a retargeted stacked PR whose older receipt lost its parent branch, or a depth, targeted or exception refusal, run /gstack-ship on the new head. When `--head` is not the checked-out HEAD, -check it out and carry there. +check it out and carry there. For a public-repo refusal, delete the path or id +from the runs block entry the refusal names, or run /gstack-ship on the new head +for a fresh receipt. ### An unattended /gstack-ship stops on an open gate finding @@ -7933,6 +7953,37 @@ completes in one call: after `RUN_ABANDONED` the record is ended, so never rerun it, even when `RUN_ABANDON_PR` says the PR body entry was skipped or not recorded (add that entry with `gstack-ship-receipt abandoned` instead). + +### `gstack-ship-receipt abandoned` refuses a PR (exit 3) + +**Meaning.** `gstack-ship-receipt abandoned --pr ` (which `gstack-ship-run +abandon` calls) marks only this checkout's own open PR, and changed nothing +because one check failed: + +- this checkout has no branch, or `gh pr view` did not name the PR's head + branch and repository; +- the PR's head is on another repository than the one this branch pushes to + (its `branch..pushRemote`, else `remote.pushDefault`, else `origin`, at + that remote's `pushurl` or `url`), which is how a fork's PR from a branch of + the same name looks; +- the PR's head branch is not this checkout's branch; +- the PR is merged or closed, not open; +- the PR body records no entry (a stub, stop record or receipt) for the run, so + the run never wrote to this PR; +- on a repository `gh` does not report private, the runs block would hold a + home folder path, from `--by`, `--reason` or an earlier entry + ([public repositories](#receipt-public-repo)). A Capy id in `--by` or + `--reason` is not refused: it is replaced by `a private message` + (`RUN_ABANDON_REDACTED:`). + +`--body ` edits a body you hold, so only the last check applies to it. + +**Fix.** Check out the branch the run shipped and pass the PR that branch +opened. A contributor whose `origin` is upstream sets +`git config branch..pushRemote ` so the check reads the fork. +A run that never wrote to the PR needs no mark: the run record is already +abandoned. Keep home paths out of `--reason`. + ### `SHIP_RUN_RECORD_UNREADABLE` diff --git a/lib/gate-dispositions.ts b/lib/gate-dispositions.ts index 347e611b5..1ff8dc553 100644 --- a/lib/gate-dispositions.ts +++ b/lib/gate-dispositions.ts @@ -17,7 +17,7 @@ import { createHash } from 'node:crypto'; import { spawnSync } from './spawn-sync'; import * as fs from 'node:fs'; -import { appendRows, locate, readRecord, type ApprovalRow, type Env, type RecordError, type StoreLocation } from './approval-record'; +import { appendRows, locate, readRecord, repoVisibility, type ApprovalRow, type Env, type RecordError, type RepoVisibility, type StoreLocation } from './approval-record'; import type { ShipReceipt } from './headless-artifacts'; import type { ResultCodeName } from './result-codes'; import { isGstackActor, redactInternalIds, type RuledNote } from './ruled-notes'; @@ -140,7 +140,8 @@ export type GateAcceptanceCode = Extract `GATE_DISPOSITION: ${gateDispositionText(d)}`); + const bodyHas = (text: string) => o.body.split(/\r?\n/).some(b => b.trim() === `Gate disposition: ${text}`); + let visibility: RepoVisibility | undefined; + const isPrivate = () => (visibility ??= repoVisibility(o.cwd, o.env ?? process.env)) === 'private'; if (!applied.length && !listed.length && !o.accepted?.length) return { lines, applied, noteRows }; const problems: string[] = []; for (const d of applied) { - const r = listed.find(l => l.approval === d.approval); + const r = listed.find(l => l.approval === d.approval), legacy = dispositionLine(securityRedacted(d)); if (!r) problems.push(recorded ? `the receipt omits applied disposition ${d.approval}` : `the receipt has no gate_dispositions field (written before receipts always recorded it, or edited), but ${where} applies disposition ${d.approval}`); else if (gateDispositionText(r as GateDisposition) !== gateDispositionText(d)) problems.push(`the receipt's disposition ${d.approval} differs from the store's row`); - if (!o.body.split(/\r?\n/).some(b => b.trim() === `Gate disposition: ${gateDispositionText(d)}`)) problems.push(`the PR body lacks the line "Gate disposition: ${gateDispositionText(d)}"`); + if (!bodyHas(gateDispositionText(d)) && !(legacy !== gateDispositionText(d) && bodyHas(legacy) && isPrivate())) problems.push(`the PR body lacks the line "Gate disposition: ${gateDispositionText(d)}"`); } for (const l of listed) if (!applied.some(d => d.approval === l.approval)) problems.push(`the receipt lists disposition ${l.approval}, which ${where} does not apply at ${o.pin.slice(0, 12)}: this lander may read another GSTACK_STATE_ROOT or approvals mirror than the one the owner recorded into (set GSTACK_APPROVALS_DIR to it), or the row was removed after the receipt was written`); if (o.accepted) { @@ -177,12 +181,14 @@ export function gateAcceptance(o: { cwd: string; branch: string; pin: string; bo * (GST-1955), so the dispositions command, finish, the receipt and the queue's store check render one line. */ export const publicGateDisposition = (d: GateDisposition): GateDisposition => { - const p = isSecurityFinding(d.finding) ? { ...d, finding: REDACTED_FINDING, reason: REDACTED_REASON, words: REDACTED_WORDS } : d; + const p = securityRedacted(d); return { ...p, by: redactInternalIds(p.by), reason: redactInternalIds(p.reason), words: redactInternalIds(p.words) }; }; +const securityRedacted = (d: GateDisposition): GateDisposition => isSecurityFinding(d.finding) ? { ...d, finding: REDACTED_FINDING, reason: REDACTED_REASON, words: REDACTED_WORDS } : d; +const dispositionLine = (d: GateDisposition) => `${d.finding} [gate ${d.gate_id}] at ${d.head.slice(0, 12)} by ${d.by} at ${d.at}: ${d.reason} — "${d.words}" (approval ${d.approval})`; /** The one-line form finish prints after `GATE_DISPOSITION: ` and the PR body carries after `Gate disposition: `, from publicGateDisposition. */ -export const gateDispositionText = (disposition: GateDisposition) => { const d = publicGateDisposition(disposition); return `${d.finding} [gate ${d.gate_id}] at ${d.head.slice(0, 12)} by ${d.by} at ${d.at}: ${d.reason} — "${d.words}" (approval ${d.approval})`; }; +export const gateDispositionText = (disposition: GateDisposition) => dispositionLine(publicGateDisposition(disposition)); /** * The dispositions that close a review row's gate findings: the same fingerprint and gate_id on a gate finding the logger left diff --git a/lib/pr-review-history.ts b/lib/pr-review-history.ts index 816d8ed99..e2e01b935 100644 --- a/lib/pr-review-history.ts +++ b/lib/pr-review-history.ts @@ -48,7 +48,7 @@ export function prReviewHistory(body: string): PrReviewHistory { const ordered: Array = []; all.forEach((e, i) => { if (e.status === 'voided' || e.carry_kind || e.carried_from) { ordered.push(e); return; } - const key = e.run ? `run:${runId(e.run)}@${e.head}` : `#${i}`; + const key = typeof e.run === 'string' && e.run ? `run:${runId(e.run)}@${e.head}` : `#${i}`; if (!reviewed.has(key)) ordered.push(key); reviewed.set(key, e); }); @@ -73,8 +73,9 @@ export function prReviewHistory(body: string): PrReviewHistory { */ export function placeRunEntry(body: string, entry: ReceiptRun): string { const runs = receiptRuns(body).filter(r => !(entry.status && r.status && sameRun(r.run, entry.run))); - if (entry.mark && runs.some(r => JSON.stringify(r) === JSON.stringify(entry))) return body; - const kept = keptRuns([...runs, JSON.parse(JSON.stringify(entry)) as ReceiptRun]); + const [placed] = keptRuns([JSON.parse(JSON.stringify(entry)) as ReceiptRun]); + if (entry.mark && keptRuns(runs).some(r => JSON.stringify(r) === JSON.stringify(placed))) return body; + const kept = keptRuns([...runs, placed!]); const block = '```' + RUNS_FENCE + '\n' + kept.map(r => JSON.stringify(r)).join('\n') + '\n```\n'; if (RUNS_RE.test(body)) return body.replace(RUNS_RE, () => block); if (extractReceipt(body).found) { diff --git a/lib/ruled-notes.ts b/lib/ruled-notes.ts index 0157af485..999509e15 100644 --- a/lib/ruled-notes.ts +++ b/lib/ruled-notes.ts @@ -34,8 +34,17 @@ export const OWNER_REF = /^[A-Z][A-Z0-9]*-[1-9]\d*:[A-Za-z0-9][\w.:+-]*$/; /** * A Capy thread or message id as public text must never carry it (GST-1955, CAPY-1 qm#3938): a `jam_` thread id, an `icm_` or `iev_` * message id, or a relay ref in OWNER_REF's shape, `:`. A thread code alone (`GStack Minder (GSTA-36)`) names a ruler. + * Two exemptions sit on top of those catches (GST-4105), each a lookaround that leaves the matched text as it was: an id right after a + * `/` is a file name (`test/jam_fix.ts`) unless it is a full 26-character Capy id, and a ref's message part must be a Capy id, an + * ISO date or time (`2026-11-19`, `2026-11-28T09:28Z`) or epoch seconds (`1732790000`), so `SHA-256:abc`, `UTF-8:x`, `PR-12:fix` and `A-1:b` are text. A relayed ruling's ref reads + * PRIVATE_REF on a public repository whatever its shape (repoRuledNotes). */ -export const INTERNAL_ID = /\b(?:jam|icm|iev)_[A-Za-z0-9]+|\b[A-Z][A-Z0-9]*-[1-9]\d*:[A-Za-z0-9][\w.:+-]*/; +export const INTERNAL_ID = /\b(?:(?)` between the ruler and ` at