Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA
TypeScript
Stop mistaking ordinary text for Capy ids and check every part of a public PR body (GST-4105) (#4872)
Garry Tandade7cacf16c
diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receiptindex 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<number> {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<typeof appliedGateDispositions>['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<number> {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<number> {}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.<name>.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.mdnew file mode 100644index 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.mdindex 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 asand `gstack-post` refuses to send such text, exit 1: a PR body and every GitHubpost are public, so a security finding appears only in the redacted form gstackrenders ([security findings stay private](ship-policy.md#security-findings-stay-private)).+<a id="receipt-public-repo"></a>+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/<user>/`,+`/Users/<user>/`, `/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 <the run dir's name>`, 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 andwrite again. For a security fingerprint, replace the text that names it with theline `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, whenHEAD 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 inthe body is unchanged and still names the old head, so `gstack-ship-queueready` refuses `QUEUE_RECEIPT_STALE`.@@ -7622,7 +7640,9 @@ already rewritten and the receipt predates `head_tree`, run /gstack-ship on thehead; next time merge the base in instead of rebasing. For a retargeted stackedPR whose older receipt lost its parent branch, or a depth, targeted or exceptionrefusal, 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.<a id="gate-finding-open-unattended"></a>### 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 neverrerun it, even when `RUN_ABANDON_PR` says the PR body entry was skipped or notrecorded (add that entry with `gstack-ship-receipt abandoned` instead).+<a id="receipt-abandoned-refused"></a>+### `gstack-ship-receipt abandoned` refuses a PR (exit 3)++**Meaning.** `gstack-ship-receipt abandoned --pr <n>` (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.<name>.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 <file>` 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.<name>.pushRemote <fork remote>` 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`.+<a id="ship-run-record-unreadable"></a>### `SHIP_RUN_RECORD_UNREADABLE`diff --git a/lib/gate-dispositions.ts b/lib/gate-dispositions.tsindex 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<ResultCodeName, 'QUEUE_GATE_DISPOSITION* The lander's check (docs/ship-policy.md#gate-dispositions), one function for `land --pin`, `verify --pin` and `ready`: the* dispositions `branch`'s store applies at `pin`, re-derived here, each printed as GATE_DISPOSITION. It refuses when the* receipt's gate_dispositions or the PR body's `Gate disposition:` lines differ from them, and, with `accepted` (land and- * verify; ready passes none), when an applied disposition is not accepted or an accepted id is not applied.+ * verify; ready passes none), when an applied disposition is not accepted or an accepted id is not applied. On a repository gh+ * reports private, a body written before GST-1955 that carries the line with its Capy ids unredacted still counts (GST-4105).*/export function gateAcceptance(o: { cwd: string; branch: string; pin: string; body: string; receipt?: ShipReceipt; accepted?: readonly string[]; env?: Env; noted?: readonly ApprovalRow[] }):{ lines: string[]; applied: GateDisposition[]; noteRows?: ApprovalRow[]; failure?: { code: GateAcceptanceCode; message: string; fix: string } } {@@ -154,13 +155,16 @@ export function gateAcceptance(o: { cwd: string; branch: string; pin: string; boconst listed = recorded ?? [];const where = `the store at ${loc.mirror ?? loc.file}${o.noted?.length ? ' with the READY note\'s rows' : ''}`;const lines = applied.map(d => `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 leftdiff --git a/lib/pr-review-history.ts b/lib/pr-review-history.tsindex 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<ReceiptRun | string> = [];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.tsindex 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, `<thread code>:<message id or timestamp>`. 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(?:(?<!\/)|(?=(?:jam|icm|iev)_[A-Za-z0-9]{26}(?![A-Za-z0-9])))(?:jam|icm|iev)_[A-Za-z0-9]+|\b[A-Z][A-Z0-9]*-[1-9]\d*:(?=(?:jam|icm|iev)_[A-Za-z0-9]|\d{4}-\d\d-\d\d|\d{9,}(?!\w))[A-Za-z0-9][\w.:+-]*/;+/**+ * A Ruled note line whose relay (ruledNoteText's ` (relayed from <ref>)` between the ruler and ` at <time>: `) names anything but+ * PRIVATE_REF: on a public repository its ref is internal whatever its shape. The reason after the time is never read here.+ */+export const RELAYED_REF = /^Ruled note: \S+ at [0-9a-f]{12} ruled by .*? \(relayed from (?!a private message\) at )[^()]*\) at \d{4}-\d\d-\d\dT/;/** 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);@@ -47,7 +56,7 @@ export const keepsInternalIds = (text: string, cwd: string, env: Env = process.e* 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.some(n => n.relayed || INTERNAL_ID.test(`${n.by} ${n.reason}`)) || renderMode(repoVisibility(cwd, env, target), false) === 'full' ? 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 = '<thread code>:<message id or timestamp>, 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)';diff --git a/test/ship-receipt-public-safe.test.ts b/test/ship-receipt-public-safe.test.tsindex 1dfa665d6..e077e05fa 100644--- a/test/ship-receipt-public-safe.test.ts+++ b/test/ship-receipt-public-safe.test.ts@@ -8,7 +8,9 @@import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test';import * as fs from 'node:fs';import * as path from 'node:path';+import { bunIsolationArgs } from '../lib/bun-isolation';import { EXIT } from '../lib/headless-artifacts';+import { INTERNAL_ID, redactInternalIds } from '../lib/ruled-notes';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';@@ -23,10 +25,10 @@ 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[]) => '<!-- gstack:agent-notes -->\n<details><summary>Agent notes</summary>\n\n\`\`\`' + RUNS_FENCE + '\n' + entries.map(e => JSON.stringify(e)).join('\n') + '\n\`\`\`\n\n</details>\n';+/** gh pr view's answer for an open PR whose head is `branch` on `owner`/fx (the fixture's origin is github.com/fx/fx) and whose body records run ship-4590's started stub. */+const VIEW = (branch: string, owner = 'fx', o: { state?: string; body?: string } = {}) => JSON.stringify({ body: o.body ?? runsBody({ head: H, run: 'ship-4590', status: 'started', review_loop: LOOP }), headRefName: branch, headRepository: { name: 'fx' }, headRepositoryOwner: { login: owner }, state: o.state ?? 'OPEN' });+const VIEW_FEAT = VIEW('feat');/** 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":""}') {@@ -38,7 +40,7 @@ function fixture(visibility: 'PUBLIC' | 'PRIVATE' | '', view = '{"body":""}') {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`,+ `if [ "$1" = pr ] && [ "$2" = view ]; then printf '%s\\n' '${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') : ''; };@@ -300,3 +302,214 @@ describe('a Captain ruling and gate disposition on a public repository write cleexpect(extractReceipt(text).receipt?.gate_dispositions?.[0]).toMatchObject({ by, words: 'do it (a private message)' });});});++// Value: protects=INTERNAL_ID keeps every Capy id and relay ref it caught while look-alike text (hashes, encodings, issue refs, file+// names) stops reading as one; fails_when=SHA-256:abc, UTF-8:x, PR-12:fix, A-1:b or test/jam_fix.ts is refused or redacted on a+// public repository, or any earlier catch slips through; seam=lib/ruled-notes.ts INTERNAL_ID, redactInternalIds, publicReceiptLeaks+describe('INTERNAL_ID leaves look-alike text alone and keeps every Capy id catch (GST-4105)', () => {+ const caught = ['jam_01abc', 'icm_01M8GG556RYA3HGG7Q12G7GP1J', 'iev_01M8GG5564BWTXRD3PP941B4PD', 'GSTA-36:icm_01M8GG556RYA3HGG7Q12G7GP1J', 'per GSTA-36:icm_01abc',+ REF, 'GSTA-36:2026-11-28T09:28Z', 'GSTA-36:2026-11-19', 'GSTA-36:1732790000', 'ends GSTA-36:1732790000.', 'GSTA-36:iev_01abc', '(jam_01abc)', 'see .capy/work/jam_01M8GSKHFHTDZWPHJVG6ZVJ3D4/x', 'ids/icm_01M8GG556RYA3HGG7Q12G7GP1J'];+ const text = ['SHA-256:abc', 'SHA-256:1234567890abcdef', 'UTF-8:x', 'PR-12:fix', 'A-1:b', 'test/jam_fix.ts', 'GStack Minder (GSTA-36)', 'my_jam_fix', 'approval a-315e17d615b1', 'lib/icm_parse.ts'];++ test('each earlier catch still matches and each look-alike does not', () => {+ expect(caught.filter(s => !INTERNAL_ID.test(s))).toEqual([]);+ expect(text.filter(s => INTERNAL_ID.test(s))).toEqual([]);+ });++ test('redaction replaces only the ids, and a receipt holding only look-alikes has no leak', () => {+ expect(redactInternalIds('SHA-256:abc and UTF-8:x per GSTA-36:icm_01abc in test/jam_fix.ts (jam_01abc), PR-12:fix at GBRA-108:2026-11-19T12:29:59Z'))+ .toBe('SHA-256:abc and UTF-8:x per a private message in test/jam_fix.ts (a private message), PR-12:fix at a private message');+ expect(publicReceiptLeaks({ reason: text.join(' '), gate: { 'PR-12:fix': 1, 'test/jam_fix.ts': true } })).toEqual([]);+ expect(publicReceiptLeaks({ reason: 'see GSTA-36:2026-11-28T09:28Z', note: 'x/jam_01M8GSKHFHTDZWPHJVG6ZVJ3D4' })).toEqual(['reason (a Capy thread or message id)', 'note (a Capy thread or message id)']);+ });++ test('a relay ref INTERNAL_ID does not match still reads a private message on a public repository, and its old body line is refused', () => {+ const f = fixture('PRIVATE');+ const rule = bin(f, 'gstack-approvals', ['rule', '--finding', 'src/x.ts:1:edit-share-race', '--head', f.git('rev-parse', 'HEAD').stdout.trim(), '--reason', 'ships as a disclosed note', '--words', 'B, note it', '--by', 'GBrain Minder (GBRA-108)', '--owner-ref', 'GBRA-108:fix']);+ expect(rule.status, rule.stderr).toBe(0);+ const full = bin(f, 'gstack-approvals', ['rulings']).stdout.trim();+ expect(full).toContain('(relayed from GBRA-108:fix)');+ setGh(f, 'PUBLIC');+ const redacted = bin(f, 'gstack-approvals', ['rulings']).stdout.trim();+ expect(redacted).toContain('(relayed from a private message)');+ const stale = write(f, bodyFile(f, `## Pre-Landing Review\n\n${full}\n${redacted}\n`));+ expect([stale.status, stale.stderr]).toEqual([EXIT.fail, expect.stringContaining('names a Capy thread or message id or relays from a ref')]);+ const clean = write(f, bodyFile(f, `## Pre-Landing Review\n\n${redacted}\n`));+ expect(clean.status, clean.stderr).toBe(EXIT.ok);+ });++ test('a reason that says relayed from in its own words is no relay, so the line rulings prints writes on a public repository', () => {+ const f = fixture('PUBLIC');+ const rule = bin(f, 'gstack-approvals', ['rule', '--finding', 'src/x.ts:1:edit-share-race', '--head', f.git('rev-parse', 'HEAD').stdout.trim(), '--reason', 'kept as is (relayed from the owner) for now', '--words', 'B, note it', '--by', 'GBrain Minder (GBRA-108)']);+ expect(rule.status, rule.stderr).toBe(0);+ const line = bin(f, 'gstack-approvals', ['rulings']).stdout.trim();+ expect(line).toContain(': kept as is (relayed from the owner) for now (approval ');+ const w = write(f, bodyFile(f, `## Pre-Landing Review\n\n${line}\n`));+ expect(w.status, w.stderr).toBe(EXIT.ok);+ });+});++// Value: protects=a hand-edited runs block never throws the round count and a repeated mark is placed once; fails_when=a non-string+// run throws in prReviewHistory, or the same abandon mark lands twice because one side holds the run dir path; seam=lib/pr-review-history.ts+describe('the runs block reads hand-edited entries safely (GST-4105)', () => {+ test('a non-string run counts as its own entry instead of throwing', () => {+ const body = runsBody({ head: H, run: 42, review_loop: LOOP }, { head: H, run: { dir: 'ship-1' }, review_loop: LOOP }, { head: H, run: 'ship-2', review_loop: LOOP });+ expect(prReviewHistory(body)).toMatchObject({ rounds: 3, runs: 3 });+ });++ test('a mark already in the block is not placed again when one side holds the run dir path', () => {+ const mark = { head: H, run: 'ship-4590', mark: 'abandoned' as const, by: 'GStack Minder (GSTA-36)', reason: 'stopped' };+ const body = runsBody(mark);+ expect(placeRunEntry(body, { ...mark, run: HOME_RUN })).toBe(body);+ const fromPath = runsBody({ ...mark, run: HOME_RUN });+ expect(placeRunEntry(fromPath, mark)).toBe(fromPath);+ expect(receiptRuns(placeRunEntry(body, { ...mark, reason: 'other' }))).toHaveLength(2);+ });+});++// Value: protects=a private repository's PR body written before GST-1955 still lands while a public one must carry the redacted line;+// fails_when=the queue refuses the legacy unredacted line on a private repository, or accepts it on a public one;+// seam=gateAcceptance (lib/gate-dispositions.ts), the check land, verify and ready share+describe('the queue takes a private repository\'s legacy gate disposition line (GST-4105)', () => {+ test('private accepts the legacy and the redacted line; public accepts only the redacted line', () => {+ const f = fixture('PRIVATE');+ const head = f.git('rev-parse', 'HEAD').stdout.trim();+ 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 (GSTA-36:icm_01M8GG556RYA3HGG7Q12G7GP1J)', '--by', 'GStack Minder (GSTA-36)']);+ expect(g.status, g.stderr).toBe(0);+ const redacted = bin(f, 'gstack-approvals', ['dispositions']).stdout.trim();+ expect(redacted).toContain('"do it (a private message)"');+ const script = path.join(f.root, 'accept.ts');+ fs.writeFileSync(script, [+ "import * as fs from 'node:fs';",+ `import { appliedGateDispositions, gateAcceptance } from ${JSON.stringify(path.join(path.dirname(BIN), 'lib', 'gate-dispositions.ts'))};`,+ 'const [head, mode, file] = process.argv.slice(2) as [string, string, string];',+ 'const { applied } = appliedGateDispositions(process.cwd(), { pin: head });',+ "if (mode === 'show') { console.log(JSON.stringify(applied)); process.exit(0); }",+ "const r = gateAcceptance({ cwd: process.cwd(), branch: 'feat', pin: head, body: fs.readFileSync(file, 'utf8'), receipt: { gate_dispositions: applied } as any });",+ "console.log(r.failure?.message ?? 'ok');",+ ].join('\n'));+ const accept = (mode: string, file = '') => f.run(process.execPath, [...bunIsolationArgs(), script, head, mode, file], { GSTACK_APPROVALS_MIRROR: '0' });+ const shown = accept('show');+ expect(shown.status, shown.stderr).toBe(0);+ const [d] = JSON.parse(shown.stdout) as Array<Record<string, string>>;+ const legacy = `Gate disposition: ${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})`;+ expect(legacy).toContain('GSTA-36:icm_');+ const legacyBody = bodyFile(f, `## Summary\n\n${legacy}\n`), redactedBody = path.join(f.root, 'redacted.md');+ fs.writeFileSync(redactedBody, `## Summary\n\n${redacted}\n`);+ expect([accept('check', legacyBody).stdout.trim(), accept('check', redactedBody).stdout.trim()]).toEqual(['ok', 'ok']);+ setGh(f, 'PUBLIC');+ expect(accept('check', legacyBody).stdout.trim()).toContain('the PR body lacks the line "Gate disposition: ');+ expect(accept('check', redactedBody).stdout.trim()).toBe('ok');+ });+});++// Value: protects=the runs block write, carry and abandon post is scanned like the receipt, so a hand-written home path or Capy id in+// an earlier entry or an abandon reason never publishes on a public repository; fails_when=write, carry or abandon posts one;+// seam=runsBlockLeaks in gstack-ship-receipt write, carry and abandoned+describe('the rendered runs block is scanned before it publishes (GST-4105)', () => {+ const handWritten = { head: H, run: 'ship-1', mark: 'abandoned', by: 'GStack Minder (GSTA-36)', reason: 'logs in /home/user/.capy/work/ship-1' };++ test('write refuses a body whose runs block holds a home path on a public repository and writes it on a private one', () => {+ const f = fixture('PUBLIC');+ const body = bodyFile(f, '## Summary\n\nA change.\n\n' + runsBody(handWritten));+ const before = fs.readFileSync(body, 'utf8');+ const pub = write(f, body, ['--run', 'ship-2']);+ expect([pub.status, pub.stderr]).toEqual([EXIT.fail, expect.stringContaining(`runs block holds ${RUNS_FENCE}[0].reason (a home path)`)]);+ expect(pub.stderr).toContain('(RECEIPT_INVALID)');+ expect(pub.stderr).not.toContain('/home/user');+ expect(fs.readFileSync(body, 'utf8')).toBe(before);+ setGh(f, 'PRIVATE');+ const priv = write(f, body, ['--run', 'ship-2']);+ expect(priv.status, priv.stderr).toBe(EXIT.ok);+ expect(receiptRuns(fs.readFileSync(body, 'utf8'))).toEqual([expect.objectContaining({ reason: handWritten.reason })]);+ });++ test('carry refuses a public body whose runs block holds a Capy id', () => {+ const f = fixture('PUBLIC');+ 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\n' + runsBody({ ...handWritten, reason: 'per jam_01abc' }), { schema_version: 1, pr: 5, head: reviewed, base: 'main', queue_mode: 'stamp-at-merge', run: 'ship-2', review_loop: LOOP } as any));+ const before = fs.readFileSync(body, 'utf8');+ const r = bin(f, 'gstack-ship-receipt', ['carry', '--body', body]);+ expect([r.status, r.stderr + r.stdout]).toEqual([EXIT.refused, expect.stringContaining(`${RUNS_FENCE}[0].reason (a Capy thread or message id)`)]);+ expect(fs.readFileSync(body, 'utf8')).toBe(before);+ });++ test('abandon refuses a home path in its reason on a public repository and keeps it on a private one', () => {+ const args = ['abandoned', '--run', 'ship-1', '--by', 'GStack Minder (GSTA-36)', '--reason', 'see /home/user/.capy/work/ship-1/log'];+ const f = fixture('PUBLIC');+ const body = bodyFile(f);+ const pub = bin(f, 'gstack-ship-receipt', [...args, '--body', body]);+ expect([pub.status, pub.stderr]).toEqual([EXIT.refused, expect.stringContaining(`${RUNS_FENCE}[0].reason (a home path)`)]);+ expect(fs.readFileSync(body, 'utf8')).toBe('## Summary\n\nA change.\n');+ const p = fixture('PRIVATE');+ const kept = bodyFile(p);+ expect(bin(p, 'gstack-ship-receipt', [...args, '--body', kept]).status).toBe(EXIT.ok);+ expect(receiptRuns(fs.readFileSync(kept, 'utf8'))[0]).toMatchObject({ reason: 'see /home/user/.capy/work/ship-1/log' });+ });++ test('abandon checks its own entry even when a runs block quoted above the Agent notes is the one it would edit', () => {+ const args = ['abandoned', '--run', 'ship-1', '--by', 'GStack Minder (GSTA-36)', '--reason', 'see /home/user/.capy/work/ship-1/log'];+ const f = fixture('PUBLIC');+ const text = '## Summary\n\n\`\`\`' + RUNS_FENCE + '\n' + JSON.stringify({ head: H, run: 'ship-0', review_loop: LOOP }) + '\n\`\`\`\n\n' + runsBody({ head: H, run: 'ship-1', status: 'started', review_loop: LOOP });+ const body = bodyFile(f, text);+ const pub = bin(f, 'gstack-ship-receipt', [...args, '--body', body]);+ expect([pub.status, pub.stderr]).toEqual([EXIT.refused, expect.stringContaining('abandon.reason (a home path)')]);+ expect(fs.readFileSync(body, 'utf8')).toBe(text);+ });+});++// Value: protects=abandon marks only an open PR that records the run, on the repository the branch pushes to; fails_when=a merged or+// closed PR, a PR with no entry for the run, or a contributor's fork PR (origin is upstream) is handled wrongly;+// seam=prOffBranch and the run-entry check in gstack-ship-receipt abandoned+describe('abandon needs an open PR that records the run, on the branch\'s push remote (GST-4105)', () => {+ const abandon = (f: ShipFx, pr = '3983') => bin(f, 'gstack-ship-receipt', ['abandoned', '--pr', pr, '--run', HOME_RUN, '--by', 'GStack Minder (GSTA-36)', '--reason', 'stopped answering']);++ test('a merged or closed PR is refused before any edit', () => {+ for (const state of ['MERGED', 'CLOSED']) {+ const f = fixture('PUBLIC', VIEW('feat', 'fx', { state }));+ const r = abandon(f);+ expect([r.status, r.stderr]).toEqual([EXIT.refused, expect.stringContaining(`PR #3983 is ${state.toLowerCase()}, not open`)]);+ expect(ghLog(f)).not.toContain('pr edit');+ }+ });++ test('a PR whose body records no entry for the run is refused; one with its stop record is marked', () => {+ const f = fixture('PUBLIC', VIEW('feat', 'fx', { body: runsBody({ head: H, run: 'ship-9', status: 'started', review_loop: LOOP }) }));+ const r = abandon(f);+ expect([r.status, r.stderr]).toEqual([EXIT.refused, expect.stringContaining("PR #3983's body records no entry for run ship-4590")]);+ expect(ghLog(f)).not.toContain('pr edit');+ setGh(f, 'PUBLIC', VIEW('feat', 'fx', { body: runsBody({ head: H, run: HOME_RUN, mark: 'stop', tree: 'b'.repeat(40), at: '2026-11-28T09:28:00Z' }) }));+ const ok = abandon(f);+ expect(ok.status, ok.stderr).toBe(EXIT.ok);+ expect(ghLog(f)).toContain('pr edit 3983');+ });++ test('a contributor whose branch pushes to a fork marks the fork PR and refuses the upstream one', () => {+ const f = fixture('PUBLIC', VIEW('feat', 'me'));+ f.git('remote', 'add', 'fork', 'https://github.com/me/fx.git');+ f.git('config', 'branch.feat.pushRemote', 'fork');+ const ok = abandon(f);+ expect(ok.status, ok.stderr).toBe(EXIT.ok);+ expect(ghLog(f)).toContain('pr edit 3983');+ setGh(f, 'PUBLIC', VIEW('feat', 'fx'));+ const upstream = abandon(f, '3984');+ expect([upstream.status, upstream.stderr]).toEqual([EXIT.refused, expect.stringContaining("PR #3984's head is on fx/fx, not this checkout's push remote fork me/fx")]);+ expect(ghLog(f)).not.toContain('pr edit 3984');+ });++ test('origin\'s pushurl names the fork, and a branch that only tracks another remote still pushes to origin', () => {+ const f = fixture('PUBLIC', VIEW('feat', 'me'));+ f.git('config', 'remote.origin.pushurl', 'https://github.com/me/fx.git');+ const fork = abandon(f);+ expect(fork.status, fork.stderr).toBe(EXIT.ok);+ f.git('config', '--unset', 'remote.origin.pushurl');+ f.git('remote', 'add', 'upstream', 'https://github.com/up/fx.git');+ f.git('config', 'branch.feat.remote', 'upstream');+ setGh(f, 'PUBLIC', VIEW('feat', 'fx'));+ const tracked = abandon(f, '3985');+ expect(tracked.status, tracked.stderr).toBe(EXIT.ok);+ expect(ghLog(f)).toContain('pr edit 3985');+ });+});+