diff --git a/bin/gstack-review-read b/bin/gstack-review-read index d67d32525..c1fe1cf03 100755 --- a/bin/gstack-review-read +++ b/bin/gstack-review-read @@ -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); diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receipt index e226fd3e4..052166997 100755 --- a/bin/gstack-ship-receipt +++ b/bin/gstack-ship-receipt @@ -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/'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; sides: ReadonlyArray; own: (rel: string) => BranchSide | undefined }): { changed: Array<{ path: string; class: ReturnType }>; 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(); - 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 diff --git a/changelog.d/step-11-5-base-merge-only.md b/changelog.d/step-11-5-base-merge-only.md new file mode 100644 index 000000000..55c2fc713 --- /dev/null +++ b/changelog.d/step-11-5-base-merge-only.md @@ -0,0 +1,4 @@ +--- +important: blocker +--- +**Step 11.5 keeps a reviewed head current across base-only merges.** When a merge lane merges main into a PR after its review, `gstack-review-read` now reads the review rows CURRENT if every commit since the review is a clean merge of the base and the branch's own patch is byte-identical, so a /ship run that stopped before its receipt finishes without another review round (harness-evals#515). An own edit, a conflict resolution, an edit inside a merge, base context moved beside the branch's hunks or an uncommitted change still reads STALE and says which. diff --git a/docs/ship-policy.md b/docs/ship-policy.md index 342408659..82106eaa8 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -1849,6 +1849,18 @@ Step 9 row of the same pass, commit and bound tree, because Step 9 carries Step that is missing or changed attaches nothing, and any row that claims issues but lists no findings reads `it lists no findings (fcount 0) but claims …` with the cause (harness-evals#515, GST-3296). +A row read on other content still reads `CURRENT` when HEAD is the row's commit +plus clean merges of `origin/` and nothing else, the head R51 counts as +already reviewed (harness-evals#515 at 2d3ab19d, GST-3308). Every commit after +the reviewed one must be a two-parent merge whose second parent the base holds and +whose tree is exactly what `git merge-tree --write-tree` writes for its parents, +the working tree must be HEAD's, and the branch's patch against the base must be +the reviewed one twice over: the product patch-id the receipt carry compares +(`lib/ship-receipt-patch.ts`) and the patch-id over every path, so tests, +release metadata and gate paths stay covered. The reason then names the reviewed +base to save with the reviewed tree for finish's `--reviewed-base`. +An own edit, a conflict resolution, an edit inside a merge, base context moved +beside the branch's hunks or an uncommitted change reads `STALE` and says which. **Security findings stay private (GST-3076).** A PR body keeps every earlier diff --git a/docs/skills.md b/docs/skills.md index 27247e967..edd625160 100644 --- a/docs/skills.md +++ b/docs/skills.md @@ -261,7 +261,7 @@ Every review (CEO, Eng, Design) logs its result. At the end of each review, you Eng Review is the only required gate (disable with `gstack-config set skip_eng_review true`). CEO and Design are informational — recommended for product and UI changes respectively. -Diff reviews use the `review_freshness` grade computed by `gstack-review-read`, shared by `/ship` and `/land-and-deploy`. CURRENT requires a clean, reviewer-reported completed and converged pass whose captured start and finish fingerprints match the current working-tree content. Tracked edits and non-ignored untracked source both count; an identical commit hash or zero commits since review is not a fallback. +Diff reviews use the `review_freshness` grade computed by `gstack-review-read`, shared by `/ship` and `/land-and-deploy`. CURRENT requires a clean, reviewer-reported completed and converged pass whose captured start and finish fingerprints match the current working-tree content. Tracked edits and non-ignored untracked source both count; an identical commit hash or zero commits since review is not a fallback. The one exception is a head that holds only clean merges of the base on top of the reviewed commit, with the branch's own patch unchanged: it still grades CURRENT, and the reason names the reviewed base ([ship policy](ship-policy.md)). A captured pass with different start/end content grades STALE, as does a previously verified pass whose fingerprint no longer matches. Missing or reused start receipts, legacy log-only records, incomplete or nonconverged passes, and unresolved findings cannot grade CURRENT; missing evidence grades UNVERIFIED. Ship telemetry is not a review pass. After fixes, run a genuine full re-review with a new start receipt rather than capturing one only to log the result. Completion remains reviewer-reported, not independent proof that a model read the source. diff --git a/lib/review-evidence.ts b/lib/review-evidence.ts index 120ed384b..9bcc11345 100644 --- a/lib/review-evidence.ts +++ b/lib/review-evidence.ts @@ -431,7 +431,13 @@ export function rulingGap(rec: Record, ruled: ReadonlySet, return `${left.length} finding(s) still need an owner ruling at this head: ${left.slice(0, 10).join('; ')}${left.length > 10 ? `; +${left.length - 10} more` : ''} (a noted or deferred CRITICAL still counts as open)`; } -export function reviewFreshness(rec: Record, currentWtree: string, ruled: ReadonlySet = new Set(), gated: ReadonlySet = new Set()): { status: string; reason: string } | undefined { +/** + * A row's freshness at the current content. A clean read of other content reads STALE, except a head `baseMerged` accepts + * (gstack-review-read passes baseMergeOnly, lib/ship-receipt-patch.ts): the reviewed commit plus clean merges of the base with + * the branch's patch unchanged, which R51 counts as already reviewed (GST-3308, harness-evals#515). + */ +export function reviewFreshness(rec: Record, currentWtree: string, ruled: ReadonlySet = new Set(), gated: ReadonlySet = new Set(), + baseMerged?: (rec: Record, reviewedWtree: string) => { ok: true; note: string } | { ok: false; why: string }): { status: string; reason: string } | undefined { if (!DIFF_REVIEWS.has(rec.skill)) return; if (rec.skill === 'ship') return { status: 'UNVERIFIED', reason: 'ship telemetry is not a review pass' }; const binding = rec.review_binding; @@ -447,8 +453,11 @@ export function reviewFreshness(rec: Record, currentWtree: string, !wtree || binding.start_wtree !== wtree || binding.end_wtree !== wtree) { return { status: 'UNVERIFIED', reason: 'missing start capture or incomplete/nonconverged pass' }; } + let merged: string | undefined; if (!currentWtree || currentWtree === 'unknown' || wtree !== currentWtree) { - return { status: 'STALE', reason: 'working-tree content differs from reviewed content' }; + const carried = currentWtree && currentWtree !== 'unknown' ? baseMerged?.(rec, wtree) : undefined; + if (!carried?.ok) return { status: 'STALE', reason: `working-tree content differs from reviewed content${carried ? ` (${carried.why})` : ''}` }; + merged = carried.note; } // B7: a derived row carries findings_open; a resolved critical finding no // longer counts against it. Claimed rows keep the conservative reading of @@ -460,5 +469,5 @@ export function reviewFreshness(rec: Record, currentWtree: string, (Array.isArray(rec.findings) && rec.findings.some(unresolvedFinding))) { return { status: 'UNVERIFIED', reason: 'review has unresolved findings or did not finish clean' }; } - return { status: 'CURRENT', reason: 'completed clean pass on unchanged content' }; + return { status: 'CURRENT', reason: merged ? `completed clean pass; ${merged}` : 'completed clean pass on unchanged content' }; } diff --git a/lib/ship-receipt-patch.ts b/lib/ship-receipt-patch.ts new file mode 100644 index 000000000..3eaa7b5e7 --- /dev/null +++ b/lib/ship-receipt-patch.ts @@ -0,0 +1,195 @@ +/** + * The branch's patch against its base, as the receipt carry and Step 11.5 compare it (docs/ship-policy.md#receipt-carry). + * patchId hashes one diff with `git patch-id --verbatim`, which ignores the hunk line numbers a base merge shifts; the + * product patch-id leaves out tests and release metadata (productSpec). baseMergeOnly (GST-3308, harness-evals#515) says + * whether HEAD holds only clean merges of the base on top of a reviewed commit with the branch's own patch unchanged, the + * head R51 counts as already reviewed. + */ +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { spawnSync } from './spawn-sync'; +import { isRegistryUnavailable, loadRegistryFromBase } from './regen'; +import { readPregateFile } from './pregate/index'; +import { isUnavailable, loadPolicyFromBase, matchesAny, type ShipPolicy } from './ship-policy'; +import { stampOnlyLine, type BranchSide } from './stamp-only'; +import { CARRY_METADATA_GLOBS, CARRY_TEST_GLOBS, classifyCarryPath } from './ship-receipt'; + +function git(args: string[], cwd?: string): string | undefined { + const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 30_000, maxBuffer: 256 * 1024 * 1024 }); + return r.status === 0 ? r.stdout.trim() : undefined; +} + +/** + * 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. + */ +export 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 */ } + } +} + +/** + * 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/'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. + */ +export 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)); +} + +export interface ProductRules { extra: { metadata: string[]; outputs: readonly string[]; fragments?: string }; metadata: string[]; templates: readonly string[]; placeholders: readonly string[] } +export 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. + */ +export function productSpec(repoRoot: string, rules: ProductRules, from: string, to: string, branch?: { touched: ReadonlySet; sides: ReadonlyArray; own: (rel: string) => BranchSide | undefined }): { changed: Array<{ path: string; class: ReturnType }>; 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(); + 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. */ +export 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); +} + + +export type BaseMergeOnly = { ok: true; note: string } | { ok: false; why: string }; + +/** + * Whether HEAD is the reviewed commit plus clean merges of origin/ and nothing else: every first-parent commit after + * it is a two-parent merge whose second parent the base holds and whose tree is exactly what `git merge-tree` writes for + * its parents (no conflict resolution, no edit inside the merge), the working tree is HEAD's, and the branch's patch + * against the base is the reviewed one: the product patch-id the carry compares, and the patch-id over every path, so a + * test, release-metadata or gate path the product patch-id leaves out stays covered too. + */ +export function baseMergeOnly(cwd: string, base: string, reviewed: unknown, reviewedTree: string, currentWtree: string): BaseMergeOnly { + const no = (why: string): BaseMergeOnly => ({ ok: false, why }); + const repoRoot = git(['rev-parse', '--show-toplevel'], cwd); + if (!repoRoot) return no('not inside a git checkout'); + if (typeof reviewed !== 'string' || !/^[0-9a-f]{40,64}$/.test(reviewed)) return no('the row names no full reviewed commit'); + if (git(['rev-parse', '--verify', '--quiet', `${reviewed}^{commit}`], repoRoot) !== reviewed) return no(`the reviewed commit ${reviewed.slice(0, 12)} is not in this clone`); + if (git(['rev-parse', `${reviewed}^{tree}`], repoRoot) !== reviewedTree) return no(`the review read content its commit ${reviewed.slice(0, 12)} does not hold`); + const head = git(['rev-parse', 'HEAD'], repoRoot); + if (!head || git(['rev-parse', 'HEAD^{tree}'], repoRoot) !== currentWtree) return no('the working tree has changes HEAD does not hold'); + const baseRef = `origin/${base.replace(/^origin\//, '')}`; + if (!git(['rev-parse', '--verify', '--quiet', `${baseRef}^{commit}`], repoRoot)) return no(`${baseRef} does not resolve (fetch it)`); + const ancestor = (a: string, d: string) => spawnSync('git', ['merge-base', '--is-ancestor', a, d], { cwd: repoRoot, timeout: 30_000 }).status === 0; + if (!ancestor(reviewed, head)) return no(`the reviewed commit ${reviewed.slice(0, 12)} is not an ancestor of HEAD (rebased or force-pushed)`); + const chain = (git(['rev-list', '--first-parent', '--parents', `${reviewed}..${head}`], repoRoot) ?? '').split('\n').filter(Boolean).map(l => l.split(' ')); + if (!chain.length || chain.at(-1)![1] !== reviewed) return no(`HEAD's first-parent history does not run back to the reviewed commit ${reviewed.slice(0, 12)}`); + for (const [commit, ...parents] of chain) { + const c = commit!.slice(0, 12); + if (parents.length !== 2) return no(`commit ${c} after the reviewed one is not a merge of ${baseRef}`); + if (!ancestor(parents[1]!, baseRef)) return no(`merge ${c} brings in ${parents[1]!.slice(0, 12)}, which ${baseRef} does not hold`); + const replay = spawnSync('git', ['merge-tree', '--write-tree', '--no-messages', parents[0]!, parents[1]!], { cwd: repoRoot, encoding: 'utf8', timeout: 120_000 }); + if (replay.status === 1) return no(`merge ${c} had conflicts, so its resolution is unreviewed`); + if (replay.status !== 0) return no(`git merge-tree --write-tree could not replay merge ${c} (git 2.39 or later)`); + if (replay.stdout.split('\n')[0]!.trim() !== git(['rev-parse', `${commit}^{tree}`], repoRoot)) return no(`merge ${c} holds changes its clean merge does not (an edit inside the merge)`); + } + const rules = productRules(repoRoot, base, []); + const product = [productPatchAgainstBase(repoRoot, rules, baseRef, reviewed), productPatchAgainstBase(repoRoot, rules, baseRef, head)]; + for (const id of product) if (typeof id !== 'string') return no(`git could not compute the product patch-id: ${id.error}`); + if (product[0] !== product[1]) return no(`the branch's product patch changed (patch-id ${(product[0] as string).slice(0, 12) || 'none'} reviewed, ${(product[1] as string).slice(0, 12) || 'none'} now)`); + const bases = [git(['merge-base', baseRef, reviewed], repoRoot), git(['merge-base', baseRef, head], repoRoot)]; + if (!bases[0] || !bases[1]) return no(`cannot resolve the merge base with ${baseRef}`); + const whole = [patchId(repoRoot, bases[0], reviewed, ['.']), patchId(repoRoot, bases[1], head, ['.'])]; + for (const id of whole) if (typeof id !== 'string') return no(`git could not compute the branch's patch-id: ${id.error}`); + if (whole[0] !== whole[1]) return no('the branch\'s patch on a path the product patch-id leaves out (tests, release metadata) changed'); + return { ok: true, note: `HEAD ${head.slice(0, 12)} adds only ${chain.length} clean merge(s) of ${baseRef} to the reviewed commit ${reviewed.slice(0, 12)}, and the branch's patch is unchanged (product patch-id ${(product[1] as string).slice(0, 12) || 'none'}); save the reviewed base ${bases[0]} for finish's --reviewed-base` }; +} diff --git a/test/ship-finish-ruled-notes.test.ts b/test/ship-finish-ruled-notes.test.ts index 752e28379..afee9e3e0 100644 --- a/test/ship-finish-ruled-notes.test.ts +++ b/test/ship-finish-ruled-notes.test.ts @@ -701,8 +701,9 @@ const HE515_FINDINGS = [ const HE515_STEP9 = { pass: 2, completed: true, converged: false, cycles: 1, critical: 9, informational: 5 }; const HE515_NATIVE = { pass: 2, source: 'in-host', host: 'capy', phase: 'adversarial', gate: 'issues_found', status: 'issues_found', completed: true, converged: false, outside_provider: 'host-subagent', outside_status: 'completed' }; -function he515(findings: Record[] = HE515_FINDINGS, step9: Record = {}, findingsArg?: string) { - const f = shipFixture({ 'src/x.ts': 'export const x = 1;\n' }, { 'src/x.ts': 'export const x = 2;\n' }); +function he515(findings: Record[] = HE515_FINDINGS, step9: Record = {}, findingsArg?: string, + files: [Record, Record] = [{ 'src/x.ts': 'export const x = 1;\n' }, { 'src/x.ts': 'export const x = 2;\n' }]) { + const f = shipFixture(...files); ships.push(f); const file = path.join(path.dirname(f.state), 'p2-findings.jsonl'); fs.writeFileSync(file, findings.map(x => JSON.stringify(x)).join('\n') + '\n'); @@ -786,3 +787,98 @@ describe('rulings close a stopped review whose findings are in its findings file }); }); + +// harness-evals#515 at 2d3ab19d (GST-3308): both rows read CURRENT at the reviewed head 630a9903, then the merge lane merged +// origin/main in with no conflicts and the PR's patch byte-identical, and Step 11.5 read both STALE because it compared whole +// trees. R51 counts that head as reviewed. Seven-line files put the base's edits next to the branch's own hunks. +const seven = (tag: string, at: Record = {}) => Array.from({ length: 7 }, (_, i) => at[i + 1] ?? `export const ${tag}${i + 1} = ${i + 1};`).join('\n') + '\n'; +const sevenTests = (at: Record = {}) => ["import { expect, test } from 'bun:test';", ...Array.from({ length: 6 }, (_, i) => `test('t${i + 2}', () => { expect(${at[i + 2] ?? i + 2}).toBeGreaterThan(0); });`)].join('\n') + '\n'; +const HE515_MERGE_FILES: [Record, Record] = [ + { 'src/x.ts': seven('x'), 'test/x.test.ts': sevenTests() }, + { 'src/x.ts': seven('x', { 2: 'export const x2 = 20;' }), 'test/x.test.ts': sevenTests({ 2: 20 }) }, +]; +/** #515's stopped pass 2, every blocker ruled at the reviewed head, then the base moves by `base`. */ +function he515Merged(base: Record) { + const { f, head } = he515(HE515_FINDINGS, {}, undefined, HE515_MERGE_FILES); + ruleAll(f, head, [...HE515_OPEN, ...HE515_PARTIAL]); + const reviewed = he515Rows(f)[0].review_binding.end_wtree as string; + const reviewedBase = f.git('merge-base', 'origin/main', 'HEAD').stdout.trim(); + f.advanceBase(base); + expect(f.git('fetch', '-q', 'origin').status).toBe(0); + return { f, head, reviewed, reviewedBase, merge: () => f.git('merge', '-q', '--no-edit', 'origin/main') }; +} +const freshness = (f: ShipFx) => he515Rows(f).map(r => r.review_freshness); +const staleBecause = (why: string) => Array(2).fill({ status: 'STALE', reason: `working-tree content differs from reviewed content (${why})` }); +const MAIN_MOVES = { 'docs/main.md': '# main moved\n', 'src/main.ts': 'export const main = 1;\n' }; + +// Value: protects=harness-evals#515 at 2d3ab19d: a head that only merges in the base, with the branch's patch unchanged, keeps +// both Step 11.5 rows CURRENT and finish binds the reviewed tree without a new review round; fails_when=gstack-review-read reads +// either row STALE after a clean base merge, or reads CURRENT after an own edit, a conflict resolution, an edit inside the merge, +// moved context beside the branch's product or test hunks, or uncommitted changes; seam=gstack-review-read's baseMergeOnly over +// the stored rows and finish --reviewed-base; no_claim=the receipt carry route +describe('Step 11.5 keeps a reviewed head CURRENT across base-only merges (harness-evals#515, GST-3308)', () => { + test('#515: a clean merge of main keeps both rows CURRENT, names the reviewed base, and finish binds with no new review', () => { + const { f, head, reviewed, reviewedBase, merge } = he515Merged(MAIN_MOVES); + expect(merge().status).toBe(0); + const now = f.git('rev-parse', 'HEAD').stdout.trim(); + const why = new RegExp(`^completed clean pass; HEAD ${now.slice(0, 12)} adds only 1 clean merge\\(s\\) of origin/main to the reviewed commit ${head.slice(0, 12)}, and the branch's patch is unchanged \\(product patch-id [0-9a-f]{12}\\); save the reviewed base ${reviewedBase} for finish's --reviewed-base$`); + expect(freshness(f)).toEqual(Array(2).fill({ status: 'CURRENT', reason: expect.stringMatching(why) })); + const r = finishAfterAudit(f, reviewed, reviewedBase); + expect([r.status, lineOf(r.stdout, 'ROUTE')], r.stdout).toEqual([0, expect.stringMatching(/ behavior=0 /)]); + }); + + test('an own edit after the merge stays STALE', () => { + const { f, merge } = he515Merged(MAIN_MOVES); + expect(merge().status).toBe(0); + f.write({ 'src/x.ts': seven('x', { 2: 'export const x2 = 21;' }) }); f.commit('edit after the merge'); + expect(freshness(f)).toEqual(staleBecause(`commit ${f.git('rev-parse', 'HEAD').stdout.trim().slice(0, 12)} after the reviewed one is not a merge of origin/main`)); + }); + + test('a conflict resolution stays STALE, even one that keeps the branch\'s side', () => { + const { f, merge } = he515Merged({ ...MAIN_MOVES, 'src/x.ts': seven('x', { 2: 'export const x2 = 30;' }) }); + expect(merge().status).not.toBe(0); + f.write({ 'src/x.ts': seven('x', { 2: 'export const x2 = 20;' }) }); f.commit('merge origin/main: keep ours'); + expect(freshness(f)).toEqual(staleBecause(`merge ${f.git('rev-parse', 'HEAD').stdout.trim().slice(0, 12)} had conflicts, so its resolution is unreviewed`)); + }); + + test('an edit inside a clean merge to a protected path stays STALE', () => { + const { f, merge } = he515Merged(MAIN_MOVES); + expect(merge().status).toBe(0); + f.write({ '.github/workflows/ci.yml': 'name: ci\non: push\n' }); + expect(f.git('add', '-A').status).toBe(0); + expect(f.git('commit', '-q', '--amend', '--no-edit').status).toBe(0); + expect(freshness(f)).toEqual(staleBecause(`merge ${f.git('rev-parse', 'HEAD').stdout.trim().slice(0, 12)} holds changes its clean merge does not (an edit inside the merge)`)); + }); + + test('base context moved beside the branch\'s product hunk, or its test hunk, stays STALE', () => { + const product = he515Merged({ 'src/x.ts': seven('x', { 5: 'export const x5 = 50;' }) }); + expect(product.merge().status).toBe(0); + expect(freshness(product.f)).toEqual(Array(2).fill({ status: 'STALE', reason: expect.stringMatching(/^working-tree content differs from reviewed content \(the branch's product patch changed \(patch-id [0-9a-f]{12} reviewed, [0-9a-f]{12} now\)\)$/) })); + const tests = he515Merged({ 'test/x.test.ts': sevenTests({ 2: 2, 5: 50 }) }); + expect(tests.merge().status).toBe(0); + expect(freshness(tests.f)).toEqual(staleBecause('the branch\'s patch on a path the product patch-id leaves out (tests, release metadata) changed')); + }); + + test('uncommitted changes after the merge stay STALE', () => { + const { f, merge } = he515Merged(MAIN_MOVES); + expect(merge().status).toBe(0); + f.write({ 'docs/main.md': '# edited\n' }); + expect(freshness(f)).toEqual(staleBecause('the working tree has changes HEAD does not hold')); + }); + + test('a clean merge of a branch the base does not hold stays STALE', () => { + const { f } = he515Merged(MAIN_MOVES); + expect(f.git('checkout', '-q', '-b', 'side', 'origin/main').status).toBe(0); + f.write({ 'src/side.ts': 'export const side = 1;\n' }); f.commit('side'); + const side = f.git('rev-parse', 'HEAD').stdout.trim(); + expect(f.git('checkout', '-q', 'feat').status).toBe(0); + expect(f.git('merge', '-q', '--no-edit', 'side').status).toBe(0); + expect(freshness(f)).toEqual(staleBecause(`merge ${f.git('rev-parse', 'HEAD').stdout.trim().slice(0, 12)} brings in ${side.slice(0, 12)}, which origin/main does not hold`)); + }); + + test('a rebase onto the moved base stays STALE', () => { + const { f, head } = he515Merged(MAIN_MOVES); + expect(f.git('rebase', '-q', 'origin/main').status).toBe(0); + expect(freshness(f)).toEqual(staleBecause(`the reviewed commit ${head.slice(0, 12)} is not an ancestor of HEAD (rebased or force-pushed)`)); + }); +});