Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): stop the bug lane refusing a fix the stable already shipped (PRD-7941) (#3403)
Andrew Mikofalvy8ee5ed1b6473
diff --git a/.github/scripts/bug-lane-refusal-payload.mjs b/.github/scripts/bug-lane-refusal-payload.mjsindex 4a061d714..705e1e465 100644--- a/.github/scripts/bug-lane-refusal-payload.mjs+++ b/.github/scripts/bug-lane-refusal-payload.mjs@@ -169,6 +169,15 @@ export function classifyRefs(refs, gitShow) {* genuinely cannot ship from one that is only blocked by churn, without* opening the run.*/+/**+ * The classifier ran on this ref and found NO conflicting path.+ *+ * Deliberately `Array.isArray` and not `!r.files?.length`: the question is+ * whether classification happened and came back empty, which is a real and+ * reportable state, versus a caller that simply did not supply the field.+ */+const classifiedWithNoPaths = (r) => Array.isArray(r.files) && r.files.length === 0;+export function describeRefusal({ verdict, refs }) {if (verdict === 'fail') {return {@@ -184,6 +193,20 @@ export function describeRefusal({ verdict, refs }) {'Every collision is in a path that neither ships nor gates verification. The fix itself applies cleanly to the stable.',};}+ // No recorded conflicting path anywhere. The severe headline below asserts+ // "at least one collision carries behavior", and with zero paths there is no+ // collision to say that about — saying it anyway is how a pick that applied+ // EMPTY (the stable already had the fix) got reported as a fix that depends+ // on later work. The verify stage now routes empty picks away from here+ // entirely, so reaching this branch means the pick failed some third way;+ // report the uncertainty instead of inventing a cause for it.+ if (refs.length > 0 && refs.every(classifiedWithNoPaths)) {+ return {+ headline: 'Bug lane: the pick failed without a conflicting path',+ meaning:+ 'The cherry-pick exited non-zero but left no conflicting file, so its cause is not visible from here. Read the run log before concluding anything about the fix.',+ };+ }return {headline: 'Bug lane: the fix does not apply to the current stable',meaning:@@ -205,6 +228,12 @@ export function optionsFor({ verdict, refs }) {'The fixes ride their cycle’s stable. Forcing them past a red verification is not an option this lane offers.',];}+ if (refs.length > 0 && refs.every(classifiedWithNoPaths)) {+ return [+ 'Open the run log and read the cherry-pick output — the failure left no conflicting path, so the log is the only place the cause exists.',+ 'Do not hand-cut a point release off this page alone. Confirm what actually failed first; the fix may already be in the stable.',+ ];+ }const allInert = refs.length > 0 && refs.every((r) => r.inert);if (allInert) {return [@@ -227,6 +256,18 @@ function refLines(refs) {const tickets = (entry.tickets ?? []).join(', ');const label = [`\`${entry.ref.slice(0, 9)}\``, tickets && `(${tickets})`].filter(Boolean).join(' ');const shown = entry.files.slice(0, MAX_FILES_SHOWN);+ // "conflicted in 0 files:" followed by nothing is the shape that made a+ // page unreadable — it states a conflict and then lists no evidence for+ // it, while the line below cheerfully reports every file applying cleanly.+ // Say the actual fact instead.+ if (entry.files.length === 0) {+ const total = Number(entry.totalFiles);+ lines.push(+ `${label} — the pick failed but git reported no conflicting file` ++ `${Number.isFinite(total) && total > 0 ? `; all ${total} file${total === 1 ? '' : 's'} in the commit applied cleanly` : ''}.`,+ );+ continue;+ }lines.push(`${label} — conflicted in ${entry.files.length} file${entry.files.length === 1 ? '' : 's'}:`,);diff --git a/.github/scripts/bug-lane-refusal-payload.test.mjs b/.github/scripts/bug-lane-refusal-payload.test.mjsindex 967c93d55..e62a3f22c 100644--- a/.github/scripts/bug-lane-refusal-payload.test.mjs+++ b/.github/scripts/bug-lane-refusal-payload.test.mjs@@ -157,15 +157,25 @@ describe('classifyRefs', () => {});describe('describeRefusal', () => {- const inert = [{ ref: 'a', inert: true, files: [] }];- const behavioral = [{ ref: 'a', inert: false, files: [] }];+ // Production-shaped. `classifyRefs` derives `inert` as+ // `files.length > 0 && files.every(...)`, so a ref carrying the flag ALWAYS+ // carries the paths it was derived from; an empty `files` is a distinct+ // state (the pick failed without conflicting) and gets its own class below.+ const inert = [+ { ref: 'a', inert: true, files: [{ path: 'packages/app/package.json', inert: true, detail: 'test:e2e only' }] },+ ];+ const behavioral = [+ { ref: 'a', inert: false, files: [{ path: 'packages/server/src/boot.ts', inert: false, detail: 'carries behavior' }] },+ ];+ const noPaths = [{ ref: 'a', inert: false, totalFiles: 37, files: [] }];- test('the three refusal classes read differently at a glance', () => {+ test('the four refusal classes read differently at a glance', () => {const h = (args) => describeRefusal(args).headline;const drift = h({ verdict: 'conflict', refs: inert });const real = h({ verdict: 'conflict', refs: behavioral });const red = h({ verdict: 'fail', refs: [] });- expect(new Set([drift, real, red]).size).toBe(3);+ const unknown = h({ verdict: 'conflict', refs: noPaths });+ expect(new Set([drift, real, red, unknown]).size).toBe(4);expect(drift).toMatch(/config drift, not by the fix/);expect(real).toMatch(/does not apply/);});@@ -175,21 +185,53 @@ describe('describeRefusal', () => {/does not apply/,);});++ // The shape that shipped a false alarm: a pick that applied EMPTY because+ // the stable already contained the fix exited non-zero with no conflicting+ // path, and the severe branch asserted a behavior-carrying collision it had+ // no evidence for — telling the reader the fix depended on later work when+ // it was already released.+ test('no recorded conflicting path never claims a behavior-carrying collision', () => {+ const { headline, meaning } = describeRefusal({ verdict: 'conflict', refs: noPaths });+ expect(headline).not.toMatch(/does not apply to the current stable/);+ expect(meaning).not.toMatch(/carries behavior/);+ expect(meaning).toMatch(/no conflicting file/);+ });++ // A batch where one ref genuinely collided must still report the severe+ // case; the no-path class is only for a batch with no evidence at all.+ test('a mixed batch with real paths keeps the severe headline', () => {+ expect(describeRefusal({ verdict: 'conflict', refs: [...noPaths, ...behavioral] }).headline).toMatch(+ /does not apply/,+ );+ });});describe('optionsFor', () => {+ const withPath = (inertFlag) => [+ { ref: 'x', inert: inertFlag, files: [{ path: 'p/package.json', inert: inertFlag, detail: 'd' }] },+ ];+test('the inert case never points at resolve_paths, which would refuse', () => {- const opts = optionsFor({ verdict: 'conflict', refs: [{ ref: 'a', inert: true, files: [] }] });+ const opts = optionsFor({ verdict: 'conflict', refs: withPath(true) });expect(opts.join('\n')).not.toMatch(/-f resolve_paths=/);expect(opts.join('\n')).toMatch(/allowlist is code/);});test('inert and behavioral give different advice', () => {- const a = optionsFor({ verdict: 'conflict', refs: [{ ref: 'x', inert: true, files: [] }] });- const b = optionsFor({ verdict: 'conflict', refs: [{ ref: 'x', inert: false, files: [] }] });+ const a = optionsFor({ verdict: 'conflict', refs: withPath(true) });+ const b = optionsFor({ verdict: 'conflict', refs: withPath(false) });expect(a).not.toEqual(b);expect(b.join('\n')).toMatch(/smaller self-contained commit/);});++ // Without evidence the advice must not send someone to hand-cut a release:+ // the likeliest cause of a pathless failure is that the fix already shipped.+ test('no recorded path sends the reader to the log, not to a hand-cut release', () => {+ const opts = optionsFor({ verdict: 'conflict', refs: [{ ref: 'x', inert: false, files: [] }] }).join('\n');+ expect(opts).not.toMatch(/smaller self-contained commit/);+ expect(opts).toMatch(/run log/);+ });});describe('buildSlackPayload', () => {@@ -216,6 +258,25 @@ describe('buildSlackPayload', () => {expect(body).toContain('27 other files in the commit applied cleanly');});+ // The verbatim shape of the page that went out for PRD-7310 over v0.50.2:+ // 37 files, none conflicting, because the stable already shipped the fix.+ // It rendered "conflicted in 0 files:" with nothing under it, immediately+ // followed by "37 other files applied cleanly" — a stated conflict with no+ // evidence, contradicted by its own next line.+ test('a pathless failure renders no empty conflict list and no phantom count', () => {+ const body = buildSlackPayload({+ verdict: 'conflict',+ stable: 'v0.50.2',+ refs: [{ ref: '4cef9c5a587dc26ea4bcb5fe2ab134a1fa8ec00d', tickets: ['PRD-7310'], totalFiles: 37, inert: false, files: [] }],+ runUrl: '',+ }).blocks[1].text.text;+ expect(body).not.toContain('conflicted in 0 files');+ expect(body).not.toContain('37 other files');+ expect(body).toContain('PRD-7310');+ expect(body).toContain('no conflicting file');+ expect(body).toContain('all 37 files in the commit applied cleanly');+ });+test('keeps the silence-is-deliberate note', () => {const body = buildSlackPayload({ verdict: 'conflict', stable: 'v1', refs, runUrl: '' }).blocks[1].text.text;@@ -293,6 +354,30 @@ describe('workflow wiring', () => {expect(step('Page on a refusal')).toContain('bug-lane-refusal-payload.mjs');});+ // A pick onto a stable that already contains the fix exits non-zero with no+ // conflicting path. Treated as a conflict it pages a refusal claiming the+ // fix depends on later work — the opposite of the truth — so it must be+ // classified BEFORE the conflict bookkeeping runs.+ test('the verify step separates an empty pick from a conflict', () => {+ const verify = shellOf('Verify the synthetic tree');+ const emptyGuard = verify.indexOf('git diff --quiet HEAD');+ const recordConflict = verify.indexOf('CONFLICT_JSON=$(jq');+ expect(emptyGuard).toBeGreaterThan(-1);+ expect(recordConflict).toBeGreaterThan(-1);+ expect(emptyGuard).toBeLessThan(recordConflict);+ expect(verify).toContain('already-in-stable');+ });++ // The guarantee the whole change rests on: an all-already tick is silent+ // BY CONSTRUCTION, because the paging chain only ever fires on the two+ // verdicts that represent a real question for a human.+ test('only conflict and fail can reach the pager', () => {+ const gate = step('Refusal signature');+ const verdicts = [...gate.matchAll(/verdict == '([a-z-]+)'/g)].map((m) => m[1]);+ expect(new Set(verdicts)).toEqual(new Set(['conflict', 'fail']));+ expect(verdicts).not.toContain('already-in-stable');+ });+// `${V:-{\}}` expands to a LITERAL `{\}` — a brace in a parameter-expansion// default is not escapable there. jq --argjson then refuses, and the enriched// page degrades to the plain fallback on every single run, with nothing indiff --git a/.github/scripts/bug-lane.mjs b/.github/scripts/bug-lane.mjsindex 945f07001..e5151f1b2 100644--- a/.github/scripts/bug-lane.mjs+++ b/.github/scripts/bug-lane.mjs@@ -206,6 +206,52 @@ function realNewestStableTag() {return null;}+/**+ * Is this commit's change already in the stable?+ *+ * Asked by CONTENT, not by lineage. A stable is cut by cherry-picking onto the+ * previous stable, so the shipped copy of a fix is a DIFFERENT commit than the+ * one on main and no ancestry test can see it. Asking only the lineage+ * question re-qualifies a fix the lane itself just released; the pick then+ * lands empty, which downstream reads as a conflict and pages a refusal saying+ * the fix depends on later work — the exact opposite of the truth.+ *+ * Exported as a factory, like the resolver boundaries beside it, so the git+ * behavior is exercised against a real repository rather than asserted about.+ */+export function makeIsInStable(stable, git = (args) => spawnSync('git', args, { encoding: 'utf8', env: gitCleanEnv() })) {+ return (sha) => {+ // Ancestry first: exact, cheap, and the common case for a fix that has not+ // been released yet. Three-way, matching the sibling selectors: exit 0 is+ // contained, exit 1 a clean miss, anything else an infrastructure failure+ // that must not read as "not contained" — the pure core degrades that+ // commit with a containment-error warning instead.+ const ancestry = git(['merge-base', '--is-ancestor', sha, stable]);+ if (ancestry.status === 0) return true;+ if (ancestry.status !== 1) {+ throw new Error(+ `git merge-base --is-ancestor ${sha} ${stable} failed (exit ${ancestry.status}): ${ancestry.error?.message ?? String(ancestry.stderr || '').trim()}`,+ );+ }+ // `git cherry <upstream> <head> <limit>` restricted to this one commit: it+ // prints "- <sha>" when an equivalent patch is already upstream and+ // "+ <sha>" when it is not. This is git's own duplicate detection, the+ // same equivalence rebase uses to drop already-applied commits.+ //+ // A failure here is deliberately NOT rethrown. Ancestry has already+ // answered "no", so falling through returns exactly what this function+ // returned before patch-equivalence existed — never a regression — and the+ // verify stage's empty-pick guard still catches whatever slips past.+ // Throwing would turn a rare git hiccup into a containment-error that+ // disqualifies a genuinely shippable fix.+ const equivalent = git(['cherry', stable, sha, `${sha}^`]);+ if (equivalent.status !== 0) return false;+ return String(equivalent.stdout || '')+ .trimStart()+ .startsWith('-');+ };+}+/*** The pending pile at HEAD, oldest adding commit first so the cherry-pick* batch replays in merge order. `%x1f` keeps subjects with any character out@@ -249,21 +295,7 @@ async function main() {const result = await evaluateBugLane({pendingChangesets: realPendingChangesets(),- // Three-way, matching the sibling selectors: exit 0 is contained, exit 1 a- // clean miss, anything else an infrastructure failure that must not read- // as "not contained" — the pure core degrades that commit with a- // containment-error warning instead.- isInStable: (sha) => {- const res = spawnSync('git', ['merge-base', '--is-ancestor', sha, stable], {- encoding: 'utf8',- env: gitCleanEnv(),- });- if (res.status === 0) return true;- if (res.status === 1) return false;- throw new Error(- `git merge-base --is-ancestor ${sha} ${stable} failed (exit ${res.status}): ${res.error?.message ?? String(res.stderr || '').trim()}`,- );- },+ isInStable: makeIsInStable(stable),resolveChangesetPrUrl: makeResolveChangesetPrUrl(process.env.LINK_REPO || DEFAULT_LINK_REPO),resolveIssuesForUrl: makeResolveIssuesForUrl(process.env.LINEAR_API_KEY),});diff --git a/.github/scripts/bug-lane.test.mjs b/.github/scripts/bug-lane.test.mjsindex cf22b3061..1df95cc25 100644--- a/.github/scripts/bug-lane.test.mjs+++ b/.github/scripts/bug-lane.test.mjs@@ -1,5 +1,10 @@-import { describe, expect, test } from 'vitest';-import { evaluateBugLane } from './bug-lane.mjs';+import { execFileSync, spawnSync } from 'node:child_process';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterAll, beforeAll, describe, expect, test } from 'vitest';+import { gitCleanEnv } from '../../scripts/git-clean-env.mjs';+import { evaluateBugLane, makeIsInStable } from './bug-lane.mjs';const FIX_A = 'a'.repeat(40);const FIX_B = 'b'.repeat(40);@@ -129,3 +134,103 @@ describe('evaluateBugLane', () => {expect(r2.fixRefs).toEqual([]);});});++/**+ * The real git boundary, against a repository shaped like production.+ *+ * A stable is not a prefix of main: it is cut by cherry-picking fixes onto the+ * previous stable, so the shipped copy of a fix is a different commit object+ * with a different SHA. An ancestry-only containment test cannot see it, which+ * is what let the lane re-qualify a fix it had already released and then page+ * a refusal saying that fix depended on later work.+ */+describe('makeIsInStable', () => {+ let dir;+ let fixOnMain;+ let laterOnMain;++ // `gitCleanEnv()` is mandatory, not tidiness: these tests run under the+ // pre-push hook, and an unscrubbed `git init` there inherits GIT_DIR from+ // the push and flips core.bare on the SHARED config when the push comes from+ // a linked worktree.+ const git = (...args) =>+ execFileSync('git', args, { cwd: dir, encoding: 'utf8', env: gitCleanEnv() }).trim();+ /** The injected boundary, bound to the fixture repo. */+ const inRepo = (args) => spawnSync('git', args, { cwd: dir, encoding: 'utf8', env: gitCleanEnv() });++ beforeAll(() => {+ dir = mkdtempSync(join(tmpdir(), 'ok-bug-lane-containment-'));+ git('init', '--initial-branch=main', '--quiet');+ git('config', 'user.email', 't@t');+ git('config', 'user.name', 't');+ git('config', 'commit.gpgsign', 'false');++ writeFileSync(join(dir, 'base.txt'), 'base\n');+ git('add', '-A');+ git('commit', '-m', 'base', '--quiet');+ const base = git('rev-parse', 'HEAD');++ // main: base -> fix -> later+ writeFileSync(join(dir, 'fix.txt'), 'the fix\n');+ git('add', '-A');+ git('commit', '-m', 'fix: the bug', '--quiet');+ fixOnMain = git('rev-parse', 'HEAD');++ writeFileSync(join(dir, 'later.txt'), 'later feature\n');+ git('add', '-A');+ git('commit', '-m', 'feat: later', '--quiet');+ laterOnMain = git('rev-parse', 'HEAD');++ // stable: base -> prior point release -> fix'+ //+ // The prior commit is load-bearing, not scenery. Cherry-picking straight+ // onto `base` would give the copy the same parent, tree, message, author+ // and (within the same second) timestamp as the original — so git hashes+ // it to the SAME object and the fixture stops reproducing anything. A real+ // stable always carries earlier point releases, so this is also the+ // faithful shape, and it makes the distinct SHA a structural guarantee+ // rather than a matter of how fast the suite happens to run.+ git('checkout', '--quiet', '-b', 'stable', base);+ writeFileSync(join(dir, 'prior.txt'), 'earlier point release\n');+ git('add', '-A');+ git('commit', '-m', 'fix: an earlier point release', '--quiet');+ git('cherry-pick', fixOnMain);+ git('tag', 'v1.0.0');+ git('checkout', '--quiet', 'main');+ });++ afterAll(() => rmSync(dir, { recursive: true, force: true }));++ test('the cherry-picked copy on the stable is NOT an ancestor of it', () => {+ // Guards the premise: were this ever false the fixture would have stopped+ // reproducing the production topology, and the test below would pass for+ // the wrong reason.+ expect(git('rev-parse', 'v1.0.0')).not.toBe(fixOnMain);+ expect(inRepo(['merge-base', '--is-ancestor', fixOnMain, 'v1.0.0']).status).toBe(1);+ });++ test('a fix already released into the stable reads as contained', () => {+ expect(makeIsInStable('v1.0.0', inRepo)(fixOnMain)).toBe(true);+ });++ test('a commit the stable does not carry reads as not contained', () => {+ expect(makeIsInStable('v1.0.0', inRepo)(laterOnMain)).toBe(false);+ });++ test('a genuine ancestor still reads as contained', () => {+ expect(makeIsInStable('v1.0.0', inRepo)(git('rev-parse', 'v1.0.0^'))).toBe(true);+ });++ // Ancestry has already answered "no" by then, so a failing equivalence probe+ // must degrade to that answer rather than disqualifying the commit outright.+ test('an equivalence probe that fails degrades to not-contained, not an error', () => {+ const flaky = (args) =>+ args[0] === 'cherry' ? { status: 128, stdout: '', stderr: 'boom' } : inRepo(args);+ expect(makeIsInStable('v1.0.0', flaky)(laterOnMain)).toBe(false);+ });++ test('an ancestry probe that fails is still an infrastructure error', () => {+ const broken = () => ({ status: 128, stdout: '', stderr: 'not a git repository' });+ expect(() => makeIsInStable('v1.0.0', broken)(laterOnMain)).toThrow(/merge-base/);+ });+});diff --git a/.github/workflows/bug-lane.yml b/.github/workflows/bug-lane.ymlindex 39bea9b49..63d7dc463 100644--- a/.github/workflows/bug-lane.yml+++ b/.github/workflows/bug-lane.yml@@ -146,6 +146,10 @@ jobs:# later work from one blocked by an unrelated rewrite of a line of CI# config, and that is the whole question a reader has.CONFLICT_JSON='[]'+ # Refs whose pick landed empty: the stable already contains the+ # change. Not survivors (committing one would re-release), and+ # emphatically not conflicts.+ ALREADY=()for ref in "${REFS[@]}"; doif git cherry-pick "$ref"; thenSURVIVORS+=("$ref")@@ -158,6 +162,26 @@ jobs:while IFS= read -r f; do[[ -n "$f" ]] && CONFLICTED+=("$f")done < <(git diff --name-only --diff-filter=U || true)+ # An EMPTY pick, not a conflict. git exits non-zero for both, but+ # empty means every hunk was already present — the stable already+ # ships this fix under a different SHA, which is how every point+ # release lands. Zero unmerged paths AND a tree identical to HEAD+ # is the signature; a real conflict leaves unmerged paths, and a+ # partial application leaves a dirty tree.+ #+ # Reporting this as a conflict is what made a shipped fix page as+ # "does not apply to the current stable": the refusal carried no+ # conflicting path, and the payload builder fails closed to the+ # severe wording when it has no paths to judge. The containment+ # pre-filter should have caught this upstream; this is the+ # backstop that makes the silence a guarantee rather than a+ # consequence of that filter being right.+ if [[ ${#CONFLICTED[@]} -eq 0 ]] && git diff --quiet HEAD; then+ git cherry-pick --abort || true+ ALREADY+=("$ref")+ echo "::notice::bug-lane: ${ref} is already contained in ${STABLE} (the pick applies empty); skipped — nothing left to ship, and nothing to report."+ continue+ fiTOTAL_FILES=$(git show --pretty=format: --name-only "$ref" | grep -c . || true)# `${a[@]+"${a[@]}"}` so an empty array is not an unbound-variable# error under `set -u`: a pick can fail without conflicting (an@@ -180,7 +204,27 @@ jobs:if [[ ${#DROPPED[@]} -gt 0 ]]; thenecho "dropped_refs=$(IFS=','; echo "${DROPPED[*]}")" >> "$GITHUB_OUTPUT"fi+ if [[ ${#ALREADY[@]} -gt 0 ]]; then+ echo "already_refs=$(IFS=','; echo "${ALREADY[*]}")" >> "$GITHUB_OUTPUT"+ fiif [[ ${#SURVIVORS[@]} -eq 0 ]]; then+ # Nothing survived AND nothing genuinely conflicted: every candidate+ # was already in the stable. That is a no-op tick, not a refusal —+ # there is no question for a human and therefore no message. A+ # distinct verdict rather than reusing "conflict" is the whole+ # point: the paging steps gate on conflict/fail, so this is silent+ # by construction instead of by a suppression rule someone could+ # later relax. Visible in the run summary for anyone who looks.+ if [[ ${#DROPPED[@]} -eq 0 ]]; then+ echo "verdict=already-in-stable" >> "$GITHUB_OUTPUT"+ echo "::notice::bug-lane: every qualifying fix is already contained in ${STABLE}; nothing to ship, nothing to page."+ {+ echo "### Bug lane — already in the stable"+ echo "Every qualifying fix is already contained in \`${STABLE}\`: ${ALREADY[*]}."+ echo "The picks apply empty, so there is nothing left to release. No page — this is a no-op tick, not a refusal."+ } >> "$GITHUB_STEP_SUMMARY"+ exit 0+ fiecho "verdict=conflict" >> "$GITHUB_OUTPUT"echo "::notice::bug-lane: no qualifying fix is self-contained over ${STABLE}; nothing ships this tick."exit 0