fix(release): preserve recovery and publish diagnostics

This commit is contained in:
Miguel Ángel
2026-08-23 20:40:48 +00:00
parent 4c6e53132e
commit dcd23fcfca
8 changed files with 151 additions and 9 deletions
+5
View File
@@ -80,3 +80,8 @@ fully covers it; never soften the unknown-rule failure into a warning.
After updating and reviewing the guard, rerun the original merged-PR workflow for recovery.
Do not push a stable tag, select a different SHA, or introduce a manual publish path.
Bypass rejection is intentional: a ruleset result of `bypass` permanently blocks that merge SHA
from publishing. Release PRs must merge normally with their required approval and checks. If a
release PR was bypass-merged, prepare a fresh release PR and merge it normally; rerunning the
bypassed event cannot turn its historical rule-suite result into `pass`.
+36 -1
View File
@@ -3,7 +3,11 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "nod
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, it } from "node:test";
import { runPublishPackages, type PublishCommand } from "./publish-packages.ts";
import {
runPublishPackages,
sanitizePublishError,
type PublishCommand,
} from "./publish-packages.ts";
import { type PublishablePackage } from "./release-packages.ts";
const normal: PublishablePackage = {
@@ -93,6 +97,37 @@ describe("shared package publisher", () => {
}
});
it("preserves useful publish output while redacting secrets and user paths", async () => {
const root = fixture();
const logs: string[] = [];
const error = Object.assign(new Error("npm publish failed for /home/private-user/project"), {
stdout: "uploaded package metadata\n",
stderr:
"npm ERR! code E403\n//registry.npmjs.org/:_authToken=super-secret\naccess_token=also-secret\n",
});
try {
assert.match(sanitizePublishError(error), /E403/);
assert.doesNotMatch(sanitizePublishError(error), /super-secret|also-secret|private-user/);
await assert.rejects(
runPublishPackages(
{ root, version: "1.2.3", distTag: "latest", roster: [normal, cli] },
{
packageExists: async () => false,
command: async () => {
throw error;
},
log: (message) => logs.push(message),
},
),
/E403/,
);
assert.match(logs.join("\n"), /uploaded package metadata|E403/);
assert.doesNotMatch(logs.join("\n"), /super-secret|also-secret|private-user/);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
it("fails reconciliation before any npm boundary when a public workspace is omitted", async () => {
const root = fixture();
let calls = 0;
+39 -5
View File
@@ -30,6 +30,32 @@ type PublishInput = {
};
type PublishResult = { published: string[]; skipped: string[]; failed: string[] };
function outputText(value: unknown): string {
if (typeof value === "string") return value;
if (Buffer.isBuffer(value)) return value.toString("utf8");
return "";
}
// Keep all credential/path redaction in one boundary before diagnostics reach logs or errors.
// fallow-ignore-next-line complexity
export function sanitizePublishError(error: unknown): string {
const record = error && typeof error === "object" ? error : {};
const parts = [
error instanceof Error ? error.message : String(error),
outputText("stdout" in record ? record.stdout : undefined),
outputText("stderr" in record ? record.stderr : undefined),
];
return parts
.filter(Boolean)
.join("\n")
.replace(/(authorization:\s*bearer\s+)\S+/gi, "$1[redacted]")
.replace(/((?:_authToken|access_token|token|password|secret)\s*[=:]\s*)\S+/gi, "$1[redacted]")
.replace(/\/home\/[^/\s]+/g, "$HOME")
.replace(/[A-Za-z]:\\Users\\[^\\\s]+/g, "$HOME")
.trim()
.slice(0, 8_000);
}
// The two allowed publish modes converge here so CLI restoration cannot be bypassed.
// fallow-ignore-next-line complexity
async function publishEntry(
@@ -80,6 +106,7 @@ export async function runPublishPackages(
): Promise<PublishResult> {
const roster = validatePublishablePackages(input.root, input.roster ?? PUBLISHABLE_PACKAGES);
const result: PublishResult = { published: [], skipped: [], failed: [] };
const failedDetails: string[] = [];
for (const entry of roster) {
if (await dependencies.packageExists(entry.npmName, input.version)) {
dependencies.log(`⏭️ ${entry.npmName}@${input.version} already published — skipping`);
@@ -91,13 +118,20 @@ export async function runPublishPackages(
await publishEntry(input.root, entry, input.distTag, dependencies.command);
dependencies.log(`✅ ${entry.npmName}@${input.version} published`);
result.published.push(entry.npmName);
} catch {
dependencies.log(`❌ ${entry.npmName}@${input.version} failed to publish`);
} catch (error) {
const diagnostic = sanitizePublishError(error);
dependencies.log(
`❌ ${entry.npmName}@${input.version} failed to publish${diagnostic ? `:\n${diagnostic}` : ""}`,
);
result.failed.push(entry.npmName);
failedDetails.push(`${entry.npmName}: ${diagnostic || "unknown publish failure"}`);
}
}
if (result.failed.length > 0)
throw new Error(`Packages failed to publish: ${result.failed.join(", ")}`);
if (result.failed.length > 0) {
throw new Error(
`Packages failed to publish: ${result.failed.join(", ")}\n${failedDetails.join("\n")}`,
);
}
return result;
}
@@ -111,7 +145,7 @@ const defaultDependencies: PublishDependencies = {
}
},
command: async (executable, args, cwd) => {
await execFileAsync(executable, [...args], { cwd });
await execFileAsync(executable, [...args], { cwd, maxBuffer: 16 * 1024 * 1024 });
},
log: console.log,
};
+2
View File
@@ -128,6 +128,8 @@ test("effective non-check rule enforcement and maintenance are explicit", () =>
assert.match(releaseRunbook, /NON_CHECK_RULES/);
assert.match(releaseRunbook, /GitHub adds.*rule type/i);
assert.match(releaseRunbook, /rerun the original merged-PR workflow/i);
assert.match(releaseRunbook, /bypass rejection is intentional/i);
assert.match(releaseRunbook, /merge.*normally/i);
});
test("the workflow invokes one shared publisher and owns no package roster", () => {
+5
View File
@@ -6,6 +6,7 @@ import { describe, it } from "node:test";
import {
PUBLISHABLE_PACKAGES,
discoverWorkspacePackages,
validateRepositoryPublishablePackages,
validatePublishablePackages,
type PublishablePackage,
} from "./release-packages.ts";
@@ -35,6 +36,10 @@ function fixture(): string {
// One fixture-backed matrix documents the complete reconciliation contract.
// fallow-ignore-next-line unit-size
describe("publishable package roster", () => {
it("directly reconciles the actual repository packages tree", () => {
assert.deepEqual(validateRepositoryPublishablePackages(), PUBLISHABLE_PACKAGES);
});
it("covers every public workspace exactly once and excludes private workspaces", () => {
const root = fixture();
try {
+7
View File
@@ -1,6 +1,8 @@
import { existsSync, readFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
const REPOSITORY_ROOT = join(import.meta.dirname, "..");
export type PublishMode = "workspace" | "manifest-name-override";
export type PublishablePackage = {
@@ -172,3 +174,8 @@ export function validatePublishablePackages(
}
return roster;
}
/** CI-facing contract that directly reconciles the checked-out repository tree. */
export function validateRepositoryPublishablePackages(): readonly PublishablePackage[] {
return validatePublishablePackages(REPOSITORY_ROOT);
}
+3 -3
View File
@@ -384,9 +384,9 @@ export async function runStableReleaseGuard({
}
}
function createGitHubClient({ repository, token }) {
export function createGitHubClient({ repository, token, fetchImpl = fetch }) {
const request = async (path, requestBudgetMs) => {
const response = await fetch(`https://api.github.com${path}`, {
const response = await fetchImpl(`https://api.github.com${path}`, {
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${token}`,
@@ -420,7 +420,7 @@ function createGitHubClient({ repository, token }) {
paginate(`/repos/${repository}/pulls/${number}/reviews`, null, requestBudgetMs),
getRuleSuite: async (sha, requestBudgetMs) => {
const suites = await paginate(
`/repos/${repository}/rulesets/rule-suites?ref=${encodeURIComponent("refs/heads/main")}`,
`/repos/${repository}/rulesets/rule-suites?ref=${encodeURIComponent("refs/heads/main")}&time_period=month`,
null,
requestBudgetMs,
);
+54
View File
@@ -3,6 +3,7 @@ import { describe, it } from "node:test";
import {
assertImmutableRelease,
collectEffectiveApprovals,
createGitHubClient,
evaluateRequiredChecks,
extractEffectiveRules,
parseGuardTimeoutMs,
@@ -475,3 +476,56 @@ describe("stable release guard timeout configuration", () => {
}
});
});
describe("rule-suite recovery lookback", () => {
function clientForSuites(suites, requests) {
return createGitHubClient({
repository: "heygen-com/hyperframes",
token: "test-token",
fetchImpl: async (url) => {
requests.push(String(url));
return new Response(JSON.stringify(suites), {
status: 200,
headers: { "content-type": "application/json" },
});
},
});
}
it("finds an exact passing merge suite older than the default day within the month", async () => {
const requests = [];
const client = clientForSuites(
[
{
id: 1,
after_sha: mergeSha,
ref: "refs/heads/main",
result: "pass",
pushed_at: "2026-08-16T00:00:00Z",
},
],
requests,
);
assert.deepEqual(await client.getRuleSuite(mergeSha, 1_000), {
afterSha: mergeSha,
ref: "refs/heads/main",
result: "pass",
});
assert.match(requests[0], /time_period=month/);
});
it("fails closed when the month response is absent or ambiguous", async () => {
for (const suites of [
[],
[
{ after_sha: mergeSha, ref: "refs/heads/main", result: "pass" },
{ after_sha: mergeSha, ref: "refs/heads/main", result: "pass" },
],
]) {
await assert.rejects(
clientForSuites(suites, []).getRuleSuite(mergeSha, 1_000),
/Expected one rule suite/,
);
}
});
});