From 0a6bb42e7484f61330daa2ad87f98c7e2ad534b3 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Wed, 18 Nov 2026 11:47:25 +0800 Subject: [PATCH 001/213] Reused CI runs that passed only after a re-run are now marked instead of shown as clean passes (GST-3054) (#4473) When /ship reuses a CI run that passed only after its failed jobs were re-run, its CI line and its final summary line now add `rerun= attempts=`. Why: gbrain's CI now records which test files passed on a re-run (gbrain#9690), and a pass on a re-run must read as flaky, never as clean. Nothing to do: runs without that record print as before; a malformed record is refused with `CI_CARRY_RERUN_MALFORMED`. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/outside-voice#1 reader=outside-voice Review-Finding: p1/outside-voice#2 reader=outside-voice Review-Finding: p1/adversarial-native#2 reader=adversarial-native Review-Finding: p1/red-team#1 reader=red-team --- bin/gstack-doctor-components.sh | 1 + bin/gstack-evidence | 21 ++-- changelog.d/ci-carry-marks-rerun-passes.md | 1 + docs/pregate.md | 5 +- docs/ship-policy.md | 11 +++ docs/troubleshooting.md | 17 ++++ lib/ci-carry.ts | 2 +- lib/headless-artifacts.ts | 5 +- lib/result-codes-release.ts | 5 + lib/run-evidence.ts | 42 ++++++-- lib/ship-receipt.ts | 11 ++- test/ci-carry-rerun.test.ts | 98 +++++++++++++++++++ test/evidence-reuse.test.ts | 12 +++ .../ci-carry-rerun/malformed.tree.json | 19 ++++ .../ci-carry-rerun/no-fields.tree.json | 14 +++ test/fixtures/ci-carry-rerun/rerun.tree.json | 22 +++++ test/helpers/free-fixtures-data.ts | 1 + 17 files changed, 270 insertions(+), 17 deletions(-) create mode 100644 changelog.d/ci-carry-marks-rerun-passes.md create mode 100644 test/ci-carry-rerun.test.ts create mode 100644 test/fixtures/ci-carry-rerun/malformed.tree.json create mode 100644 test/fixtures/ci-carry-rerun/no-fields.tree.json create mode 100644 test/fixtures/ci-carry-rerun/rerun.tree.json diff --git a/bin/gstack-doctor-components.sh b/bin/gstack-doctor-components.sh index 8226db50449..c6731247495 100644 --- a/bin/gstack-doctor-components.sh +++ b/bin/gstack-doctor-components.sh @@ -337,6 +337,7 @@ gstack_result_anchor() { RECEIPT_CARRY_REFUSED) printf '%s' 'receipt-carry-refused' ;; PROSE_LINT_FOUND) printf '%s' 'prose-lint-found' ;; REVIEW_LOOP_EXCEPTION_INVALID) printf '%s' 'review-loop-exception-invalid' ;; + CI_CARRY_RERUN_MALFORMED) printf '%s' 'ci-carry-rerun-malformed' ;; RECEIPT_CARRY_TREE_MISMATCH) printf '%s' 'receipt-carry-tree-mismatch' ;; RECEIPT_CARRY_PRODUCT_CHANGED) printf '%s' 'receipt-carry-product-changed' ;; RECEIPT_CARRY_SCOPED_REVIEW) printf '%s' 'receipt-carry-scoped-review' ;; diff --git a/bin/gstack-evidence b/bin/gstack-evidence index 753a4c4453b..924f8cccdb2 100755 --- a/bin/gstack-evidence +++ b/bin/gstack-evidence @@ -101,7 +101,7 @@ import { isUnavailable, loadPolicyFromBase, resolveBaseBranch } from "../lib/shi import { versionAtRef } from "../lib/restamp"; import { bashCommandInvocation, runScriptSync, wtreeFingerprint } from "../lib/script-invocation"; import { carriedFromLine, findCarry, laneMapping, mappingCoverage, perFileCommand } from "../lib/ci-carry"; -import { DEFAULT_MAX_AGE_HOURS, runChanged } from "../lib/run-evidence"; +import { DEFAULT_MAX_AGE_HOURS, rerunByRun, rerunMarker, runChanged } from "../lib/run-evidence"; import { isConfigUnavailable, loadConfigFromBase } from "../lib/pregate/config"; import { buildRunCheck } from "../lib/pregate/run-check"; import { readTestLaneExceptions, testLaneExceptionText, type BoundLaneException } from "../lib/test-lane-exception"; @@ -149,6 +149,8 @@ interface EvidenceRecord { skipped_here?: { label: string; files: string[]; tests_ran: number | "unknown"; not_owed?: string[] }; /** The owner's test-lane exception that let a lane carry with uncovered inventory files, and the preflight of exactly them here (GST-1595). */ exception?: BoundLaneException; + /** Per carried run (`/`) whose tree.json lists files that passed only on a re-run: how many, and the run's attempts (record-ci, GST-3054). */ + rerun?: Record; } /** Bytes of streamed output kept for the tests_ran parse (the 2MB log would truncate the summary). */ @@ -714,7 +716,7 @@ function reused(file: string, label: string, cmdSha: string, maxAgeHours: number /** record-ci's record line, the one lib/ci-carry.ts recordCiResult reads. */ const recordedCiLine = (r: EvidenceRecord): string => - `gstack-evidence: recorded label=${r.label} exit=0 tests_ran=${r.tests_ran}${r.tests_unit ? ` unit=${r.tests_unit}` : ""} log=- source=ci runs=${r.runs!.join(",")} policy=${r.policy}${r.skipped_here ? ` skipped_here=${r.skipped_here.files.length} tests_ran_here=${r.skipped_here.tests_ran}${r.skipped_here.not_owed ? ` not_owed_here=${r.skipped_here.not_owed.length}` : ""}` : ""}`; + `gstack-evidence: recorded label=${r.label} exit=0 tests_ran=${r.tests_ran}${r.tests_unit ? ` unit=${r.tests_unit}` : ""} log=- source=ci runs=${r.runs!.join(",")}${rerunMarker(Object.values(r.rerun ?? {}))} policy=${r.policy}${r.skipped_here ? ` skipped_here=${r.skipped_here.files.length} tests_ran_here=${r.skipped_here.tests_ran}${r.skipped_here.not_owed ? ` not_owed_here=${r.skipped_here.not_owed.length}` : ""}` : ""}`; /** * record-ci's reuse (GST-1795): the label's newest ledger row stands only when it is the CI row this record-ci would write again @@ -802,7 +804,9 @@ async function cmdRecordCi(argv: string[]): Promise { } if (!v.ok) return none(v.reason, `${v.detail}${v.reason === "inventory_uncovered" && !atHead.length && elsewhere.length ? `; test-lane exception ${elsewhere.join(", ")} binds another head, not HEAD ${head.slice(0, 12)}` : ""}`, v.diagnosis); const runs = v.runs.map((r) => `${r.run_id}/${r.run_attempt}`); - const prior = v.excepted?.length ? null : reusableCiRow(label, { commit: head, wtree: tree, cmd_sha256: sha256(command), runs, profiles: m.profiles, policy: loaded.label, jobs: m.jobs, tests_ran: v.tests, tests_unit: v.unit, not_owed: v.notOwed }, v.remainder ?? [], m.per_file); + const reran = rerunByRun(v.runs); + const rerun = reran.size ? Object.fromEntries(reran) : undefined; + const prior = v.excepted?.length ? null : reusableCiRow(label, { commit: head, wtree: tree, cmd_sha256: sha256(command), runs, profiles: m.profiles, policy: loaded.label, jobs: m.jobs, tests_ran: v.tests, tests_unit: v.unit, not_owed: v.notOwed, rerun }, v.remainder ?? [], m.per_file); if (prior) { console.error(recordedCiLine(prior)); if (prior.not_owed) console.error(`gstack-evidence: not owed: ${prior.not_owed}`); @@ -867,7 +871,7 @@ async function cmdRecordCi(argv: string[]): Promise { } const rec: EvidenceRecord = { ts: new Date(v.runs.map((r) => r.finished_at).sort()[0]!).toISOString(), label, command, cmd_sha256: sha256(command), exit: 0, duration_s: 0, - commit: head, tree, dirty: false, wtree: tree, tests_ran: testsRan, source: "ci", runs, profiles: m.profiles, policy: loaded.label, ...(m.jobs ? { jobs: m.jobs } : {}), ...(v.unit ? { tests_unit: v.unit } : {}), ...(v.notOwed ? { not_owed: v.notOwed } : {}), ...(here ? { skipped_here: here } : {}), ...(exception ? { exception } : {}), + commit: head, tree, dirty: false, wtree: tree, tests_ran: testsRan, source: "ci", runs, profiles: m.profiles, policy: loaded.label, ...(m.jobs ? { jobs: m.jobs } : {}), ...(v.unit ? { tests_unit: v.unit } : {}), ...(v.notOwed ? { not_owed: v.notOwed } : {}), ...(here ? { skipped_here: here } : {}), ...(exception ? { exception } : {}), ...(rerun ? { rerun } : {}), }; appendJsonl(paths.file, rec, { mode: 0o600 }); console.error(recordedCiLine(rec)); @@ -897,9 +901,14 @@ function cmdCarried(argv: string[]): number { for (const r of records) latest.set(r.label, r); const carried = [...latest.values()].filter((r) => r.source === "ci" && !!wtree && r.wtree === wtree && Array.isArray(r.runs) && typeof r.policy === "string" && r.policy.startsWith(policyRef) && gradeRecord(r, { maxAgeHours: DEFAULT_MAX_AGE_HOURS, allowPaths: [], wtreeNow: wtree }).verdict === "FRESH") - .flatMap((r) => r.runs!.map((ref) => { const [run, attempt] = ref.split("/").map(Number); return { lane: r.label, run, attempt, tree: r.wtree!, ...(r.exception ? { exception: r.exception } : {}) }; })); + .flatMap((r) => r.runs!.map((ref) => { + const [run, attempt] = ref.split("/").map(Number); + const re = r.rerun?.[ref]; + const reran = re && Number.isInteger(re.files) && re.files > 0 && Array.isArray(re.attempts) && re.attempts.every((n) => Number.isInteger(n) && n > 0) ? { rerun: re.files, attempts: re.attempts } : {}; + return { lane: r.label, run, attempt, tree: r.wtree!, ...reran, ...(r.exception ? { exception: r.exception } : {}) }; + })); if (argv.includes("--json")) console.log(JSON.stringify(carried)); - else for (const c of carried) console.log(`CI_CARRIED: ${c.lane} run=${c.run}/${c.attempt} tree=${c.tree.slice(0, 12)}`); + else for (const c of carried) console.log(`CI_CARRIED: ${c.lane} run=${c.run}/${c.attempt} tree=${c.tree.slice(0, 12)}${"rerun" in c ? rerunMarker([{ files: c.rerun!, attempts: c.attempts! }]) : ""}`); return 0; } diff --git a/changelog.d/ci-carry-marks-rerun-passes.md b/changelog.d/ci-carry-marks-rerun-passes.md new file mode 100644 index 00000000000..0f4d5bff0e7 --- /dev/null +++ b/changelog.d/ci-carry-marks-rerun-passes.md @@ -0,0 +1 @@ +- **A CI run that passed only after its failed jobs were re-run is now marked wherever gstack reuses it.** When a run's `tree.json` lists `rerun_files` and `attempts` (gbrain writes these since gbrain#9690), the `CI_CARRY:` line, the `SHIP_RECEIPT:` line's `ci_carried=` field, and the receipt line `gstack-ship-queue ready` and `land` print now add `rerun= attempts=`, so a pass on a re-run reads as flaky instead of as a clean first-attempt pass. The run is still accepted. A `tree.json` without those fields prints exactly as before, and a malformed `rerun_files` or `attempts` refuses that run with `CI_CARRY_RERUN_MALFORMED`. diff --git a/docs/pregate.md b/docs/pregate.md index b37dec29fc7..25d3c12a462 100644 --- a/docs/pregate.md +++ b/docs/pregate.md @@ -1339,7 +1339,10 @@ each mapped lane from the green run at that exact tree, reuses or runs the rest, checks every lane FRESH and reruns the pregate there, whose tests stage carries the same run. `gstack-ship-receipt write` records the carried runs as `ci_carried: [{ lane, run, attempt, tree }]`, and the `SHIP_RECEIPT:` line names -them (`ci_carried=:/`). Each `record-ci` gets the base +them (`ci_carried=:/`). A run whose `tree.json` lists +`rerun_files` adds `rerun` and `attempts` to its entries and +`rerun= attempts=` after `ci_carried=`, as its `CI_CARRY:` line does +([ship-policy.md](ship-policy.md#ci-carry-rerun)). Each `record-ci` gets the base policy's [`ci_record_timeout_s`](ship-policy.md#ci-record-timeout) (600 s by default, 3600 s at most), and accept prints it as `CI_RECORD_TIMEOUT:`. diff --git a/docs/ship-policy.md b/docs/ship-policy.md index 3dbda57606f..aba79c3181d 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -2730,6 +2730,17 @@ body plain: they become main's history. A `pull_request` CI run tests GitHub's merge commit rather than your branch, so on a branch behind main `gstack-ci-carry` reports `tree_mismatch`: dispatch the workflow on the branch (`gh workflow run --ref `). +- **A carried run that passed only after a re-run is marked, not refused.** + When only a run's failed jobs were re-run, its `tree.json` may list + `rerun_files` (the files whose newest result came from a re-run attempt) and + `attempts` (for example `[1, 2]`). The carry still accepts the run, but the + `CI_CARRY:` line, the `SHIP_RECEIPT:` line's `ci_carried=` field, and the + receipt line `ready` and `land` print all add `rerun= attempts=`, + so a pass on a re-run reads as flaky, never as a clean first-attempt pass. A + `tree.json` without `rerun_files`, or with an empty list, prints exactly as + before. A `rerun_files` that is not a list of paths, or `attempts` that is not + a list of attempt numbers, refuses that run + ([`CI_CARRY_RERUN_MALFORMED`](troubleshooting.md#ci-carry-rerun-malformed)). #### Every check land makes diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 27b7bf46fe9..103cbb718c6 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -7251,6 +7251,23 @@ pass the `gstack-review-scope summary` file as `--review-loop`, put the printed line in the PR body, and write again ([ship-policy.md](ship-policy.md#ship-receipt)). + +### `CI_CARRY_RERUN_MALFORMED` + +**Meaning.** A CI run's `tree.json` names `rerun_files` or `attempts`, the +fields that say some test files passed only on a re-run attempt, but in a shape +gstack cannot read: `rerun_files` is not a list of file paths, or `attempts` is +not a list of attempt numbers of 1 or more. gstack fails closed: that run is not +evidence, the carry refuses it (`rerun_malformed` in the `CI_CARRY: none` or +`no_verified_run` detail), and the lane runs here instead. A well-formed record +is accepted and marked `rerun= attempts=` +([ship-policy.md](ship-policy.md#ci-carry-rerun)). + +**Fix.** Fix the workflow step that writes `tree.json` so it writes +`"rerun_files": ["test/a.test.ts", …]` and `"attempts": [1, 2]`, or leaves both +out. Then dispatch a fresh run at the same head and rerun +`gstack-ci-carry wait`. + ### `RECEIPT_CARRY_TREE_MISMATCH` diff --git a/lib/ci-carry.ts b/lib/ci-carry.ts index d183da7ebdd..15a3c5d1fc6 100644 --- a/lib/ci-carry.ts +++ b/lib/ci-carry.ts @@ -83,7 +83,7 @@ function newestVerified(src: RunSource, name: string, profile: RunProfile, heads for (const run of listed) { const v = verifyRun(src.deps, { repo: src.repo, runRef: String(run.id), profileName: name, profile, vetoHeads: heads, now: src.now, unchanged: src.unchanged, docsOnly }); if (v.ok) return v; - refusals.push(`run ${run.id}: ${v.reason}${v.fix ? ` (the pull request's base moved after the run; fix: ${v.fix})` : ''}`); + refusals.push(`run ${run.id}: ${v.reason}${v.reason === 'rerun_malformed' ? ` (${v.detail})` : ''}${v.fix ? ` (the pull request's base moved after the run; fix: ${v.fix})` : ''}`); } return no('no_verified_run', `${name}: ${refusals.join('; ')}`); } diff --git a/lib/headless-artifacts.ts b/lib/headless-artifacts.ts index 983ceb4ac33..e612e1047c6 100644 --- a/lib/headless-artifacts.ts +++ b/lib/headless-artifacts.ts @@ -104,8 +104,8 @@ export interface ShipReceipt { gate?: Record; ci?: Record; spend_usd?: number | string; predecessor?: string; /** The run's calls from the call log (lib/ship-clock.ts callsSince: gstack-command calls plus keep-alives), so a 200-call run shows at the receipt; absent on older receipts. */ calls?: number; - /** GSTA-258: the lanes CI carried at this head's tree, one entry per run (gstack-evidence carried). */ - ci_carried?: Array<{ lane: string; run: number; attempt: number; tree: string; exception?: BoundLaneException }>; + /** GSTA-258: the lanes CI carried at this head's tree, one entry per run (gstack-evidence carried); `rerun` and `attempts` when files passed only on a re-run (GST-3054). */ + ci_carried?: Array<{ lane: string; run: number; attempt: number; tree: string; rerun?: number; attempts?: number[]; exception?: BoundLaneException }>; session_kind?: string; artifacts_consumed?: string; run?: string; // C-stamp (C3/C5/C7): the tree receipt's verdicts and the policy provenance, all optional. thread?: string; tree?: string; gate_reuse?: string; policy?: string; queue_mode?: string; preregistration?: string; history?: string; @@ -267,6 +267,7 @@ export const ARTIFACT_SCHEMAS = { schema_version: { const: 1 }, pr: { type: 'integer' }, head: str, version: str, base: str, gated_tree: str, gate: { type: 'object' }, ci: { type: 'object' }, spend_usd: { type: ['number', 'string'] }, calls: { type: 'integer', minimum: 0 }, predecessor: str, ci_carried: { type: 'array', items: { type: 'object', required: ['lane', 'run', 'attempt', 'tree'], properties: { lane: str, run: { type: 'integer', minimum: 1 }, attempt: { type: 'integer', minimum: 1 }, tree: str, + rerun: { type: 'integer', minimum: 1 }, attempts: { type: 'array', items: { type: 'integer', minimum: 1 } }, exception: { type: 'object', required: ['head', 'files', 'by', 'reason', 'at', 'approval', 'preflight'], properties: { head: str, files: strList, by: str, reason: str, at: str, approval: str, preflight: { type: 'object', required: ['label', 'tests_ran'], properties: { label: str, tests_ran: { type: 'integer', minimum: 1 } } } } } } } }, session_kind: str, artifacts_consumed: { ...str, description: '/' }, run: str, diff --git a/lib/result-codes-release.ts b/lib/result-codes-release.ts index e396cc9bea5..1ff6ce0f2f5 100644 --- a/lib/result-codes-release.ts +++ b/lib/result-codes-release.ts @@ -420,6 +420,11 @@ export const RELEASE_RESULT_CODES = { summary: 'write --review-loop-exception got an exception that is malformed, accepts a stop the review loop does not show (a fix_check with review_loop.fix_checks 0 or missing, or a second_pass with fewer than two passes or no deferred finding), names a head that is not the receipt head or its ancestor, or is missing from the PR body', fix: 'pass { accepted_by, date, via, reason } plus fix_check: { head, findings } or second_pass: { head, deferred: [] } with the owner’s words, the --review-loop summary that shows that stop, and the printed "Review-loop exception: …" line in the body', }, + CI_CARRY_RERUN_MALFORMED: { + anchor: 'ci-carry-rerun-malformed', + summary: 'a CI run\'s tree.json carries rerun_files or attempts in a shape gstack cannot read (rerun_files not a list of paths, attempts not a list of attempt numbers), so the run is not evidence and no lane carries from it', + fix: 'fix the workflow step that writes tree.json (rerun_files: ["test/a.test.ts", …], attempts: [1, 2]), dispatch a fresh run at the same head, then rerun gstack-ci-carry wait', + }, RECEIPT_CARRY_TREE_MISMATCH: { anchor: 'receipt-carry-tree-mismatch', summary: 'the branch was rebased or force-pushed since its /ship receipt, and HEAD\'s tree is not a tree the receipt covers, so no review saw this code', diff --git a/lib/run-evidence.ts b/lib/run-evidence.ts index 4d51dada620..1edf6a23fe2 100644 --- a/lib/run-evidence.ts +++ b/lib/run-evidence.ts @@ -55,7 +55,7 @@ export interface ApiRun { repository?: { full_name: string } | null; head_repository?: { full_name: string } | null; head_branch?: string | null; } export interface ApiJob { name: string; conclusion: string | null; started_at?: string | null; completed_at?: string | null } -export interface TreeRecord { run_id?: unknown; run_attempt?: unknown; event?: unknown; sha?: unknown; head_sha?: unknown; tree?: unknown; reused?: unknown; reuse?: unknown; sizing_experiment?: unknown; os?: unknown; files?: unknown; tests?: unknown; skipped_files?: unknown } +export interface TreeRecord { run_id?: unknown; run_attempt?: unknown; event?: unknown; sha?: unknown; head_sha?: unknown; tree?: unknown; reused?: unknown; reuse?: unknown; sizing_experiment?: unknown; os?: unknown; files?: unknown; tests?: unknown; skipped_files?: unknown; rerun_files?: unknown; attempts?: unknown } /** What a red run's reader needs beyond RunDeps (lib/pregate/flaky-exception.ts): every file of one artifact, and a pull request's head. */ export interface RunArtifactDeps { @@ -78,10 +78,11 @@ export interface RunDeps { export type RunRefusal = 'run_ref_invalid' | 'other_repository' | 'fork_run' | 'workflow_mismatch' | 'event_mismatch' | 'run_in_progress' | 'run_not_success' | 'job_missing' | 'job_ambiguous' | 'job_skipped' | 'job_not_success' | 'artifact_missing' | 'artifact_mismatch' - | 'artifact_reused' | 'sizing_experiment' | 'tree_mismatch' | 'newer_run_vetoes' | 'run_changed' | 'run_stale' | 'os_mismatch' | 'api_error'; + | 'artifact_reused' | 'sizing_experiment' | 'tree_mismatch' | 'newer_run_vetoes' | 'run_changed' | 'run_stale' | 'os_mismatch' | 'rerun_malformed' | 'api_error'; /** `skipped`: the files whose every test skipped on the runner (tree.json `skipped_files`, GST-1190); undefined when an older tree.json does not say. */ /** `docs_only`: a pull_request run whose gate skipped every skippable job on a change lib/docs-only.ts calls human docs only; it ran and recorded no tests (R81). */ -export interface RunEvidence { run_id: number; run_attempt: number; head_sha: string; tree: string; profile: string; event: string; finished_at: string; files: string[]; tests: number | null; skipped?: string[]; skipped_jobs?: string[]; docs_only?: true } +/** `rerun`: the files whose newest result came from a re-run attempt (tree.json `rerun_files`, gbrain#9690), with the run's `attempts`; set only when a file passed on a re-run (GST-3054). */ +export interface RunEvidence { run_id: number; run_attempt: number; head_sha: string; tree: string; profile: string; event: string; finished_at: string; files: string[]; tests: number | null; skipped?: string[]; skipped_jobs?: string[]; docs_only?: true; rerun?: string[]; attempts?: number[] } /** `fix`: the one command that clears a refusal the caller can repair, such as a pull_request run that tested a merge with an older base. */ export type RunVerdict = { ok: true; evidence: RunEvidence } | { ok: false; reason: RunRefusal; detail: string; fix?: string }; @@ -243,12 +244,16 @@ export function verifyRun(deps: RunDeps, o: { repo: string; runRef: string; prof if (rec.files !== undefined && (!Array.isArray(rec.files) || rec.files.some(f => typeof f !== 'string'))) return fail('artifact_mismatch', `${at}'s ${p.artifact} files is not a list of paths`); if (rec.tests !== undefined && (!Number.isInteger(rec.tests) || (rec.tests as number) < 0)) return fail('artifact_mismatch', `${at}'s ${p.artifact} tests is not a non-negative integer`); if (rec.skipped_files !== undefined && (!Array.isArray(rec.skipped_files) || rec.skipped_files.some(f => typeof f !== 'string'))) return fail('artifact_mismatch', `${at}'s ${p.artifact} skipped_files is not a list of paths`); + if (rec.rerun_files !== undefined && (!Array.isArray(rec.rerun_files) || rec.rerun_files.some(f => typeof f !== 'string'))) return fail('rerun_malformed', `${at}'s ${p.artifact} rerun_files is not a list of paths (CI_CARRY_RERUN_MALFORMED)`); + if (rec.attempts !== undefined && (!Array.isArray(rec.attempts) || rec.attempts.some(n => !Number.isInteger(n) || (n as number) < 1))) return fail('rerun_malformed', `${at}'s ${p.artifact} attempts is not a list of attempt numbers (CI_CARRY_RERUN_MALFORMED)`); const files = ((rec.files ?? []) as string[]).map(normalPath); const tests = rec.tests === undefined ? null : (rec.tests as number); const changed = runChanged(deps, id, run.run_attempt); if (changed) return fail('run_changed', changed); const skipped = rec.skipped_files === undefined ? {} : { skipped: (rec.skipped_files as string[]).map(normalPath) }; - return { ok: true, evidence: { run_id: id, run_attempt: run.run_attempt, head_sha: run.head_sha, tree: headTree, profile: o.profileName, event: run.event, finished_at: finishedAt!, files, tests, ...skipped, ...(skippedJobs.length ? { skipped_jobs: skippedJobs } : {}) } }; + const rerun = ((rec.rerun_files ?? []) as string[]).map(normalPath); + const reran = rerun.length ? { rerun, attempts: [...new Set((rec.attempts ?? []) as number[])].sort((a, b) => a - b) } : {}; + return { ok: true, evidence: { run_id: id, run_attempt: run.run_attempt, head_sha: run.head_sha, tree: headTree, profile: o.profileName, event: run.event, finished_at: finishedAt!, files, tests, ...skipped, ...(skippedJobs.length ? { skipped_jobs: skippedJobs } : {}), ...reran } }; } catch (e: any) { return fail('api_error', `reading run ${id} failed: ${String(e?.message ?? e).slice(0, 300)}`); } @@ -322,9 +327,34 @@ export function verifyFromRun(src: RunSource, ref: string, names: string[], tree return refusals.length === 1 ? { ok: false, ...refusals[0]! } : { ok: false, reason: 'no_verified_run', detail: refusals.map(r => `${r.detail} (${r.reason})`).join(' | ') }; } -/** The receipt suffix a run clear records: runs, profiles and the verification time, read back by `parseRunReceipt`. */ +/** + * The receipt suffix a run clear records: runs, profiles and the verification time, read back by `parseRunReceipt`. A run some of + * whose files passed only on a re-run adds `rerun= attempts=` (GST-3054): allowed, but never shown as a clean pass. + */ export function runReceiptFields(evidence: RunEvidence[], now: Date): string { - return `runs=${evidence.map(e => `${e.run_id}/${e.run_attempt}`).join(',')} profiles=${evidence.map(e => e.profile).join(',')} heads=${[...new Set(evidence.map(e => e.head_sha.slice(0, 12)))].join(',')} verified=${now.toISOString()}`; + return `runs=${evidence.map(e => `${e.run_id}/${e.run_attempt}`).join(',')} profiles=${evidence.map(e => e.profile).join(',')} heads=${[...new Set(evidence.map(e => e.head_sha.slice(0, 12)))].join(',')}${rerunMarker([...rerunByRun(evidence).values()])} verified=${now.toISOString()}`; +} + +/** The re-run record per carried run (`/`): the distinct re-run files and attempts across every profile that read that run, so two profiles on one run count each file once. */ +export function rerunByRun(evidence: Array>): Map { + const runs = new Map; attempts: Set }>(); + for (const e of evidence) { + if (!e.rerun?.length) continue; + const key = `${e.run_id}/${e.run_attempt}`; + const run = runs.get(key) ?? { files: new Set(), attempts: new Set() }; + for (const f of e.rerun) run.files.add(f); + for (const n of e.attempts ?? []) run.attempts.add(n); + runs.set(key, run); + } + return new Map([...runs].map(([key, r]) => [key, { files: r.files.size, attempts: [...r.attempts].sort((a, b) => a - b) }])); +} + +/** ` rerun= attempts=` over the runs with re-run files, each run counted once, or '' when every run passed first time (GST-3054). */ +export function rerunMarker(runs: Array<{ files: number; attempts: number[] }>): string { + const reran = runs.filter(r => r.files > 0); + if (!reran.length) return ''; + const attempts = [...new Set(reran.flatMap(r => r.attempts))].sort((a, b) => a - b); + return ` rerun=${reran.reduce((n, r) => n + r.files, 0)} attempts=${attempts.length ? attempts.join(',') : 'unrecorded'}`; } export function parseRunReceipt(receipt: string): { runs: string[]; profiles: string[]; tree: string | null } | null { diff --git a/lib/ship-receipt.ts b/lib/ship-receipt.ts index a65895b27db..4c8aee22658 100644 --- a/lib/ship-receipt.ts +++ b/lib/ship-receipt.ts @@ -16,6 +16,7 @@ import { matchesAny } from './ship-policy'; import { ruledNoteText } from './ruled-notes'; import { gateDispositionText } from './gate-dispositions'; import { laneExceptionBodyLines } from './test-lane-exception'; +import { rerunMarker } from './run-evidence'; import { stampFileKind, versionStampOnly } from './pregate/stamp-only'; import { stampOnlyLine, type BranchSide } from './stamp-only'; @@ -207,7 +208,15 @@ export function receiptSummaryLine(r: ShipReceipt): string { if (loop) parts.push(`passes=${loop.passes} blocking_found=${loop.blocking_found} deferred=${loop.deferred}` + (loop.fix_checks ? ` fix_checks=${loop.fix_checks}` : '') + (loop.rounds !== undefined ? ` rounds=${loop.rounds}` : '') + (loop.dispatches ? ` dispatches=${Object.values(loop.dispatches).reduce((a, c) => a + c, 0)}` : '')); if (r.carry && typeof r.carry.from === 'string') parts.push(`carried_from=${r.carry.from.slice(0, 12)}`); - if (Array.isArray(r.ci_carried) && r.ci_carried.length) parts.push(`ci_carried=${r.ci_carried.map(c => `${c.lane}:${c.run}/${c.attempt}`).join(',')}`); + if (Array.isArray(r.ci_carried) && r.ci_carried.length) { + const runs = new Map(); + for (const c of r.ci_carried) { + const key = `${c.run}/${c.attempt}`; + const seen = runs.get(key) ?? { files: 0, attempts: [] }; + runs.set(key, { files: Math.max(seen.files, typeof c.rerun === 'number' ? c.rerun : 0), attempts: [...seen.attempts, ...(Array.isArray(c.attempts) ? c.attempts : [])] }); + } + parts.push(`ci_carried=${r.ci_carried.map(c => `${c.lane}:${c.run}/${c.attempt}`).join(',')}${rerunMarker([...runs.values()])}`); + } if (r.base_red && typeof r.base_red.base === 'string') parts.push(`base_red=${r.base_red.base.slice(0, 12)}`); return `SHIP_RECEIPT: ${oneLine(parts.join(' '))}`; } diff --git a/test/ci-carry-rerun.test.ts b/test/ci-carry-rerun.test.ts new file mode 100644 index 00000000000..bf82b7cb12e --- /dev/null +++ b/test/ci-carry-rerun.test.ts @@ -0,0 +1,98 @@ +/** + * GST-3054: a carried CI run whose tree.json says some files passed only on a re-run attempt (gbrain#9690's + * `rerun_files` and `attempts`) still carries, but every carry receipt and the SHIP_RECEIPT line say so + * (`rerun= attempts=`), and a malformed record fails closed. The dependencies are fakes; nothing reaches GitHub. + */ +import { describe, expect, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { findCarry } from '../lib/ci-carry'; +import { RESULT_CODES } from '../lib/result-codes'; +import { receiptSummaryLine, validateReceipt } from '../lib/ship-receipt'; +import { rerunByRun, runReceiptFields, type ApiRun, type RunDeps, type RunProfile, type RunSource, type TreeRecord } from '../lib/run-evidence'; + +const REPO = 'garrytan/gstack'; +const HEAD = 'a'.repeat(40); +const TREE = 'b'.repeat(40); +const NOW = new Date('2026-11-02T12:00:00Z'); +const PROFILE: RunProfile = { workflow: 'free-tests.yml', events: ['workflow_dispatch'], jobs: ['free-tests'], artifact: 'tested-tree', os: 'Linux' }; +const FIXTURES = path.join(import.meta.dir, 'fixtures', 'ci-carry-rerun'); +const fixture = (name: string): TreeRecord => JSON.parse(fs.readFileSync(path.join(FIXTURES, name), 'utf8')); +const INVENTORY = ['test/a.test.ts', 'test/b.test.ts', 'test/c.test.ts']; + +function source(rec: TreeRecord): RunSource { + const r: ApiRun = { id: rec.run_id as number, run_attempt: rec.run_attempt as number, status: 'completed', conclusion: 'success', event: 'workflow_dispatch', head_sha: HEAD, + path: '.github/workflows/free-tests.yml', created_at: '2026-11-02T10:00:00Z', updated_at: '2026-11-02T11:30:00Z', repository: { full_name: REPO }, head_repository: { full_name: REPO } }; + const deps: RunDeps = { + run: () => r, + runsForHead: (_wf, sha) => (sha === HEAD ? [r] : []), + jobs: () => [{ name: 'free-tests', conclusion: 'success', completed_at: '2026-11-02T11:30:00Z' }], + artifact: () => rec, + commitTree: sha => (sha === HEAD ? TREE : null), + }; + return { repo: REPO, deps, profiles: { 'ci-reuse/free-tests': PROFILE }, now: NOW }; +} +const carry = (rec: TreeRecord, inventory = true) => findCarry(source(rec), { profiles: ['ci-reuse/free-tests'], head: HEAD, tree: TREE, wtree: () => TREE, ...(inventory ? { inventory: () => INVENTORY } : {}) }); +const receipt = (ci_carried: unknown) => ({ schema_version: 1 as const, head: HEAD, base: 'main', ci_carried } as Parameters[0]); + +describe('a carried run that passed only after a re-run (GST-3054)', () => { + // Value: protects=a tree.json without rerun_files carries exactly as before; fails_when=the marker appears on a clean first-attempt run + test('a tree.json without rerun_files or attempts carries with no rerun marker', () => { + for (const inventory of [true, false]) { + const v = carry(fixture('no-fields.tree.json'), inventory); + expect(v.ok).toBe(true); + if (!v.ok) return; + expect(v.receipt).not.toMatch(/ rerun=| attempts=/); + expect(v.runs[0]!.rerun).toBeUndefined(); + expect(v.runs[0]!.attempts).toBeUndefined(); + } + const empty = carry({ ...fixture('no-fields.tree.json'), rerun_files: [], attempts: [1] }); + expect(empty.ok).toBe(true); + expect(empty.ok ? empty.receipt : '').not.toContain('rerun='); + const line = receiptSummaryLine(receipt([{ lane: 'free', run: 4, attempt: 1, tree: TREE }])); + expect(line).toContain('ci_carried=free:4/1'); + expect(line).not.toMatch(/ rerun=| attempts=/); + }); + + // Value: protects=a re-run pass is marked, never presented as clean; fails_when=rerun_files is ignored again or the carry refuses it + test('rerun_files carries, and the carry receipt names the re-run count and the attempts', () => { + for (const inventory of [true, false]) { + const v = carry(fixture('rerun.tree.json'), inventory); + expect(v.ok).toBe(true); + if (!v.ok) return; + expect(v.receipt).toContain(' runs=5/2 '); + expect(v.receipt).toContain(' rerun=2 attempts=1,2 '); + expect([v.runs[0]!.rerun, v.runs[0]!.attempts]).toEqual([['test/b.test.ts', 'test/c.test.ts'], [1, 2]]); + } + }); + + // Value: protects=the SHIP_RECEIPT line ready and land print shows the marker; fails_when=the receipt drops it or it fails schema validation + test('the receipt records rerun and attempts per carried run, and SHIP_RECEIPT shows them after ci_carried', () => { + const r = receipt([{ lane: 'free', run: 5, attempt: 2, tree: TREE, rerun: 2, attempts: [1, 2] }, { lane: 'lint', run: 5, attempt: 2, tree: TREE, rerun: 2, attempts: [1, 2] }]); + expect(validateReceipt(r)).toEqual([]); + expect(receiptSummaryLine(r)).toContain('ci_carried=free:5/2,lint:5/2 rerun=2 attempts=1,2'); + expect(validateReceipt(receipt([{ lane: 'free', run: 5, attempt: 2, tree: TREE, rerun: '2', attempts: 'x' }])).length).toBeGreaterThan(0); + }); + + // Value: protects=an unmarked lane on the same run never hides the marker, and two profiles on one run count each file once; fails_when=the last entry or profile overwrites or double-counts + test('lanes and profiles that share a run keep the marker and count each re-run file once', () => { + expect(receiptSummaryLine(receipt([{ lane: 'free', run: 5, attempt: 2, tree: TREE, rerun: 1, attempts: [1, 2] }, { lane: 'lint', run: 5, attempt: 2, tree: TREE }]))).toContain('ci_carried=free:5/2,lint:5/2 rerun=1 attempts=1,2'); + const run = { run_id: 5, run_attempt: 2, head_sha: HEAD, tree: TREE, event: 'workflow_dispatch', finished_at: '2026-11-02T11:30:00Z', files: INVENTORY, tests: 3, rerun: ['test/b.test.ts'], attempts: [2, 1, 2] }; + expect(runReceiptFields([{ ...run, profile: 'one' }, { ...run, profile: 'two' }], NOW)).toContain(' rerun=1 attempts=1,2 '); + expect([...rerunByRun([run, { ...run, rerun: ['test/c.test.ts'] }])]).toEqual([['5/2', { files: 2, attempts: [1, 2] }]]); + }); + + // Value: protects=fail closed on a malformed re-run record; fails_when=a non-array or non-string rerun_files, or bad attempts, carries + test('a malformed rerun_files or attempts refuses with CI_CARRY_RERUN_MALFORMED', () => { + const bad: Array> = [{}, { rerun_files: [1] }, { rerun_files: ['test/b.test.ts'], attempts: '1,2' }, { rerun_files: ['test/b.test.ts'], attempts: [0, 2] }, { rerun_files: ['test/b.test.ts'], attempts: ['2'] }]; + for (const over of bad) { + const v = carry({ ...fixture('malformed.tree.json'), ...over }); + expect(v.ok).toBe(false); + if (v.ok) return; + expect(v.reason).toBe('no_verified_run'); + expect(v.detail).toContain('rerun_malformed'); + expect(v.detail).toContain('(CI_CARRY_RERUN_MALFORMED)'); + } + expect(RESULT_CODES.CI_CARRY_RERUN_MALFORMED.anchor).toBe('ci-carry-rerun-malformed'); + }); +}); diff --git a/test/evidence-reuse.test.ts b/test/evidence-reuse.test.ts index 4011dcd704b..273adc82193 100644 --- a/test/evidence-reuse.test.ts +++ b/test/evidence-reuse.test.ts @@ -128,6 +128,18 @@ describe('gstack-evidence record-ci and carried (A4)', () => { expect(JSON.parse(run(['carried', '--json']).stdout)).toEqual([]); }); + // Value: protects=GST-3054, a carried run that passed only on a re-run reaches the receipt's ci_carried entry marked; fails_when=the + // ledger's rerun record is dropped on the way to the receipt, or a forged one with bad attempts is copied into it + test('carried copies a CI row\'s re-run record into its ci_carried entry, and drops a malformed one', () => { + expect(run(['run', '--label', 'unit', '--', lane(2)]).status).toBe(0); + fs.appendFileSync(ledger(), JSON.stringify({ ...ciRow(), rerun: { '41/2': { files: 290, attempts: [1, 2] } } }) + '\n'); + expect(JSON.parse(run(['carried', '--base', 'main', '--json']).stdout)).toEqual([{ lane: 'free', run: 41, attempt: 2, tree: wtree(), rerun: 290, attempts: [1, 2] }]); + expect(run(['carried', '--base', 'main']).stdout).toContain('CI_CARRIED: free run=41/2 tree='); + expect(run(['carried', '--base', 'main']).stdout).toContain(' rerun=290 attempts=1,2'); + fs.appendFileSync(ledger(), JSON.stringify({ ...ciRow(), rerun: { '41/2': { files: 290, attempts: '1,2' } } }) + '\n'); + expect(JSON.parse(run(['carried', '--base', 'main', '--json']).stdout)).toEqual([{ lane: 'free', run: 41, attempt: 2, tree: wtree() }]); + }); + // Value: protects=record-ci finds and verifies the CI run itself, so no caller supplies run ids, a test count or a tree (/ship pass 1 red-team#1); // fails_when=the forged call from that finding writes a FRESH carried row; seam=no origin, so the base's ship_lanes_from is unreadable test('record-ci takes no run facts from its caller and records nothing without a verified run', () => { diff --git a/test/fixtures/ci-carry-rerun/malformed.tree.json b/test/fixtures/ci-carry-rerun/malformed.tree.json new file mode 100644 index 00000000000..11d69c3c976 --- /dev/null +++ b/test/fixtures/ci-carry-rerun/malformed.tree.json @@ -0,0 +1,19 @@ +{ + "run_id": 6, + "run_attempt": 2, + "event": "workflow_dispatch", + "sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "tree": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "files": [ + "test/a.test.ts", + "test/b.test.ts", + "test/c.test.ts" + ], + "tests": 60, + "os": "Linux", + "rerun_files": "test/b.test.ts", + "attempts": [ + 1, + 2 + ] +} diff --git a/test/fixtures/ci-carry-rerun/no-fields.tree.json b/test/fixtures/ci-carry-rerun/no-fields.tree.json new file mode 100644 index 00000000000..08b4760b519 --- /dev/null +++ b/test/fixtures/ci-carry-rerun/no-fields.tree.json @@ -0,0 +1,14 @@ +{ + "run_id": 4, + "run_attempt": 1, + "event": "workflow_dispatch", + "sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "tree": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "files": [ + "test/a.test.ts", + "test/b.test.ts", + "test/c.test.ts" + ], + "tests": 60, + "os": "Linux" +} diff --git a/test/fixtures/ci-carry-rerun/rerun.tree.json b/test/fixtures/ci-carry-rerun/rerun.tree.json new file mode 100644 index 00000000000..52bf1091c6d --- /dev/null +++ b/test/fixtures/ci-carry-rerun/rerun.tree.json @@ -0,0 +1,22 @@ +{ + "run_id": 5, + "run_attempt": 2, + "event": "workflow_dispatch", + "sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "tree": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "files": [ + "test/a.test.ts", + "test/b.test.ts", + "test/c.test.ts" + ], + "tests": 60, + "os": "Linux", + "rerun_files": [ + "test/b.test.ts", + "test/c.test.ts" + ], + "attempts": [ + 1, + 2 + ] +} diff --git a/test/helpers/free-fixtures-data.ts b/test/helpers/free-fixtures-data.ts index e8a831859d4..f0ba1201048 100644 --- a/test/helpers/free-fixtures-data.ts +++ b/test/helpers/free-fixtures-data.ts @@ -51,6 +51,7 @@ export const FREE_FIXTURES: Readonly> = { 'test/fixtures/ceo-split-collection-3638.json': ['test/ceo-split-collection.test.ts'], 'test/fixtures/ceo-split-wording-variants.json': ['test/ceo-split-collection.test.ts'], 'test/fixtures/ceo-stale-fill-decision/**': ['test/ceo-stale-fill-decision.test.ts'], + 'test/fixtures/ci-carry-rerun/**': ['test/ci-carry-rerun.test.ts'], 'test/fixtures/ci-gate/**': ['test/gstack-ci-gate.test.ts'], 'test/fixtures/claude-agent-payload-2.1.292.json': ['test/autoplan-publication-payload.test.ts', 'test/autoplan-schema-canary-compare.test.ts'], 'test/fixtures/claude-native-journal-roots-2.1.284.json': ['test/autoplan-publication-hook.test.ts', 'test/plan-count-transcript.test.ts'], From 9222485040b84f97f45ad36b1b7373a2c28a3077 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Wed, 18 Nov 2026 11:55:13 +0800 Subject: [PATCH 002/213] Review planner sends Swift health, permission and on-device storage code to full review (GST-3052) (#4472) /ship's review planner now sends Swift code that asks for a privacy permission, reads HealthKit or calendar data, or writes, deletes or protects users' files on the device to the full review panel. Why: since #4469, iOS changes that asked for microphone permission, wrote and deleted meeting transcript files, or read calendars got the light, one-reader review. Reported from the GHome iOS app's PR review. Nothing to do: plain SwiftUI views, UserDefaults settings and file reads still plan light. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/red-team#1 reader=red-team Review-Finding: p1/red-team#2 reader=red-team --- changelog.d/review-plan-swift-user-data.md | 1 + docs/review-policy.md | 9 ++- lib/review-risk.ts | 32 ++++++++++- .../review-pins/files/lib/review-risk.ts.json | 2 +- .../review-pins/replays/GST-3052.json | 1 + test/review-plan-cli.test.ts | 14 +++++ test/review-risk-redos.test.ts | 7 ++- test/review-risk-routing.test.ts | 56 +++++++++++++++++++ 8 files changed, 116 insertions(+), 6 deletions(-) create mode 100644 changelog.d/review-plan-swift-user-data.md create mode 100644 test/fixtures/review-pins/replays/GST-3052.json diff --git a/changelog.d/review-plan-swift-user-data.md b/changelog.d/review-plan-swift-user-data.md new file mode 100644 index 00000000000..3f149149288 --- /dev/null +++ b/changelog.d/review-plan-swift-user-data.md @@ -0,0 +1 @@ +- **/ship's review plan now sends Swift code that touches private user data to the full review panel (GST-3052).** Once `.swift` stopped failing closed, an iOS change that asked for microphone or speech permission, read HealthKit or calendar data, or wrote and deleted users' files on the device planned the light review. Swift lines that request a privacy permission (speech, microphone, HealthKit, calendars, location, camera, photos, tracking) now count as security, and lines that read HealthKit, EventKit or contacts, write, delete or protect files on the device, use an app group container, exclude files from backup, or declare how long data is kept count as user data. Plain SwiftUI views, UserDefaults settings and file reads stay light. Reported from the GHome iOS app's PR review. diff --git a/docs/review-policy.md b/docs/review-policy.md index f483e3e5452..2f73ee8f646 100644 --- a/docs/review-policy.md +++ b/docs/review-policy.md @@ -429,7 +429,14 @@ rules are coarse on purpose and parse no import clause or call arguments; 200,000-character hostile lines, its anchor followed by a long run of the characters it repeats included. `test/review-risk-redos.test.ts` (GST-898) holds every risk pattern, R51's `rm` and `rmSync` rules included, under 100 ms on 100,000-character hostile lines. An `rmSync(` or `rm(` call (`fs.rm`, `fs.promises.rm` or an imported `rm`) counts as security when `recursive: true` follows within 500 characters, whatever the arguments hold (a `path.join(...)` first argument or a `)` in a comment included) and also when a formatter split a new call across lines, which is read over the file's changed lines joined (GST-942; an edit to one line of an existing split call is read on its own); a call with more than 500 characters before the first `)` after it counts on its own. **data** is user data: a path naming pii, gdpr, ccpa, privacy, personal, account, customer, cookie, persistence, storage or database, or a line -that drops a table or column, deletes rows or bulk-deletes records. Auth scope, +that drops a table or column, deletes rows or bulk-deletes records. On `.swift` +paths outside XCTest targets (a `Tests/` or `*Tests/` directory, or a +`*Tests.swift` file), a privacy permission request (speech, microphone, +HealthKit, calendars, location, camera, photos) is security, and a HealthKit, +EventKit or Contacts read, an on-device file write or delete, a file protection +class, an app group container, backup exclusion or a declared retention period is +data; UserDefaults settings, SwiftUI views and file reads are neither, and a call +split across lines is read over the file's changed lines joined (GST-3052). Auth scope, migrations and deleted code paths were already gate class. `RISK_RULES` hashes the patterns and `DEPTH_RULES` includes it. diff --git a/lib/review-risk.ts b/lib/review-risk.ts index f413feaedb0..27870b5ecc2 100644 --- a/lib/review-risk.ts +++ b/lib/review-risk.ts @@ -124,6 +124,31 @@ export const DATA_LINE = [ /\.(?:deleteMany|destroyAll|bulkDelete)\s*\(/, /\b(?:destroy_all|delete_all)\b/, ]; +/** + * Swift code that reaches private user data (GST-3052: ghome#10, #14 and #31 planned light once .swift stopped failing closed). + * Read on .swift paths only, so this module and TypeScript never match. A privacy permission request is security, as a consent + * path is; HealthKit and EventKit reads, on-device file writes, deletes, protection classes, app group containers, backup + * exclusion and a declared retention period are data. UserDefaults, SwiftUI, file reads and EventKit type names are not. + * A call split across lines (`removeItem(` then `at: url)`) is read over the file's changed lines joined, as SECURITY_JOINED is. + * XCTest files (a Tests/ or *Tests/ target directory, a *Tests.swift file) read as code to the classifier but are skipped here: + * their temp-file setup and cleanup is not user data (GSTA-604 replay: ghome#17 gained data from test cleanup alone). + */ +export const SWIFT_PATH = /\.swift$/i; +export const SWIFT_TEST_PATH = /(^|\/)\w{0,80}Tests\/|Tests\.swift$/; +export const SWIFT_SECURITY_LINE = [ + /\brequest\w{0,40}Authorization\b/, /\brequest(?:Full|WriteOnly)?Access(?:To(?:Events|Reminders))?\b/, /\brequestRecordPermission\b/, +]; +export const SWIFT_DATA_LINE = [ + /^\s{0,40}import\s{1,20}(?:HealthKit|EventKit|Contacts)\b/, /\b(?:HKHealthStore|EKEventStore|CNContactStore)\b/, /\bHK[A-Z]\w{0,40}Query\b/, + /\.(?:events|calendars|calendarItems)\s{0,20}\(\s{0,20}(?:matching|for)\s{0,20}:/, /\bpredicateFor(?:Events|Reminders|IncompleteReminders|CompletedReminders)\w{0,40}\s{0,20}\(/, /\.fetchReminders\s{0,20}\(/, + /\.write\s{0,20}\(\s{0,20}(?:to(?:File)?\s{0,20}:\s{0,20}(?![\s&])|contentsOf\s{0,20}:)/, /\.(?:removeItem|trashItem)\s{0,20}\(\s{0,20}at(?:Path)?\s{0,20}:/, /\.createFile\s{0,20}\(\s{0,20}atPath\s{0,20}:/, /\.replaceItem(?:At)?\s{0,20}\(/, + /\bFileHandle\s{0,20}\(\s{0,20}for(?:WritingTo|WritingAtPath|Updating|UpdatingAtPath)\s{0,20}:/, /\bOutputStream\s{0,20}\(\s{0,20}(?:url|toFileAtPath)\s{0,20}:/, + /\bNSFileProtection\w{0,60}|\bFileProtectionType\b|\.(?:complete|no)FileProtection\w{0,60}|\.protectionKey\b/, + /\bforSecurityApplicationGroupIdentifier\b|\bUserDefaults\s{0,20}\(\s{0,20}suiteName\s{0,20}:\s{0,20}"group\./, /\bisExcludedFromBackup\w{0,20}/, + /\b(?:let|var)\s{1,20}(?:\w{0,60}(?:Retention|RetainFor|RetainDays|RetainUntil|Purge|MaxAge|KeepFor|KeepDays|KeepUntil|DeleteAfter|TTL|Ttl)|(?:retention|retain(?:For|Days|Until)|purge|maxAge|keep(?:For|Days|Until)|deleteAfter|ttl))\w{0,60}\b/, + /\b(?:olderThan|purgeBefore|deleteBefore|deleteAfter)\s{0,20}:/, +]; + /** * Data and config files (HARN-1, harness-evals#231): judged by their path only, so a lease_usd value in a VM record never names money. * A key in a config file still names a secret. @@ -155,7 +180,7 @@ export const RISK_RULES = createHash('sha256').update(JSON.stringify({ RISK_CLASSES, MONEY_PATH_TOKENS, AUTH_PATH_TOKENS, AUTH_PATH_PREFIXES, KEY_NAME, SECURITY_PATH_TOKENS, DATA_PATH_TOKENS, EVAL_PATH_TOKENS, MONEY_LINE_TOKENS, MONEY_PAIRS, SPEND_PAIRS, REPORTED_COST_WORDS, MONEY_USD_WORDS, SECRET_SCAN, - patterns: Object.entries({ PROSE_PATH: [PROSE_PATH], DOC_SECRET_LINE, CONFIG_DATA_PATH: [CONFIG_DATA_PATH], STATS_SCRIPT: [STATS_SCRIPT], MONEY_LINE, PAID_MONEY_LINE, USD_COMPARE, RESULTS_TREE: [RESULTS_TREE], PRICE_USD_KEY: [PRICE_USD_KEY], PRICE_KEY_EXEMPT: [PRICE_KEY_EXEMPT], SECRET_LINE, SECRET_PATH: [SECRET_PATH], TOKEN_PATH: [TOKEN_PATH], TOKEN_SOURCE: [TOKEN_SOURCE], SECURITY_LINE, SECURITY_JOINED, DATA_LINE, SVG_PATH: [SVG_PATH], SVG_ACTIVE }).map(([k, v]) => [k, v.map(r => '/' + r.source + '/' + r.flags)]), + patterns: Object.entries({ PROSE_PATH: [PROSE_PATH], DOC_SECRET_LINE, CONFIG_DATA_PATH: [CONFIG_DATA_PATH], STATS_SCRIPT: [STATS_SCRIPT], MONEY_LINE, PAID_MONEY_LINE, USD_COMPARE, RESULTS_TREE: [RESULTS_TREE], PRICE_USD_KEY: [PRICE_USD_KEY], PRICE_KEY_EXEMPT: [PRICE_KEY_EXEMPT], SECRET_LINE, SECRET_PATH: [SECRET_PATH], TOKEN_PATH: [TOKEN_PATH], TOKEN_SOURCE: [TOKEN_SOURCE], SECURITY_LINE, SECURITY_JOINED, DATA_LINE, SVG_PATH: [SVG_PATH], SVG_ACTIVE, SWIFT_PATH: [SWIFT_PATH], SWIFT_TEST_PATH: [SWIFT_TEST_PATH], SWIFT_SECURITY_LINE, SWIFT_DATA_LINE }).map(([k, v]) => [k, v.map(r => '/' + r.source + '/' + r.flags)]), })).digest('hex').slice(0, 16); export const tokens = (p: string) => p.replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean); @@ -187,6 +212,7 @@ export function matchRisk(i: RiskInput): Map { const config = !exe && CONFIG_DATA_PATH.test(p); const pathOnly = config || stats; const prose = PROSE_PATH.test(p); + const swift = SWIFT_PATH.test(p) && !SWIFT_TEST_PATH.test(p); if (i.scopeAuth && t.some(x => AUTH_PATH_TOKENS.includes(x) || AUTH_PATH_PREFIXES.some(a => x.startsWith(a)))) hit('auth', 'auth path: ' + p); if (secretPath(p, [...(i.added?.[p] ?? []), ...(i.removed?.[p] ?? [])])) hit('secret', 'secret path: ' + p); const money = !(i.dataPaths?.includes(p) && RESULTS_TREE.test(p)); @@ -202,8 +228,12 @@ export function matchRisk(i: RiskInput): Map { if (!why.has('money') && (PAID_MONEY_LINE.some(r => r.test(line)) || (money && (usdMoney(line) || namesMoney(tokens(line), MONEY_LINE_TOKENS) || (!prose && pairs(tokens(line), SPEND_PAIRS)))))) hit('money', 'money line: ' + p); if (!why.has('security') && SECURITY_LINE.some(r => r.test(line))) hit('security', 'security line: ' + p); if (!why.has('data') && DATA_LINE.some(r => r.test(line))) hit('data', 'data line: ' + p); + if (swift && !why.has('security') && SWIFT_SECURITY_LINE.some(r => r.test(line))) hit('security', 'Swift permission request: ' + p); + if (swift && !why.has('data') && SWIFT_DATA_LINE.some(r => r.test(line))) hit('data', 'Swift user-data line: ' + p); } if (!why.has('security') && [i.added?.[p], i.removed?.[p]].some(l => l && SECURITY_JOINED.some(r => r.test(l.join('\n'))))) hit('security', 'security lines: ' + p); + if (swift && !why.has('security') && [i.added?.[p], i.removed?.[p]].some(l => l && SWIFT_SECURITY_LINE.some(r => r.test(l.join('\n'))))) hit('security', 'Swift permission request lines: ' + p); + if (swift && !why.has('data') && [i.added?.[p], i.removed?.[p]].some(l => l && SWIFT_DATA_LINE.some(r => r.test(l.join('\n'))))) hit('data', 'Swift user-data lines: ' + p); } return new Map(RISK_CLASSES.filter(c => why.has(c)).map(c => [c, why.get(c)!])); } diff --git a/test/fixtures/review-pins/files/lib/review-risk.ts.json b/test/fixtures/review-pins/files/lib/review-risk.ts.json index 61b0e5c8539..db763b59283 100644 --- a/test/fixtures/review-pins/files/lib/review-risk.ts.json +++ b/test/fixtures/review-pins/files/lib/review-risk.ts.json @@ -1 +1 @@ -{"sha":"2dbe134d502279da7a5f27e5370bb45a9658f01322030b1e27180d0e9e11285d","replay":"GST-3041"} +{"sha":"1bf74fcb384978ba30b36f02959a8e30c1f8feb9bbb549a99fbd9ff70496c80d","replay":"GST-3052"} diff --git a/test/fixtures/review-pins/replays/GST-3052.json b/test/fixtures/review-pins/replays/GST-3052.json new file mode 100644 index 00000000000..7dc0a9848a2 --- /dev/null +++ b/test/fixtures/review-pins/replays/GST-3052.json @@ -0,0 +1 @@ +{"replay":"GST-3052","justification":"GST-3052 no-loss replay (GSTA-604, preregistered as reports/GSTA-604-prereg.md sha256 95d75d44): review-risk.ts adds Swift-only line rules (SWIFT_SECURITY_LINE for privacy permission requests, SWIFT_DATA_LINE for HealthKit, EventKit and contacts access, on-device file writes, deletes, protection, app groups, backup exclusion and retention), read per line and over a file's changed lines joined, and skipped on XCTest paths; they only add security and data hits. Planner depth from 29e95022 (old) and 39009fa5 (new): the last 200 first-parent main commits (64862e41..29e95022) are 200 identical (129 full, 71 light); the 34 merged Apple-platform PRs (garrytan/ghome 33, garrytan/imsg-reader 1) have 0 lowered, 3 raised light to full (ghome#10 data, #14 security, #31 data) and 31 unchanged, no risk class lost. A read-only gpt-6.2-sol reader labeled all 3 raises true positives and 35 of 49 matched lines true (PR level 11 of 12). Reviewer text is unchanged."} diff --git a/test/review-plan-cli.test.ts b/test/review-plan-cli.test.ts index ceadee1f2cd..fec89275488 100644 --- a/test/review-plan-cli.test.ts +++ b/test/review-plan-cli.test.ts @@ -77,6 +77,20 @@ describe('gstack-review-plan', () => { const client = run(repo({ ...ui, 'App/Client.swift': 'final class Client {\n func load(_ r: URLRequest) async throws -> Data { try await URLSession.shared.data(for: r).0 }\n}\n' }), []); expect(client.stdout).toMatch(/^REVIEW_DEPTH: full .*risk:security/m); }); + // Value: protects=an iOS PR that writes or deletes users' files on the device, or reads their calendars, plans full even when it + // also touches Markdown and tests, while a SwiftUI view that reads a UserDefaults setting stays light; fails_when=the Swift + // user-data rules stop reaching gstack-review-plan; why_new=GST-3052: ghome#10 (spill files written and deleted) and ghome#31 + // (calendar choices, read through EventKit) planned light (GSTA-601); seam=gstack-review-plan on a real repo; no_claim=what the readers find + test('a Swift diff that writes and deletes spill files, or reads calendars, plans full; a SwiftUI settings view stays light (GST-3052)', () => { + const view = 'import SwiftUI\nstruct SettingsView: View {\n @AppStorage("speaksAnswers") private var speaksAnswers = true\n var body: some View { Toggle("Speak answers", isOn: $speaksAnswers) }\n}\n'; + const shared = { 'DESIGN.md': '# Design\n', 'App/Home/SettingsView.swift': view, 'Tests/AppTests/SettingsTests.swift': 'import XCTest\n' }; + const control = run(repo({ ...shared, 'App/Home/PickerModel.swift': 'final class PickerModel {\n let defaults: UserDefaults\n init(defaults: UserDefaults = .standard) { self.defaults = defaults }\n var chosen: Data? { defaults.data(forKey: "picker.chosen") }\n func save(_ blob: Data) { defaults.set(blob, forKey: "picker.chosen") }\n}\n' }), []); + expect(control.stdout).toMatch(/^REVIEW_DEPTH: light /m); + const spill = 'import Foundation\npublic struct DraftSpill {\n public let file: URL\n public func reserve(_ size: Int) throws {\n guard FileManager.default.createFile(atPath: file.path, contents: Data(count: size)) else { throw CocoaError(.fileWriteUnknown) }\n }\n public func discard() { try? FileManager.default.removeItem(at: file) }\n}\n'; + expect(run(repo({ ...shared, 'Packages/Core/Sources/Core/Capture/DraftSpill.swift': spill }), []).stdout).toMatch(/^REVIEW_DEPTH: full .*risk:data/m); + const agenda = 'import EventKit\nfinal class AgendaSource {\n private let events = EKEventStore()\n func calendarNames() -> [String] { events.calendars(for: .event).map(\\.title) }\n}\n'; + expect(run(repo({ ...shared, 'App/Meeting/AgendaSource.swift': agenda }), []).stdout).toMatch(/^REVIEW_DEPTH: full .*risk:data/m); + }); test('a docs diff that publishes numbers keeps the outside voice', () => { const r = run(repo({ 'docs/bench.md': 'Median latency fell 42% to 180 ms.\n' }), []); expect(r.stdout).toContain('DISPATCH: outside-voice outside-voice effort=host'); diff --git a/test/review-risk-redos.test.ts b/test/review-risk-redos.test.ts index af76051c762..56b8e51f2d1 100644 --- a/test/review-risk-redos.test.ts +++ b/test/review-risk-redos.test.ts @@ -5,7 +5,7 @@ */ import { describe, expect, test } from 'bun:test'; import { SVG_REFUSED, svgDrawing } from '../lib/review-depth'; -import { DATA_LINE, MONEY_LINE, SECRET_LINE, SECRET_PATH, SECURITY_JOINED, SECURITY_LINE, USD_COMPARE, matchRisk, usdMoney } from '../lib/review-risk'; +import { DATA_LINE, MONEY_LINE, SECRET_LINE, SECRET_PATH, SECURITY_JOINED, SECURITY_LINE, SWIFT_DATA_LINE, SWIFT_SECURITY_LINE, USD_COMPARE, matchRisk, usdMoney } from '../lib/review-risk'; const L = 100_000; const ms = (f: () => unknown) => { const t = performance.now(); f(); return performance.now() - t; }; @@ -15,7 +15,7 @@ const security = (line: string) => matchRisk({ codePaths: ['x.sh'], added: { 'x. describe('linear time on hostile input', () => { // Value: protects=gstack-review-plan, the targeted pass and the queue depth check never stall on one added line; // fails_when=any risk pattern backtracks quadratically on its anchor followed by a long run of the class it repeats, - // or on a line of repeated anchors; seam=every pattern in SECURITY_LINE, DATA_LINE, SECRET_LINE, MONEY_LINE and SECRET_PATH + // or on a line of repeated anchors; seam=every pattern in SECURITY_LINE, DATA_LINE, SECRET_LINE, MONEY_LINE, SECRET_PATH, SWIFT_SECURITY_LINE and SWIFT_DATA_LINE const hostile = [ run('rm -', 'r'), run('rm -', 'f'), run('rm -r', 'r'), run('rm -f', 'a'), run('rm\t-', 'r'), run('rm ', ' '), run('rm -', 'r', '1'), run('rm -', 'rf', '_'), run('', 'rm -r '), run('', 'rmSync('), run('rmSync(', ' '), run('rmSync(', 'recursive '), run('rmSync(', 'recursive: '), run('', '.rm('), run('.rm(', ' '), run('.rm(', 'recursive: '), run('', 'rm('), run('rm(', ' '), run('rmSync(', ' \n'), @@ -26,8 +26,9 @@ describe('linear time on hostile input', () => { run('DELETE', ' '), run('drop', ' '), run('truncate', ' '), run('delete from', ' '), run('delete from ', 'a.'), run('', 'delete from a '), run('.deleteMany', ' '), run('', 'a_'), run('', 'aU'), run('a', 'A'), run('spend', '_'), run('new Anthropic', ' '), run('.messages.create', ' '), run('$', 'A_'), run('${', 'A_'), run('', '$A_'), run('process.env.', 'A_'), run('process.env[', ' '), run('os.environ[', ' '), run('os.getenv(', ' '), run('ENV[', ' '), + run('request', 'a'), run('', 'requestA'), run('HK', 'A'), run('', 'HKAQuery '), run('.write(', ' '), run('.write(to:', ' '), run('let ', 'a'), run('let ', 'Purge'), run('', 'let x'), run('import', ' '), run('NSFileProtection', 'a'), ]; - test.each(Object.entries({ SECURITY_LINE, SECURITY_JOINED, DATA_LINE, SECRET_LINE, MONEY_LINE, USD_COMPARE, SECRET_PATH: [SECRET_PATH] }))('every %s pattern finishes under 100 ms on each 100k-character hostile line', (_n, patterns) => { + test.each(Object.entries({ SECURITY_LINE, SECURITY_JOINED, DATA_LINE, SECRET_LINE, MONEY_LINE, USD_COMPARE, SECRET_PATH: [SECRET_PATH], SWIFT_SECURITY_LINE, SWIFT_DATA_LINE }))('every %s pattern finishes under 100 ms on each 100k-character hostile line', (_n, patterns) => { const slow = patterns.flatMap(r => hostile.map(([label, s]) => [r.source.slice(0, 50), label, Math.round(ms(() => r.test(s)))] as const)).filter(([, , t]) => t >= 100); expect(slow).toEqual([]); }, 120_000); diff --git a/test/review-risk-routing.test.ts b/test/review-risk-routing.test.ts index 5f05c886753..e115aaae6ab 100644 --- a/test/review-risk-routing.test.ts +++ b/test/review-risk-routing.test.ts @@ -292,6 +292,62 @@ describe('GST-3041: Swift networking is security, SwiftUI is not', () => { }); }); +describe('GST-3052: Swift user-data access, permission requests and on-device storage plan full; plain SwiftUI does not', () => { + // Value: protects=an iOS diff that reads health or calendar data, asks for a privacy permission, or writes, deletes, protects + // or sets how long user files live on the device reaches the full panel now that .swift no longer fails closed; + // fails_when=any line below reads light, an ordinary SwiftUI or UserDefaults line raises a class, or a non-Swift path + // naming these APIs (this module's own patterns) raises one; why_new=GST-3052: ghome#10, #14 and #31 planned light; + // seam=matchRisk; no_claim=what the full panel finds + test.each([ + 'SFSpeechRecognizer.requestAuthorization { status in done(status == .authorized) }', + 'let granted = await AVAudioApplication.requestRecordPermission()', + 'AVAudioSession.sharedInstance().requestRecordPermission { ok in done(ok) }', + 'try await health.requestAuthorization(toShare: [], read: readTypes)', + 'let ok = try await events.requestFullAccessToEvents()', + 'events.requestAccess(to: .event) { ok, _ in done(ok) }', + 'locations.requestWhenInUseAuthorization()', + 'AVCaptureDevice.requestAccess(for: .audio) { _ in }', + 'PHPhotoLibrary.requestAuthorization(for: .readWrite) { _ in }', + ])('%s is security', line => { + expect(risk(['App/Talk/Dictation.swift'], { 'App/Talk/Dictation.swift': [line] })).toEqual(['security']); + }); + test.each([ + 'import HealthKit', 'private let health = HKHealthStore()', + 'let query = HKSampleQuery(sampleType: sleep, predicate: nil, limit: 50, sortDescriptors: nil) { _, _, _ in }', + 'let stats = HKStatisticsCollectionQuery(quantityType: steps, quantitySamplePredicate: nil, options: .cumulativeSum, anchorDate: start, intervalComponents: day)', + 'import EventKit', 'private let events = EKEventStore()', 'return events.calendars(for: .event).map(Self.summary)', + 'let found = events.events(matching: events.predicateForEvents(withStart: from, end: to, calendars: nil))', + 'try blob.write(to: notesURL, options: [.atomic, .completeFileProtection])', 'try text.write(to: fileURL, atomically: true, encoding: .utf8)', + 'try? FileManager.default.removeItem(at: draftFile)', 'try files.removeItem(atPath: path)', 'try FileManager.default.trashItem(at: old, resultingItemURL: nil)', + 'guard FileManager.default.createFile(atPath: spill.path, contents: Data(count: size)) else { throw SpillError.create }', + 'let handle = try FileHandle(forWritingTo: spill)', 'let handle = try FileHandle(forUpdating: spill)', 'try handle.write(contentsOf: page)', + 'try files.setAttributes([.protectionKey: FileProtectionType.complete], ofItemAtPath: path)', 'let mode = NSFileProtectionCompleteUntilFirstUserAuthentication', + 'let shared = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.example.app")', + 'values.isExcludedFromBackup = true', + 'static let recordingRetentionDays = 7', 'let keepDays: Int = 30', 'try archive.prune(olderThan: cutoff)', + ])('%s is data', line => { + expect(risk(['Packages/Core/Sources/Core/Notes/Store.swift'], { 'Packages/Core/Sources/Core/Notes/Store.swift': [line] })).toEqual(['data']); + }); + test('ordinary SwiftUI, UserDefaults, reads and type mentions raise no class', () => { + for (const line of [ + 'import SwiftUI', 'struct HealthCard: View {', ' var body: some View { Text(event.title) }', '@AppStorage("speaksAnswers") private var speaksAnswers = true', + 'let on = UserDefaults.standard.bool(forKey: "speaksAnswers")', 'defaults.set(encoded, forKey: Self.key)', 'didSet { defaults?.set(speaksAnswers, forKey: Self.speaksKey) }', + 'switch SFSpeechRecognizer.authorizationStatus() {', 'func tint(of calendar: EKCalendar) -> Color { Color(cgColor: calendar.cgColor) }', + 'let bytes = try Data(contentsOf: url)', 'let scratch = FileManager.default.temporaryDirectory', 'print(line, to: &log)', 'stream.write(to: &output)', + 'let expiresAt = token.expiresAt', 'let settled = true', 'let subtitle = "Today"', 'func requestAccessToken() async throws -> String', + ]) expect(risk(['App/Home/HealthCard.swift'], { 'App/Home/HealthCard.swift': [line] })).toEqual([]); + }); + test('a product file named *Test.swift is still read, and a call split across lines still matches', () => { + expect(risk(['App/Hearing/HearingTest.swift'], { 'App/Hearing/HearingTest.swift': ['guard await AVAudioApplication.requestRecordPermission() else { return }'] })).toEqual(['security']); + for (const lines of [['try FileManager.default.removeItem(', ' at: draftFile', ')'], ['try blob.write(', ' to: notesURL,', ' options: .atomic', ')'], ['let handle = try FileHandle(', ' forWritingTo: spill', ')']]) + expect(risk(['App/Notes/Store.swift'], { 'App/Notes/Store.swift': lines })).toEqual(['data']); + }); + test('the Swift rules read only .swift paths outside XCTest targets', () => { + for (const p of ['lib/review-risk.ts', 'docs/ios.md', 'Sources/Bridge.m', 'Tests/AppTests/StoreTests.swift', 'Packages/Core/Tests/CoreTests/Support.swift', 'App/StoreTests.swift']) + expect(risk([p], { [p]: ['const r = /\\bHKHealthStore\\b/;', 'SFSpeechRecognizer.requestAuthorization { _ in }', 'try FileManager.default.removeItem(at: url)'] })).toEqual([]); + }); +}); + describe('GST-850: money reaches metering, charge and credit code', () => { // Value: protects=a billing-client or metering diff gets the money reader; fails_when=gbrain-evals #289 reads required=none again, // or costume, a CLI usage line or a proxy with no billing names money; seam=matchRisk and targetedClasses From 33b1a965bacb9ae28ac9281a1a70cbd987e54c01 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Wed, 18 Nov 2026 11:56:41 +0800 Subject: [PATCH 003/213] /ship's push step ends with one line that says whether it pushed (GST-3053) (#4474) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit /ship's push step now always ends with one line that says what happened: `PUSH: pushed …`, `PUSH: already_pushed …` or `PUSH: failed reason=`, with the remote, branch and full commit. Why: an eval grader looked for a `git push` call and counted 48 real /ship pushes as "no push"; scripts and graders can now match this one line instead. If a script of yours matched the old `PUSH: ALREADY_PUSHED ` or `PUSH: pushed to origin/` lines, update it; the exit status is unchanged. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- bin/gstack-doctor-components.sh | 3 + ...ip-push-prints-one-stable-line-gst-3053.md | 1 + docs/troubleshooting.md | 34 +++++++++ docs/unattended.md | 27 +++++++ lib/result-codes-release.ts | 16 +++++ lib/ship-release.ts | 52 ++++++++------ ship/DRIVER.md | 6 +- ship/DRIVER.md.tmpl | 6 +- ship/SKILL.md | 9 +-- ship/SKILL.md.tmpl | 9 +-- test/fixtures/golden/agy-ship-SKILL.md | 9 +-- test/fixtures/golden/claude-ship-SKILL.md | 9 +-- test/fixtures/golden/codex-ship-SKILL.md | 9 +-- test/fixtures/golden/factory-ship-SKILL.md | 9 +-- test/ship-driver.test.ts | 2 +- test/ship-plan-completion-invariants.test.ts | 7 +- test/ship-release.test.ts | 71 +++++++++++++++++-- test/ship-workflow-clarity.test.ts | 2 +- ...-push-prints-one-stable-line-gst-3053.json | 4 ++ 19 files changed, 224 insertions(+), 61 deletions(-) create mode 100644 changelog.d/ship-push-prints-one-stable-line-gst-3053.md create mode 100644 test/size-ledger/ship/ship-push-prints-one-stable-line-gst-3053.json diff --git a/bin/gstack-doctor-components.sh b/bin/gstack-doctor-components.sh index c6731247495..ed561a833c6 100644 --- a/bin/gstack-doctor-components.sh +++ b/bin/gstack-doctor-components.sh @@ -373,6 +373,9 @@ gstack_result_anchor() { FETCH_VIOLATION) printf '%s' 'fetch-violation' ;; FETCH_RERUN_BLOCKED) printf '%s' 'fetch-rerun-blocked' ;; FETCH_RERUN_SPENT) printf '%s' 'fetch-rerun-spent' ;; + PUSH_REFUSED) printf '%s' 'push-refused' ;; + PUSH_REJECTED) printf '%s' 'push-rejected' ;; + PUSH_GIT_FAILED) printf '%s' 'push-git-failed' ;; APPROVAL_RECORD_INVALID) printf '%s' 'approval-record-invalid' ;; APPROVAL_RECORD_SECRET) printf '%s' 'approval-record-secret' ;; APPROVAL_RECORD_NO_BRANCH) printf '%s' 'approval-record-no-branch' ;; diff --git a/changelog.d/ship-push-prints-one-stable-line-gst-3053.md b/changelog.d/ship-push-prints-one-stable-line-gst-3053.md new file mode 100644 index 00000000000..4a694dd9d12 --- /dev/null +++ b/changelog.d/ship-push-prints-one-stable-line-gst-3053.md @@ -0,0 +1 @@ +- **/ship's push step now always ends with one line that says whether it pushed (GST-3053).** `gstack-ship-release push` (Step 17) finishes with exactly one of `PUSH: pushed remote=origin ref= head=`, `PUSH: already_pushed remote=origin ref= head=` or `PUSH: failed reason=PUSH_REFUSED|PUSH_REJECTED|PUSH_GIT_FAILED`, so a script or eval grader can tell that /ship pushed by matching that line instead of looking for a `git push` call. Exit status is unchanged. Each reason code has a troubleshooting entry, and the format is documented in docs/unattended.md#push-line. An eval had graded 48 real /ship pushes as "no push" because it searched for the git command. The line's shape changed. The old `PUSH: ALREADY_PUSHED ` and `PUSH: pushed to origin/` lines are gone, so update anything that matched them. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 103cbb718c6..9fa1bc80b7b 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -5788,6 +5788,40 @@ origin cannot be reached, from its local stable ref and release tags. **Fix.** Run `git fetch origin --tags` in the gstack checkout, or point `GSTACK_STABLE_REPO` at a gstack checkout that has the tags, then rerun. + +### `PUSH_REFUSED` + +**Meaning.** `gstack-ship-release push` stopped before `git push` ran and +ended with `PUSH: failed reason=PUSH_REFUSED`: a usage error, HEAD on another +branch than Step 1 saved, the unanswered one-time pre-push offer, open gate +findings on a ready PR, sealed output, the early secrets scan, the pre-push +guards, or a never-pushed branch name that is not plain words. Nothing was +pushed. [The push line](unattended.md#push-line). + +**Fix.** Follow the `STOP:` line printed just above it, then rerun +`gstack-ship-release push`. + + +### `PUSH_REJECTED` + +**Meaning.** `git push` was rejected: the remote branch has commits this +branch lacks (non-fast-forward), or the remote refused the update. Nothing +was pushed. + +**Fix.** Fetch and inspect the remote, merge it under Step 3's conflict +rules, run Steps 5-16 again, then rerun push. Never force-push. + + +### `PUSH_GIT_FAILED` + +**Meaning.** `git ls-remote` could not read the remote branch, or +`git push` failed for a reason other than a rejection: authentication, a +pre-push hook or the network. Nothing was pushed. + +**Fix.** Repair the cause git printed in the `STOP:` line, repeat Step 16 +(even when the content is unchanged), then rerun push. Never bypass a failed +guard. + ### `QUEUE_NOT_READY` diff --git a/docs/unattended.md b/docs/unattended.md index 68c4da48dd2..64feaca8e2e 100644 --- a/docs/unattended.md +++ b/docs/unattended.md @@ -167,6 +167,33 @@ generated tests), the parent pushes those commits itself, then reruns the receipt write, the body post and `result` at the pushed head: a receipt for an unpushed head is `QUEUE_RECEIPT_STALE` to the queue. + +### The push line: `PUSH:` + +Step 17's `gstack-ship-release push` (early or final) always ends with exactly +one line saying whether the branch reached the remote, so a parent, a report or +an outside probe can tell that `/ship` pushed without looking for a +`git push` call: + +``` +PUSH: pushed remote=origin ref= head= +PUSH: already_pushed remote=origin ref= head= +PUSH: failed reason= +``` + +`pushed` means this run's `git push` updated the branch; `already_pushed` +means the remote branch already pointed at HEAD, so nothing was sent. `failed` +means nothing was pushed, with one of three codes: +[`PUSH_REFUSED`](troubleshooting.md#push-refused) (a check stopped it before +`git push` ran), [`PUSH_REJECTED`](troubleshooting.md#push-rejected) +(non-fast-forward, or the remote refused the update) and +[`PUSH_GIT_FAILED`](troubleshooting.md#push-git-failed) (git could not read +the remote, or `git push` failed on authentication, a hook or the network). +The line is the last one printed, after any `STOP:` or `NEXT:` line, on +stdout (stderr for a usage error), and the exit status keeps its meaning: 0 +for `pushed` and `already_pushed`, 3 for a stop, 2 for a usage error. Match +`^PUSH: (pushed|already_pushed) ` for "this run's branch is on the remote". + ### The review loop's counters The receipt's `review_loop` object, written from `gstack-review-scope summary diff --git a/lib/result-codes-release.ts b/lib/result-codes-release.ts index 1ff6ce0f2f5..54a4ced8fce 100644 --- a/lib/result-codes-release.ts +++ b/lib/result-codes-release.ts @@ -607,4 +607,20 @@ export const RELEASE_RESULT_CODES = { summary: 'the stage\'s one rerun fetched too, so the pass stopped with its readers quarantined, resuming it starts no later stage and returns no reader output, and verify refuses', fix: 'deal with the printed paths, find out why readers keep fetching, then start a fresh pass under a new --pass and --out; a third attempt is never automatic', }, + // GST-3053: gstack-ship-release push's last line, `PUSH: failed reason=` (docs/unattended.md#push-line). + PUSH_REFUSED: { + anchor: 'push-refused', + summary: 'gstack-ship-release push stopped before git push ran (a usage error, the wrong branch, the unanswered pre-push offer, open gate findings on a ready PR, sealed output, the secrets scan, the pre-push guards or a branch name that is not plain words), so nothing was pushed', + fix: 'follow the STOP: line above it, then rerun gstack-ship-release push', + }, + PUSH_REJECTED: { + anchor: 'push-rejected', + summary: 'git push was rejected: the remote branch has commits this branch lacks (non-fast-forward) or the remote refused the update, so nothing was pushed', + fix: 'fetch and merge the remote under Step 3\'s conflict rules, run Steps 5-16 again, then rerun push; never force-push', + }, + PUSH_GIT_FAILED: { + anchor: 'push-git-failed', + summary: 'git could not read the remote branch or git push failed for another reason (authentication, a pre-push hook or the network), so nothing was pushed', + fix: 'repair the cause git printed in the STOP: line, repeat Step 16, then rerun push; never bypass a guard', + }, } as const satisfies Record; diff --git a/lib/ship-release.ts b/lib/ship-release.ts index 7f36f8b3448..d2966444628 100644 --- a/lib/ship-release.ts +++ b/lib/ship-release.ts @@ -737,7 +737,7 @@ export async function accept(argv: readonly string[], cwd: string): Promise path.resolve(cwd, git(cwd, ['rev-parse', '--git-path', `gstack/${name}`]).stdout.trim() || `.git/gstack/${name}`); const tree = git(cwd, ['rev-parse', 'HEAD^{tree}']).stdout.trim(); const out = gitPath('pregate-guards.json'); @@ -752,7 +752,7 @@ function prepushGuards(cwd: string, branch: string, base: string | undefined): { let res: { status?: string; verdict?: string; tree?: string; code?: string; detail?: string; fix?: string; checks?: { id: string; status: string; detail?: string; fix?: string }[] } = {}; try { res = JSON.parse(pg.stdout.trim().split('\n').pop() ?? ''); } catch { /* unreadable: stops below */ } const heads = res.status === 'refused' && res.code === 'POLICY_SOURCE_UNAVAILABLE' ? git(cwd, ['ls-remote', '--heads', 'origin'], 120_000) : null; - if (heads && heads.status !== 0) return { line: 'GUARDS: not run (origin unreachable)', stop: `cannot verify the remote branch (${firstLine(heads.stderr)}): restore access before pushing` }; + if (heads && heads.status !== 0) return { line: 'GUARDS: not run (origin unreachable)', stop: `cannot verify the remote branch (${firstLine(heads.stderr)}): restore access before pushing`, code: 'PUSH_GIT_FAILED' }; if (heads && heads.stdout.split('\n').every(l => !l.trim() || l.trim().endsWith(`\trefs/heads/${branch}`))) return { line: `GUARDS: not run (origin has no branch but ${branch}, so no base to read guards from)` }; if (res.status === 'refused') return { line: `GUARDS: refused ${res.code}`, stop: `the pre-push guards could not run (${res.detail}; fix: ${res.fix}): repair it, then rerun push` }; const bad = (res.checks ?? []).filter(c => c.status !== 'pass' && c.status !== 'warn').map(c => `${c.id}: ${c.fix ?? c.detail ?? c.status}`).join('; '); @@ -764,60 +764,70 @@ function prepushGuards(cwd: string, branch: string, base: string | undefined): { return { line, stop: `the pre-push guards did not pass (${bad || firstLine(pg.stderr || pg.stdout)}): fix it, commit, then rerun push` }; } +/** Every push run's last line (docs/unattended.md#push-line): outside observers match it instead of a git push call. */ +export type PushFailure = 'PUSH_REFUSED' | 'PUSH_REJECTED' | 'PUSH_GIT_FAILED'; +export const pushFailedLine = (code: PushFailure) => `PUSH: failed reason=${code}`; + export function push(argv: readonly string[], cwd: string): Report { - const { flag, has } = flagReader(argv); const r = new Report(); + return r.add(pushOnce(argv, cwd, r)); +} + +function pushOnce(argv: readonly string[], cwd: string, r: Report): string { + const { flag, has } = flagReader(argv); + const refuse = (what: string, code: PushFailure = 'PUSH_REFUSED') => { r.stop(what); return pushFailedLine(code); }; const branch = git(cwd, ['branch', '--show-current']).stdout.trim(); - if (!branch) return r.stop('detached HEAD: push needs the feature branch'); - if (branch !== flag('--branch')) return r.stop(`HEAD is on ${branch}, not the branch Step 1 saved (${flag('--branch')}): check out the saved branch, then rerun push`); + if (!branch) return refuse('detached HEAD: push needs the feature branch'); + if (branch !== flag('--branch')) return refuse(`HEAD is on ${branch}, not the branch Step 1 saved (${flag('--branch')}): check out the saved branch, then rerun push`); const guard = bin(cwd, 'gstack-config', ['get', 'redact_prepush_hook'], 30_000).stdout.trim() || 'false'; const prompted = fs.existsSync(path.join(resolveStateRoot(process.env), '.redact-prepush-prompted')); const deferred = guard !== 'true' && !prompted && process.env.GSTACK_SESSION_KIND === 'unattended'; r.add(`REDACT_PREPUSH: ${guard} prompted=${prompted ? 'yes' : 'no'}${deferred ? ' deferred=unattended' : ''}`); - if (guard !== 'true' && !prompted && !deferred) return r.stop('Step 17\'s one-time pre-push guard offer is unanswered: run the guard block and ask it, then rerun push'); + if (guard !== 'true' && !prompted && !deferred) return refuse('Step 17\'s one-time pre-push guard offer is unanswered: run the guard block and ask it, then rerun push'); const gateOpen = Number(flag('--gate-open') ?? '0'); if (gateOpen > 0) { - if (!hostedOrigin(cwd)) return r.stop('open-PR lookup unavailable: origin is a local path, not a hosted remote gh can map; it must succeed before pushing open gate findings'); + if (!hostedOrigin(cwd)) return refuse('open-PR lookup unavailable: origin is a local path, not a hosted remote gh can map; it must succeed before pushing open gate findings'); const pr = gh(cwd, ['pr', 'list', '--head', branch, '--state', 'open', '--json', 'number,isDraft', '--jq', '[.[] | select(.isDraft | not) | .number] | first // empty']); - if (pr.status !== 0) return r.stop(`open-PR lookup failed (${firstLine(pr.stderr)}): it must succeed before pushing open gate findings`); - if (pr.stdout.trim() && !has('--gate-open-approved')) return r.stop(`${gateOpen} open gate finding(s) and ready PR #${pr.stdout.trim()}: spawned/headless sessions stop here; otherwise ask (resolve now, or publish with the banner and rerun with --gate-open-approved)`); + if (pr.status !== 0) return refuse(`open-PR lookup failed (${firstLine(pr.stderr)}): it must succeed before pushing open gate findings`); + if (pr.stdout.trim() && !has('--gate-open-approved')) return refuse(`${gateOpen} open gate finding(s) and ready PR #${pr.stdout.trim()}: spawned/headless sessions stop here; otherwise ask (resolve now, or publish with the banner and rerun with --gate-open-approved)`); } const sealed = bin(cwd, 'gstack-pregate', ['sealed'], 120_000); r.add(`SEALED: ${sealed.status === 0 ? 'clear' : sealed.status === 1 ? 'refused' : `not checked (exit ${sealed.status})`}`); - if (sealed.status === 1) return r.stop(`sealed output would be published: ${firstLine(sealed.stderr)}; remove it from the commits, then repeat Step 16`); - if (sealed.status !== 0) return r.stop(`the sealed-output guard did not run (exit ${sealed.status}: ${firstLine(sealed.stderr || sealed.stdout)}); repair it, then rerun push`); + if (sealed.status === 1) return refuse(`sealed output would be published: ${firstLine(sealed.stderr)}; remove it from the commits, then repeat Step 16`); + if (sealed.status !== 0) return refuse(`the sealed-output guard did not run (exit ${sealed.status}: ${firstLine(sealed.stderr || sealed.stdout)}); repair it, then rerun push`); if (has('--early')) { const out = path.resolve(cwd, git(cwd, ['rev-parse', '--git-path', 'gstack/pregate-early-push.json']).stdout.trim() || '.git/gstack/pregate-early-push.json'); const scan = bin(cwd, 'gstack-pregate', ['--stage', 'preflight', '--only', 'secrets', '--out', out, ...(flag('--base') ? ['--base', flag('--base')!] : [])], 600_000); const verdict = /^PREGATE: (.+?) tree=/m.exec(scan.stdout + scan.stderr)?.[1] ?? `unreadable (exit ${scan.status})`; r.add(`SECRETS: ${verdict} (early push)`); - if (scan.status !== 0 || !/^(pass|warn)/.test(verdict)) return r.stop(`the secrets scan did not pass before the early push (${firstLine(scan.stderr) || verdict}): remove the finding from the commits, then rerun push --early`); + if (scan.status !== 0 || !/^(pass|warn)/.test(verdict)) return refuse(`the secrets scan did not pass before the early push (${firstLine(scan.stderr) || verdict}): remove the finding from the commits, then rerun push --early`); } const guards = prepushGuards(cwd, branch, flag('--base')); r.add(guards.line); - if (guards.stop) return r.stop(guards.stop); + if (guards.stop) return refuse(guards.stop, guards.code); const local = git(cwd, ['rev-parse', 'HEAD']).stdout.trim(); const remote = git(cwd, ['ls-remote', '--heads', 'origin', `refs/heads/${branch}`], 120_000); - if (remote.status !== 0) return r.stop(`cannot verify the remote branch (${firstLine(remote.stderr)}): restore access before pushing`); - if (remote.stdout.split(/\s/)[0] === local) return r.add(`PUSH: ALREADY_PUSHED ${local.slice(0, 12)}`).next('Step 18'); + if (remote.status !== 0) return refuse(`cannot verify the remote branch (${firstLine(remote.stderr)}): restore access before pushing`, 'PUSH_GIT_FAILED'); + if (remote.stdout.split(/\s/)[0] === local) { r.next('Step 18'); return `PUSH: already_pushed remote=origin ref=${branch} head=${local}`; } let plain: PlainFinding[] = []; try { if (!remote.stdout.trim()) plain = checkBranch(branch, loadPlainTitlePolicy(git(cwd, ['rev-parse', '--show-toplevel']).stdout.trim())); } - catch (e: any) { return r.stop(`.gstack/plain-titles.json is invalid (${e.message}): fix it, then rerun push`); } - if (plain.length) return r.add(`BRANCH: refused ${plain.map(f => `"${f.match}"`).join(', ')}`).stop(`the branch name ${branch} is not plain words (docs/ship-policy.md#plain-titles): rename it with git branch -m [-], then rerun push --branch `); + catch (e: any) { return refuse(`.gstack/plain-titles.json is invalid (${e.message}): fix it, then rerun push`); } + if (plain.length) { r.add(`BRANCH: refused ${plain.map(f => `"${f.match}"`).join(', ')}`); return refuse(`the branch name ${branch} is not plain words (docs/ship-policy.md#plain-titles): rename it with git branch -m [-], then rerun push --branch `); } const p = git(cwd, ['push', '-u', 'origin', branch], 600_000); if (p.status !== 0) { const nff = /non-fast-forward|fetch first|rejected/.test(p.stderr); - return r.stop(nff ? 'non-fast-forward: fetch and merge the remote under Step 3\'s conflict rules, run Steps 5-16, then push again; never force-push' - : `push failed (${firstLine(p.stderr)}): repair the auth, hook or network cause, repeat Step 16, then push; never bypass a guard`); + return nff ? refuse('non-fast-forward: fetch and merge the remote under Step 3\'s conflict rules, run Steps 5-16, then push again; never force-push', 'PUSH_REJECTED') + : refuse(`push failed (${firstLine(p.stderr)}): repair the auth, hook or network cause, repeat Step 16, then push; never bypass a guard`, 'PUSH_GIT_FAILED'); } - return r.add(`PUSH: pushed ${local.slice(0, 12)} to origin/${branch}`).next('Step 18'); + r.next('Step 18'); + return `PUSH: pushed remote=origin ref=${branch} head=${local}`; } export async function release(argv: readonly string[], cwd: string): Promise<{ text: string; exit: number }> { const [cmd, ...rest] = argv; const { flag, has } = flagReader(rest); if (!cmd || cmd === '--help' || cmd === '-h' || has('--help')) return { text: RELEASE_HELP + '\n', exit: cmd ? 0 : 2 }; - const usage = (m: string) => ({ text: `gstack-ship-release: ${m}\n`, exit: 2 }); + const usage = (m: string) => ({ text: `gstack-ship-release: ${m}\n${cmd === 'push' ? `${pushFailedLine('PUSH_REFUSED')}\n` : ''}`, exit: 2 }); if (cmd !== 'push' && !flag('--base')) return usage(`${cmd} needs --base `); if (cmd === 'push' && !flag('--branch')) return usage('push needs --branch '); if (cmd === 'accept' && !(lanes(rest) as unknown[]).length) return usage('accept needs at least one --lane