mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-24 17:11:28 +01:00
Step 11.5 keeps a reviewed head current across base-only merges (GST-3308) (#4577)
When main is merged into a pull request after its code review, /ship no longer throws that review away. If every commit since the review is a clean merge of the base branch and the pull request's own changes are byte-identical, `gstack-review-read` now reports the review as current, so /ship finishes without another review round. Nothing to do. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/specialist-batched#1 reader=specialist-batched
This commit is contained in:
1 parent
14a84980ee
commit
92c57ca4ce
8 files changed
+345
-142
No files matched your search
+19
-3
@@ -15,7 +15,8 @@
|
||||
# UNVERIFIED, its reason names the findings no ruling covers yet (rulingGap, GST-3267), or says the row
|
||||
# lists no findings at all. A stopped row logged with --findings shows that file's findings, and a native
|
||||
# row that lists none shows its pass's review-row findings, with `findings_from` naming the source
|
||||
# (withCollectedFindings, GST-3296).
|
||||
# (withCollectedFindings, GST-3296). A row read on other content stays CURRENT when HEAD is its commit plus clean merges of
|
||||
# the base with the branch's patch unchanged, and its reason names the reviewed base (baseMergeOnly, GST-3308).
|
||||
set -euo pipefail
|
||||
GSTACK_BUN_CONFIG=/dev/null; case "${OSTYPE:-}" in msys*|cygwin*) if command -v cygpath >/dev/null 2>&1; then GSTACK_BUN_CONFIG=NUL; fi ;; esac
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
@@ -29,7 +30,7 @@ gstack_state_root_select
|
||||
GSTACK_HOME="$_gstack_sr_root"
|
||||
WTREE=$("$SCRIPT_DIR/gstack-wtree" --review 2>/dev/null || echo "unknown")
|
||||
if [ -f "$GSTACK_HOME/projects/$SLUG/$BRANCH-reviews.jsonl" ]; then
|
||||
GSTACK_REVIEW_LIB="$SCRIPT_DIR/../lib/review-evidence.ts" GSTACK_GATE_LIB="$SCRIPT_DIR/../lib/gate-dispositions.ts" GSTACK_RULED_LIB="$SCRIPT_DIR/../lib/ruled-notes.ts" GSTACK_REVIEW_WTREE="$WTREE" bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e '
|
||||
GSTACK_REVIEW_LIB="$SCRIPT_DIR/../lib/review-evidence.ts" GSTACK_PATCH_LIB="$SCRIPT_DIR/../lib/ship-receipt-patch.ts" GSTACK_POLICY_LIB="$SCRIPT_DIR/../lib/ship-policy.ts" GSTACK_GATE_LIB="$SCRIPT_DIR/../lib/gate-dispositions.ts" GSTACK_RULED_LIB="$SCRIPT_DIR/../lib/ruled-notes.ts" GSTACK_REVIEW_WTREE="$WTREE" bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e '
|
||||
const { reviewFreshness, rulingGap, withCollectedFindings } = await import(process.env.GSTACK_REVIEW_LIB);
|
||||
const { dispositionedOn, gateKey, readGateDispositions, ruledOn, showDispositioned } = await import(process.env.GSTACK_GATE_LIB);
|
||||
const { readRuledNotes } = await import(process.env.GSTACK_RULED_LIB);
|
||||
@@ -43,6 +44,21 @@ if [ -f "$GSTACK_HOME/projects/$SLUG/$BRANCH-reviews.jsonl" ]; then
|
||||
try { const rec = JSON.parse(line); return rec && typeof rec === "object" && !Array.isArray(rec) ? rec : null; } catch { return null; }
|
||||
});
|
||||
withCollectedFindings(recs.filter(Boolean));
|
||||
const now = process.env.GSTACK_REVIEW_WTREE;
|
||||
let baseMerged;
|
||||
if (now && now !== "unknown" && recs.some(rec => rec && [rec.wtree, rec.review_binding?.end_wtree].some(w => typeof w === "string" && w !== now))) {
|
||||
try {
|
||||
const { baseMergeOnly } = await import(process.env.GSTACK_PATCH_LIB);
|
||||
const { resolveBaseBranch } = await import(process.env.GSTACK_POLICY_LIB);
|
||||
const merges = new Map();
|
||||
let base;
|
||||
baseMerged = (rec, wtree) => {
|
||||
const key = rec.commit_full + " " + wtree;
|
||||
if (!merges.has(key)) merges.set(key, baseMergeOnly(process.cwd(), base ??= resolveBaseBranch(process.cwd()), rec.commit_full, wtree, now));
|
||||
return merges.get(key);
|
||||
};
|
||||
} catch (e) { console.error("gstack-review-read: base-merge check unavailable, rows read on other content stay STALE: " + e.message); }
|
||||
}
|
||||
for (const rec of recs) {
|
||||
try {
|
||||
if (!rec) throw new Error("malformed");
|
||||
@@ -53,7 +69,7 @@ if [ -f "$GSTACK_HOME/projects/$SLUG/$BRANCH-reviews.jsonl" ]; then
|
||||
const closed = dispositionedOn(process.cwd(), rec, dispositions);
|
||||
const ruled = ruledOn(process.cwd(), rec, rulings);
|
||||
const ruledSet = new Set(ruled.map(n => n.finding)), gatedSet = new Set(closed.map(d => gateKey(d.finding, d.gate_id)));
|
||||
const freshness = reviewFreshness(rec, process.env.GSTACK_REVIEW_WTREE, ruledSet, gatedSet);
|
||||
const freshness = reviewFreshness(rec, process.env.GSTACK_REVIEW_WTREE, ruledSet, gatedSet, baseMerged);
|
||||
const gap = freshness?.status === "UNVERIFIED" ? rulingGap(rec, ruledSet, gatedSet) : undefined;
|
||||
if (freshness) rec.review_freshness = gap ? { ...freshness, reason: freshness.reason + ": " + gap } : freshness;
|
||||
if (ruled.length) rec.ruled_notes = ruled.map(n => n.approval);
|
||||
|
||||
+4
-133
@@ -43,14 +43,14 @@ import { handOff, hostPublishes } from '../lib/host-publish';
|
||||
import { EXIT, exitTableHelp, NO_STOP_CLASSES, type ShipReceipt } from '../lib/headless-artifacts';
|
||||
import { resultLine, resultLineWithDocs } from '../lib/result-codes';
|
||||
import { versionAtRef } from '../lib/restamp';
|
||||
import { branchSides, stampOnlyLine, type BranchSide } from '../lib/stamp-only';
|
||||
import { branchSides } from '../lib/stamp-only';
|
||||
import { runScriptSync } from '../lib/script-invocation';
|
||||
import { readPregateFile, verifyPregate } from '../lib/pregate/index';
|
||||
import { exceptionConsumerProblem } from '../lib/pregate/flaky-exception';
|
||||
import { installedGstackVersion, isUnavailable, loadPolicyFromBase, matchesAny, policyUnavailableLine, resolveBaseBranch, stampFilesInTree, validatePolicy, type ShipPolicy } from '../lib/ship-policy';
|
||||
import { installedGstackVersion, isUnavailable, loadPolicyFromBase, policyUnavailableLine, resolveBaseBranch, stampFilesInTree, validatePolicy, type ShipPolicy } from '../lib/ship-policy';
|
||||
import { approvalForReceipt } from '../lib/approval-citations';
|
||||
import {
|
||||
CARRY_METADATA_GLOBS, CARRY_NAMED_PATHS, CARRY_TEST_GLOBS,
|
||||
CARRY_NAMED_PATHS,
|
||||
bindReceipt, carryReceipt, recheckCarried, classifyCarryPath, computeCensus, extractReceipt, landedStackParent, missingIssueLines, orderReceipt, parseReviewLoop, placeReceipt, planCarry, planTreeCarry,
|
||||
receiptIssuesFrom, receiptRuns, receiptSummaryLine, renderCensus, renderReceiptBlock, unruledOpenBlockers, validateReceipt, type CensusPr,
|
||||
} from '../lib/ship-receipt';
|
||||
@@ -69,7 +69,7 @@ import { laneExceptionBodyLines } from '../lib/test-lane-exception';
|
||||
import { grantedStop, grantMarker, historyLine, placeRunEntry, prReviewHistory, reviewRoute, runStub, stopFrom, stopMarker } from '../lib/pr-review-history';
|
||||
import { grantFor, readReviewRoundGrants, type ReviewRoundGrant } from '../lib/review-round-grant';
|
||||
import { readMechanicalLines } from '../lib/ship-mechanical';
|
||||
import { isRegistryUnavailable, loadRegistryFromBase } from '../lib/regen';
|
||||
import { patchId, productPatchAgainstBase, productRules, productSpec, verifiedOutputs } from '../lib/ship-receipt-patch';
|
||||
import { runCalls } from '../lib/ship-clock';
|
||||
|
||||
const HELP = `gstack-ship-receipt — the \`\`\`gstack-ship-receipt\`\`\` block (docs/ship-policy.md#ship-receipt)
|
||||
@@ -534,47 +534,6 @@ function writeRunRecord(a: { receipt: ShipReceipt; head: string; pr: string | un
|
||||
return status === 'complete' ? EXIT.ok : EXIT.fail;
|
||||
}
|
||||
|
||||
/**
|
||||
* One diff's patch-id over a pathspec; empty when the diff is empty. `--verbatim`
|
||||
* keeps whitespace in the hash (the default and `--stable` strip it, so a space
|
||||
* moved in a shell line would read as the same patch) while still ignoring the
|
||||
* hunk line numbers a base merge shifts.
|
||||
*/
|
||||
function patchId(repoRoot: string, from: string, to: string, pathspec: string[]): string | { error: string } {
|
||||
const firstLine = (s: string | null | undefined, fallback: string) => (s ?? '').trim().split('\n')[0]?.slice(0, 200) || fallback;
|
||||
const root = path.resolve(repoRoot, git(['rev-parse', '--git-path', 'gstack-patch-id'], repoRoot)?.trim() || '.git/gstack-patch-id');
|
||||
sweepStalePatchDirs(root);
|
||||
let dir: string;
|
||||
try { fs.mkdirSync(root, { recursive: true }); dir = fs.mkdtempSync(path.join(root, 'run-')); } catch (e) { return { error: `cannot create a temp file under ${root} (${firstLine((e as Error).message, 'mkdtemp failed')}); make that directory writable` }; }
|
||||
const file = path.join(dir, 'diff.patch');
|
||||
let fd: number | undefined;
|
||||
try {
|
||||
const diff = spawnSync('git', ['diff', '--no-color', '--no-ext-diff', '--full-index', `--output=${file}`, from, to, '--', ...pathspec], { cwd: repoRoot, encoding: 'utf8', timeout: 120_000 });
|
||||
if (diff.status !== 0) return { error: `git diff ${from.slice(0, 12)} ${to.slice(0, 12)}: ${firstLine(diff.stderr, diff.signal ? `killed by ${diff.signal}` : `exit ${diff.status}`)}` };
|
||||
fd = fs.openSync(file, 'r');
|
||||
const id = spawnSync('git', ['patch-id', '--verbatim'], { cwd: repoRoot, stdio: [fd, 'pipe', 'pipe'], encoding: 'utf8', timeout: 120_000 });
|
||||
if (id.status !== 0) return { error: `git patch-id --verbatim: ${firstLine(id.stderr, id.signal ? `killed by ${id.signal}` : `exit ${id.status}`)}` };
|
||||
return id.stdout.trim().split(/\s+/)[0] ?? '';
|
||||
} finally {
|
||||
if (fd !== undefined) fs.closeSync(fd);
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** A carry killed mid patch-id (preflight's timeout) skips patchId's `finally`; its product diff is removed by the next run once an hour old. */
|
||||
let swept = false;
|
||||
function sweepStalePatchDirs(root: string): void {
|
||||
if (swept) return;
|
||||
swept = true;
|
||||
const cutoff = Date.now() - 60 * 60 * 1000;
|
||||
let names: string[] = [];
|
||||
try { names = fs.readdirSync(root).filter(n => n.startsWith('run-')); } catch { return; }
|
||||
for (const n of names) {
|
||||
const p = path.join(root, n);
|
||||
try { if (fs.statSync(p).mtimeMs < cutoff) fs.rmSync(p, { recursive: true, force: true }); } catch { /* another run removed it */ }
|
||||
}
|
||||
}
|
||||
|
||||
/** `git patch-id --verbatim` exists from git 2.39 (docs/ship-policy.md#receipt-carry); an older git is a named refusal, never a silent fallback to the whitespace-stripping default. */
|
||||
const CARRY_MIN_GIT = '2.39';
|
||||
function gitVersionBelow(repoRoot: string, minimum: string): string | null {
|
||||
@@ -600,94 +559,6 @@ function pregateFieldFor(repoRoot: string, file: string, head: string): { ok: tr
|
||||
return { ok: true, field: { pregate: `${read.file.verdict ?? 'pass'} @${read.file.tree.slice(0, 12)} (${read.file.checks.length} checks, current for ${head.slice(0, 12)})`, requires_remote: remote.length ? remote.map(r => `${r.lane}: ${r.receipt}`) : undefined, flaky_exception: exceptions.length ? exceptions.map(e => ({ lane: e.lane, runs: e.runs, cases: e.cases, grant: e.grant, by: e.by })) : undefined } };
|
||||
}
|
||||
|
||||
/**
|
||||
* Generated outputs the carry may set aside as metadata: the paths the pregate
|
||||
* passed for HEAD proved (its regen check deleted each touched output and the
|
||||
* entry's command recreated it byte-identically), when that check ran
|
||||
* origin/<base>'s `.gstack/generated.json` at the commit this carry reads and the
|
||||
* path is an output of an entry with a `command` there. A proven name with glob
|
||||
* syntax is product too: the carry uses these paths as pathspec globs.
|
||||
*/
|
||||
function verifiedOutputs(repoRoot: string, base: string, pregateFile: string | undefined): string[] {
|
||||
if (!pregateFile) return [];
|
||||
const regen = readPregateFile(pregateFile).file?.checks.find(c => c.id === 'regen');
|
||||
if (!regen || regen.status !== 'pass' || !regen.proven?.length) return [];
|
||||
const load = loadRegistryFromBase(repoRoot, base);
|
||||
if (isRegistryUnavailable(load) || load.errors.length || regen.inputs?.registry !== load.source.label) return [];
|
||||
const owned = load.registry.entries.filter(e => e.command).flatMap(e => e.outputs);
|
||||
return regen.proven.filter(p => !/[*?[\]\\]/.test(p) && matchesAny(owned, p));
|
||||
}
|
||||
|
||||
interface ProductRules { extra: { metadata: string[]; outputs: readonly string[]; fragments?: string }; metadata: string[]; templates: readonly string[]; placeholders: readonly string[] }
|
||||
function productRules(repoRoot: string, base: string, outputs: readonly string[]): ProductRules {
|
||||
const load = loadPolicyFromBase(repoRoot, base);
|
||||
const policy: ShipPolicy | null = isUnavailable(load) ? null : load.policy;
|
||||
const fragments = policy?.changelog_fragments?.dir.replace(/^(\.\/)+/, '').replace(/\/+$/, '');
|
||||
const extra = { metadata: [...(policy?.stamp_files ?? []), ...(policy?.stamp_paths ?? []), ...(policy?.release_outputs ?? []), ...(policy?.changelog ? [policy.changelog] : [])], outputs, fragments };
|
||||
return { extra, metadata: [...CARRY_METADATA_GLOBS, ...extra.metadata, ...(fragments ? [`${fragments}/*.md`] : []), ...outputs], templates: policy?.stamp_patterns ?? [], placeholders: policy?.stamp_placeholders ?? [] };
|
||||
}
|
||||
|
||||
/**
|
||||
* The product pathspec between two commits: every path but tests and release
|
||||
* metadata, where a metadata-listed path whose change from `from` to `to` is
|
||||
* not a stamp stays product (every glob that matches it leaves the exclusion).
|
||||
* With `branch` (the paths the branch itself changed against the base, and its
|
||||
* base..head ranges), only the branch's own non-stamp changes demote a glob: a
|
||||
* touched path whose change is not a stamp on either side, or between the two
|
||||
* heads. A path only a base merge brought in has the same patch against the base
|
||||
* at both heads, and demoting its glob would pull a matching path the branch did
|
||||
* change, such as a CHANGELOG fragment next to the base's changelog.d/README.md
|
||||
* (GST-343, #3606), into the product patch-id at one head only.
|
||||
*/
|
||||
function productSpec(repoRoot: string, rules: ProductRules, from: string, to: string, branch?: { touched: ReadonlySet<string>; sides: ReadonlyArray<readonly [string, string]>; own: (rel: string) => BranchSide | undefined }): { changed: Array<{ path: string; class: ReturnType<typeof classifyCarryPath> }>; product: string[]; tests: string[]; demoted: string[]; ownRows: string[] } | undefined {
|
||||
const changedRaw = git(['diff', '--name-only', from, to], repoRoot);
|
||||
if (changedRaw === undefined) return undefined;
|
||||
const blobAt = (ref: string, p: string): string | null => { const r = spawnSync('git', ['show', `${ref}:${p}`], { cwd: repoRoot, encoding: 'utf8', timeout: 30_000, maxBuffer: 16 * 1024 * 1024 }); return r.status === 0 ? r.stdout : null; };
|
||||
const versionAt = (ref: string): string | null => {
|
||||
const file = blobAt(ref, 'VERSION');
|
||||
if (file !== null) return file.trim() || null;
|
||||
try { const v = JSON.parse(blobAt(ref, 'package.json') ?? 'null')?.version; return typeof v === 'string' ? v : null; } catch { return null; }
|
||||
};
|
||||
const versions = new Map<string, string | null>();
|
||||
const version = (ref: string) => { if (!versions.has(ref)) versions.set(ref, versionAt(ref)); return versions.get(ref)!; };
|
||||
const stamped = (p: string) => matchesAny(rules.metadata, p) && !matchesAny(rules.extra.outputs, p);
|
||||
const classify = (p: string, a: string, b: string) => classifyCarryPath(p, rules.extra, stamped(p) ? { before: blobAt(a, p), after: blobAt(b, p), oldVersion: version(a), newVersion: version(b), templates: rules.templates, placeholders: rules.placeholders, side: a === from && b === to ? branch?.own(p) : undefined } : undefined);
|
||||
// A stamp file the branch changed on neither side beyond a stamp against that side's base (back at the base's content
|
||||
// after a changelog-fragment conversion, or only its version moved) holds none of the branch's product: whatever else
|
||||
// differs between the two heads came from the base (GST-1210).
|
||||
// The same `ls-tree` entry (mode and object id, empty when absent) is an unchanged side; a failed read never is.
|
||||
const entryAt = (ref: string, p: string) => git(['ls-tree', ref, '--', p], repoRoot);
|
||||
const sameEntry = (a: string, b: string, p: string) => { const x = entryAt(a, p); return x !== undefined && x === entryAt(b, p); };
|
||||
const ownStampOnly = (p: string) => !!branch?.touched.has(p) && stamped(p) && branch.sides.every(([a, b]) => sameEntry(a, b, p) || classify(p, a, b) === 'metadata');
|
||||
const changed = changedRaw.split('\n').filter(Boolean).map(p => ({ path: p, class: ownStampOnly(p) ? 'metadata' as const : classify(p, from, to) }));
|
||||
const excludeGlobs = (globs: readonly string[]) => globs.map(g => `:(exclude,glob)${g}`);
|
||||
const demoted = !branch ? changed.filter(c => c.class === 'product' && matchesAny(rules.metadata, c.path)).map(c => c.path)
|
||||
: [...branch.touched].filter(p => stamped(p) && (changed.some(c => c.path === p && c.class === 'product') || branch.sides.some(([a, b]) => blobAt(a, p) !== blobAt(b, p) && classify(p, a, b) === 'product')));
|
||||
const metadataGlobs = rules.metadata.filter(g => !demoted.some(p => matchesAny([g], p)));
|
||||
// A demoted path whose from-to change is, line for line, a stamp on the branch's own rows (named by their position in
|
||||
// `from`), a regular file with the reviewed mode at both heads (GST-980): never the whole-text version swap.
|
||||
const ownRows = demoted.filter(p => {
|
||||
const side = branch?.own(p);
|
||||
const mode = (ref: string) => /^(100644|100755) blob /.exec(git(['ls-tree', ref, '--', p], repoRoot) ?? '')?.[1];
|
||||
const before = blobAt(from, p), after = blobAt(to, p), oldVersion = version(from), newVersion = version(to);
|
||||
if (!side || before === null || after === null || !oldVersion || !newVersion || !mode(from) || mode(from) !== mode(to)) return false;
|
||||
const was = before.split('\n');
|
||||
const now = after.split('\n');
|
||||
const lines = was.map((_, i) => i).filter(i => was[i] !== now[i]);
|
||||
return was.length === now.length && lines.length > 0 && lines.every(i => side.at.has(i + 1) && stampOnlyLine(was[i]!, now[i]!, oldVersion, newVersion, rules.templates, side, i + 1, rules.placeholders));
|
||||
});
|
||||
return { changed, product: ['.', ...excludeGlobs(CARRY_TEST_GLOBS), ...excludeGlobs(metadataGlobs)], tests: [...CARRY_TEST_GLOBS.map(g => `:(glob)${g}`), ...excludeGlobs(metadataGlobs)], demoted, ownRows };
|
||||
}
|
||||
|
||||
/** A commit's product patch-id against its merge base with the base ('' for no product diff), as write records it and a rewritten-history carry recomputes it. */
|
||||
function productPatchAgainstBase(repoRoot: string, rules: ProductRules, baseRef: string, commit: string): string | { error: string } {
|
||||
const mergeBase = git(['merge-base', baseRef, commit], repoRoot);
|
||||
if (!mergeBase) return { error: `cannot resolve the merge base of ${baseRef} and ${commit.slice(0, 12)}` };
|
||||
const spec = productSpec(repoRoot, rules, mergeBase, commit);
|
||||
if (!spec) return { error: `git diff ${mergeBase.slice(0, 12)} ${commit.slice(0, 12)} failed` };
|
||||
return patchId(repoRoot, mergeBase, commit, spec.product);
|
||||
}
|
||||
|
||||
/**
|
||||
* The receipt follows HEAD when the reviewed product is unchanged
|
||||
* (docs/unattended.md#the-terminal-line; harness lane E row 3). Four Captains
|
||||
|
||||
Reference in new issue
Block a user