Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): let point release ship dependency-patch fixes (PRD-7749) (#3138)
Andrew Mikofalvy8c126bfa13d3
diff --git a/.github/scripts/point-release-plan.mjs b/.github/scripts/point-release-plan.mjsindex 4a6a63151..fb8e500a5 100644--- a/.github/scripts/point-release-plan.mjs+++ b/.github/scripts/point-release-plan.mjs@@ -18,7 +18,7 @@* rather than that "the point release failed".*/import { spawnSync } from 'node:child_process';-import { appendFileSync } from 'node:fs';+import { appendFileSync, readFileSync, writeFileSync } from 'node:fs';import { pathToFileURL } from 'node:url';import {computePointReleaseVersion,@@ -108,6 +108,371 @@ function splitList(raw) {return items;}+/**+ * Split the operator's `resolve_paths` input into paths.+ *+ * Empty by default and empty for every automated dispatch, so the lane's+ * behavior on an unexpected conflict is unchanged: hard fail. Authorizing a+ * path is a deliberate, per-run operator act.+ */+export function parseResolvePaths(raw) {+ return splitList(raw);+}++/**+ * Config paths whose merge conflict MAY be resolved instead of refused, each+ * paired with the coherence check its resolution must survive.+ *+ * The allowlist is deliberately one entry. A fix delivered as a pnpm dependency+ * patch has to register itself in `pnpm-workspace.yaml`, and the registration+ * blocks there are dense: every entry sits within three lines of every other,+ * so any unrelated registration landing between the last stable and the fix+ * puts the fix's own line inside a rewritten hunk. That is an artifact of+ * diffing an unordered mapping by line, not evidence that the fix depends on+ * anything in between. `pnpm-lock.yaml` has the same churn but is not on this+ * list and does not need to be: it is enormous and sorted, so unrelated entries+ * are thousands of lines away and merge cleanly on their own. A conflict there+ * is a real signal and keeps refusing.+ *+ * Nothing that carries behavior is eligible. Source, workflows, and patch+ * contents are never resolvable, at any input.+ */+const RESOLVABLE_PATH_VERIFIERS = Object.freeze({+ 'pnpm-workspace.yaml': verifyWorkspaceMatchesLockfile,+});++export const RESOLVABLE_PATHS = Object.freeze(Object.keys(RESOLVABLE_PATH_VERIFIERS));++/**+ * Does the operator's `resolve_paths` input name only allowlisted paths?+ *+ * Checked before the tree is touched, so a typo or an over-broad input refuses+ * in a second rather than after a pick. The allowlist is the security boundary+ * here: without it the input is a general "resolve my conflicts" switch aimed+ * at whatever the operator types, which is exactly the escape hatch this lane+ * must not grow.+ */+export function guardResolvePathsAllowlisted({ resolvePaths }) {+ const offenders = resolvePaths.filter((p) => !RESOLVABLE_PATHS.includes(p));+ if (offenders.length > 0) {+ return refuse(+ 'resolve-path-not-allowlisted',+ `Not resolvable: ${offenders.join(', ')}. Only ${RESOLVABLE_PATHS.join(', ')} may be resolved, because ` ++ 'only their conflicts can be re-derived as entry-level changes and checked afterwards. A conflict ' ++ 'anywhere else means the fix depends on something between the last stable and now, and still refuses.',+ );+ }+ return pass(+ resolvePaths.length === 0+ ? 'No conflict resolution authorized; any conflict hard-fails.'+ : `Conflict resolution authorized for: ${resolvePaths.join(', ')}.`,+ );+}++const indentOf = (line) => line.length - line.trimStart().length;+const isBlank = (line) => line.trim() === '';++/**+ * The key an entry line declares, or null when the line is not a mapping entry.+ *+ * Quoted keys are read to their closing quote rather than to the first colon,+ * since the keys in these files are package specs that may contain one.+ */+function entryKey(line) {+ const body = line.trim();+ if (body === '' || body.startsWith('#') || body.startsWith('-')) return null;+ const quote = body[0];+ if (quote === "'" || quote === '"') {+ const close = body.indexOf(quote, 1);+ if (close < 0) return null;+ if (body[close + 1] !== ':') return null;+ return body.slice(1, close);+ }+ const colon = body.indexOf(':');+ if (colon <= 0) return null;+ return body.slice(0, colon);+}++/**+ * The mapping block a header line opens: where it ends, at what indentation its+ * entries sit, and the entries themselves — as `keys` for membership, and as an+ * `entries` key-to-value map for the comparisons that care what each assigns.+ *+ * A block runs from just after its header to the first non-blank line indented+ * no deeper than the header. `end` excludes the trailing blank lines so an+ * insertion lands against the last entry rather than after a paragraph break.+ *+ * This is a line scanner, not a YAML parser, and deliberately so: the workflow+ * runs `node` against a bare checkout with no dependency install, so there is+ * no parser to reach for. It therefore understands only the shape these two+ * files actually use — one key per line, a single-line value, one level of+ * nesting beneath an entry — and everything outside it reads as an entry with+ * no value, which fails the comparisons closed rather than passing something+ * unread. A new pnpm output shape is a refusal, not a silent misread.+ */+export function readBlock(lines, headerIndex) {+ const headerIndent = indentOf(lines[headerIndex]);+ let end = headerIndex + 1;+ while (end < lines.length && (isBlank(lines[end]) || indentOf(lines[end]) > headerIndent)) end++;+ while (end > headerIndex + 1 && isBlank(lines[end - 1])) end--;++ let entryIndent = null;+ for (let i = headerIndex + 1; i < end; i++) {+ if (isBlank(lines[i]) || entryKey(lines[i]) === null) continue;+ if (entryIndent === null || indentOf(lines[i]) < entryIndent) entryIndent = indentOf(lines[i]);+ }++ const entries = new Map();+ for (let i = headerIndex + 1; i < end; i++) {+ if (isBlank(lines[i]) || indentOf(lines[i]) !== entryIndent) continue;+ const key = entryKey(lines[i]);+ if (key !== null) entries.set(key, entryValue(lines[i]));+ }+ return { headerIndex, headerIndent, entryIndent, end, keys: new Set(entries.keys()), entries };+}++/**+ * What an entry line assigns, normalized.+ *+ * Quoting is not meaningful here and is not consistent across the two files+ * that get compared — the same override reads `"@types/node": ^24.7.0` in one+ * and `'@types/node': ^24.7.0` in the other — so surrounding quotes come off+ * both sides rather than reading as a difference. An entry that opens a nested+ * mapping assigns nothing and reads as empty.+ */+function entryValue(line) {+ const body = line.trim();+ const key = entryKey(line);+ if (key === null) return '';+ const after = body.slice(body.indexOf(':', body.indexOf(key) + key.length) + 1).trim();+ const quote = after[0];+ if ((quote === "'" || quote === '"') && after.endsWith(quote) && after.length > 1) {+ return after.slice(1, -1);+ }+ return after;+}++/** Every entry declared directly under a top-level mapping, or null when absent. */+export function readTopLevelBlockEntries(text, header) {+ const lines = String(text).split('\n');+ const headerIndex = lines.findIndex((line) => line === `${header}:`);+ if (headerIndex < 0) return null;+ return readBlock(lines, headerIndex).entries;+}++function refuseResolution(message) {+ throw new PointReleaseRefusal('resolve-not-derivable', message);+}++/**+ * Re-derive the fix's own change to a config file as an entry-level edit of the+ * last stable's copy of it, rather than as the textual hunk git could not place.+ *+ * The result is the stable file with exactly the entries the fix added added,+ * and exactly the entries it removed removed. That is the only resolution that+ * is correct, and the reason is concrete rather than aesthetic: taking the+ * fix's copy of the file wholesale adopts entries the synthetic tree cannot+ * honor (a patch registration whose `.patch` file is not in the tree, an+ * override the lockfile never resolved), and keeping the stable's copy+ * wholesale drops the fix's own entry while the lockfile keeps it. Both+ * produce a tree that cannot install; only the entry-level union matches the+ * lockfile git already merged cleanly beside it.+ *+ * Every step that cannot be re-derived unambiguously refuses. A modified entry,+ * an added line that is not a mapping entry, a block whose header is not in the+ * stable file, a line that does not appear exactly where it is expected to:+ * each of those is a real disagreement between the fix and the stable, and this+ * function is only allowed to handle the case where there is none.+ */+export function deriveEntryLevelResolution({ base, fixBefore, fixAfter }) {+ const baseLines = String(base).split('\n');+ const beforeLines = String(fixBefore).split('\n');+ const afterLines = String(fixAfter).split('\n');++ const beforeSet = new Set(beforeLines);+ const afterSet = new Set(afterLines);+ const added = afterLines.filter((line) => !isBlank(line) && !beforeSet.has(line));+ const removed = beforeLines.filter((line) => !isBlank(line) && !afterSet.has(line));++ if (added.length === 0 && removed.length === 0) {+ refuseResolution(+ 'The fix makes no line-level change to this file, so the conflict does not come from the fix. ' ++ 'Nothing can be re-derived.',+ );+ }++ const count = (lines, needle) => lines.reduce((n, line) => n + (line === needle ? 1 : 0), 0);+ const resolved = [...baseLines];++ // Removals first: they are matched against the stable file as it stands, and+ // doing them after an insertion would let a just-added line satisfy one.+ for (const line of removed) {+ if (count(resolved, line) !== 1) {+ refuseResolution(+ `The fix removes a line that does not appear exactly once in the last stable: ${line.trim()}. ` ++ 'The stable has already diverged on that entry.',+ );+ }+ resolved.splice(resolved.indexOf(line), 1);+ }++ // Group the additions by the block they belong to, in the order the fix wrote+ // them. Only mapping entries qualify: a comment or a sequence item has no key+ // to place it by, so a fix that adds one refuses here rather than having this+ // code guess what it was attached to.+ const pending = new Map();+ for (const line of added) {+ const key = entryKey(line);+ if (key === null || indentOf(line) === 0) {+ refuseResolution(+ `The fix adds a line that is not an indented mapping entry: ${line.trim()}. Only entries inside an ` ++ 'existing block can be re-derived; anything else changes the file structure.',+ );+ }+ if (count(afterLines, line) !== 1 || count(resolved, line) !== 0) {+ refuseResolution(+ `The fix's added line is ambiguous against the last stable: ${line.trim()}. It must be unique in the ` ++ 'fix and absent from the stable.',+ );+ }++ const at = afterLines.indexOf(line);+ let headerIndex = -1;+ for (let i = at - 1; i >= 0; i--) {+ if (isBlank(afterLines[i]) || indentOf(afterLines[i]) >= indentOf(line)) continue;+ headerIndex = i;+ break;+ }+ if (headerIndex < 0) {+ refuseResolution(`The fix's added line sits in no enclosing block: ${line.trim()}.`);+ }+ const header = afterLines[headerIndex];+ if (count(resolved, header) !== 1) {+ refuseResolution(+ `The block this entry belongs to is not in the last stable, or is not unique there: ${header.trim()}. ` ++ 'There is nowhere unambiguous to place the entry.',+ );+ }+ if (readBlock(resolved, resolved.indexOf(header)).keys.has(key)) {+ refuseResolution(+ `The last stable already declares '${key}' in ${header.trim()} with a different value, so the fix ` ++ 'CHANGES that entry rather than adding one. Re-deriving would silently pick a side.',+ );+ }+ if (!pending.has(header)) pending.set(header, []);+ pending.get(header).push(line);+ }++ // Append rather than sort into place: appending is inside the right block by+ // construction, and where an entry sits in an unordered mapping carries no+ // meaning. Guessing a sorted position would, since the stable's block need+ // not be sorted at all.+ for (const [header, entries] of pending) {+ // Located afresh per block, so an insertion into an earlier one does not+ // leave a later block's index stale.+ const block = readBlock(resolved, resolved.indexOf(header));+ resolved.splice(block.end, 0, ...entries);+ }++ // The transform claimed above, asserted rather than trusted. Anything that+ // reordered, duplicated or dropped a line the fix did not name shows up here.+ const ok =+ resolved.length === baseLines.length + added.length - removed.length &&+ sameSet(diffLines(resolved, baseLines), added) &&+ sameSet(diffLines(baseLines, resolved), removed) &&+ isSubsequence(+ baseLines.filter((line) => !removed.includes(line)),+ resolved,+ );+ if (!ok) {+ throw new PointReleaseRefusal(+ 'resolve-incoherent',+ 'The re-derived file is not the last stable plus exactly the entries the fix added, minus exactly the ' ++ 'entries it removed. Refusing rather than shipping a tree nobody wrote.',+ );+ }++ return { resolved: resolved.join('\n'), added, removed };+}++const diffLines = (from, to) => {+ const other = new Set(to);+ return from.filter((line) => !isBlank(line) && !other.has(line));+};+const sameSet = (a, b) => a.length === b.length && a.every((line) => b.includes(line));++function isSubsequence(needles, haystack) {+ let at = 0;+ for (const needle of needles) {+ at = haystack.indexOf(needle, at);+ if (at < 0) return false;+ at++;+ }+ return true;+}++/**+ * The workspace-file blocks the lockfile mirrors, and how far each is+ * comparable.+ *+ * pnpm hard-fails a frozen install when EITHER of these disagrees between the+ * two files, and the failure text names the block. Checking only one of them+ * would leave a re-derivation of the other verified by a comparison that+ * passes vacuously, since an untouched block trivially matches.+ */+const LOCKFILE_MIRRORED_BLOCKS = Object.freeze([+ // The workspace file assigns a patch PATH; the lockfile opens a nested+ // hash + path mapping. Only the key sets are comparable.+ { block: 'patchedDependencies', compareValues: false },+ // Both assign the same version spec, and a spec that disagrees fails a frozen+ // install exactly as hard as a missing key.+ { block: 'overrides', compareValues: true },+]);++/**+ * Does the re-derived workspace file still agree with the lockfile beside it?+ *+ * The lockfile is an independent arbiter: git merged it on its own, from the+ * same two sides, so it says what the resolution should have been without this+ * code having any say. Both of the resolutions this lane refuses to perform are+ * caught by exactly this comparison, and so is a derivation bug.+ *+ * Without it the failure surfaces as ERR_PNPM_LOCKFILE_CONFIG_MISMATCH in the+ * publish job, after the tag and the Release already exist.+ *+ * Fails closed. An unreadable lockfile is not agreement.+ */+export function verifyWorkspaceMatchesLockfile({ resolved, readWorktreeFile }) {+ const lockfile = readWorktreeFile('pnpm-lock.yaml');+ const notes = [];+ for (const { block, compareValues } of LOCKFILE_MIRRORED_BLOCKS) {+ const inWorkspace = readTopLevelBlockEntries(resolved, block) ?? new Map();+ const inLockfile = readTopLevelBlockEntries(lockfile, block) ?? new Map();+ const render = (entries) =>+ [...entries]+ .map(([key, value]) => (compareValues ? `${key}: ${value}` : key))+ .sort()+ .join('\n');+ const left = render(inWorkspace);+ const right = render(inLockfile);+ if (left !== right) {+ const only = (a, b) =>+ [...a]+ .filter(([key, value]) => !b.has(key) || (compareValues && b.get(key) !== value))+ .map(([key, value]) => (compareValues ? `${key}: ${value}` : key));+ throw new PointReleaseRefusal(+ 'resolve-incoherent',+ `The re-derived pnpm-workspace.yaml disagrees with the merged pnpm-lock.yaml on '${block}'. Only in the ` ++ `workspace file: [${only(inWorkspace, inLockfile).join(', ') || 'none'}]. Only in the lockfile: ` ++ `[${only(inLockfile, inWorkspace).join(', ') || 'none'}]. A frozen install refuses on that mismatch, ` ++ 'which would fail the publish after the tag already exists.',+ );+ }+ notes.push(`${block} (${inWorkspace.size})`);+ }+ return `agrees with the lockfile on ${notes.join(' and ')}.`;+}+/*** Is every fix ref already contained in the public repo's `main`?*@@ -325,8 +690,10 @@ function checkGuard(trail, verdict) {** io.readAnchorVersion() -> 'X.Y.Z' changeset anchor in the checked-out tree* io.git.newestStableTag / revParse / isOnMain / tagExists / isAncestor /- * changesetIds / bumpTypeOf (read-only)- * io.git.checkoutDetached / cherryPick / revert / headSha (local only)+ * changesetIds / bumpTypeOf / conflictedPaths / fileAt (read-only)+ * io.git.checkoutDetached / cherryPick / revert / stage /+ * continueApply / headSha (local only)+ * io.fs.readWorktreeFile / writeWorktreeFile (local only)* io.git.tag / pushTag (REMOTE)* io.gh.newestNativeConfigPrebuildHeadSha (read-only)* io.gh.createRelease / dispatch (REMOTE)@@ -345,8 +712,16 @@ function checkGuard(trail, verdict) {* when a precondition says no, a plain Error when the boundary itself failed.*/export function runPointRelease(opts, io) {- const { mode, fixRefs, anchorDeltaIds, dryRun = true, dispatchedBy = '', selfRepo = '', bridgeConfigured = true } =- opts;+ const {+ mode,+ fixRefs,+ anchorDeltaIds,+ resolvePaths = [],+ dryRun = true,+ dispatchedBy = '',+ selfRepo = '',+ bridgeConfigured = true,+ } = opts;if (mode !== 'cherry-pick' && mode !== 'revert') {throw new Error(`Point-release mode '${mode}' is not one of: cherry-pick, revert.`);@@ -366,18 +741,35 @@ export function runPointRelease(opts, io) {checkGuard(guards, guardAnchor({ anchorVersion: io.readAnchorVersion(), latestStableTag }));checkGuard(guards, guardRefsOnMain({ fixRefs, isOnMain: io.git.isOnMain }));+ checkGuard(guards, guardResolvePathsAllowlisted({ resolvePaths }));const resolvedRefs = fixRefs.map((ref) => ({ ref, sha: io.git.revParse(ref), onMain: true }));// Build the synthetic commit. Detaching first is what keeps the pile out of// the release: the tree starts as the last stable, so the only thing the// release can contain beyond it is what the picks add.+ const resolutions = [];io.git.checkoutDetached(latestStableSha);for (const { ref } of resolvedRefs) {- applyFix(mode, ref, io);+ applyFix(mode, ref, io, resolvePaths, resolutions);}const syntheticSha = io.git.headSha();+ // Loud, and in the guard trail rather than only in the plan JSON: a release+ // built on a re-derived config file is not a plain pick, and the operator+ // reading the run log has to see which entries were transplanted before they+ // decide to arm it.+ for (const r of resolutions) {+ const entries = [...r.removed.map((line) => `-${line.trim()}`), ...r.added.map((line) => `+${line.trim()}`)];+ guards.push(+ pass(`Re-derived ${r.path} for ${r.ref} rather than refusing the conflict: ${entries.join(' ')} — ${r.verified}`),+ );+ warnings.push(+ `${r.ref} did not apply cleanly: ${r.path} conflicted and was re-derived as the last stable plus the ` ++ `entries the fix itself changed (${entries.join(' ')}). Read that diff before arming a real run.`,+ );+ }+const version = computePointReleaseVersion({ syntheticSha, latestStableTag, latestStableSha, mode }, io.git);checkGuard(guards, guardTagFree({ tag: version.tag, tagExists: io.git.tagExists }));@@ -424,6 +816,7 @@ export function runPointRelease(opts, io) {latestStableVersion: version.latestStableVersion,latestStableSha,fixRefs: resolvedRefs,+ resolvedPaths: resolutions,syntheticSha,syntheticTree: {sha: syntheticSha,@@ -505,28 +898,114 @@ export function runPointRelease(opts, io) {/*** Apply one fix onto the detached last-stable head.*- * git already fails on a conflict, so the catch adds only context; it re-throws- * and never swallows. The context is worth the wrapper: git's own message says- * which paths collided, which reads as a mechanical problem an operator might- * try to hand-resolve, when the actual finding is that the fix depends on- * something between last stable and now and therefore cannot ship alone.+ * A conflict is a hard fail, and stays one for anything the operator did not+ * explicitly authorize. git's own message names the paths that collided, which+ * reads as a mechanical problem someone might try to hand-resolve, when the+ * finding is usually that the fix depends on something between the last stable+ * and now and therefore cannot ship alone.*- * There is deliberately no strategy or conflict-resolution option to reach for.- * Any resolution would produce a tree that is neither last stable nor the fix- * as reviewed, shipped straight to the default install channel with no soak.+ * The exception is narrow and has to be asked for by path. A fix delivered as a+ * dependency patch is disqualified by drift in a config registry rather than by+ * any dependency of its own, and the `authorized` set is how an operator says+ * so for one named file after a dry run showed them the conflict. Even then the+ * conflict is not resolved so much as sidestepped: the file is re-derived from+ * the stable plus the fix's own entries, and every step that cannot be derived+ * unambiguously refuses. There is still no strategy option to reach for, and no+ * way to authorize a path that carries behavior.*/-function applyFix(mode, ref, io) {+function applyFix(mode, ref, io, authorized, resolutions) {+ let conflict;try {if (mode === 'revert') io.git.revert(ref);else io.git.cherryPick(ref);+ return;} catch (err) {+ conflict = err;+ }++ const conflicted = io.git.conflictedPaths();++ // The apply failed but git left nothing unmerged, so it did not fail on a+ // conflict: an empty pick, a dirty tree, a spawn failure. Calling any of+ // those "not self-contained" would send the operator to pick a different+ // commit over a problem that is not about the commit at all, so the original+ // error propagates with git's own text and the run exits as undecided rather+ // than as a refusal.+ if (conflicted.length === 0) throw conflict;++ const unauthorized = conflicted.filter((path) => !authorized.includes(path));+ if (unauthorized.length > 0) {+ // Named rather than left in git's own text, because which paths collided is+ // the whole finding: it is what tells the operator whether the fix depends+ // on something in between or merely landed beside a config registry that+ // drifted. Everything unauthorized is listed, not just the first.+ const eligible = unauthorized.filter((path) => RESOLVABLE_PATHS.includes(path));+ // Spelled as the flag the operator just typed, so it splices straight into+ // the `gh workflow run` line they are re-running under time pressure.+ const hint =+ eligible.length > 0+ ? ` ${eligible.join(', ')} is a config registry whose conflict can be re-derived from the entries the fix ` ++ `itself changes. Re-run with \`-f resolve_paths=${eligible.join(',')}\` to authorize that, and read the ` ++ 'resolved entries the plan prints before arming a real run.'+ : '';throw new PointReleaseRefusal('apply-conflict',- `Applying ${ref} onto the last stable hit a conflict (${mode}): ${err.message}. The fix is not ` +- 'self-contained over the current stable, so it cannot ship as a point release. Promote through ' +- 'the normal stable path, or pick the smaller commit that is self-contained.',+ `Applying ${ref} onto the last stable hit a conflict (${mode}): ${messageOf(conflict)}. Unresolved ` ++ `conflicts in: ${unauthorized.join(', ')}. The fix is not self-contained over the current stable, so it ` ++ 'cannot ship as a point release. Promote through the normal stable path, or pick the smaller commit that ' ++ 'is self-contained.' ++ hint,);}++ for (const path of conflicted) {+ resolutions.push(resolveConflictedPath({ mode, ref, path }, io));+ io.git.stage(path);+ }+ io.git.continueApply(mode);+}++const messageOf = (err) => (err instanceof Error ? err.message : String(err));++/**+ * Re-derive one authorized path and write it into the working tree.+ *+ * The base is HEAD rather than the stable tag, so a second ref in the same run+ * derives against what the first one produced instead of silently reverting it.+ * Revert mode reads the fix's two sides swapped, since a revert applies that+ * commit's change backwards.+ */+function resolveConflictedPath({ mode, ref, path }, io) {+ const read = (rev) => {+ try {+ return io.git.fileAt(rev, path);+ } catch (err) {+ // Only git's own "that tree has no such path" is a structural finding —+ // the fix creates or deletes the file, which is not an entry-level edit.+ // Anything else (a spawn failure, a broken object store) is the run being+ // unable to decide, and reclassifying it as a refusal would hand the+ // operator a factually wrong diagnosis plus the exit code that tells them+ // to change their approach rather than to re-run.+ if (!/does not exist in|exists on disk, but not in/.test(messageOf(err))) throw err;+ throw new PointReleaseRefusal(+ 'resolve-not-derivable',+ `${path} does not exist at ${rev}, so the fix creates or deletes it rather than editing entries in it.`,+ );+ }+ };++ const { resolved, added, removed } = deriveEntryLevelResolution({+ base: read('HEAD'),+ fixBefore: read(mode === 'revert' ? ref : `${ref}^`),+ fixAfter: read(mode === 'revert' ? `${ref}^` : ref),+ });++ const verified = RESOLVABLE_PATH_VERIFIERS[path]({+ resolved,+ readWorktreeFile: io.fs.readWorktreeFile,+ });+ io.fs.writeWorktreeFile(path, resolved);+ return { ref, path, added, removed, verified };}// The changesets each fix ref introduced on its own, which is what the delta@@ -629,6 +1108,13 @@ export function formatReleaseNotes(plan) {function realIo() {return {readAnchorVersion,+ // Working-tree reads and writes, kept off the git boundary because they are+ // not git operations: the only writer is the config re-derivation, and the+ // only reader is the coherence check that follows it.+ fs: {+ readWorktreeFile: (path) => readFileSync(path, 'utf8'),+ writeWorktreeFile: (path, content) => writeFileSync(path, content),+ },git: {...realGit,// Containment in the public repo's main, which the run's own checkout@@ -655,6 +1141,21 @@ function realIo() {// --no-edit only suppresses the message editor; the pick is otherwise// whatever git produces, and a conflict still fails.revert: (ref) => void runGit(['revert', '--no-edit', ref]),+ // The unmerged entries git left in the index, which is the authoritative+ // list of what actually collided. Reading it from the exception text+ // instead would depend on git's advice formatting.+ conflictedPaths: () =>+ runGit(['diff', '--name-only', '--diff-filter=U'])+ .split('\n')+ .map((line) => line.trim())+ .filter((line) => line !== ''),+ fileAt: (rev, path) => runGit(['show', `${rev}:${path}`]),+ stage: (path) => void runGit(['add', '--', path]),+ // Finishes the in-progress apply with the message git already staged, so+ // the synthetic commit still carries the fix's own subject. core.editor+ // is neutralized for this one invocation because a runner has no editor.+ continueApply: (mode) =>+ void runGit(['-c', 'core.editor=true', mode === 'revert' ? 'revert' : 'cherry-pick', '--continue']),headSha: () => runGit(['rev-parse', 'HEAD']).trim(),tag: (tag, sha) => void runGit(['tag', tag, sha]),pushTag: (tag) => void runGit(['push', 'origin', tag]),@@ -739,6 +1240,7 @@ function main() {mode: process.env.MODE,fixRefs: parseFixRefs(process.env.FIX_REFS),anchorDeltaIds: process.env.ANCHOR_DELTA_IDS,+ resolvePaths: parseResolvePaths(process.env.RESOLVE_PATHS),dryRun,dispatchedBy: process.env.DISPATCHED_BY || '',selfRepo: process.env.GITHUB_REPOSITORY || '',@@ -789,6 +1291,7 @@ function main() {`point_release_version=${plan.version}`,`latest_stable_tag=${plan.latestStableTag}`,`synthetic_sha=${plan.syntheticSha}`,+ `resolved_paths=${JSON.stringify(plan.resolvedPaths.map((r) => r.path))}`,`delta_ids=${JSON.stringify(plan.mainReset.deltaIds ?? [])}`,`main_reset_dispatched=${plan.mainReset.dispatch ? 'true' : 'false'}`,'',diff --git a/.github/scripts/point-release-plan.test.mjs b/.github/scripts/point-release-plan.test.mjsindex 4d1f47ef8..b44da7189 100644--- a/.github/scripts/point-release-plan.test.mjs+++ b/.github/scripts/point-release-plan.test.mjs@@ -1,15 +1,20 @@import { readFileSync } from 'node:fs';import { describe, expect, test } from 'vitest';import {+ deriveEntryLevelResolution,guardAnchor,guardDeltaMatchesFix,guardMainResetDeltaIds,guardNativeConfigProvenance,guardPatchOnly,guardRefsOnMain,+ guardResolvePathsAllowlisted,guardTagFree,parseFixRefs,+ parseResolvePaths,+ RESOLVABLE_PATHS,runPointRelease,+ verifyWorkspaceMatchesLockfile,} from './point-release-plan.mjs';// Build an isOnMain / tagExists boundary from a plain list. The sentinel@@ -226,11 +231,290 @@ describe('guardMainResetDeltaIds', () => {});});+// The three-ref fixture the resolution path is built around, reduced from the+// real refusal that motivated it: between the last stable and the fix, the+// patchedDependencies block was re-sorted and gained an unrelated entry, so the+// fix's own single added line no longer has its diff context. Its patch file is+// not in the synthetic tree, which is why taking the fix's whole file is not+// merely disallowed but broken.+//+// The `overrides:` block is load-bearing, not scenery: it is the second block+// the lockfile mirrors, so without it here the overrides half of the coherence+// check would compare two empty maps and pass vacuously on every test.+const WS_STABLE = `packages:+ - 'packages/*'++overrides:+ 'radix-ui': 1.4.3+ "@types/node": ^24.7.0++patchedDependencies:+ '@handlewithcare/[email protected]': patches/@handlewithcare%[email protected]+ '[email protected]': patches/[email protected]+ '@pierre/[email protected]': patches/@pierre%[email protected]+`;++const WS_FIX_PARENT = `packages:+ - 'packages/*'++overrides:+ 'radix-ui': 1.4.3+ "@types/node": ^24.7.0++patchedDependencies:+ '@handlewithcare/[email protected]': patches/@handlewithcare%[email protected]+ '@lingui/[email protected]': patches/@lingui%[email protected]+ '@pierre/[email protected]': patches/@pierre%[email protected]+ '[email protected]': patches/[email protected]+`;++const WS_FIX = WS_FIX_PARENT.replace(+ " '[email protected]'",+);++// pnpm writes some keys quoted and some bare in the same block, so the key+// reader has to survive both to compare the two files at all.+// Quoting deliberately differs from the workspace file on every key: pnpm+// writes each file's keys its own way, so a comparison that treated quoting as+// a difference would refuse every legitimate resolution.+const LOCK_AFTER_MERGE = `lockfileVersion: '9.0'++overrides:+ radix-ui: 1.4.3+ '@types/node': ^24.7.0++patchedDependencies:+ '@handlewithcare/[email protected]':+ hash: aaa+ path: patches/@handlewithcare%[email protected]+ '@pierre/[email protected]':+ hash: bbb+ path: patches/@pierre%[email protected]+ hash: ccc+ path: patches/[email protected]+ hash: ddd+ path: patches/[email protected]++importers:+`;++describe('parseResolvePaths', () => {+ test('is empty for a blank input, so nothing is authorized by default', () => {+ expect(parseResolvePaths(undefined)).toEqual([]);+ expect(parseResolvePaths(' ')).toEqual([]);+ });++ test('splits and dedupes like the sibling list inputs', () => {+ expect(parseResolvePaths('pnpm-workspace.yaml, pnpm-workspace.yaml')).toEqual(['pnpm-workspace.yaml']);+ });+});++describe('guardResolvePathsAllowlisted', () => {+ test('passes on an empty input and says nothing is authorized', () => {+ const r = guardResolvePathsAllowlisted({ resolvePaths: [] });+ expect(r).toMatchObject({ ok: true, code: null });+ expect(r.message).toMatch(/hard-fail/i);+ });++ test('passes on an allowlisted config path', () => {+ expect(guardResolvePathsAllowlisted({ resolvePaths: ['pnpm-workspace.yaml'] })).toMatchObject({+ ok: true,+ });+ });++ test('refuses a source path, naming every offender', () => {+ const r = guardResolvePathsAllowlisted({+ resolvePaths: ['pnpm-workspace.yaml', 'packages/app/src/main.tsx', '.github/workflows/release.yml'],+ });+ expect(r.ok).toBe(false);+ expect(r.code).toBe('resolve-path-not-allowlisted');+ expect(r.message).toContain('packages/app/src/main.tsx');+ expect(r.message).toContain('.github/workflows/release.yml');+ });++ test('refuses a glob or a parent directory rather than expanding it', () => {+ expect(guardResolvePathsAllowlisted({ resolvePaths: ['*'] }).code).toBe('resolve-path-not-allowlisted');+ expect(guardResolvePathsAllowlisted({ resolvePaths: ['.'] }).code).toBe('resolve-path-not-allowlisted');+ });+});++describe('deriveEntryLevelResolution', () => {+ test('rebuilds the stable file with the entry the fix added and nothing else', () => {+ const { resolved, added, removed } = deriveEntryLevelResolution({+ base: WS_STABLE,+ fixBefore: WS_FIX_PARENT,+ fixAfter: WS_FIX,+ });+ expect(added).toEqual([" '[email protected]': patches/[email protected]"]);+ expect(removed).toEqual([]);+ // The entry the fix brought is registered; the unrelated entry that drifted+ // in alongside it is NOT, because its patch file is not in this tree.+ expect(resolved).toContain("'[email protected]': patches/[email protected]");+ expect(resolved).not.toContain('@lingui/core');+ // The stable's own order is preserved rather than replaced by the fix's.+ expect(resolved).toBe(+ `${WS_STABLE} '[email protected]': patches/[email protected]\n`,+ );+ });++ test('lands the entry inside its block, not at the end of the file', () => {+ // The block happens to be last in the reduced fixture, so pin the general+ // case too: with a section after it, the entry still goes in the block.+ const withTail = `${WS_STABLE}\nonlyBuiltDependencies:\n - electron\n`;+ const { resolved } = deriveEntryLevelResolution({+ base: withTail,+ fixBefore: WS_FIX_PARENT,+ fixAfter: WS_FIX,+ });+ const lines = resolved.split('\n');+ const at = lines.findIndex((l) => l.includes('react-resizable-panels'));+ expect(at).toBeGreaterThan(lines.indexOf('patchedDependencies:'));+ expect(at).toBeLessThan(lines.indexOf('onlyBuiltDependencies:'));+ });++ test('carries a removal through as a deletion of that exact entry', () => {+ const fixAfter = WS_FIX_PARENT.replace(" '[email protected]': patches/[email protected]\n", '');+ const { resolved, added, removed } = deriveEntryLevelResolution({+ base: WS_STABLE,+ fixBefore: WS_FIX_PARENT,+ fixAfter,+ });+ expect(added).toEqual([]);+ expect(removed).toEqual([" '[email protected]': patches/[email protected]"]);+ expect(resolved).not.toContain('y-prosemirror');+ expect(resolved).toContain('@pierre/trees');+ });++ test('refuses when the stable already declares the added key with a different value', () => {+ // Not an addition at all: the fix and the stable disagree about one entry,+ // and re-deriving would silently pick a side.+ const base = WS_STABLE.replace(+ " '@pierre/[email protected]': patches/@pierre%[email protected]",+ " '[email protected]': patches/[email protected]",+ );+ expect(() => deriveEntryLevelResolution({ base, fixBefore: WS_FIX_PARENT, fixAfter: WS_FIX })).toThrow(+ /CHANGES that entry/,+ );+ });++ test('refuses when the block the entry belongs to is not in the stable file', () => {+ const base = "packages:\n - 'packages/*'\n";+ expect(() => deriveEntryLevelResolution({ base, fixBefore: WS_FIX_PARENT, fixAfter: WS_FIX })).toThrow(+ /not in the last stable/,+ );+ });++ test.each([+ ['a new top-level key', `${WS_FIX_PARENT}ignorePatchFailures: false\n`],+ // A comment and a sequence item both have no key to place them by, so+ // deriving one would mean guessing what it was attached to.+ ['a comment inside the block', WS_FIX_PARENT.replace('patchedDependencies:\n', 'patchedDependencies:\n # note\n')],+ ['a sequence item', WS_FIX_PARENT.replace(" - 'packages/*'\n", " - 'packages/*'\n - 'apps/*'\n")],+ ])('refuses %s, which is not an indented mapping entry', (_label, fixAfter) => {+ expect(() => deriveEntryLevelResolution({ base: WS_STABLE, fixBefore: WS_FIX_PARENT, fixAfter })).toThrow(+ /not an indented mapping entry/,+ );+ });++ test('refuses to remove a line the stable no longer has', () => {+ const fixAfter = WS_FIX_PARENT.replace(" '@lingui/[email protected]': patches/@lingui%[email protected]\n", '');+ expect(() => deriveEntryLevelResolution({ base: WS_STABLE, fixBefore: WS_FIX_PARENT, fixAfter })).toThrow(+ /does not appear exactly once in the last stable/,+ );+ });++ test('refuses when the fix does not touch the file at all', () => {+ expect(() =>+ deriveEntryLevelResolution({+ base: WS_STABLE,+ fixBefore: WS_FIX_PARENT,+ fixAfter: WS_FIX_PARENT,+ }),+ ).toThrow(/makes no line-level change/);+ });+});++describe('verifyWorkspaceMatchesLockfile', () => {+ const resolved = deriveEntryLevelResolution({+ base: WS_STABLE,+ fixBefore: WS_FIX_PARENT,+ fixAfter: WS_FIX,+ }).resolved;++ test('passes when the re-derived registrations match the merged lockfile', () => {+ const note = verifyWorkspaceMatchesLockfile({+ resolved,+ readWorktreeFile: () => LOCK_AFTER_MERGE,+ });+ expect(note).toMatch(/agrees with the lockfile/);+ expect(note).toContain('patchedDependencies');+ });++ test('catches taking the fix file wholesale, which registers a patch that is not in the tree', () => {+ expect(() =>+ verifyWorkspaceMatchesLockfile({+ resolved: WS_FIX,+ readWorktreeFile: () => LOCK_AFTER_MERGE,+ }),+ ).toThrow(/@lingui\/core/);+ });++ test('catches keeping the stable file wholesale, which drops the fix own registration', () => {+ expect(() =>+ verifyWorkspaceMatchesLockfile({+ resolved: WS_STABLE,+ readWorktreeFile: () => LOCK_AFTER_MERGE,+ }),+ ).toThrow(/react-resizable-panels/);+ });++ test('reads through the two files differing quote styles rather than calling them a mismatch', () => {+ // The same override is `"@types/node"` in the workspace file and+ // `'@types/node'` in the lockfile. Treating that as a difference would+ // refuse every legitimate resolution.+ expect(verifyWorkspaceMatchesLockfile({ resolved, readWorktreeFile: () => LOCK_AFTER_MERGE })).toContain(+ 'overrides',+ );+ });++ test('checks overrides too, not just patch registrations', () => {+ // pnpm hard-fails a frozen install on an overrides mismatch exactly as it+ // does on patchedDependencies. Checking only the latter would verify an+ // overrides re-derivation with a comparison that passes vacuously.+ const withExtraOverride = resolved.replace(" 'radix-ui': 1.4.3", " 'radix-ui': 1.4.3\n 'left-pad': 1.3.0");+ expect(() =>+ verifyWorkspaceMatchesLockfile({ resolved: withExtraOverride, readWorktreeFile: () => LOCK_AFTER_MERGE }),+ ).toThrow(/overrides.*left-pad/s);+ });++ test('catches an overrides VALUE that drifted, not just a missing key', () => {+ const bumped = resolved.replace(" 'radix-ui': 1.4.3", " 'radix-ui': 1.9.9");+ expect(() =>+ verifyWorkspaceMatchesLockfile({ resolved: bumped, readWorktreeFile: () => LOCK_AFTER_MERGE }),+ ).toThrow(/radix-ui: 1\.9\.9/);+ });++ test('fails closed when the lockfile cannot be read', () => {+ expect(() =>+ verifyWorkspaceMatchesLockfile({+ resolved,+ readWorktreeFile: () => {+ throw new Error('ENOENT');+ },+ }),+ ).toThrow();+ });+});+describe('guard codes', () => {test('every guard refuses with its own distinct code', () => {const refusals = [guardAnchor({ anchorVersion: '0.32.0', latestStableTag: 'v0.32.1' }),guardRefsOnMain({ fixRefs: ['stray'], isOnMain: membership() }),+ guardResolvePathsAllowlisted({ resolvePaths: ['packages/app/src/main.tsx'] }),guardTagFree({ tag: 'v0.32.1', tagExists: membership('v0.32.1') }),guardDeltaMatchesFix({ mode: 'revert', addedIds: ['x'], fixChangesetIds: [] }),guardPatchOnly({ bump: 'major' }),@@ -261,6 +545,12 @@ function makeIo(overrides = {}) {ancestries = [['prebuild-sha', 'synthetic-sha']],cherryPick,revert,+ // Conflict simulation. `conflicts` is the unmerged path list git would+ // report; `files` is a `${rev}:${path}` -> contents map the derivation and+ // its coherence check read from.+ conflicts = [],+ files = {},+ worktree = {},} = overrides;const calls = { tag: 0, pushTag: 0, createRelease: 0, dispatch: 0 };@@ -268,6 +558,10 @@ function makeIo(overrides = {}) {const releases = [];const applied = [];const checkedOut = [];+ const staged = [];+ const continued = [];+ const written = {};+ const reads = [];return {calls,@@ -275,6 +569,27 @@ function makeIo(overrides = {}) {releases,applied,checkedOut,+ staged,+ continued,+ written,+ reads,+ // Exposed so a multi-pick test can advance it the way git does: each pick+ // merges the lockfile again, so the arbiter a derivation is checked against+ // is the one for the pick being applied, not the end state.+ worktree,+ fs: {+ readWorktreeFile: (path) => {+ if (!(path in worktree)) throw new Error(`no worktree file ${path}`);+ return worktree[path];+ },+ // Recorded where `fileAt('HEAD', …)` will find it, so a second ref in the+ // same run derives against what the first one produced. A fake that kept+ // returning the tag's copy would let a regression that silently reverts+ // the first derivation pass.+ writeWorktreeFile: (path, content) => {+ written[path] = content;+ },+ },readAnchorVersion: () => anchorVersion,git: {newestStableTag: () => stableTag,@@ -292,6 +607,21 @@ function makeIo(overrides = {}) {checkoutDetached: (sha) => checkedOut.push(sha),cherryPick: cherryPick ?? ((ref) => applied.push(['cherry-pick', ref])),revert: revert ?? ((ref) => applied.push(['revert', ref])),+ conflictedPaths: () => [...conflicts],+ fileAt: (rev, path) => {+ const key = `${rev}:${path}`;+ reads.push(key);+ // HEAD tracks the working tree once something has been written to it,+ // which is what makes a second ref derive against the first's output.+ if (rev === 'HEAD' && path in written) return written[path];+ if (!(key in files)) throw new Error(`fatal: path '${path}' does not exist in '${rev}'`);+ return files[key];+ },+ stage: (path) => staged.push(path),+ continueApply: (mode) => {+ continued.push(mode);+ applied.push([mode, 'continued']);+ },headSha: () => 'synthetic-sha',tag: () => calls.tag++,pushTag: () => calls.pushTag++,@@ -310,6 +640,29 @@ function makeIo(overrides = {}) {};}+// A cherry-pick that collides in the workspace config and nowhere else, which+// is the shape the resolution path exists for.+const conflictIo = (overrides = {}) =>+ makeIo({+ cherryPick: () => {+ throw new Error('CONFLICT (content): Merge conflict in pnpm-workspace.yaml');+ },+ conflicts: ['pnpm-workspace.yaml'],+ files: {+ 'HEAD:pnpm-workspace.yaml': WS_STABLE,+ 'fix1^:pnpm-workspace.yaml': WS_FIX_PARENT,+ 'fix1:pnpm-workspace.yaml': WS_FIX,+ },+ worktree: { 'pnpm-lock.yaml': LOCK_AFTER_MERGE },+ changesets: {+ 'stable-sha': ['keep-a'],+ 'synthetic-sha': ['keep-a', 'shiny-fix'],+ fix1: ['keep-a', 'shiny-fix'],+ 'fix1^': ['keep-a'],+ },+ ...overrides,+ });+describe('runPointRelease dry run', () => {test('revert mode over v0.32.0 plans v0.32.1 and touches nothing remote', () => {const io = makeIo();@@ -604,6 +957,7 @@ describe('runPointRelease refusals', () => {[member]: () => {throw new Error('CONFLICT (content): Merge conflict in packages/cli/src/index.ts');},+ conflicts: ['packages/cli/src/index.ts'],changesets: {'stable-sha': ['keep-a'],'synthetic-sha': ['keep-a', 'shiny-fix'],@@ -619,30 +973,102 @@ describe('runPointRelease refusals', () => {}expect(refusal?.code).toBe('apply-conflict');expect(refusal?.message).toMatch(/conflict/i);+ expect(refusal?.message).toContain('packages/cli/src/index.ts');expect(io.calls).toEqual({ tag: 0, pushTag: 0, createRelease: 0, dispatch: 0 });});- test('offers no conflict-resolution escape hatch to reach for', () => {+ test('an apply that fails without leaving a conflict propagates as undecided, not as a refusal', () => {+ // An empty pick, a dirty tree, a git spawn failure. None of them says the+ // fix depends on something between the last stable and now, so calling them+ // `apply-conflict` would send the operator to pick a different commit over+ // a problem that is not about the commit — and would exit 2 ("you have+ // something to do") where the honest answer is exit 1 ("re-run it").+ const io = makeIo({+ cherryPick: () => {+ throw new Error('error: git failed to execute (exit null)');+ },+ conflicts: [],+ });+ let caught;+ try {+ runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1'], dryRun: false }, io);+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(Error);+ expect(caught?.code).toBeUndefined();+ expect(caught?.message).toContain('git failed to execute');+ expect(io.calls).toEqual({ tag: 0, pushTag: 0, createRelease: 0, dispatch: 0 });+ });++ test('a conflict in an allowlisted path still hard-fails when it was not authorized', () => {+ // The default is unchanged, and the refusal is where the operator learns+ // the option exists at all — naming a path is a decision made after seeing+ // a dry run refuse, not something to reach for pre-emptively.+ const io = conflictIo();+ let refusal;+ try {+ runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1'], dryRun: false }, io);+ } catch (err) {+ refusal = err;+ }+ expect(refusal?.code).toBe('apply-conflict');+ expect(refusal.message).toContain('resolve_paths=pnpm-workspace.yaml');+ expect(io.written).toEqual({});+ expect(io.staged).toEqual([]);+ expect(io.continued).toEqual([]);+ expect(io.calls).toEqual({ tag: 0, pushTag: 0, createRelease: 0, dispatch: 0 });+ });++ test('still names the eligible config path in the hint when source conflicted too', () => {+ // The shape an operator actually meets: a pick that collides in source AND+ // in the config registry, with nothing authorized. The refusal has to list+ // both paths (so they can see the source conflict is the real blocker) and+ // still name the one that would be resolvable on its own. An `eligible`+ // filter written against the wrong list would drop the hint here while the+ // single-path test above kept passing.+ const io = conflictIo({ conflicts: ['pnpm-workspace.yaml', 'packages/cli/src/index.ts'] });+ let refusal;+ try {+ runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1'], dryRun: false }, io);+ } catch (err) {+ refusal = err;+ }+ expect(refusal?.code).toBe('apply-conflict');+ expect(refusal.message).toContain('packages/cli/src/index.ts');+ expect(refusal.message).toContain('-f resolve_paths=pnpm-workspace.yaml');+ // The hint names only the allowlisted path, never the source one.+ expect(refusal.message).not.toContain('resolve_paths=pnpm-workspace.yaml,packages');+ expect(io.written).toEqual({});+ });++ test('offers no side-picking escape hatch to reach for', () => {const source = readFileSync(new URL('./point-release-plan.mjs', import.meta.url), 'utf8');- // Git's merge-strategy and pick-continuation affordances, in the forms they+ // Git's merge-strategy and pick-skipping affordances, in the forms they// would actually appear in an argv array. Bare 'ours'/'theirs' are matched// quoted so ordinary prose like "now yours" does not trip the check.- const escapes = [- '--strategy',- '-Xours',- '-Xtheirs',- "'ours'",- "'theirs'",- '--continue',- '--skip',- '--abort',- '--no-commit',- ];+ // Both of those sides are not merely disallowed by policy: taking either+ // one wholesale for pnpm-workspace.yaml produces a tree whose patch+ // registrations or overrides disagree with the lockfile, which cannot+ // install at all.+ const escapes = ['--strategy', '-Xours', '-Xtheirs', "'ours'", "'theirs'", '--skip', '--abort', '--no-commit'];for (const escape of escapes) {expect(source).not.toContain(escape);}});+ test('the resolvable-path allowlist admits config registries only, never behavior', () => {+ // The allowlist is the whole security boundary of the resolution path: it+ // is what keeps `resolve_paths` from becoming a general "resolve my+ // conflicts" switch aimed at whatever an operator types. Growing it is a+ // deliberate act that should fail this test first.+ expect(RESOLVABLE_PATHS).toEqual(['pnpm-workspace.yaml']);+ for (const path of RESOLVABLE_PATHS) {+ expect(path.endsWith('.yaml') || path.endsWith('.json')).toBe(true);+ expect(path).not.toMatch(/^(packages|src|scripts|patches|\.github)\//);+ }+ });+test('rejects a mode it does not recognize rather than defaulting to cherry-pick', () => {const io = makeIo();expect(() => runPointRelease({ mode: 'rebase', fixRefs: ['bad1'], dryRun: true }, io)).toThrow(/not one of/);@@ -650,6 +1076,278 @@ describe('runPointRelease refusals', () => {});});+describe('runPointRelease with an authorized config path', () => {+ const authorized = ['pnpm-workspace.yaml'];++ test('re-derives the file, finishes the pick, and ships', () => {+ const io = conflictIo();+ const plan = runPointRelease(+ { mode: 'cherry-pick', fixRefs: ['fix1'], resolvePaths: authorized, dryRun: false },+ io,+ );++ expect(io.written['pnpm-workspace.yaml']).toContain("'[email protected]'");+ expect(io.written['pnpm-workspace.yaml']).not.toContain('@lingui/core');+ expect(io.staged).toEqual(['pnpm-workspace.yaml']);+ expect(io.continued).toEqual(['cherry-pick']);+ expect(io.calls).toMatchObject({ tag: 1, pushTag: 1, createRelease: 1 });++ expect(plan.resolvedPaths).toHaveLength(1);+ expect(plan.resolvedPaths[0]).toMatchObject({+ ref: 'fix1',+ path: 'pnpm-workspace.yaml',+ removed: [],+ });+ });++ test('the derivation reads the stable from HEAD, not from the tag', () => {+ const io = conflictIo();+ runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1'], resolvePaths: authorized, dryRun: true }, io);+ expect(io.reads).toContain('HEAD:pnpm-workspace.yaml');+ expect(io.reads).not.toContain('stable-sha:pnpm-workspace.yaml');+ });++ test('a second conflicting ref derives against the first one output, not back onto the tag', () => {+ // The invariant reading from HEAD exists for. Both refs register a patch+ // and both conflict; if the second derived from the tag again it would+ // silently drop the first ref's entry, and the release would ship claiming+ // a fix whose registration is not in the tree.+ const withBoth = LOCK_AFTER_MERGE.replace(+ ' [email protected]:',+ ` [email protected]:+ hash: eee+ path: patches/[email protected]+ [email protected]:`,+ );+ const io = conflictIo({+ onMain: ['fix1', 'fix2'],+ files: {+ 'HEAD:pnpm-workspace.yaml': WS_STABLE,+ 'fix1^:pnpm-workspace.yaml': WS_FIX_PARENT,+ 'fix1:pnpm-workspace.yaml': WS_FIX,+ 'fix2^:pnpm-workspace.yaml': WS_FIX,+ 'fix2:pnpm-workspace.yaml': WS_FIX.replace(+ " '[email protected]'",+ ),+ },+ changesets: {+ 'stable-sha': ['keep-a'],+ 'synthetic-sha': ['keep-a', 'fix1-cs', 'fix2-cs'],+ fix1: ['keep-a', 'fix1-cs'],+ 'fix1^': ['keep-a'],+ fix2: ['keep-a', 'fix1-cs', 'fix2-cs'],+ 'fix2^': ['keep-a', 'fix1-cs'],+ },+ });++ // git re-merges the lockfile on each pick, so the second derivation is+ // checked against a lockfile that now carries both entries.+ const finishPick = io.git.continueApply;+ io.git.continueApply = (mode) => {+ io.worktree['pnpm-lock.yaml'] = withBoth;+ finishPick(mode);+ };++ const plan = runPointRelease(+ { mode: 'cherry-pick', fixRefs: ['fix1', 'fix2'], resolvePaths: authorized, dryRun: true },+ io,+ );++ expect(plan.resolvedPaths).toHaveLength(2);+ expect(io.continued).toEqual(['cherry-pick', 'cherry-pick']);+ // Both entries survive, and the second derivation did not revert the first.+ const final = io.written['pnpm-workspace.yaml'];+ expect(final).toContain("'[email protected]'");+ expect(final).toContain("'[email protected]'");+ expect(final).not.toContain('@lingui/core');+ });++ test('a missing path at a fix revision refuses as not-derivable', () => {+ const io = conflictIo({+ files: { 'HEAD:pnpm-workspace.yaml': WS_STABLE, 'fix1^:pnpm-workspace.yaml': WS_FIX_PARENT },+ });+ let refusal;+ try {+ runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1'], resolvePaths: authorized, dryRun: false }, io);+ } catch (err) {+ refusal = err;+ }+ expect(refusal?.code).toBe('resolve-not-derivable');+ expect(io.written).toEqual({});+ expect(io.staged).toEqual([]);+ expect(io.continued).toEqual([]);+ expect(io.calls).toEqual({ tag: 0, pushTag: 0, createRelease: 0, dispatch: 0 });+ });++ test('git other not-in-this-tree wording also refuses as not-derivable', () => {+ // git says "does not exist in" for a path absent from the tree and "exists+ // on disk, but not in" when the working tree has it and the tree-ish does+ // not. Both mean the same thing here; only the first arrives through the+ // fake's own message, so without this the second alternative could be+ // dropped in a refactor with the suite still green.+ const io = conflictIo();+ const real = io.git.fileAt;+ io.git.fileAt = (rev, path) => {+ if (rev === 'fix1') throw new Error(`fatal: path '${path}' exists on disk, but not in 'fix1'`);+ return real(rev, path);+ };+ let refusal;+ try {+ runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1'], resolvePaths: authorized, dryRun: false }, io);+ } catch (err) {+ refusal = err;+ }+ expect(refusal?.code).toBe('resolve-not-derivable');+ expect(io.written).toEqual({});+ expect(io.continued).toEqual([]);+ });++ test('an unreadable revision propagates as undecided rather than posing as a structural finding', () => {+ // A spawn failure is not the fix creating or deleting the file. Dressing it+ // as `resolve-not-derivable` would tell the operator to go find a+ // disagreement between the fix and the stable that does not exist.+ const io = conflictIo();+ io.git.fileAt = () => {+ throw new Error('git show HEAD:pnpm-workspace.yaml failed (exit null): spawn ENOMEM');+ };+ let caught;+ try {+ runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1'], resolvePaths: authorized, dryRun: false }, io);+ } catch (err) {+ caught = err;+ }+ expect(caught?.code).toBeUndefined();+ expect(caught?.message).toContain('ENOMEM');+ expect(io.written).toEqual({});+ expect(io.continued).toEqual([]);+ });++ test('revert mode reads the fix two sides swapped, so it removes the entry', () => {+ const io = conflictIo({+ revert: () => {+ throw new Error('CONFLICT (content): Merge conflict in pnpm-workspace.yaml');+ },+ changesets: { 'stable-sha': ['keep-a'], 'synthetic-sha': ['keep-a'] },+ files: {+ 'HEAD:pnpm-workspace.yaml': WS_STABLE,+ 'bad1:pnpm-workspace.yaml': WS_FIX_PARENT,+ 'bad1^:pnpm-workspace.yaml': WS_FIX_PARENT.replace(+ " '@pierre/[email protected]': patches/@pierre%[email protected]\n",+ '',+ ),+ },+ worktree: {+ 'pnpm-lock.yaml': `lockfileVersion: '9.0'++overrides:+ radix-ui: 1.4.3+ '@types/node': ^24.7.0++patchedDependencies:+ '@handlewithcare/[email protected]':+ hash: aaa+ path: patches/@handlewithcare%[email protected]+ hash: ddd+ path: patches/[email protected]++importers:+`,+ },+ });+ runPointRelease({ mode: 'revert', fixRefs: ['bad1'], resolvePaths: authorized, dryRun: false }, io);+ expect(io.written['pnpm-workspace.yaml']).not.toContain('@pierre/trees');+ expect(io.written['pnpm-workspace.yaml']).toContain('y-prosemirror');+ expect(io.continued).toEqual(['revert']);+ });++ test('a dry run performs the resolution and still touches nothing remote', () => {+ // The whole point of authorizing a path is to see what it produces before+ // arming, so the derivation has to run on the dry pass too.+ const io = conflictIo();+ const plan = runPointRelease(+ { mode: 'cherry-pick', fixRefs: ['fix1'], resolvePaths: authorized, dryRun: true },+ io,+ );+ expect(io.written['pnpm-workspace.yaml']).toContain("'[email protected]'");+ expect(plan.resolvedPaths[0].added).toEqual([+ " '[email protected]': patches/[email protected]",+ ]);+ expect(io.calls).toEqual({ tag: 0, pushTag: 0, createRelease: 0, dispatch: 0 });+ });++ test('says so loudly, in the guard trail and as a warning', () => {+ const io = conflictIo();+ const plan = runPointRelease(+ { mode: 'cherry-pick', fixRefs: ['fix1'], resolvePaths: authorized, dryRun: true },+ io,+ );+ expect(plan.guards.some((g) => g.message.includes('Re-derived pnpm-workspace.yaml'))).toBe(true);+ const warning = plan.warnings.join(' ');+ expect(warning).toContain('did not apply cleanly');+ expect(warning).toContain('[email protected]');+ });++ test('authorizing one path does not license a second, unauthorized one', () => {+ const io = conflictIo({ conflicts: ['pnpm-workspace.yaml', 'packages/app/src/main.tsx'] });+ let refusal;+ try {+ runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1'], resolvePaths: authorized, dryRun: false }, io);+ } catch (err) {+ refusal = err;+ }+ expect(refusal?.code).toBe('apply-conflict');+ expect(refusal.message).toContain('packages/app/src/main.tsx');+ expect(io.written).toEqual({});+ expect(io.continued).toEqual([]);+ });++ test('refuses when the re-derived file disagrees with the merged lockfile', () => {+ // The lockfile is the independent arbiter: git merged it from the same two+ // sides with no help from this code, so a mismatch means the derivation is+ // wrong, and a frozen install would fail after the tag already existed.+ const io = conflictIo({+ worktree: {+ 'pnpm-lock.yaml': LOCK_AFTER_MERGE.replace(/ {2}react-resizable-panels@4\.12\.1:\n.*\n.*\n/, ''),+ },+ });+ let refusal;+ try {+ runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1'], resolvePaths: authorized, dryRun: false }, io);+ } catch (err) {+ refusal = err;+ }+ expect(refusal?.code).toBe('resolve-incoherent');+ expect(io.written).toEqual({});+ expect(io.continued).toEqual([]);+ expect(io.calls).toEqual({ tag: 0, pushTag: 0, createRelease: 0, dispatch: 0 });+ });++ test('refuses before the pick when the named path is not allowlisted', () => {+ const io = conflictIo();+ let refusal;+ try {+ runPointRelease(+ {+ mode: 'cherry-pick',+ fixRefs: ['fix1'],+ resolvePaths: ['packages/app/src/main.tsx'],+ dryRun: false,+ },+ io,+ );+ } catch (err) {+ refusal = err;+ }+ expect(refusal?.code).toBe('resolve-path-not-allowlisted');+ // Ahead of the detach, so an over-broad input costs a second and leaves no+ // working state behind.+ expect(io.checkedOut).toEqual([]);+ expect(io.applied).toEqual([]);+ });+});+// The workflow and this script are two files that have to agree on a set of// literal names: the env vars the workflow sets and the script reads, and the// step outputs the script writes and the workflow reads back. Nothing at runtimediff --git a/.github/workflows/point-release.yml b/.github/workflows/point-release.ymlindex 68a729b08..7303ec850 100644--- a/.github/workflows/point-release.yml+++ b/.github/workflows/point-release.yml@@ -23,6 +23,17 @@ name: Point release# no tag, no Release, no dispatch. Arming a real run means unchecking dry_run# deliberately, having read the plan a dry run printed.#+# A conflict is a hard fail, with one narrow exception that must be asked for.+# A fix delivered as a pnpm dependency patch has to register itself in+# pnpm-workspace.yaml, whose registration blocks are dense enough that any other+# patch landing since the last stable puts the fix's own line inside a rewritten+# hunk — so the fix is disqualified by config churn rather than by any+# dependency of its own. `resolve_paths` lets an operator name that one file,+# after a dry run showed them the conflict; the file is then rebuilt as the last+# stable plus the entries the fix itself changed, checked against the lockfile+# git merged beside it, and printed. The allowlist is code, not input: nothing+# that carries behavior can be named, and everything else still refuses.+## All decision logic lives in .github/scripts/point-release-plan.mjs, which is# unit-tested; this file only supplies credentials, a full-history checkout and# a committer identity. Keeping the guards in tested JavaScript rather than@@ -68,6 +79,10 @@ on:description: "Changeset id(s) for main-reset to consolidate. Revert mode has none of its own — name one here or the main-reset dispatch is skipped and the anchor stays behind."required: falsetype: string+ resolve_paths:+ description: "Config path(s) whose conflict may be re-derived instead of refused. Allowlisted config registries only (pnpm-workspace.yaml); a conflict anywhere else always hard-fails. Blank by default."+ required: false+ type: stringdry_run:description: "Compute and print the plan without touching anything remote. Uncheck to actually ship."required: false@@ -193,6 +208,10 @@ jobs:MODE: ${{ inputs.mode }}FIX_REFS: ${{ inputs.fix_refs }}ANCHOR_DELTA_IDS: ${{ inputs.anchor_delta_ids }}+ # Blank unless an operator deliberately named a path, so automated+ # dispatches (the bug lane) never resolve anything and keep the+ # unconditional hard-fail on conflict.+ RESOLVE_PATHS: ${{ inputs.resolve_paths }}# The script arms a real run only on the literal string "false", so any# other value — including an unset variable — stays a dry run.DRY_RUN: ${{ inputs.dry_run }}@@ -213,6 +232,7 @@ jobs:SYNTHETIC_SHA: ${{ steps.plan.outputs.synthetic_sha }}DELTA_IDS: ${{ steps.plan.outputs.delta_ids }}MAIN_RESET_DISPATCHED: ${{ steps.plan.outputs.main_reset_dispatched }}+ RESOLVED_PATHS: ${{ steps.plan.outputs.resolved_paths }}MODE: ${{ inputs.mode }}FIX_REFS: ${{ inputs.fix_refs }}run: |@@ -227,6 +247,11 @@ jobs:echo "- Over stable: \`${LATEST_STABLE_TAG}\`"echo "- Mode: \`${MODE}\` of \`${FIX_REFS}\`"echo "- Changeset delta for main-reset: \`${DELTA_IDS}\` (dispatched: ${MAIN_RESET_DISPATCHED})"+ if [[ -n "${RESOLVED_PATHS:-}" && "$RESOLVED_PATHS" != "[]" ]]; then+ echo "- **Re-derived config paths: \`${RESOLVED_PATHS}\`** — the pick conflicted there and the file"+ echo " was rebuilt as the last stable plus the entries the fix itself changed. The exact entries"+ echo " are in the run log and in the plan JSON; read them before arming."+ fiif [[ "$DRY_RUN" == "true" ]]; thenecho ""echo "Re-run with **dry_run unchecked** to ship this plan."