diff --git a/bin/gstack-approvals b/bin/gstack-approvals index c326233e9..aec5d1bf7 100755 --- a/bin/gstack-approvals +++ b/bin/gstack-approvals @@ -28,7 +28,7 @@ import { spawnSync } from 'node:child_process'; import * as path from 'node:path'; import { EXIT, exitTableHelp } from '../lib/headless-artifacts'; import { appendRows, branchExists, buildRow, importAutoplan, locate, readRecord, renderMode, renderRecord, repoVisibility, syncRecord, type RecordError, type StoreLocation } from '../lib/approval-record'; -import { isGstackActor, openShipRun, OWNER_REF, OWNER_REF_SHAPE, RULED_NOTE_SCOPE, ruledNoteRow, ruledNoteSource, ruledNotes, ruledNoteText } from '../lib/ruled-notes'; +import { isGstackActor, openShipRun, OWNER_REF, OWNER_REF_SHAPE, repoRuledNotes, RULED_NOTE_SCOPE, ruledNoteRow, ruledNoteSource, ruledNotes, ruledNoteText } from '../lib/ruled-notes'; import { resultLine } from '../lib/result-codes'; import { parsePlanLine, publicPlanLine, resolvePlan } from '../lib/plan-record'; import { TEST_LANE_EXCEPTION_SCOPE, testLaneExceptionRow } from '../lib/test-lane-exception'; @@ -46,13 +46,16 @@ const HELP = `gstack-approvals — the per-thread approval record (capy/skill/gs the owner's ruling that a review finding ships as a disclosed note (docs/ship-policy.md#ruled-notes); the receipt write counts that finding closed at a head that holds the ruled head, and the receipt and PR body list it; inside this checkout's open /ship run it needs --owner-ref, the message the lane relays the owner's - words from, and the row, receipt and Ruled note line then say relayed from it (APPROVAL_RULING_RUN_OPEN without); + words from, and the row, receipt and Ruled note line then say relayed from it (APPROVAL_RULING_RUN_OPEN without; + on a repository gh does not report private, the line and receipt say relayed from a private message, and the + ref stays in the row); the ref is ${OWNER_REF_SHAPE}; --not-security: the owner's call that a red-team finding is not security class, so public text shows it; --finding edit: rules an edit after the final review a note: finish routes that path at the head's bytes as RULED_EDIT instead of stopping (docs/ship-policy.md#ruled-edits); refused while a /ship run is open on this checkout - rulings the "Ruled note: …" lines the Pre-Landing Review and the PR body carry + rulings the "Ruled note: …" lines the Pre-Landing Review and the PR body carry, in the form + finish prints and receipt write checks gate --finding --gate-id --head --reason --words --by the owner's disposition of a gate finding an unattended /ship logged open (docs/ship-policy.md#gate-dispositions); @@ -268,7 +271,7 @@ function main(argv: string[]): number { return EXIT.ok; } if (cmd === 'rulings') { - const notes = ruledNotes(readRecord(loc).rows); + const notes = repoRuledNotes(ruledNotes(readRecord(loc).rows), process.cwd()); process.stdout.write(notes.length ? notes.map(n => `Ruled note: ${ruledNoteText(n)}\n`).join('') : 'RULED_NOTES: none\n'); return EXIT.ok; } diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receipt index c784f2e06..f51702566 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, - RUNS_FENCE, receiptIssuesFrom, receiptRuns, receiptSummaryLine, renderCensus, renderReceiptBlock, unruledOpenBlockers, validateReceipt, type CensusPr, + publicReceiptLeaks, RUNS_FENCE, receiptIssuesFrom, receiptRuns, receiptSummaryLine, renderCensus, renderReceiptBlock, runId, 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,8 @@ 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 { bodyListsLine, publicRuledNote, readRuledNotes, ruledNoteText } from '../lib/ruled-notes'; +import { bodyLineText, bodyListsLine, INTERNAL_ID, keepsInternalIds, publicRuledNote, readRuledNotes, redactInternalIds, 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'; import { laneExceptionBodyLines } from '../lib/test-lane-exception'; @@ -304,9 +305,11 @@ async function cmdWrite(rest: string[], json: boolean): Promise { if (flag(rest, '--review-loop-exception') !== undefined) { process.stderr.write(resultLineWithDocs('gstack-ship-receipt write', 'REVIEW_LOOP_EXCEPTION_INVALID', '--review-loop-exception was removed with fix-check grants (GST-3562 part 4): an open finding at the round cap ships only as a Ruled note the lane\'s Captain records with gstack-approvals rule; nothing written') + '\n'); return EXIT.usage; } const leaked = securityFingerprints(bodyText); if (leaked.length) { process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_INVALID', `${bodyFile} names security finding ${leaked.join(', ')}: a PR body is public, so a security finding appears only as the redacted line gstack-approvals rulings, dispositions or gstack-review-scope render prints, and its location and reason stay in the private record (docs/troubleshooting.md#security-finding-in-body); nothing written`) + '\n'); return EXIT.fail; } - const ruledNotes = readRuledNotes(repoRoot); + 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; } 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; } @@ -352,6 +355,8 @@ async function cmdWrite(rest: string[], json: boolean): Promise { try { targeted = parseReviewTargeted(jsonArg(flag(rest, '--review-targeted')), product.product_patch_id ?? 'none', read => reviewedProduct(repoRoot, base, read, pregateFile).product_patch_id, read => targetedClassesSince(repoRoot, read, headSha ?? head, base, review.exclude.state === 'active' ? review.exclude.excluded : undefined), read => plainDocsSince(repoRoot, read, headSha ?? head, base), read => spawnSync('git', ['merge-base', '--is-ancestor', read, headSha ?? head], { cwd: repoRoot, timeout: 30_000 }).status === 0, read => ruledChangeSince(repoRoot, read, headSha ?? head, base)); } catch (e: any) { targeted = { ok: false, message: `--review-targeted: ${e.message}` }; } } if (targeted && !targeted.ok) { process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_INVALID', `${targeted.message}; nothing written`) + '\n'); return EXIT.fail; } + const edits = targeted?.ok ? targeted.targeted.ruled_edits ?? [] : []; + if (targeted?.ok && edits.length && !keepsInternalIds(edits.map(e => e.by).join(' '), repoRoot, process.env, flag(rest, '--repo'))) targeted.targeted.ruled_edits = edits.map(e => ({ ...e, by: redactInternalIds(e.by) })); for (const e of targeted?.ok ? targeted.targeted.ruled_edits ?? [] : []) process.stderr.write(`TARGETED_RULED: ${e.path} (the targeted record read at ${targeted!.ok ? targeted!.targeted.read?.slice(0, 12) : ''} carries across the edit ruled by ${e.by}, approval ${e.approval}; no targeted class changed)\n`); const approval = approvalForReceipt({ repoRoot, base, head, citationText: [bodyText, ...flags(rest, '--approval')].join('\n'), runDirs: flags(rest, '--approval-run') }); if (approval.kind === 'invalid') { @@ -389,7 +394,7 @@ async function cmdWrite(rest: string[], json: boolean): Promise { gate: jsonArg(flag(rest, '--gate')), ci: jsonArg(flag(rest, '--ci')), ci_carried: carried, spend_usd: flag(rest, '--spend-usd') !== undefined ? (Number.isFinite(Number(flag(rest, '--spend-usd'))) ? Number(flag(rest, '--spend-usd')) : flag(rest, '--spend-usd')) : undefined, calls: callsArg(rest), - session_kind: sessionKind, artifacts_consumed: flag(rest, '--artifacts-consumed'), run: flag(rest, '--run'), thread: flag(rest, '--thread'), + session_kind: sessionKind, artifacts_consumed: flag(rest, '--artifacts-consumed'), run: runFlag(rest), thread: flag(rest, '--thread'), policy: flag(rest, '--policy') ?? tree?.policy, queue_mode: flag(rest, '--queue-mode'), preregistration: flag(rest, '--preregistration'), history: flag(rest, '--history'), ...pregate, issues: issuesFile ? receiptIssuesFrom(issuesFile) : undefined, approval: approval.kind === 'ok' ? approval.approval : undefined, review_loop: reviewLoop, ...(docs?.ok ? { docs: docs.docs } : {}), ...product, @@ -410,6 +415,12 @@ async function cmdWrite(rest: string[], json: boolean): Promise { process.stderr.write('gstack-ship-receipt write: nothing written\n'); return EXIT.fail; } + const leaks = publicReceiptLeaks(receipt); + const visibility = leaks.length ? repoVisibility(repoRoot, process.env, flag(rest, '--repo')) : 'private'; + if (renderMode(visibility, false) !== 'full') { + process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_INVALID', `the receipt holds ${leaks.join(', ')}, and the repository's visibility is ${visibility}, not private: a PR body is public, so pass --run , leave --thread out and keep home paths and Capy thread or message ids out of every flag and of the records the receipt copies (no-stop evidence, gate dispositions, CI-carry and flaky exceptions); nothing written`) + '\n'); + return EXIT.fail; + } const targetedVerdict = receiptTargetedAtHead(repoRoot, `origin/${base.replace(/^origin\//, '')}`, receipt, receipt.head); if (targetedVerdict.line.includes('(unchecked: ')) process.stderr.write(targetedVerdict.line + '\n'); if (!targetedVerdict.ok) { @@ -862,10 +873,13 @@ function cmdCarry(rest: string[], json: boolean): number { // A receipt that records a version names HEAD's, read as write reads it: a restamp after a base merge moves it (GST-1030). // A head with no version source keeps the recorded one (write --version named it). const version = receipt.version === undefined ? undefined : (receiptVersion(repoRoot, head, base) ?? receipt.version); - const rebound = { ...receipt, ...(version !== undefined ? { version } : {}), ...(retarget ? { base: base.replace(/^origin\//, '') } : {}), ...(pregateField ?? {}), ...depthField }; + const rebound = { ...receipt, ...(typeof receipt.run === 'string' ? { run: runId(receipt.run) } : {}), ...(version !== undefined ? { version } : {}), ...(retarget ? { base: base.replace(/^origin\//, '') } : {}), ...(pregateField ?? {}), ...depthField }; 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 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`); 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); @@ -961,6 +975,27 @@ function readBody(rest: string[]): { ok: true; body: string; pr?: string } | { o try { return { ok: true, body: JSON.parse(r.out).body ?? '', pr }; } catch { return { ok: false, why: 'gh returned no JSON body', fix: 'rerun; check gh auth status' }; } } +/** --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); }; + +/** + * 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. + */ +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 } } = {}; + 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}`; +} + /** Write the body back: to --body, to a HOST_PUBLISH hand-off on Capy (GST-3183), else through gh pr edit. */ function postBody(rest: string[], pr: string | undefined, body: string): string | null { const bodyFile = flag(rest, '--body'); @@ -997,7 +1032,7 @@ function cmdHistory(rest: string[], json: boolean): number { const h = prReviewHistory(read.body); const route = reviewRoute(h); const flagsLine = `PR_REVIEW_FLAGS: --prior-rounds ${h.rounds} --prior-full ${h.full}`; - const used = flag(rest, '--run') ? receiptedRun(read.body, flag(rest, '--run')!) : undefined; + const used = runFlag(rest) ? receiptedRun(read.body, runFlag(rest)!) : undefined; if (json) { process.stdout.write(JSON.stringify({ pr, ...h, route, run_used: used?.head ?? null }) + '\n'); return EXIT.ok; } process.stdout.write(`${historyLine(pr, h)}\n${flagsLine}\nPR_REVIEW_ROUTE: ${route.route} (${route.reason})\n${used ? `PR_REVIEW_RUN_USED: run=${used.run} receipted at ${used.head.slice(0, 12)}\n` : ''}`); return EXIT.ok; @@ -1007,7 +1042,7 @@ const ancestorIn = (repoRoot: string) => (a: string, d: string) => a === d || sp /** Step 9 on NEXT: stop (GST-2968): record the review this run stopped on, in the PR body when one exists and in the run record (HARN-138: a stop before any PR records the run record only). */ function cmdStop(rest: string[]): number { - const run = flag(rest, '--run'), since = flag(rest, '--since'); + const run = runFlag(rest), since = flag(rest, '--since'); if (!run || !/^[\w.:-]{1,120}$/.test(run) || !since) { process.stderr.write('gstack-ship-receipt stop: --run and --since are required\n'); return EXIT.usage; } const repoRoot = git(['rev-parse', '--show-toplevel']); if (!repoRoot) { process.stderr.write('gstack-ship-receipt stop: run it inside the git checkout\n'); return EXIT.usage; } @@ -1031,7 +1066,7 @@ function cmdStop(rest: string[]): number { /** Step 9: this run's rounds so far, recorded before its receipt exists (a started stub), or voided. */ function cmdStub(rest: string[]): number { - const run = flag(rest, '--run'); + const run = runFlag(rest); if (!run || !/^[\w.:-]{1,120}$/.test(run)) { process.stderr.write('gstack-ship-receipt stub: --run is required\n'); return EXIT.usage; } const read = readBody(rest); if (!read.ok) { process.stderr.write(`gstack-ship-receipt stub: ${read.why}; fix: ${read.fix}\n`); return EXIT.fail; } @@ -1051,13 +1086,17 @@ function cmdStub(rest: string[]): number { /** gstack-ship-run abandon's PR-body half (GST-3260): a mark:abandoned entry in the runs block naming the run, who ended it and why. */ function cmdAbandoned(rest: string[]): number { - const run = flag(rest, '--run'), by = flag(rest, '--by')?.trim(), reason = flag(rest, '--reason')?.trim(); + const run = runFlag(rest), by = flag(rest, '--by')?.trim(), reason = flag(rest, '--reason')?.trim(); if (!run || !/^[\w.:-]{1,128}$/.test(run) || !by || !reason || /[\x00-\x1f\x7f]/.test(by + reason)) { process.stderr.write('gstack-ship-receipt abandoned: --run , --by and --reason are required\n'); return EXIT.usage; } const read = readBody(rest); if (!read.ok) { process.stderr.write(`gstack-ship-receipt abandoned: ${read.why}; fix: ${read.fix}\n`); return EXIT.fail; } const head = git(['rev-parse', 'HEAD'])?.toLowerCase(); if (!head) { process.stderr.write('gstack-ship-receipt abandoned: cannot resolve HEAD\n'); return EXIT.usage; } - const err = postBody(rest, read.pr, placeRunEntry(read.body, abandonMarker({ head, run, by, reason }))); + 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; } + 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) }))); 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/fix-public-pr-body-leaks.md b/changelog.d/fix-public-pr-body-leaks.md new file mode 100644 index 000000000..a6423d271 --- /dev/null +++ b/changelog.d/fix-public-pr-body-leaks.md @@ -0,0 +1,4 @@ +--- +important: security +--- +**`/gstack-ship` no longer puts home folder paths or Capy thread and message ids into PR bodies on public repositories.** The ship receipt stored `--run` as given, so runs that passed their run folder's path published `/home//...`. It now keeps only the folder's name, both when writing and when carrying a receipt to a new head, and older receipts that still hold the full path keep matching their run. On a repository GitHub doesn't report as private (checking the `--repo` a command publishes to as well as the checkout's own), a receipt that would still hold a home path or a Capy id (`jam_`, `icm_`, `iev_` or `:`) in any value or key is refused before anything is written or carried. A ruling relayed from a Capy message reads "relayed from a private message" in `gstack-approvals rulings`, in finish's output and in the receipt, and a Capy id in a ruling's ruler or reason, or in a gate disposition's recorder, reason or words, reads the same way, so a PR carrying a Captain's ruling still gets a clean receipt. The approval record keeps the real references. `gstack-ship-receipt abandoned` refuses a PR whose head isn't this checkout's branch on its origin repository, instead of marking someone else's or a fork's PR, and leaves Capy ids out of the entry it writes on a public repository. diff --git a/docs/ship-policy.md b/docs/ship-policy.md index bfbdc7f20..8cde626f8 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -1856,7 +1856,8 @@ relays the owner's words with `--owner-ref :`, and its `RULED_NOTE:`, receipt entry and `Ruled note:` line say `(relayed from )`, so a reader can check the words against that -message; without it the refusal is `APPROVAL_RULING_RUN_OPEN`. `add` refuses a +message. On a repository gh does not report as private they say `(relayed from a private +message)` instead, and the ref stays in the approval record. Without `--owner-ref` the refusal is `APPROVAL_RULING_RUN_OPEN`. `add` refuses a `ruled_note` scope, so `rule` is the only path. A review-log field never makes a ruling: `ruled`, `action: "ruled"` or any other claim the lane writes on its own row is ignored. Step 16's `finish` reads the branch's rulings diff --git a/lib/approval-record.ts b/lib/approval-record.ts index 62e293fc5..4efef5e98 100644 --- a/lib/approval-record.ts +++ b/lib/approval-record.ts @@ -297,10 +297,10 @@ export type RepoVisibility = 'public' | 'private' | 'unknown'; /** * The repository's visibility as GitHub reports it through gh, for the repository gh acts on by default (GH_REPO, its - * default repo, an upstream remote) and for the origin remote a PR is opened against: private only when every one - * asked is private, public when any is public, and unknown for anything gh cannot answer. + * default repo, an upstream remote) and for the origin remote a PR is opened against, plus `target` when a command publishes to an + * explicit --repo: private only when every one asked is private, public when any is public, and unknown for anything gh cannot answer. */ -export function repoVisibility(cwd: string, env: Env = process.env): RepoVisibility { +export function repoVisibility(cwd: string, env: Env = process.env, target?: string): RepoVisibility { const ask = (repo: string[]): RepoVisibility => { const r = spawnSync('gh', ['repo', 'view', ...repo, '--json', 'visibility', '-q', '.visibility'], { cwd, env, encoding: 'utf8', timeout: 15_000 }); if (r.status !== 0) return 'unknown'; @@ -309,7 +309,7 @@ export function repoVisibility(cwd: string, env: Env = process.env): RepoVisibil }; const origin = spawnSync('git', ['remote', 'get-url', 'origin'], { cwd, env, encoding: 'utf8', timeout: 15_000 }); const slug = origin.status === 0 ? /([^/:]+\/[^/]+?)(?:\.git)?\/*$/.exec(origin.stdout.trim())?.[1] : undefined; - const seen = [ask([]), ...(slug ? [ask([slug])] : [])]; + const seen = [ask([]), ...(slug ? [ask([slug])] : []), ...(target ? [ask([target])] : [])]; return seen.includes('public') ? 'public' : seen.every(v => v === 'private') ? 'private' : 'unknown'; } diff --git a/lib/gate-dispositions.ts b/lib/gate-dispositions.ts index 16545559f..347e611b5 100644 --- a/lib/gate-dispositions.ts +++ b/lib/gate-dispositions.ts @@ -20,7 +20,7 @@ import * as fs from 'node:fs'; import { appendRows, locate, readRecord, type ApprovalRow, type Env, type RecordError, type StoreLocation } from './approval-record'; import type { ShipReceipt } from './headless-artifacts'; import type { ResultCodeName } from './result-codes'; -import { isGstackActor, type RuledNote } from './ruled-notes'; +import { isGstackActor, redactInternalIds, type RuledNote } from './ruled-notes'; import { isSecurityFinding, REDACTED_FINDING, REDACTED_REASON, REDACTED_WORDS } from './security-findings'; import { openRun, readRunRecord, withGateLock } from './ship-run-record'; @@ -171,8 +171,15 @@ export function gateAcceptance(o: { cwd: string; branch: string; pin: string; bo return problems.length ? { lines, applied, noteRows, failure: { code: 'QUEUE_GATE_DISPOSITION', message: problems.join('; '), fix } } : { lines, applied, noteRows }; } -/** The disposition as public text may carry it: a security-class finding's fingerprint, reason and owner words stay in the approval record (GST-3076). */ -export const publicGateDisposition = (d: GateDisposition): GateDisposition => isSecurityFinding(d.finding) ? { ...d, finding: REDACTED_FINDING, reason: REDACTED_REASON, words: REDACTED_WORDS } : d; +/** + * The disposition as public text may carry it: a security-class finding's fingerprint, reason and owner words stay in the approval + * record (GST-3076), and a Capy thread or message id in its recorder, reason or words reads PRIVATE_REF on every repository + * (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; + return { ...p, by: redactInternalIds(p.by), reason: redactInternalIds(p.reason), words: redactInternalIds(p.words) }; +}; /** 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})`; }; diff --git a/lib/pr-review-history.ts b/lib/pr-review-history.ts index d9dc11963..816d8ed99 100644 --- a/lib/pr-review-history.ts +++ b/lib/pr-review-history.ts @@ -9,7 +9,7 @@ */ import type { ShipReceipt } from './headless-artifacts'; import { withAgentNotes, splitAgentNotes } from './agent-notes'; -import { extractReceipt, keptRuns, receiptRun, receiptRuns, RUNS_FENCE, RUNS_RE, type ReceiptRun } from './ship-receipt'; +import { extractReceipt, keptRuns, receiptRun, receiptRuns, runId, RUNS_FENCE, RUNS_RE, sameRun, type ReceiptRun } from './ship-receipt'; import { FULL_PASS_CAP } from './review-depth'; export interface PrReviewHistory { @@ -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:${e.run}@${e.head}` : `#${i}`; + const key = e.run ? `run:${runId(e.run)}@${e.head}` : `#${i}`; if (!reviewed.has(key)) ordered.push(key); reviewed.set(key, e); }); @@ -72,7 +72,7 @@ export function prReviewHistory(body: string): PrReviewHistory { * The receipt, when there is one, is unchanged; a body without one gets the block in its Agent notes section. */ export function placeRunEntry(body: string, entry: ReceiptRun): string { - const runs = receiptRuns(body).filter(r => !(entry.status && r.status && r.run === entry.run)); + 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 block = '```' + RUNS_FENCE + '\n' + kept.map(r => JSON.stringify(r)).join('\n') + '\n```\n'; @@ -99,7 +99,7 @@ export const stopMarker = (o: { head: string; tree: string; run: string; at?: st /** gstack-ship-run abandon's entry (GST-3260): who ended a run that stopped working, and why, at the head it was abandoned on. */ export const abandonMarker = (o: { head: string; run: string; by: string; reason: string }): ReceiptRun => ({ head: o.head, run: o.run, mark: 'abandoned', by: o.by, reason: o.reason }); /** The newest receipt a run id already wrote, in the runs block or current: a run id names one /ship run (gstack-evals#406). */ -export const receiptedRun = (body: string, run: string) => entries(body).filter(e => e.run === run && !e.mark && !e.status).at(-1); +export const receiptedRun = (body: string, run: string) => entries(body).filter(e => sameRun(e.run, run) && !e.mark && !e.status).at(-1); /** The rows a /ship stop can follow: a full pass or a Step 11 voice (#4591 stopped on its voices); a legacy fix-check row too. */ const STOP_READERS = new Set(['review', 'review-fix-check', 'adversarial-review', 'codex-review']); diff --git a/lib/ruled-notes.ts b/lib/ruled-notes.ts index 180c30827..0157af485 100644 --- a/lib/ruled-notes.ts +++ b/lib/ruled-notes.ts @@ -5,7 +5,7 @@ * full sha of the stop head the owner ruled at; the row's `by` is the ruler and its `recorded_at` the time. A review-log field * never makes one, so the lane that logged a finding cannot close it. */ -import { locate, readRecord, type ApprovalRow, type Env } from './approval-record'; +import { locate, readRecord, renderMode, repoVisibility, type ApprovalRow, type Env } from './approval-record'; import { isSecurityFinding, REDACTED_FINDING, REDACTED_REASON } from './security-findings'; import { openRun, readRunRecord } from './ship-run-record'; import { spawnSync } from './spawn-sync'; @@ -31,6 +31,24 @@ export const RULED_NOTE_SCOPE = /^\s*ruled_note\b/; export const ruledNoteRow = (finding: string, head: string, reason: string) => ({ scope: `ruled_note ${finding} ${head}`, ask: `ruled_note ${finding} at ${head}: ${reason}` }); /** Where a lane relays the owner's ruling from: `:`, a message a reader can look up. */ 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. + */ +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.:+-]*/; +/** What public text says in place of an INTERNAL_ID: the relay a Ruled note names, and any id in an abandon entry's who and why. */ +export const PRIVATE_REF = 'a private message'; +export const redactInternalIds = (text: string) => text.replace(new RegExp(INTERNAL_ID.source, 'g'), PRIVATE_REF); +/** Whether public text for the repository at cwd (and an explicit --repo target) may keep its internal ids: gh is asked only when text holds one, and only a repository gh reports private keeps them. */ +export const keepsInternalIds = (text: string, cwd: string, env: Env = process.env, target?: string) => !INTERNAL_ID.test(text) || renderMode(repoVisibility(cwd, env, target), false) === 'full'; +/** + * The rulings as this repository's public text carries them: gstack-approvals rulings, finish's RULED_NOTE lines and the receipt's + * ruled_notes all read them here, so all three agree. On a public or unknown-visibility repository a relayed ruling says it was + * relayed from PRIVATE_REF, an id in its ruler or reason reads PRIVATE_REF too, and the approval record's row keeps them (CAPY-1 qm#3938). + */ +export const repoRuledNotes = (notes: RuledNote[], cwd: string, env: Env = process.env, target?: string): RuledNote[] => + keepsInternalIds(notes.map(n => `${n.relayed ?? ''} ${n.by} ${n.reason}`).join(' '), cwd, env, target) ? notes + : notes.map(n => ({ ...n, by: redactInternalIds(n.by), reason: redactInternalIds(n.reason), ...(n.relayed ? { relayed: PRIVATE_REF } : {}) })); /** OWNER_REF in words, for the refusals and help that name it; a refusal never echoes the rejected ref, which may hold anything (#4718). */ export const OWNER_REF_SHAPE = ':, where the thread code is an uppercase letter, then uppercase letters or digits, a dash and a number from 1, and the message part starts with a letter or digit (GSTA-36:2026-11-19T12:29:59Z)'; const RED_TEAM = /:red-team$/i; diff --git a/lib/ship-receipt.ts b/lib/ship-receipt.ts index 431a2ec37..adc9d9a06 100644 --- a/lib/ship-receipt.ts +++ b/lib/ship-receipt.ts @@ -13,7 +13,7 @@ import { approvalSummary } from './approval-citations'; import { FRAGMENT_README } from './changelog-fragments'; import { renderIssueLines } from './issue-links'; import { matchesAny } from './ship-policy'; -import { ruledNoteText } from './ruled-notes'; +import { INTERNAL_ID, ruledNoteText } from './ruled-notes'; import { gateDispositionText } from './gate-dispositions'; import { laneExceptionBodyLines } from './test-lane-exception'; import { rerunMarker } from './run-evidence'; @@ -21,6 +21,35 @@ import { stampFileKind, versionStampOnly } from './pregate/stamp-only'; import { stampOnlyLine, type BranchSide } from './stamp-only'; export const RECEIPT_FENCE = 'gstack-ship-receipt'; + +/** + * A /ship run id as receipts store and compare it: the run dir's name (GST-1955). Runs that passed `--run` the run dir's path put + * `/home//.capy/work/ship-` in 20 of 60 merged public receipts, so write keeps the name, and every comparison reads both + * sides through runId, so an older entry that holds the path still names the same run. + */ +export const runId = (run: string) => run.replace(/[\\/]+$/, '').split(/[\\/]/).at(-1)!; +export const sameRun = (a: unknown, b: unknown) => typeof a === 'string' && typeof b === 'string' && runId(a) === runId(b); +/** A home directory at the start of a path or after a separator: `/home//`, `/Users//`, `/root/` or `C:\\Users\\`. */ +const HOME_PATH = /(?`). write and carry refuse a receipt that names any on a repository gh does not report private (GST-1955). + */ +export function publicReceiptLeaks(receipt: unknown): string[] { + const out: string[] = []; + const walk = (v: unknown, at: string): void => { + if (typeof v === 'string') for (const [re, what] of [[HOME_PATH, 'a home path'], [INTERNAL_ID, 'a Capy thread or message id']] as const) { if (re.test(v)) out.push(`${at} (${what})`); } + else if (Array.isArray(v)) v.forEach((x, i) => walk(x, `${at}[${i}]`)); + else if (v && typeof v === 'object') Object.entries(v).forEach(([k, x], i) => { + const leaky = HOME_PATH.test(k) || INTERNAL_ID.test(k), seg = leaky ? `` : k, here = at ? `${at}.${seg}` : seg; + if (leaky) out.push(`${here} (a home path or Capy id in a key)`); + walk(x, here); + }); + }; + walk(receipt, ''); + return out; +} + const KEY_ORDER: Array = [ 'schema_version', 'pr', 'head', 'version', 'base', 'gated_tree', 'predecessor', 'tree', 'gate_reuse', 'gate', 'ci', 'ci_carried', 'spend_usd', 'calls', 'session_kind', 'artifacts_consumed', 'run', 'thread', 'policy', 'queue_mode', 'preregistration', 'history', @@ -137,7 +166,7 @@ export type ReceiptRun = Pick !r.mark).slice(-RECEIPT_RUNS_KEPT)); - return runs.filter(r => r.mark || keep.has(r)); + return runs.filter(r => r.mark || keep.has(r)).map(r => typeof r.run === 'string' && r.run !== runId(r.run) ? { ...r, run: runId(r.run) } : r); } export function receiptRuns(body: string): ReceiptRun[] { const m = RUNS_RE.exec(receiptSource(body)); @@ -167,7 +196,7 @@ const STRIP_RE = /```gstack-(?:ship-receipt|receipt-runs)[ \t]*\r?\n[\s\S]*?\r?\ export function placeReceipt(body: string, receipt: ShipReceipt): string { const ex = extractReceipt(body); const prior = ex.receipt; - const runs = receiptRuns(body).filter(r => !r.status || !!receipt.carry || receipt.run === undefined || r.run !== receipt.run); + const runs = receiptRuns(body).filter(r => !r.status || !!receipt.carry || receipt.run === undefined || !sameRun(r.run, receipt.run)); if (prior && typeof prior.head === 'string' && JSON.stringify(prior) !== JSON.stringify(receipt)) runs.push(receiptRun(prior)); const kept = keptRuns(runs); const block = renderReceiptBlock(receipt) + (kept.length ? '\n```' + RUNS_FENCE + '\n' + kept.map(r => JSON.stringify(r)).join('\n') + '\n```\n' : ''); @@ -581,8 +610,9 @@ export function computeCensus(repo: string, since: string, prs: CensusPr[], coho rows.push({ number: pr.number, session_kind: r.session_kind ?? null, artifacts_consumed: r.artifacts_consumed ?? null, run: r.run ?? null, thread: r.thread ?? null, valid: true }); const kind = r.session_kind ?? 'unknown'; byKind[kind] = (byKind[kind] ?? 0) + 1; - if (r.run && seenRuns.has(r.run)) continue; - if (r.run) { seenRuns.add(r.run); runs.add(r.run); } + const id = r.run ? runId(r.run) : undefined; + if (id && seenRuns.has(id)) continue; + if (id) { seenRuns.add(id); runs.add(id); } if (r.thread) threads.add(r.thread); if (kind === 'unattended') unattended += 1; if (consumedCount(r.artifacts_consumed) > 0) { consumed += 1; if (r.thread) consumedThreads.add(r.thread); } diff --git a/lib/ship-release.ts b/lib/ship-release.ts index 7171d18a8..5d0921a40 100644 --- a/lib/ship-release.ts +++ b/lib/ship-release.ts @@ -16,13 +16,13 @@ import { versionAtRef } from './restamp'; import { classifyPath } from './review-depth'; import { matchesAny } from './ship-policy'; import { baseHolds, boundedPaths, comparePath, contextPacket, gateEditedPaths, isTestCode, PACKET_SECTION_CAP, readScopedReview, touchedPaths, type BoundedKind, type PatchSides } from './ship-patch'; -import { extractReceipt, heldBy, receiptRuns } from './ship-receipt'; +import { extractReceipt, heldBy, receiptRuns, runId } from './ship-receipt'; import { finishRun, readRunRecord } from './ship-run-record'; import { mechanicalPaths, writeMechanicalRecord } from './ship-mechanical'; import { uidSidecars } from './ship-sidecar'; import type { MechanicalConstant } from './ship-policy-mechanical'; import { forbidSpecs } from './review-fetch'; -import { readRuledNotes, ruledEditLine, ruledEdits, ruledNoteText } from './ruled-notes'; +import { readRuledNotes, repoRuledNotes, ruledEditLine, ruledEdits, ruledNoteText, type RuledNote } from './ruled-notes'; import { dispositionedOn, gateDispositionText, readGateDispositions } from './gate-dispositions'; import { parseReceiptDocs, type ReceiptDocs } from './ship-receipt-docs'; import { redactFindingSpans } from './redact-engine'; @@ -246,10 +246,10 @@ function patchBase(cwd: string, baseRef: string, commit: string, parent: string /** The owner's rulings and gate dispositions finish prints with stage 2's route (GST-1537, GST-2491). */ -function printRulings(cwd: string, r: Report): void { +function printRulings(cwd: string, r: Report, notes: readonly RuledNote[]): void { const reviewRows: Record[] = bin(cwd, 'gstack-review-read', [], 60_000).stdout.split('\n---CONFIG---')[0].split('\n') .flatMap(l => { try { const v = JSON.parse(l); return v?.skill === 'review' || v?.skill === 'review-fix-check' ? [v] : []; } catch { return []; } }); - for (const n of readRuledNotes(cwd)) if (!n.finding.startsWith('edit:')) r.add(`RULED_NOTE: ${ruledNoteText(n)}`); + for (const n of notes) if (!n.finding.startsWith('edit:')) r.add(`RULED_NOTE: ${ruledNoteText(n)}`); for (const d of readGateDispositions(cwd)) r.add(`GATE_DISPOSITION: ${gateDispositionText(d)}${reviewRows.some(v => dispositionedOn(cwd, v, [d]).length) ? '' : ' (no open gate finding at this fingerprint on a review row whose range holds this head; not applied)'}`); } @@ -299,8 +299,9 @@ function route(cwd: string, base: string, reviewed: string, reviewedBase: Review by.behavior.push(...packetBody.over); for (const k of ['context', 'tests', 'bounded'] as const) by[k] = by[k].filter(p => !packetBody.over.includes(p)); } - printRulings(cwd, r); - const edits = readRuledNotes(cwd).filter(n => n.finding.startsWith('edit:')); + const notes = repoRuledNotes(readRuledNotes(cwd), cwd); + printRulings(cwd, r, notes); + const edits = notes.filter(n => n.finding.startsWith('edit:')); const { ruled, refused: refusedEdits } = ruledEdits(cwd, [...by.behavior, ...by.docs], now, edits); by.behavior = by.behavior.filter(p => !ruled.has(p)); by.ruled = [...ruled.keys()].sort(); @@ -451,7 +452,7 @@ export async function finish(argv: readonly string[], cwd: string): Promise typeof e?.run === 'string' ? [e.run] : []) : null); + : finishRun(cwd, body ? [...receiptRuns(body), extractReceipt(body).receipt].flatMap(e => typeof e?.run === 'string' ? [runId(e.run)] : []) : null); if (ended.line) r.add(ended.line); return r; } diff --git a/scripts/lib/windows-curation.ts b/scripts/lib/windows-curation.ts index f73783918..b326b9292 100644 --- a/scripts/lib/windows-curation.ts +++ b/scripts/lib/windows-curation.ts @@ -416,6 +416,10 @@ export const KNOWN_WINDOWS_INCOMPATIBLE: Array<{ file: string; reason: string }> file: 'test/ship-finish-ruled-notes.test.ts', reason: 'drives bin/gstack-ship-release, gstack-approvals, gstack-docs-candidate and gstack-wtree (shebangs) through test/helpers/ship-bin-fixture.ts like test/ship-rereview-triggers.test.ts; windows-latest fails every case at the first bin spawn (windows-scoped-shard, run 42139467391)', }, + { + file: 'test/ship-receipt-public-safe.test.ts', + reason: 'drives bin/gstack-ship-receipt, gstack-ship-release, gstack-approvals, gstack-docs-candidate and gstack-wtree (shebangs) through test/helpers/ship-bin-fixture.ts like test/ship-finish-ruled-notes.test.ts, which windows-latest fails at the first bin spawn (windows-scoped-shard, run 42139467391)', + }, { file: 'test/ship-gate-dispositions.test.ts', reason: 'drives bin/gstack-ship-release, gstack-approvals, gstack-review-log, gstack-review-read, gstack-ship-receipt, gstack-docs-candidate and gstack-wtree (shebangs) through test/helpers/ship-bin-fixture.ts like test/ship-finish-ruled-notes.test.ts, which windows-latest fails at the first bin spawn (windows-scoped-shard, run 42139467391)', diff --git a/ship/DRIVER.md b/ship/DRIVER.md index f7b5827f2..746df27be 100644 --- a/ship/DRIVER.md +++ b/ship/DRIVER.md @@ -116,7 +116,7 @@ repo gates run with CI. Unattended, push defers the pre-push offer; else its STO ## 8. Publish: Steps 18, 19, 19-C, 20, 21, 22 - Step 18: the open-PR lookup; a plain `v ` title (`gstack-plain-title check`). `UNATTENDED_SHIP:` with no open PR at HEAD takes Step 18-H. -- Step 19 body: plain opening sentences, then sections `sections/pr-body.md` lists, led under `CAPY_PR: on` (Step 19-C) by What changed, Why and Blast radius; Agent notes last (receipt, `gstack-approvals render --plan`, `REVIEW_LOOP:`). `gstack-prose-lint --sections 'Why,Summary,Blast radius' --gate`; `gstack-issue-links`; `gstack-review-scope summary --since "$REVIEW_SINCE" --run && gstack-ship-receipt write --pr --base --gate @ --pregate --issues @ --review-loop @ --docs @ --budget-record [--review-exclude ] [--review-targeted @] --body `; `gstack-post pr-body` and `pr-title` (new PR: host PR tool; draft while a gate finding is `open`). `SHIP_RECEIPT:` opens your report. +- Step 19 body: plain opening sentences, then sections `sections/pr-body.md` lists, led under `CAPY_PR: on` (Step 19-C) by What changed, Why and Blast radius; Agent notes last (receipt, `gstack-approvals render --plan`, `REVIEW_LOOP:`). `gstack-prose-lint --sections 'Why,Summary,Blast radius' --gate`; `gstack-issue-links`; `gstack-review-scope summary --since "$REVIEW_SINCE" --run && gstack-ship-receipt write --pr --run --base --gate @ --pregate --issues @ --review-loop @ --docs @ --budget-record [--review-exclude ] [--review-targeted @] --body `; `gstack-post pr-body` and `pr-title` (new PR: host PR tool; draft while a gate finding is `open`). `SHIP_RECEIPT:` opens your report. - Steps 20 and 21 are skipped (no catch recorded, L; /retro gets no row). - Step 22: `gstack-ship-budget close --reading R --credits C` (report `BUDGET_FINAL:`, `BUDGET_TIMELINE:`, any `METER:` line), then `gstack-ship-receipt result --pr `: `GSTACK_RESULT: skill=ship status=complete head= run=`. Under a merge queue, `gstack-ship-queue ready --pr [--screen|--no-screen]` at the pushed head; paste its output. diff --git a/ship/DRIVER.md.tmpl b/ship/DRIVER.md.tmpl index 067c0dea0..69d3b4b5a 100644 --- a/ship/DRIVER.md.tmpl +++ b/ship/DRIVER.md.tmpl @@ -114,7 +114,7 @@ repo gates run with CI. Unattended, push defers the pre-push offer; else its STO ## 8. Publish: Steps 18, 19, 19-C, 20, 21, 22 - Step 18: the open-PR lookup; a plain `v ` title (`gstack-plain-title check`). `UNATTENDED_SHIP:` with no open PR at HEAD takes Step 18-H. -- Step 19 body: plain opening sentences, then sections `sections/pr-body.md` lists, led under `CAPY_PR: on` (Step 19-C) by What changed, Why and Blast radius; Agent notes last (receipt, `gstack-approvals render --plan`, `REVIEW_LOOP:`). `gstack-prose-lint --sections 'Why,Summary,Blast radius' --gate`; `gstack-issue-links`; `gstack-review-scope summary --since "$REVIEW_SINCE" --run && gstack-ship-receipt write --pr --base --gate @ --pregate --issues @ --review-loop @ --docs @ --budget-record [--review-exclude ] [--review-targeted @] --body `; `gstack-post pr-body` and `pr-title` (new PR: host PR tool; draft while a gate finding is `open`). `SHIP_RECEIPT:` opens your report. +- Step 19 body: plain opening sentences, then sections `sections/pr-body.md` lists, led under `CAPY_PR: on` (Step 19-C) by What changed, Why and Blast radius; Agent notes last (receipt, `gstack-approvals render --plan`, `REVIEW_LOOP:`). `gstack-prose-lint --sections 'Why,Summary,Blast radius' --gate`; `gstack-issue-links`; `gstack-review-scope summary --since "$REVIEW_SINCE" --run && gstack-ship-receipt write --pr --run --base --gate @ --pregate --issues @ --review-loop @ --docs @ --budget-record [--review-exclude ] [--review-targeted @] --body `; `gstack-post pr-body` and `pr-title` (new PR: host PR tool; draft while a gate finding is `open`). `SHIP_RECEIPT:` opens your report. - Steps 20 and 21 are skipped (no catch recorded, L; /retro gets no row). - Step 22: `gstack-ship-budget close --reading R --credits C` (report `BUDGET_FINAL:`, `BUDGET_TIMELINE:`, any `METER:` line), then `gstack-ship-receipt result --pr `: `GSTACK_RESULT: skill=ship status=complete head= run=`. Under a merge queue, `gstack-ship-queue ready --pr [--screen|--no-screen]` at the pushed head; paste its output. diff --git a/test/gstack-ship-receipt.test.ts b/test/gstack-ship-receipt.test.ts index afd6777be..b979baf2e 100644 --- a/test/gstack-ship-receipt.test.ts +++ b/test/gstack-ship-receipt.test.ts @@ -43,7 +43,7 @@ describe('gstack-ship-receipt write', () => { const ok = runBin(repo, 'gstack-ship-receipt', ['write', '--pr', '42', '--base', 'main', '--receipt', treeReceipt, '--gate', '{"tests":{"pass":1,"fail":0,"skip":0}}', '--ci', '@' + path.join(repo.root, 'ci.json'), '--spend-usd', '0.42', '--session-kind', 'unattended', '--artifacts-consumed', '2/3', '--run', 'run-1', '--thread', 'jam_1', '--queue-mode', 'stamp-at-merge', - '--preregistration', 'none (no preregistration_shas)', '--history', 'squash-ok', '--body', body, '--out', path.join(repo.root, 'receipt.md')], ghShim(repo, { 42: { body: '' } })); + '--preregistration', 'none (no preregistration_shas)', '--history', 'squash-ok', '--body', body, '--out', path.join(repo.root, 'receipt.md')], ghShim(repo, { 42: { body: '' } }, [], 'PRIVATE')); expect(ok.status).toBe(EXIT.ok); expect(ok.err.trim()).toBe(`SHIP_RECEIPT: pr=42 head=${head.slice(0, 12)} version=1.2.4.0 base=main gated_tree=${repo.git('rev-parse', 'HEAD^{tree}').slice(0, 12)} tree=same-modulo-stamps gate-reuse=eligible (reusable: tests; rerun: -) predecessor=${'b'.repeat(12)} session_kind=unattended artifacts_consumed=2/3 depth=light`); const parsed = extractReceipt(ok.out); diff --git a/test/helpers/restamp-fixture.ts b/test/helpers/restamp-fixture.ts index a2ed17620..8b0b22ecf 100644 --- a/test/helpers/restamp-fixture.ts +++ b/test/helpers/restamp-fixture.ts @@ -168,7 +168,7 @@ export function cleanup(repo: FixtureRepo): void { * number → JSON object and `gh pr list` with a fixed array, so queue-order * and PREDECESSOR MOVED checks run without the network. */ -export function ghShim(repo: FixtureRepo, prs: Record, list: unknown[] = []): { PATH: string } { +export function ghShim(repo: FixtureRepo, prs: Record, list: unknown[] = [], visibility?: 'PUBLIC' | 'PRIVATE'): { PATH: string } { const dir = path.join(repo.root, 'gh-shim'); fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, 'prs.json'), JSON.stringify({ prs, list })); @@ -179,6 +179,7 @@ export function ghShim(repo: FixtureRepo, prs: Record, list: un ' node -e "const d=require(process.argv[1]);const p=d.prs[process.argv[2]];if(!p){console.error(\'no such pr\');process.exit(1)}console.log(JSON.stringify(p))" "$DATA" "$3"', ' exit $?', 'fi', + ...(visibility ? [`if [ "$1" = "repo" ] && [ "$2" = "view" ]; then echo ${visibility}; exit 0; fi`] : []), 'if [ "$1" = "pr" ] && [ "$2" = "list" ]; then node -e "console.log(JSON.stringify(require(process.argv[1]).list))" "$DATA"; exit $?; fi', 'echo "gh shim: unsupported $*" >&2; exit 1', '', diff --git a/test/ship-finish-ruled-notes.test.ts b/test/ship-finish-ruled-notes.test.ts index b4fbf4781..85a6af8cd 100644 --- a/test/ship-finish-ruled-notes.test.ts +++ b/test/ship-finish-ruled-notes.test.ts @@ -132,6 +132,7 @@ describe('ruledNotes reads only approved owner rulings (GST-1537)', () => { describe('a ruling relayed into an open /ship run (GBRA-108, gbrain #9762)', () => { test('without --owner-ref it refuses as APPROVAL_RULING_RUN_OPEN; with one it records and marks the ruling relayed', () => { const { f, passHead } = rulingHead(); + f.gh('[ "$1" = repo ] && echo PRIVATE; exit 0'); const marker = path.resolve(f.work, f.git('rev-parse', '--git-path', 'gstack-ship-run').stdout.trim()); fs.writeFileSync(marker, 'ship-9762-abc\n'); const bare = rule(f, RACE, passHead, 'GBrain Minder (GBRA-108)'); diff --git a/test/ship-receipt-public-safe.test.ts b/test/ship-receipt-public-safe.test.ts new file mode 100644 index 000000000..1dfa665d6 --- /dev/null +++ b/test/ship-receipt-public-safe.test.ts @@ -0,0 +1,302 @@ +/** + * Public repositories (GST-1955, CAPY-1 qm#3938 and qm#3983): /ship's receipt, its Ruled note lines and abandon's runs-block + * entry must not carry a home path or a Capy thread or message id. 20 of 60 merged public gstack receipts held + * `"run": "/home/user/.capy/work/ship-"` because write copied --run verbatim; a relayed ruling's `relayed from + * :` was required word for word in the public PR body; and abandon posted to a PR the checkout's branch did + * not open (qm#3992 for qm#3983). + */ +import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { EXIT } from '../lib/headless-artifacts'; +import { placeRunEntry, prReviewHistory, receiptedRun, runStub } from '../lib/pr-review-history'; +import { extractReceipt, placeReceipt, publicReceiptLeaks, receiptRuns, runId, RUNS_FENCE, sameRun } from '../lib/ship-receipt'; +import { lineOf, RELEASE, shipFixture, type ShipFx } from './helpers/ship-bin-fixture'; + +setDefaultTimeout(90_000); +const BIN = path.dirname(RELEASE); +const LANE = 'tests=printf " 3 pass\\n 0 fail\\nRan 3 tests across 1 file. [5.00ms]\\n"'; +const ships: ShipFx[] = []; +afterEach(() => { while (ships.length) ships.pop()!.cleanup(); }); + +const H = 'a'.repeat(40); +const HOME_RUN = '/home/user/.capy/work/ship-4590'; +const REF = 'GBRA-108:2026-11-19T12:29:59Z'; +const LOOP = { passes: 1, blocking_found: 0, deferred: 0 }; +/** gh pr view's answer for a PR whose head is `branch` on `owner`/fx (the fixture's origin is github.com/fx/fx). */ +const VIEW = (branch: string, owner = 'fx') => JSON.stringify({ body: '', headRefName: branch, headRepository: { name: 'fx' }, headRepositoryOwner: { login: owner } }); +const VIEW_FEAT = VIEW('feat'); +const runsBody = (...entries: object[]) => '\n
Agent notes\n\n\`\`\`' + RUNS_FENCE + '\n' + entries.map(e => JSON.stringify(e)).join('\n') + '\n\`\`\`\n\n
\n'; + +/** A fixture whose gh says the repository is PUBLIC, PRIVATE or cannot say (''), answers pr view with `view`, and logs every call. */ +function fixture(visibility: 'PUBLIC' | 'PRIVATE' | '', view = '{"body":""}') { + const f = shipFixture({ 'src/x.ts': 'export const x = 1;\n' }, { 'src/x.ts': 'export const x = 2;\n' }); + ships.push(f); + setGh(f, visibility, view); + return f; +} +const setGh = (f: ShipFx, visibility: string, view = '{"body":""}') => f.gh([ + `echo "$*" >> "${path.join(f.root, 'gh.log')}"`, + `if [ "$1" = repo ]; then ${visibility ? `echo ${visibility}; exit 0` : 'exit 1'}; fi`, + `if [ "$1" = pr ] && [ "$2" = view ]; then echo '${view}'; exit 0; fi`, + 'exit 0', +].join('\n')); +const ghLog = (f: ShipFx) => { const p = path.join(f.root, 'gh.log'); return fs.existsSync(p) ? fs.readFileSync(p, 'utf8') : ''; }; +const bin = (f: ShipFx, name: string, args: string[]) => f.run(path.join(BIN, name), args, { GSTACK_APPROVALS_MIRROR: '0' }); +const write = (f: ShipFx, body: string, extra: string[] = []) => bin(f, 'gstack-ship-receipt', ['write', '--pr', '7', '--base', 'main', '--version', '1.0.0', '--session-kind', 'unattended', '--body', body, ...extra]); +const bodyFile = (f: ShipFx, text = '## Summary\n\nA change.\n') => { const p = path.join(f.root, 'body.md'); fs.writeFileSync(p, text); return p; }; +const relayedRule = (f: ShipFx, reason = 'ships as a disclosed note') => bin(f, 'gstack-approvals', ['rule', '--finding', 'src/x.ts:1:edit-share-race', '--head', f.git('rev-parse', 'HEAD').stdout.trim(), '--reason', reason, '--words', 'B, note it', '--by', 'GBrain Minder (GBRA-108)', '--owner-ref', REF]); + +// Value: protects=one run id names one /ship run whether a record holds the run dir's path or its name; fails_when=write keeps the +// path, or an older entry holding the path no longer matches its run's basename (a stub double-counted, a receipt not found); +// seam=lib/ship-receipt.ts runId and the run comparisons in placeReceipt, placeRunEntry, prReviewHistory and receiptedRun +describe('run ids are the run dir name, on write and in every comparison (GST-1955)', () => { + test('runId keeps the last path segment of a POSIX or Windows path and leaves a bare id alone', () => { + expect([runId(HOME_RUN), runId('C:\\Users\\u\\work\\ship-9\\'), runId('ship-1'), runId('ship-2/')]).toEqual(['ship-4590', 'ship-9', 'ship-1', 'ship-2']); + expect([sameRun(HOME_RUN, 'ship-4590'), sameRun('ship-4590', 'ship-4591'), sameRun(undefined, 'ship-4590')]).toEqual([true, false, false]); + }); + + test('an in-flight PR whose older entries hold the full path matches the run by its name', () => { + const stub = runStub({ head: H, run: HOME_RUN, status: 'started', loop: LOOP }); + const placed = placeReceipt(runsBody(stub), { schema_version: 1, head: H, run: 'ship-4590', review_loop: LOOP } as any); + expect(receiptRuns(placed)).toEqual([]); + expect(prReviewHistory(placed)).toMatchObject({ rounds: 1, runs: 1, stubs: 0 }); + const both = runsBody(stub, { head: H, run: 'ship-4590', review_loop: LOOP }); + expect(prReviewHistory(both)).toMatchObject({ rounds: 1 }); + const restubbed = placeRunEntry(runsBody(stub), runStub({ head: H, run: 'ship-4590', status: 'voided', loop: LOOP })); + expect(receiptRuns(restubbed)).toEqual([{ head: H, run: 'ship-4590', status: 'voided', review_loop: LOOP }]); + expect(receiptedRun(runsBody({ head: H, run: HOME_RUN, review_loop: LOOP }), 'ship-4590')).toMatchObject({ head: H }); + expect(placed).not.toContain('/home/'); + }); + + test('publicReceiptLeaks names each field that holds a home path or a Capy id, never its value, and passes ordinary fields', () => { + expect(publicReceiptLeaks({ run: HOME_RUN, thread: 'jam_01abc', history: 'C:\\Users\\runner\\x', gate: { note: 'file:///Users/garry/x' }, ruled_notes: [{ relayed: REF }], policy: '/root/.gstack/x' })).toEqual([ + 'run (a home path)', 'thread (a Capy thread or message id)', 'history (a home path)', 'gate.note (a home path)', 'ruled_notes[0].relayed (a Capy thread or message id)', 'policy (a home path)', + ]); + expect(publicReceiptLeaks({ reason: 'see icm_01M8GG556RYA3HGG7Q12G7GP1J', note: 'iev_01M8GG5564BWTXRD3PP941B4PD', gate: { '/home/user/.capy/work/ev.json': true, 'jam_01abc': 1, tests: { pass: 3 } } })).toEqual([ + 'reason (a Capy thread or message id)', 'note (a Capy thread or message id)', 'gate. (a home path or Capy id in a key)', 'gate. (a home path or Capy id in a key)', + ]); + expect(publicReceiptLeaks({ run: 'ship-4590', policy: 'origin/main@0123456789ab:.gstack/ship-policy.json', ruled_notes: [{ by: 'GStack Minder (GSTA-36)', at: '2026-11-19T12:29:59Z', relayed: 'a private message' }], gate: { path: '/workspace/home/user/x' } })).toEqual([]); + }); + + test('write stores the run dir name when --run is the run dir path', () => { + const f = fixture(''); + const body = bodyFile(f); + const w = write(f, body, ['--run', HOME_RUN]); + expect(w.status, w.stderr).toBe(EXIT.ok); + expect(extractReceipt(w.stdout).receipt?.run).toBe('ship-4590'); + expect(fs.readFileSync(body, 'utf8')).not.toContain('/home/'); + }); +}); + +// Value: protects=a receipt on a repository gh does not report private never carries a home path or a Capy id; fails_when=write +// publishes --thread jam_… or a home path in any field on a public or unknown repository, or refuses one on a private repository; +// seam=gstack-ship-receipt write's refusal after the schema check +describe('write refuses a public receipt that holds a home path or a Capy id (GST-1955)', () => { + test('public and unknown visibility refuse naming the field, private keeps the value', () => { + for (const vis of ['PUBLIC', ''] as const) { + const f = fixture(vis); + const body = bodyFile(f); + for (const extra of [['--thread', 'jam_01abc'], ['--history', '/Users/garry/notes/x']]) { + const w = write(f, body, extra); + expect([w.status, w.stderr]).toEqual([EXIT.fail, expect.stringContaining(`${extra[0]!.slice(2)} (a `)]); + expect(w.stderr).toContain('(RECEIPT_INVALID)'); + expect(w.stderr).not.toContain(extra[1]!); + expect(fs.readFileSync(body, 'utf8')).toBe('## Summary\n\nA change.\n'); + } + } + const f = fixture('PRIVATE'); + const w = write(f, bodyFile(f), ['--thread', 'jam_01abc']); + expect(w.status, w.stderr).toBe(EXIT.ok); + expect(extractReceipt(w.stdout).receipt?.thread).toBe('jam_01abc'); + }); +}); + +// Value: protects=rulings, finish and the receipt agree on one public-safe Ruled note form, and the relay ref stays in the private +// approval row; fails_when=a public PR body must carry : to satisfy write, or the three render different lines; +// seam=lib/ruled-notes.ts repoRuledNotes read by gstack-approvals rulings, gstack-ship-release finish and gstack-ship-receipt write +describe('a relayed ruling on a public repository (CAPY-1 qm#3938)', () => { + test('rulings, the receipt and finish say relayed from a private message; the row keeps the ref', () => { + const f = fixture('PUBLIC'); + const reviewed = f.run(path.join(BIN, 'gstack-wtree'), []).stdout.trim(); + const post = path.join(f.root, 'post.json'); + expect(f.run(path.join(BIN, 'gstack-docs-candidate'), ['snapshot', '--out', post, '--audit-id', 'a1', '--mode', 'edit', '--base', 'main', '--docs', 'README.md']).status).toBe(0); + expect(relayedRule(f).status).toBe(0); + const rows = JSON.parse(bin(f, 'gstack-approvals', ['list', '--json']).stdout).rows as Array<{ source: string }>; + expect(rows.map(r => r.source)).toEqual([`relayed:${REF}`]); + const line = bin(f, 'gstack-approvals', ['rulings']).stdout.trim(); + expect(line).toMatch(/^Ruled note: src\/x\.ts:1:edit-share-race at [0-9a-f]{12} ruled by GBrain Minder \(GBRA-108\) \(relayed from a private message\) at /); + const fin = f.run(RELEASE, ['finish', '--base', 'main', '--reviewed-tree', reviewed, '--docs-post', post, '--lane', LANE]); + expect(lineOf(fin.stdout, 'RULED_NOTE')).toBe(`RULED_NOTE: ${line.slice('Ruled note: '.length)}`); + const body = bodyFile(f, `## Pre-Landing Review\n\n${line}\n`); + const w = write(f, body); + expect(w.status, w.stderr).toBe(EXIT.ok); + expect(extractReceipt(w.stdout).receipt?.ruled_notes?.[0]?.relayed).toBe('a private message'); + expect(fs.readFileSync(body, 'utf8')).not.toContain('GBRA-108:'); + }); + + test('a body that still lists the internal relay line is refused on a public repository and accepted on a private one', () => { + const f = fixture('PRIVATE'); + expect(relayedRule(f).status).toBe(0); + const full = bin(f, 'gstack-approvals', ['rulings']).stdout.trim(); + expect(full).toContain(`(relayed from ${REF})`); + const body = bodyFile(f, `## Pre-Landing Review\n\n- ${full}\n`); + const ok = write(f, body); + expect(ok.status, ok.stderr).toBe(EXIT.ok); + expect(extractReceipt(ok.stdout).receipt?.ruled_notes?.[0]?.relayed).toBe(REF); + setGh(f, 'PUBLIC'); + const redacted = bin(f, 'gstack-approvals', ['rulings']).stdout.trim(); + const pub = write(f, bodyFile(f, `## Pre-Landing Review\n\n- ${full}\n${redacted}\n`)); + expect([pub.status, pub.stderr]).toEqual([EXIT.fail, expect.stringContaining('names a Capy thread or message id')]); + expect(pub.stderr).not.toContain(REF); + }); + + test('an id in the ruling\'s reason reads a private message too, so the line rulings prints still writes', () => { + const f = fixture('PUBLIC'); + expect(relayedRule(f, 'as GSTA-36:icm_01M8GG556RYA3HGG7Q12G7GP1J said').status).toBe(0); + const line = bin(f, 'gstack-approvals', ['rulings']).stdout.trim(); + expect(line).toContain(': as a private message said (approval '); + const w = write(f, bodyFile(f, `## Pre-Landing Review\n\n${line}\n`)); + expect(w.status, w.stderr).toBe(EXIT.ok); + expect(extractReceipt(w.stdout).receipt?.ruled_notes?.[0]).toMatchObject({ reason: 'as a private message said', relayed: 'a private message' }); + }); +}); + +// Value: protects=abandon marks only the PR the checkout's branch opened and keeps Capy ids out of a public runs block; +// fails_when=abandon edits another PR's body (qm#3992 for qm#3983), or posts a : or jam_ id in by or reason +// on a public repository; seam=gstack-ship-receipt abandoned, which gstack-ship-run abandon calls +describe('abandon binds its target PR and redacts Capy ids (CAPY-1 qm#3983)', () => { + const abandoned = (f: ShipFx, target: string[], reason = 'the run stopped answering') => bin(f, 'gstack-ship-receipt', ['abandoned', ...target, '--run', HOME_RUN, '--by', 'GStack Minder (GSTA-36)', '--reason', reason]); + + test('a PR whose head branch is not this checkout\'s is refused before any edit; the matching PR is marked', () => { + const f = fixture('PUBLIC', VIEW('other-branch')); + const wrong = abandoned(f, ['--pr', '3992']); + expect([wrong.status, wrong.stderr]).toEqual([EXIT.refused, expect.stringContaining("PR #3992's head branch is other-branch, not this checkout's feat")]); + expect(ghLog(f)).not.toContain('pr edit'); + setGh(f, 'PUBLIC', VIEW_FEAT); + const right = abandoned(f, ['--pr', '3983']); + expect(right.status, right.stderr).toBe(EXIT.ok); + expect(right.stdout).toContain('RUN_ABANDON_MARK: run=ship-4590 '); + expect(ghLog(f)).toContain('pr edit 3983'); + }); + + test('a detached HEAD or a PR gh cannot name a head branch for is refused before any edit', () => { + const f = fixture('PUBLIC', '{"body":""}'); + const unnamed = abandoned(f, ['--pr', '3983']); + expect([unnamed.status, unnamed.stderr]).toEqual([EXIT.refused, expect.stringContaining('gh pr view 3983 did not name its head branch and repository')]); + setGh(f, 'PUBLIC', VIEW_FEAT); + f.git('checkout', '-q', '--detach'); + const detached = abandoned(f, ['--pr', '3983']); + expect([detached.status, detached.stderr]).toEqual([EXIT.refused, expect.stringContaining('this checkout has no branch, so PR #3983 cannot be matched to it')]); + expect(ghLog(f)).not.toContain('pr edit'); + }); + + test('by and reason lose their Capy ids on a public repository and keep them on a private one', () => { + const reason = 'owner said stop in GSTA-36:icm_01M8GG556RYA3HGG7Q12G7GP1J (jam_01abc)'; + const f = fixture('PUBLIC'); + const body = bodyFile(f); + const pub = abandoned(f, ['--body', body], reason); + expect(pub.status, pub.stderr).toBe(EXIT.ok); + expect(pub.stderr).toContain('RUN_ABANDON_REDACTED:'); + expect(receiptRuns(fs.readFileSync(body, 'utf8'))).toEqual([expect.objectContaining({ mark: 'abandoned', run: 'ship-4590', by: 'GStack Minder (GSTA-36)', reason: 'owner said stop in a private message (a private message)' })]); + const p = fixture('PRIVATE'); + const kept = bodyFile(p); + expect(abandoned(p, ['--body', kept], reason).status).toBe(EXIT.ok); + expect(receiptRuns(fs.readFileSync(kept, 'utf8'))[0]).toMatchObject({ reason }); + }); +}); + +// Value: protects=the privacy decision follows the repository the text is published to, an explicit --repo included; fails_when=a +// private checkout lets write or abandon publish Capy ids to a public --repo; seam=repoVisibility's target in keepsInternalIds +// and write's refusal +describe('visibility is read for the --repo a command publishes to (#4868 second-model review)', () => { + const targetGh = (f: ShipFx) => f.gh([ + 'if [ "$1" = repo ]; then case "$*" in *acme/pub*) echo PUBLIC;; *) echo PRIVATE;; esac; exit 0; fi', + `if [ "$1" = pr ] && [ "$2" = view ]; then echo '${VIEW_FEAT}'; exit 0; fi`, + 'exit 0', + ].join('\n')); + + test('write refuses a Capy id for a public --repo from a private checkout, and keeps it without one', () => { + const f = fixture('PRIVATE'); + targetGh(f); + const body = bodyFile(f); + const pub = write(f, body, ['--thread', 'jam_01abc', '--repo', 'acme/pub']); + expect([pub.status, pub.stderr]).toEqual([EXIT.fail, expect.stringContaining('thread (a Capy thread or message id)')]); + const priv = write(f, body, ['--thread', 'jam_01abc']); + expect(priv.status, priv.stderr).toBe(EXIT.ok); + }); + + test('abandon redacts for a public --repo even when the checkout is private', () => { + const f = fixture('PRIVATE'); + targetGh(f); + const body = bodyFile(f); + expect(bin(f, 'gstack-ship-receipt', ['abandoned', '--body', body, '--repo', 'acme/pub', '--run', 'ship-1', '--by', 'GStack Minder (GSTA-36)', '--reason', 'per GSTA-36:icm_01abc']).status).toBe(EXIT.ok); + expect(receiptRuns(fs.readFileSync(body, 'utf8'))[0]).toMatchObject({ reason: 'per a private message' }); + }); +}); + +// Value: protects=abandon binds the PR to this checkout's origin repository as well as its branch; fails_when=a fork's PR from a +// branch of the same name is marked (headRefName names no repository); seam=prOffBranch in gstack-ship-receipt abandoned +describe('abandon refuses a fork PR with the same branch name (#4868 second-model review)', () => { + test('a head on another owner\'s repository is refused before any edit', () => { + const f = fixture('PUBLIC', VIEW('feat', 'someone-else')); + const r = bin(f, 'gstack-ship-receipt', ['abandoned', '--pr', '3983', '--run', 'ship-1', '--by', 'GStack Minder (GSTA-36)', '--reason', 'stopped']); + expect([r.status, r.stderr]).toEqual([EXIT.refused, expect.stringContaining("PR #3983's head is on someone-else/fx, not this checkout's origin fx/fx")]); + expect(ghLog(f)).not.toContain('pr edit'); + }); +}); + +// Value: protects=carry stores the run dir name and never republishes a Capy id on a public repository; fails_when=a carried +// receipt keeps an older write's /home/... run or jam_ thread; seam=gstack-ship-receipt carry before postBody +describe('carry normalizes the run and refuses a public receipt that still holds a Capy id (#4868 second-model review)', () => { + const carryFixture = (vis: 'PUBLIC' | 'PRIVATE', extra: Record) => { + const f = fixture(vis); + const reviewed = f.git('rev-parse', 'HEAD').stdout.trim(); + f.write({ 'test/x.test.ts': "import { expect, test } from 'bun:test';\ntest('x', () => { expect(1).toBe(1); });\n" }); f.commit('test: add x'); + const body = bodyFile(f, placeReceipt('## Summary\n\nA change.\n', { schema_version: 1, pr: 5, head: reviewed, base: 'main', queue_mode: 'stamp-at-merge', review_loop: LOOP, ...extra } as any)); + return { f, body, carry: () => bin(f, 'gstack-ship-receipt', ['carry', '--body', body]) }; + }; + + test('an older receipt\'s full-path run carries as the run dir name', () => { + const { body, carry } = carryFixture('PUBLIC', { run: HOME_RUN }); + const r = carry(); + expect(r.status, r.stderr + r.stdout).toBe(EXIT.ok); + expect(extractReceipt(fs.readFileSync(body, 'utf8')).receipt?.run).toBe('ship-4590'); + expect(fs.readFileSync(body, 'utf8')).not.toContain('/home/'); + }); + + test('a jam_ thread is refused on a public repository and carried on a private one', () => { + const pub = carryFixture('PUBLIC', { run: 'ship-1', thread: 'jam_01abc' }); + const before = fs.readFileSync(pub.body, 'utf8'); + const r = pub.carry(); + expect([r.status, r.stderr + r.stdout]).toEqual([EXIT.refused, expect.stringContaining('thread (a Capy thread or message id)')]); + expect(fs.readFileSync(pub.body, 'utf8')).toBe(before); + const priv = carryFixture('PRIVATE', { run: 'ship-1', thread: 'jam_01abc' }); + expect(priv.carry().status).toBe(EXIT.ok); + }); +}); + +// Value: protects=a public-repo PR carrying a Captain's relayed ruling and gate disposition writes a clean public-safe receipt, with +// rulings, dispositions, finish and write rendering the same lines; fails_when=write deadlocks (the body line it requires holds an +// id its leak check refuses) or any of them prints a Capy id; seam=repoRuledNotes and publicGateDisposition +describe('a Captain ruling and gate disposition on a public repository write cleanly (#4868 second-model review)', () => { + test('GStack Minder (GSTA-36) relays both with Capy ids in its words; every public line reads a private message', () => { + const f = fixture('PUBLIC'); + const head = f.git('rev-parse', 'HEAD').stdout.trim(); + const by = 'GStack Minder (GSTA-36)', relay = 'GSTA-36:icm_01M8GG556RYA3HGG7Q12G7GP1J'; + expect(bin(f, 'gstack-approvals', ['rule', '--finding', 'src/x.ts:1:edit-share-race', '--head', head, '--reason', `ships as a note per ${relay}`, '--words', 'A1', '--by', by, '--owner-ref', relay]).status).toBe(0); + const g = bin(f, 'gstack-approvals', ['gate', '--finding', 'tests/x.test.ts:3:gate-integrity', '--gate-id', '69c7c3432501', '--head', head, '--reason', 'kept as the owner ruled', '--words', `do it (${relay})`, '--by', by]); + expect(g.status, g.stderr).toBe(0); + const rulings = bin(f, 'gstack-approvals', ['rulings']).stdout.trim(), dispositions = bin(f, 'gstack-approvals', ['dispositions']).stdout.trim(); + expect(rulings).toContain(`ruled by ${by} (relayed from a private message) at `); + expect(rulings).toContain(': ships as a note per a private message (approval '); + expect(dispositions).toContain(`by ${by} at `); + expect(dispositions).toContain('"do it (a private message)"'); + const body = bodyFile(f, `## Pre-Landing Review\n\n${rulings}\n${dispositions}\n`); + const w = write(f, body); + expect(w.status, w.stderr).toBe(EXIT.ok); + const text = fs.readFileSync(body, 'utf8'); + expect(text).not.toMatch(/icm_|jam_|GSTA-36:/); + expect(extractReceipt(text).receipt?.gate_dispositions?.[0]).toMatchObject({ by, words: 'do it (a private message)' }); + }); +});