mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-26 01:43:56 +01:00
A round grant at the review round cap buys the fix round it names (GST-2968) (#4479)
When /ship stops at a pull request's review round cap, a grant naming that stop now buys one scoped review of the fix, in the same run or the next, instead of another read-only full review. Before, a grant recorded after the read-only review, or between /ship runs, bought nothing, so teams paid for extra full reviews or second grants (ghome#40: $8.78 against about $3). Nothing to do: /ship prints the grant command when it stops. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/specialist-batched#1 reader=security Review-Finding: p1/specialist-batched#2 reader=state-machines Review-Finding: p1/specialist-batched#3 reader=testing Review-Finding: p1/red-team#1 reader=red-team Review-Finding: p1/red-team#2 reader=red-team Review-Finding: p1/red-team#3 reader=red-team
This commit is contained in:
1 parent
33b1a965ba
commit
f87d4325a3
28 files changed
+761
-86
No files matched your search
@@ -129,7 +129,7 @@ export interface ShipReceipt {
|
||||
/** The owner's acceptance of a stop after a fix-check edit under frozen scope (#3559); the PR body repeats it word for word. */
|
||||
review_loop_exception?: { accepted_by: string; date: string; via: string; reason: string; fix_check?: { head: string; findings: number; files?: string[] }; second_pass?: { head: string; deferred: string[] } };
|
||||
/** Review round grants the lane or its Captain recorded for this PR (gstack-approvals round-grant, lib/review-round-grant.ts; GST-2673): never the owner's, so never in review_loop_exception. */
|
||||
review_round_grants?: Array<{ kind: 'extra-round'; head: string; pr: number; by: string; reason: string; at: string; approval: string }>;
|
||||
review_round_grants?: Array<{ kind: 'extra-round' | 'fix-check'; head: string; pr: number; by: string; reason: string; at: string; approval: string; stop_run?: string; findings?: string[] }>;
|
||||
/** The owner's rulings that a finding ships as a disclosed note (gstack-approvals rule, lib/ruled-notes.ts); the PR body lists each one word for word (GST-1537). */
|
||||
ruled_notes?: Array<{ finding: string; head: string; by: string; reason: string; at: string; approval: string }>;
|
||||
/** The owner's dispositions of gate findings (gstack-approvals gate, lib/gate-dispositions.ts); the PR body lists each one word for word (GST-2491). */
|
||||
@@ -283,7 +283,7 @@ export const ARTIFACT_SCHEMAS = {
|
||||
review_targeted: { type: 'object', required: ['classes', 'rules', 'brief_sha', 'product_patch_id', 'status', 'findings', 'raised_by'], properties: { classes: { type: 'array', items: { enum: ['money', 'gate', 'auth', 'secret'] } }, rules: str, brief_sha: str, product_patch_id: str, status: { enum: ['done', 'failed', 'not-run'] }, findings: { type: 'integer', minimum: 0 }, raised_by: str } },
|
||||
review_exclude: { type: 'object', required: ['source', 'patterns', 'applied', 'excluded', 'excluded_bytes', 'kept', 'gate_tagged', 'patterns_sha256', 'list_sha256', 'digest'], properties: { source: str, patterns: strList, applied: strList, excluded: { type: 'integer', minimum: 0 }, excluded_bytes: { type: 'integer', minimum: 0 }, kept: { type: 'integer', minimum: 0 }, gate_tagged: strList, patterns_sha256: str, list_sha256: str, digest: str } },
|
||||
review_loop_exception: { type: 'object', required: ['accepted_by', 'date', 'via', 'reason'], properties: { accepted_by: str, date: str, via: str, reason: str, fix_check: { type: 'object', required: ['head', 'findings'], properties: { head: str, findings: { type: 'integer', minimum: 0 }, files: strList } }, second_pass: { type: 'object', required: ['head', 'deferred'], properties: { head: str, deferred: strList } } } },
|
||||
review_round_grants: { type: 'array', items: { type: 'object', required: ['kind', 'head', 'pr', 'by', 'reason', 'at', 'approval'], properties: { kind: { enum: ['extra-round'] }, head: str, pr: { type: 'integer', minimum: 1 }, by: str, reason: str, at: str, approval: str } } },
|
||||
review_round_grants: { type: 'array', items: { type: 'object', required: ['kind', 'head', 'pr', 'by', 'reason', 'at', 'approval'], properties: { kind: { enum: ['extra-round', 'fix-check'] }, head: str, pr: { type: 'integer', minimum: 1 }, by: str, reason: str, at: str, approval: str, stop_run: str, findings: { type: 'array', items: str } } } },
|
||||
ruled_notes: { type: 'array', items: { type: 'object', required: ['finding', 'head', 'by', 'reason', 'at', 'approval'], properties: { finding: str, head: str, by: str, reason: str, at: str, approval: str } } },
|
||||
gate_dispositions: { type: 'array', items: { type: 'object', required: ['finding', 'gate_id', 'head', 'by', 'reason', 'words', 'at', 'approval'], properties: { finding: str, gate_id: str, head: str, by: str, reason: str, words: str, at: str, approval: str } } },
|
||||
mechanical: strList,
|
||||
|
||||
@@ -9,8 +9,9 @@
|
||||
*/
|
||||
import type { ShipReceipt } from './headless-artifacts';
|
||||
import { withAgentNotes, splitAgentNotes } from './agent-notes';
|
||||
import { extractReceipt, receiptRun, receiptRuns, RECEIPT_RUNS_KEPT, RUNS_FENCE, RUNS_RE, type ReceiptRun } from './ship-receipt';
|
||||
import { extractReceipt, keptRuns, receiptRun, receiptRuns, RUNS_FENCE, RUNS_RE, type ReceiptRun } from './ship-receipt';
|
||||
import { FULL_PASS_CAP } from './review-depth';
|
||||
import type { ReviewRoundGrant } from './review-round-grant';
|
||||
|
||||
export interface PrReviewHistory {
|
||||
/** /ship runs that reviewed (stubs and carries excluded). */
|
||||
@@ -39,7 +40,7 @@ function entries(body: string): ReceiptRun[] {
|
||||
}
|
||||
|
||||
export function prReviewHistory(body: string): PrReviewHistory {
|
||||
const all = entries(body);
|
||||
const all = entries(body).filter(e => !e.mark);
|
||||
const reviewed = new Map<string, ReceiptRun>();
|
||||
const ordered: Array<ReceiptRun | string> = [];
|
||||
all.forEach((e, i) => {
|
||||
@@ -69,7 +70,8 @@ export function prReviewHistory(body: string): PrReviewHistory {
|
||||
*/
|
||||
export function placeRunEntry(body: string, entry: ReceiptRun): string {
|
||||
const runs = receiptRuns(body).filter(r => !(entry.status && r.status && r.run === entry.run));
|
||||
const kept = [...runs, JSON.parse(JSON.stringify(entry)) as ReceiptRun].slice(-RECEIPT_RUNS_KEPT);
|
||||
if (entry.mark && runs.some(r => JSON.stringify(r) === JSON.stringify(entry))) return body;
|
||||
const kept = keptRuns([...runs, JSON.parse(JSON.stringify(entry)) as ReceiptRun]);
|
||||
const block = '```' + RUNS_FENCE + '\n' + kept.map(r => JSON.stringify(r)).join('\n') + '\n```\n';
|
||||
if (RUNS_RE.test(body)) return body.replace(RUNS_RE, () => block);
|
||||
if (extractReceipt(body).found) {
|
||||
@@ -85,7 +87,57 @@ export function placeRunEntry(body: string, entry: ReceiptRun): string {
|
||||
export const runStub = (o: { head: string; run: string; status: 'started' | 'voided'; loop: NonNullable<ShipReceipt['review_loop']> }): ReceiptRun =>
|
||||
({ head: o.head, run: o.run, status: o.status, review_loop: o.loop });
|
||||
|
||||
export type Route = { route: 'first' | 'final' | 'read-only'; reason: string };
|
||||
/**
|
||||
* A stop record (GST-2968): the review a /ship run stopped on, written by gstack-ship-receipt stop when the plan prints NEXT: stop.
|
||||
* head is the commit that review read, tree its tree; the review row bound to it (lib/ship-stop.ts). A grant marker records
|
||||
* that a run claimed a round grant before dispatching the round it buys. Markers count no round and are never trimmed.
|
||||
*/
|
||||
export const stopMarker = (o: { head: string; tree: string; run: string }): ReceiptRun => ({ head: o.head, run: o.run, mark: 'stop', tree: o.tree });
|
||||
export const grantMarker = (o: { head: string; run: string; grant: string }): ReceiptRun => ({ head: o.head, run: o.run, mark: 'grant', grant: o.grant });
|
||||
|
||||
/**
|
||||
* The stop record for the newest via:ship review row of this run (at or after since), or why none binds: the row must be complete,
|
||||
* bound to one tree from start to end (verified, or incomplete because it stopped) that is its commit's own tree, read on a clean
|
||||
* worktree, and that commit must be HEAD or an ancestor of it. A read gstack can't tie to a commit gives a grant nothing to answer.
|
||||
*/
|
||||
export function stopFrom(rows: readonly Record<string, any>[], since: string, o: { treeOf: (commit: string) => string | undefined; onHead: (commit: string) => boolean }): { ok: true; head: string; tree: string } | { ok: false; why: string } {
|
||||
const sinceMs = Date.parse(since);
|
||||
const row = rows.filter(r => r && r.via === 'ship' && r.skill === 'review' && (!Number.isFinite(sinceMs) || Date.parse(r.timestamp) >= sinceMs)).at(-1);
|
||||
if (!row) return { ok: false, why: `no via:ship review row at or after ${since}` };
|
||||
const b = row.review_binding, head = typeof row.commit_full === 'string' ? row.commit_full.toLowerCase() : '';
|
||||
if (row.completed !== true) return { ok: false, why: 'the stopping review is not complete (a reader is missing)' };
|
||||
if (!b || (b.state !== 'verified' && b.state !== 'incomplete') || typeof row.tree !== 'string' || b.start_wtree !== row.tree || b.end_wtree !== row.tree || (row.wtree !== undefined && row.wtree !== row.tree)) return { ok: false, why: `the stopping review is not bound to one committed tree (binding ${b?.state ?? 'missing'})` };
|
||||
if (!/^[0-9a-f]{40}$/.test(head) || o.treeOf(head) !== row.tree) return { ok: false, why: `the stopping review's commit ${head.slice(0, 12) || 'missing'} does not hold the tree it read` };
|
||||
if (!o.onHead(head)) return { ok: false, why: `the stopping review's commit ${head.slice(0, 12)} is not HEAD or an ancestor of it` };
|
||||
return { ok: true, head, tree: row.tree };
|
||||
}
|
||||
|
||||
export type GrantedStop = { ok: true; grant: ReviewRoundGrant; stop: ReceiptRun } | { ok: false; why: string };
|
||||
|
||||
/**
|
||||
* The fix-check grant that answers this PR's stop (GST-2968, GHOM-1): the newest stop record in the body, a fix-check grant naming
|
||||
* its run and head for this PR, not claimed by another run, and HEAD at or after the stop's head. A stop is stale once a later run
|
||||
* reviewed (a stub after it with a full pass, or a current receipt past its head): a grant then answers nothing.
|
||||
*/
|
||||
export function grantedStop(body: string, grants: readonly ReviewRoundGrant[], o: { pr: number; head: string; run?: string; isAncestor: (a: string, d: string) => boolean }): GrantedStop | null {
|
||||
const fixChecks = grants.filter(g => g.kind === 'fix-check' && g.pr === o.pr);
|
||||
if (!fixChecks.length) return null;
|
||||
const runs = receiptRuns(body);
|
||||
const at = runs.map(r => r.mark).lastIndexOf('stop');
|
||||
if (at < 0) return { ok: false, why: `no stop record in the PR body for grant ${fixChecks.at(-1)!.approval}; a fix-check grant answers the stop gstack-ship-receipt stop recorded` };
|
||||
const stop = runs[at]!;
|
||||
const current = extractReceipt(body).receipt;
|
||||
const later = runs.slice(at + 1).find(r => !r.mark && r.run !== stop.run && (r.review_loop?.passes ?? 0) > 0);
|
||||
if (later || (current && typeof current.head === 'string' && current.head !== stop.head && o.isAncestor(stop.head, current.head))) return { ok: false, why: `the stop at ${stop.head.slice(0, 12)} (run ${stop.run}) is stale: run ${later?.run ?? current?.run} reviewed after it` };
|
||||
const g = [...fixChecks].reverse().find(x => x.head === stop.head && x.stop_run === stop.run);
|
||||
if (!g) return { ok: false, why: `no fix-check grant names the newest stop (run ${stop.run} at ${stop.head.slice(0, 12)}): record one with gstack-approvals round-grant --kind fix-check --head ${stop.head} --stop-run ${stop.run}` };
|
||||
const claimed = runs.find(r => r.mark === 'grant' && r.grant === g.approval && r.run !== o.run);
|
||||
if (claimed) return { ok: false, why: `grant ${g.approval} was claimed by run ${claimed.run}: a grant buys one round` };
|
||||
if (!o.isAncestor(stop.head, o.head)) return { ok: false, why: `HEAD ${o.head.slice(0, 12)} does not contain the stop's head ${stop.head.slice(0, 12)}: a head move voids grant ${g.approval}` };
|
||||
return { ok: true, grant: g, stop };
|
||||
}
|
||||
|
||||
export type Route = { route: 'first' | 'final' | 'read-only' | 'fix-check'; reason: string };
|
||||
|
||||
/**
|
||||
* What review a head of the PR gets when carry can't keep its receipt (the PR's own lines changed; a head that only
|
||||
|
||||
@@ -435,6 +435,21 @@ export const RELEASE_RESULT_CODES = {
|
||||
summary: 'the product diff against the base changed between the receipt\'s head and HEAD (a product file differs beyond a base merge, a test-only fix, release metadata or a regenerated output), so the reviewed verdict does not cover HEAD',
|
||||
fix: 'run /ship on the new head; the receipt carries only when every changed path is a test, release metadata, a registered output the pregate regen check proved, or the base merge, and the product patch-id is unchanged; base context next to unchanged reviewed hunks is RECEIPT_CARRY_SCOPED_REVIEW instead (one scoped fix-check, no /ship)',
|
||||
},
|
||||
STOP_UNBOUND: {
|
||||
anchor: 'stop-unbound',
|
||||
summary: 'gstack-ship-receipt stop found no review of this run bound to one committed tree, so it recorded no stop record',
|
||||
fix: 'nothing for a grant to answer: the lane or its Captain ships with the open notes listed or parks; a fresh /ship run gives the head its review',
|
||||
},
|
||||
GRANT_SPENT: {
|
||||
anchor: 'grant-spent',
|
||||
summary: 'another /ship run already claimed this round grant, and a grant buys one round',
|
||||
fix: 'the lane or its Captain records a new grant for the stop the PR is at now (gstack-ship-receipt stop prints the command)',
|
||||
},
|
||||
GRANT_UNKNOWN: {
|
||||
anchor: 'grant-unknown',
|
||||
summary: 'the branch approval record holds no approved review_round_grant row with this id',
|
||||
fix: 'pass the id gstack-approvals round-grant printed, from a checkout that sees the record or its mirror',
|
||||
},
|
||||
RECEIPT_CARRY_SCOPED_REVIEW: {
|
||||
anchor: 'receipt-carry-scoped-review',
|
||||
summary: 'the branch\'s own +/- lines are the reviewed ones, but the base edited context next to them, so the merge may have spliced the two (GST-384); the receipt carries only after a scoped review of those hunks',
|
||||
|
||||
+8
-2
@@ -392,8 +392,10 @@ export interface History {
|
||||
priorRounds?: number;
|
||||
/** The full review rounds among them (--prior-full): the PR cap compares these plus this run's full passes with FULL_PASS_CAP, so a run's own fix rounds stay as the in-run table plans them. */
|
||||
priorFull?: number;
|
||||
/** The lane's or Captain's recorded round grant at this head (--round-grant): one more round for the PR, never the owner's. */
|
||||
/** The lane's or Captain's recorded round grant at this head (--round-grant): one more round for the PR, with its fix round, never the owner's. */
|
||||
roundGrant?: string;
|
||||
/** A fix-check round grant that answers the stop record at --stop (GST-2968): the stopped review's fix round, one scoped fix-check of the PR's own change since the stop's head, in this run or a new one. */
|
||||
grantedStop?: string;
|
||||
}
|
||||
export interface NextStep { step: Step; reason: string }
|
||||
|
||||
@@ -413,6 +415,9 @@ export interface NextStep { step: Step; reason: string }
|
||||
* loop, a grant the CLI bound to the last fix-check's own stop head (`chained`) adds one more the same way (GST-1681).
|
||||
*/
|
||||
export function nextStep(h: History, depth?: Depth): NextStep {
|
||||
if (h.grantedStop && h.last !== 'fix-check') return h.rangeRuntimeLines == null
|
||||
? { step: 'stop', reason: `fix-check grant ${h.grantedStop} answers the stop, but there is no fix to read since its head: commit the fix (a base merge, an empty or reverted change is none), then ask again` }
|
||||
: { step: 'fix-check', reason: `fix-check grant ${h.grantedStop} buys the stopped review's fix round: one scoped fix-check of the PR's own change since the stop's head, never a new full review and never a second fix-check` };
|
||||
const n = prCapped(h, h.lean ? leanStep(h, depth) : loopStep(h, depth));
|
||||
if (n.step !== 'stop') return n;
|
||||
if (h.gate && !h.adversarialRan) return { step: 'voices', reason: `gate class: Step 11's ${h.lean ? 'one reader' : 'voices (adversarial, outside, targeted)'} run${h.lean ? 's' : ''} before the owner's exit, then ask again with --adversarial-ran (${n.reason})` };
|
||||
@@ -437,11 +442,12 @@ function prCapped(h: History, n: NextStep): NextStep {
|
||||
if (h.last === 'none') return n.step === 'full' || n.step === 'scoped' ? { step: 'full', reason: `read-only final review (R51): this PR already had ${prior} full review rounds on earlier heads, so this head gets one full review with no fix round; a blocker goes to the lane's Captain as a decision and the count does not reopen` } : n;
|
||||
if (n.step === 'done') return n;
|
||||
if (!h.fixedBlocking && !h.blockingOpen && !h.touchedGate && n.step !== 'stop') return { step: 'done', reason: `read-only final review done (R51): its below-floor findings ship as notes in the PR body and receipt, with no fix round` };
|
||||
return { step: 'stop', reason: `PR_ROUND_CAP: the read-only final review of a PR that already had ${prior} full review rounds found a blocker; the lane's Captain decides (ship with the note, or park; a round grant recorded after this read-only review does not buy a fix round), not an owner ask` };
|
||||
return { step: 'stop', reason: `PR_ROUND_CAP: the read-only final review of a PR that already had ${prior} full review rounds found a blocker; the lane's Captain decides (ship with the note, park, or buy its fix round with a fix-check grant naming the stop gstack-ship-receipt stop records), not an owner ask` };
|
||||
}
|
||||
if (!prior || (n.step !== 'full' && n.step !== 'scoped')) return n;
|
||||
const used = prior + h.fullPasses;
|
||||
if (used < cap) return { ...n, reason: `${n.reason}; this PR already had ${prior} full review round${prior === 1 ? '' : 's'} on earlier heads, so this is its full round ${used + 1} of ${cap}${used + 1 === cap ? ', the last' : ''}` };
|
||||
if (h.roundGrant && used === cap && prior === cap - 1 && h.fullPasses === 1 && h.last === 'full') return { ...n, reason: `${n.reason}; round grant ${h.roundGrant} bought pass 1 as this PR's full round ${cap}, and this is that round's fix round, its last` };
|
||||
if (h.last !== 'none' && !h.fixedBlocking && !h.blockingOpen && !h.touchedGate) return { step: 'done', reason: `PR round cap ${cap} reached (${prior} on earlier heads): the below-floor fixes ship as notes in the PR body and receipt` };
|
||||
return { step: 'stop', reason: `PR_ROUND_CAP: this PR already had ${used} full review round${used === 1 ? '' : 's'} across its heads and /ship runs${h.roundGrant ? ` (round grant ${h.roundGrant} included)` : ''}; another needs a reason the lane or its Captain records with gstack-approvals round-grant, not an owner ask` };
|
||||
}
|
||||
|
||||
+84
-12
@@ -1,22 +1,29 @@
|
||||
/**
|
||||
* Review round grants (GST-2673, docs/review-policy.md#rounds-per-pull-request): a reason the lane or its Captain
|
||||
* records when a PR needs a review round its R51 count would not plan. kind=extra-round: one round, with its fix
|
||||
* round, past the PR's cap of two. It binds one head of one PR and is spent by the round it buys. It is recorded with gstack-approvals round-grant,
|
||||
* is never an owner ask and never a plan approval (lib/plan-record.ts NOT_PLAN_ROW). --by is recorded, not enforced.
|
||||
* round, past the PR's cap of two, at a head no review has stopped at. kind=fix-check (GST-2968): the fix round of a
|
||||
* review that already stopped, naming that stop (its run and head, lib/pr-review-history.ts stopRecord) and the
|
||||
* findings it is for. Each binds one head of one PR and is spent by the run that claims it. It is recorded with
|
||||
* gstack-approvals round-grant, is never an owner ask and never a plan approval (lib/plan-record.ts NOT_PLAN_ROW).
|
||||
* --by is recorded, not enforced.
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { locate, readRecord, type ApprovalRow, type Env } from './approval-record';
|
||||
import { GSTACK_ACTOR } from './ruled-notes';
|
||||
|
||||
export const ROUND_GRANT_KINDS = ['extra-round'] as const;
|
||||
export const ROUND_GRANT_KINDS = ['extra-round', 'fix-check'] as const;
|
||||
export type RoundGrantKind = (typeof ROUND_GRANT_KINDS)[number];
|
||||
export interface ReviewRoundGrant { kind: RoundGrantKind; head: string; pr: number; by: string; reason: string; at: string; approval: string }
|
||||
/** stop_run and findings: a fix-check grant's stop (the run that stopped at head) and the finding ids it is for. */
|
||||
export interface ReviewRoundGrant { kind: RoundGrantKind; head: string; pr: number; by: string; reason: string; at: string; approval: string; stop_run?: string; findings?: string[] }
|
||||
|
||||
const SCOPE = /^review_round_grant ([0-9a-f]{40}) pr=([1-9]\d*) kind=(extra-round)$/;
|
||||
const ASK = /^review_round_grant (extra-round) at ([0-9a-f]{40}) for pr ([1-9]\d*): (\S(?:.*\S)?)$/;
|
||||
export const STOP_RUN = /^[\w.:-]{1,120}$/;
|
||||
export const FINDING_ID = /^[\w.:/#@-]{1,200}$/;
|
||||
const SCOPE = /^review_round_grant ([0-9a-f]{40}) pr=([1-9]\d*) kind=(extra-round|fix-check)(?: stop=(\S+) findings=(\S+))?$/;
|
||||
const ASK = /^review_round_grant (extra-round|fix-check) at ([0-9a-f]{40}) for pr ([1-9]\d*): (\S(?:.*\S)?)$/;
|
||||
export const REVIEW_ROUND_GRANT_SCOPE = /^\s*review_round_grant\b/;
|
||||
|
||||
export const reviewRoundGrantRow = (head: string, pr: number, kind: RoundGrantKind, reason: string) =>
|
||||
({ scope: `review_round_grant ${head} pr=${pr} kind=${kind}`, ask: `review_round_grant ${kind} at ${head} for pr ${pr}: ${reason}` });
|
||||
export const reviewRoundGrantRow = (head: string, pr: number, kind: RoundGrantKind, reason: string, stop?: { run: string; findings: readonly string[] }) =>
|
||||
({ scope: `review_round_grant ${head} pr=${pr} kind=${kind}${stop ? ` stop=${stop.run} findings=${stop.findings.join(',')}` : ''}`, ask: `review_round_grant ${kind} at ${head} for pr ${pr}: ${reason}` });
|
||||
|
||||
export function reviewRoundGrants(rows: readonly ApprovalRow[]): ReviewRoundGrant[] {
|
||||
const out: ReviewRoundGrant[] = [];
|
||||
@@ -24,7 +31,9 @@ export function reviewRoundGrants(rows: readonly ApprovalRow[]): ReviewRoundGran
|
||||
const s = SCOPE.exec(r.scope), a = ASK.exec(r.ask);
|
||||
if (r.outcome !== 'approved' || !s || !a || GSTACK_ACTOR.test(r.by)) continue;
|
||||
if (a[1] !== s[3] || a[2] !== s[1] || a[3] !== s[2]) continue;
|
||||
out.push({ kind: s[3] as RoundGrantKind, head: s[1]!, pr: Number(s[2]), by: r.by, reason: a[4]!, at: r.recorded_at, approval: r.id });
|
||||
const findings = s[5]?.split(',');
|
||||
if ((s[3] === 'fix-check') !== (s[4] !== undefined) || (s[4] !== undefined && (!STOP_RUN.test(s[4]) || !findings!.every(f => FINDING_ID.test(f))))) continue;
|
||||
out.push({ kind: s[3] as RoundGrantKind, head: s[1]!, pr: Number(s[2]), by: r.by, reason: a[4]!, at: r.recorded_at, approval: r.id, ...(s[4] ? { stop_run: s[4], findings } : {}) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -34,10 +43,73 @@ export function readReviewRoundGrants(cwd: string, env: Env = process.env): Revi
|
||||
return 'code' in loc ? [] : reviewRoundGrants(readRecord(loc).rows);
|
||||
}
|
||||
|
||||
/** The newest grant for this PR at exactly this head. */
|
||||
/** The newest extra-round grant for this PR at exactly this head (a fix-check grant answers a stop instead: lib/pr-review-history.ts grantedStop). */
|
||||
export const grantAt = (grants: readonly ReviewRoundGrant[], pr: number, head: string) =>
|
||||
[...grants].reverse().find(g => g.pr === pr && g.head === head.toLowerCase());
|
||||
[...grants].reverse().find(g => g.kind === 'extra-round' && g.pr === pr && g.head === head.toLowerCase());
|
||||
|
||||
/**
|
||||
* The newest extra-round grant for this PR at this head, or at a head this one only merges the base into or out of (GST-2968): one is
|
||||
* the other's ancestor and the PR's own added and removed lines against baseRef are byte-identical, in the same places, at both.
|
||||
* Preflight merges the base before the review, so the head a grant names and the head the next run reads can differ that way.
|
||||
*/
|
||||
export function grantFor(repoRoot: string, grants: readonly ReviewRoundGrant[], pr: number, head: string, baseRef?: string): ReviewRoundGrant | undefined {
|
||||
const exact = grantAt(grants, pr, head);
|
||||
if (exact || !baseRef) return exact;
|
||||
return [...grants].reverse().find(g => g.kind === 'extra-round' && g.pr === pr && ownLinesSame(repoRoot, baseRef, g.head, head.toLowerCase()));
|
||||
}
|
||||
|
||||
interface Hunk { path: string; start: number; len: number; added: number }
|
||||
|
||||
/** A zero-context diff's hunks: the file (its old side, or its new side when created), the old-side start and length, and the added length. */
|
||||
function hunks(diff: string): Hunk[] {
|
||||
const out: Hunk[] = [];
|
||||
let minus = '', path = '';
|
||||
for (const l of diff.split('\n')) {
|
||||
if (l.startsWith('--- ')) minus = l.slice(4);
|
||||
else if (l.startsWith('+++ ')) path = minus === '/dev/null' ? l.slice(4) : minus;
|
||||
const m = /^@@ -(\d+)(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(l);
|
||||
if (m) out.push({ path, start: +m[1]!, len: m[2] === undefined ? 1 : +m[2], added: m[3] === undefined ? 1 : +m[3] });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The old-side line own hunk h starts at once the base's hunks have moved its file, or null when the base edited a line h changes or
|
||||
* inserted inside or right next to h, so its place can't be carried over. Spans are in half-line steps: 2n is line n, 2n+1 the gap after it.
|
||||
*/
|
||||
function carried(base: readonly Hunk[], h: Hunk): number | null {
|
||||
const span = (x: Hunk, pad: number): [number, number] => x.len ? [2 * x.start - pad, 2 * (x.start + x.len - 1) + pad] : [2 * x.start + 1 - pad, 2 * x.start + 1 + pad];
|
||||
const [lo, hi] = span(h, 1);
|
||||
let shift = 0;
|
||||
for (const b of base.filter(x => x.path === h.path)) {
|
||||
const [blo, bhi] = span(b, 0);
|
||||
if (blo <= hi && lo <= bhi) return null;
|
||||
if (bhi < lo) shift += b.added - b.len;
|
||||
}
|
||||
return h.start + shift;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a and b are on one line of history and carry byte-identical own lines against baseRef at the same places: equal
|
||||
* zero-context patch-ids, and each own hunk of a, carried through the base's changes between the two forks, starts where b's does.
|
||||
* Moving a line to another place in the same file changes no patch-id, so the places are compared too.
|
||||
*/
|
||||
export function ownLinesSame(repoRoot: string, baseRef: string, a: string, b: string): boolean {
|
||||
const git = (args: string[], input?: string) => spawnSync('git', ['-c', 'core.quotepath=off', ...args], { cwd: repoRoot, encoding: 'utf8', input, timeout: 120_000, maxBuffer: 256 * 1024 * 1024 });
|
||||
if (git(['merge-base', '--is-ancestor', a, b]).status !== 0 && git(['merge-base', '--is-ancestor', b, a]).status !== 0) return false;
|
||||
const fork = (c: string) => { const f = git(['merge-base', baseRef, c]); return f.status === 0 ? f.stdout.trim() : null; };
|
||||
const diff = (x: string, y: string) => { const d = git(['diff', '--no-color', '--no-ext-diff', '--no-textconv', '--no-renames', '--binary', '--full-index', '-U0', x, y]); return d.status === 0 ? d.stdout : null; };
|
||||
const id = (d: string) => { const p = git(['patch-id', '--verbatim'], d); return p.status === 0 ? p.stdout.trim().split(/\s+/)[0] || null : null; };
|
||||
const fa = fork(a), fb = fork(b);
|
||||
if (!fa || !fb) return false;
|
||||
const da = diff(fa, a), db = diff(fb, b), moved = fa === fb ? '' : diff(fa, fb);
|
||||
if (!da?.trim() || !db?.trim() || moved === null) return false;
|
||||
const x = id(da);
|
||||
if (x === null || x !== id(db)) return false;
|
||||
const base = hunks(moved), there = hunks(db), here = hunks(da);
|
||||
return here.length === there.length && here.every((h, i) => h.path === there[i]!.path && h.len === there[i]!.len && carried(base, h) === there[i]!.start);
|
||||
}
|
||||
|
||||
/** The text after "Review round grant: " in the PR body. */
|
||||
export const reviewRoundGrantText = (g: ReviewRoundGrant) =>
|
||||
`${g.kind} at ${g.head.slice(0, 12)} for PR #${g.pr} recorded by ${g.by} at ${g.at}: ${g.reason} (approval ${g.approval})`;
|
||||
`${g.kind} at ${g.head.slice(0, 12)} for PR #${g.pr}${g.stop_run ? ` (stop ${g.stop_run}, findings ${g.findings!.join(', ')})` : ''} recorded by ${g.by} at ${g.at}: ${g.reason} (approval ${g.approval})`;
|
||||
@@ -104,7 +104,7 @@ function integrate(cwd: string, base: string, run: string | undefined, r: Report
|
||||
r.add(`PR: #${n}`).add(line);
|
||||
// R51 per pull request (GST-2673): the rounds earlier heads spent, which Step 9 passes to every plan, and the review this
|
||||
// head gets: a product change runs Steps 2-16, whose plan is the merge head's full review; a re-check never carries.
|
||||
const hist = bin(cwd, 'gstack-ship-receipt', ['history', '--pr', n], 120_000);
|
||||
const hist = bin(cwd, 'gstack-ship-receipt', ['history', '--pr', n, '--base', base, ...(run ? ['--run', run] : [])], 120_000);
|
||||
const histLines = hist.stdout.split('\n').filter(l => /^PR_REVIEW_(HISTORY|FLAGS|ROUTE): /.test(l));
|
||||
histLines.forEach(l => r.add(l));
|
||||
if (hist.status !== 0 || !histLines.some(l => l.startsWith('PR_REVIEW_FLAGS: '))) r.add('PR_REVIEW_FLAGS: --prior-rounds 0').add(`PR_REVIEW_ROUTE: first (history unavailable: ${firstLine(hist.stderr) || `gstack-ship-receipt history exit ${hist.status}`}; the plan counts this run's rounds only)`);
|
||||
|
||||
+7
-2
@@ -133,7 +133,12 @@ export const RUNS_RE = /```gstack-receipt-runs[ \t]*\r?\n([\s\S]*?)\r?\n```[ \t]
|
||||
* carries), `carry` for any other hop. status: a /ship run that
|
||||
* started and wrote no receipt yet (`started`, its counters so far) or ended on an infrastructure failure (`voided`).
|
||||
*/
|
||||
export type ReceiptRun = Pick<ShipReceipt, 'head' | 'version' | 'gstack_version' | 'run' | 'review_loop' | 'review_loop_exception'> & { depth?: string; carried_from?: string; carry_kind?: 'carry' | 'recheck'; status?: 'started' | 'voided' };
|
||||
export type ReceiptRun = Pick<ShipReceipt, 'head' | 'version' | 'gstack_version' | 'run' | 'review_loop' | 'review_loop_exception'> & { depth?: string; carried_from?: string; carry_kind?: 'carry' | 'recheck'; status?: 'started' | 'voided'; mark?: 'stop' | 'grant'; tree?: string; grant?: string };
|
||||
/** The runs block keeps the newest RECEIPT_RUNS_KEPT run entries and every stop or grant marker (lib/pr-review-history.ts), in order. */
|
||||
export function keptRuns(runs: readonly ReceiptRun[]): ReceiptRun[] {
|
||||
const keep = new Set(runs.filter(r => !r.mark).slice(-RECEIPT_RUNS_KEPT));
|
||||
return runs.filter(r => r.mark || keep.has(r));
|
||||
}
|
||||
export function receiptRuns(body: string): ReceiptRun[] {
|
||||
const m = RUNS_RE.exec(receiptSource(body));
|
||||
return m ? m[1]!.split('\n').flatMap(l => { try { const o = JSON.parse(l); return o && typeof o.head === 'string' ? [o as ReceiptRun] : []; } catch { return []; } }) : [];
|
||||
@@ -164,7 +169,7 @@ export function placeReceipt(body: string, receipt: ShipReceipt): string {
|
||||
const prior = ex.receipt;
|
||||
const runs = receiptRuns(body).filter(r => !r.status || !!receipt.carry || receipt.run === undefined || r.run !== receipt.run);
|
||||
if (prior && typeof prior.head === 'string' && JSON.stringify(prior) !== JSON.stringify(receipt)) runs.push(receiptRun(prior));
|
||||
const kept = runs.slice(-RECEIPT_RUNS_KEPT);
|
||||
const kept = keptRuns(runs);
|
||||
const block = renderReceiptBlock(receipt) + (kept.length ? '\n```' + RUNS_FENCE + '\n' + kept.map(r => JSON.stringify(r)).join('\n') + '\n```\n' : '');
|
||||
if (ex.found && splitAgentNotes(body).notes === null) {
|
||||
const rest = body.replace(BLOCK_RE, '').replace(RUNS_RE, '').replace(/^\s+/, '');
|
||||
|
||||
+3
-2
@@ -26,6 +26,7 @@ import { isCriticalFinding, isOpenByAction } from './headless-artifacts';
|
||||
import { fingerprintPath, normalizePath } from './review-scope';
|
||||
import { forbidSpecs } from './review-fetch';
|
||||
import { readRuledNotes, ruledNoteText } from './ruled-notes';
|
||||
import { reviewRoundGrants } from './review-round-grant';
|
||||
import { dispositionedOn, gateDispositionText, gateKey, readGateDispositions } from './gate-dispositions';
|
||||
import { parseReviewLoopException, type ReviewLoopException } from './ship-receipt-depth';
|
||||
import { parseReceiptDocs, type ReceiptDocs } from './ship-receipt-docs';
|
||||
@@ -315,13 +316,13 @@ function fixChecked(cwd: string, o: BridgeOpts & { now: string; parent?: string;
|
||||
const gates = readGateDispositions(cwd);
|
||||
for (const d of gates) r.add(`GATE_DISPOSITION: ${gateDispositionText(d)}${reviewRows.some(v => dispositionedOn(cwd, v, [d]).length) ? '' : ' (no open gate finding at this fingerprint on a review row whose range holds this head; not applied)'}`);
|
||||
const gatedOn = (l: FixLink) => new Set(dispositionedOn(cwd, l.row, gates).map(d => gateKey(d.finding, d.gate_id)));
|
||||
const grants = chain.length ? (loc => 'file' in loc ? readRecord(loc).rows : [])(locate({ cwd, env: process.env })).filter(g => g.outcome === 'approved' && `${g.ask} ${g.scope}`.includes('review_loop_grant')) : [];
|
||||
const grants = chain.length ? (loc => 'file' in loc ? readRecord(loc).rows : [])(locate({ cwd, env: process.env })).filter(g => g.outcome === 'approved' && (`${g.ask} ${g.scope}`.includes('review_loop_grant') || reviewRoundGrants([g]).some(x => x.kind === 'fix-check'))) : [];
|
||||
const granted: (typeof grants[number] | undefined)[] = [];
|
||||
const used = new Set<string>();
|
||||
for (let k = chain.length - 1; k >= 0; k--) {
|
||||
const l = chain[k]!;
|
||||
const g = grants.filter(g => !used.has(g.id))
|
||||
.flatMap(g => (`${g.ask} ${g.scope}`.match(/\b[0-9a-f]{7,40}\b/g) ?? []).map(commitOf).filter(c => !!c && inRange(l, c)).map(stop => ({ g, stop })))
|
||||
.flatMap(g => { const fc = reviewRoundGrants([g]).find(x => x.kind === 'fix-check'); return (fc ? (commitOf(fc.head) === l.from ? [fc.head] : []) : `${g.ask} ${g.scope}`.match(/\b[0-9a-f]{7,40}\b/g) ?? []).map(commitOf).filter(c => !!c && inRange(l, c)).map(stop => ({ g, stop })); })
|
||||
.reduce<{ g: typeof grants[number]; stop: string } | undefined>((best, c) => (!best || ancestor(best.stop, c.stop) ? c : best), undefined)?.g;
|
||||
if (g) used.add(g.id);
|
||||
granted[k] = g;
|
||||
|
||||
Reference in new issue
Block a user