diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cf8dc70..871c2af 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -68,3 +68,45 @@ jobs: --body "Automated post-release manifest alignment. Sets package.json, manifest.json, and CHANGELOG.md to the released ${VERSION}." \ --base main --head "${BRANCH}" gh pr merge --auto --squash --delete-branch + + verify-publish: + needs: release + if: always() && needs.release.result == 'success' + runs-on: ubuntu-latest + timeout-minutes: 20 + concurrency: + group: verify-npm-publish + cancel-in-progress: false + permissions: + contents: read + issues: write + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + persist-credentials: false + + - uses: actions/setup-node@v7 + with: + node-version: "22" + + - uses: oven-sh/setup-bun@v2 + with: + bun-version: "1.3.14" + + - name: Install dependencies + run: bun install --frozen-lockfile + + - name: Ensure automation labels + env: + GH_TOKEN: ${{ github.token }} + run: | + gh label create release-stalled --force --color B60205 \ + --description "Tagged release is not visible on npm" + gh label create automation --force --color 0E8A16 \ + --description "Automated bot activity" + + - name: Verify npm publish + env: + GH_TOKEN: ${{ github.token }} + run: bun run scripts/verify-npm-release.ts diff --git a/docs/specs/2026-08-28-ci-catalog-automation.md b/docs/specs/2026-08-28-ci-catalog-automation.md index b0764e5..64fc854 100644 --- a/docs/specs/2026-08-28-ci-catalog-automation.md +++ b/docs/specs/2026-08-28-ci-catalog-automation.md @@ -165,6 +165,25 @@ When extraction fails: Successful extraction closes every matching open issue, including unlabeled legacy duplicates, with a comment referencing the checkout commit that proved recovery and its latest reachable release tag (when present). The tag is not a promise that a new release has been published. +### 3. npm publish watchdog (`release.yml`) + +After the release job succeeds, the separate `verify-publish` job checks the +latest Git tag reachable from the triggering commit, even if semantic-release +did not cut a new version on that run. It polls the public npm registry for +that exact package version every 15 seconds for up to 10 minutes. HTTP 200 +confirms visibility; 404 means the version is not yet visible, and other +registry errors are retried within the same budget. + +If the version is still not visible, the watchdog creates or updates one open +`[release-stalled] @` issue, labeled `release-stalled` and +`automation` and assigned to `BrainerVirus`. The issue records the tag, elapsed +time, last registry result, workflow run, and what to check next. Watchdog jobs +run one at a time so concurrent workflow runs do not race to create it. When npm +serves the checked version, the watchdog comments on and closes only open +`[release-stalled] @` issues matching that exact package and +version. Alerts for other versions stay open. A timeout fails only the watchdog +job: it does not gate or roll back publishing or manifest sync. + ## npm Release Policy | Event | Version bump | Publish | @@ -309,7 +328,7 @@ Do not block Plan 1 on npm publishing. | Risk | Mitigation | |---|---| | Bot PR noise | compare generated artifacts; unchanged files produce no PR | -| npm publish failure after merge | release job retries unpublished plugin versions; tag/Release only after publish succeeds | +| Tag exists but npm does not serve the release | watchdog opens a `release-stalled` issue after 10 minutes | | Extraction anchors break silently | relative model-count floor + catalog-break issue | | User on `file://` | CI cannot update that checkout; README says git pull or switch to npm | diff --git a/scripts/verify-npm-release.ts b/scripts/verify-npm-release.ts new file mode 100644 index 0000000..934d8e9 --- /dev/null +++ b/scripts/verify-npm-release.ts @@ -0,0 +1,170 @@ +#!/usr/bin/env bun +import { execFileSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { githubCli, type GhRunner } from "../src/catalog-break-reporter.js"; + +const ROOT = join(import.meta.dir, ".."); +const LABEL = "release-stalled"; +const LABELS = `${LABEL},automation`; +const ASSIGNEE = "BrainerVirus"; +const liveGh = githubCli(ROOT); +const defaultSleep = (ms: number): Promise => + new Promise((resolve) => setTimeout(resolve, ms)); + +type OpenIssue = { number: number; title: string; pull_request?: object }; + +function stalledIssueTitle(release: string): string { + return `[${LABEL}] ${release}`; +} + +function openStalledIssues(gh: GhRunner, title: string): OpenIssue[] { + const pages = gh([ + "api", + "repos/{owner}/{repo}/issues?state=open&per_page=100", + "--paginate", + "--slurp", + ]); + return (JSON.parse(pages) as OpenIssue[][]) + .flat() + .filter((issue) => !issue.pull_request && issue.title === title); +} + +function resolveStalledIssues(gh: GhRunner, release: string): void { + for (const { number } of openStalledIssues(gh, stalledIssueTitle(release))) { + const issue = String(number); + gh(["issue", "comment", issue, "--body-file", "-"], `Resolved: npm now serves ${release}.`); + gh(["issue", "close", issue, "--reason", "completed"]); + } +} + +function workflowUrl(): string { + const { GITHUB_SERVER_URL, GITHUB_REPOSITORY, GITHUB_RUN_ID } = process.env; + return GITHUB_SERVER_URL && GITHUB_REPOSITORY && GITHUB_RUN_ID + ? `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}` + : "(local run)"; +} + +function reportStalledRelease(gh: GhRunner, title: string, body: string): void { + const [existing, ...duplicates] = openStalledIssues(gh, title); + if (!existing) { + gh( + [ + "issue", + "create", + "--title", + title, + "--label", + LABELS, + "--assignee", + ASSIGNEE, + "--body-file", + "-", + ], + body, + ); + return; + } + + const issue = String(existing.number); + gh( + ["issue", "edit", issue, "--add-label", LABELS, "--add-assignee", ASSIGNEE, "--body-file", "-"], + body, + ); + for (const { number } of duplicates) { + gh(["issue", "close", String(number), "--reason", "duplicate", "--duplicate-of", issue]); + } +} + +export async function waitForNpmVersion({ + packageName, + version, + timeoutMs = 600_000, + intervalMs = 15_000, + fetchImpl = fetch, + gh = liveGh, + sleep = defaultSleep, + tag = `v${version}`, +}: { + packageName: string; + version: string; + timeoutMs?: number; + intervalMs?: number; + fetchImpl?: (url: string, init: RequestInit) => Promise>; + gh?: GhRunner; + sleep?: (ms: number) => Promise; + tag?: string; +}): Promise { + const release = `${packageName}@${version}`; + const registryUrl = `https://registry.npmjs.org/${encodeURIComponent(packageName)}/${version}`; + const start = performance.now(); + let scheduledWaitMs = 0; + let lastResult = "No registry response."; + + // Charge injected sleeps against the budget as well as real elapsed time. + const elapsedMs = () => Math.max(Math.floor(performance.now() - start), scheduledWaitMs); + while (elapsedMs() < timeoutMs) { + let status: number | undefined; + try { + const response = await fetchImpl(registryUrl, { + signal: AbortSignal.timeout(Math.ceil(Math.min(intervalMs, timeoutMs - elapsedMs()))), + }); + status = response.status; + lastResult = status === 404 ? "HTTP 404: version not yet visible." : `HTTP ${status}.`; + } catch (error) { + lastResult = `Registry request failed: ${String(error)}`; + } + + if (status === 200) { + resolveStalledIssues(gh, release); + return true; + } + + const delay = Math.min(intervalMs, timeoutMs - elapsedMs()); + if (delay <= 0) break; + await sleep(delay); + scheduledWaitMs += delay; + } + + reportStalledRelease( + gh, + stalledIssueTitle(release), + [ + `npm did not return HTTP 200 for the tagged release after ${elapsedMs()} ms.`, + "", + `- Package: \`${packageName}\``, + `- Version: \`${version}\``, + `- Tag: \`${tag}\``, + `- Workflow run: ${workflowUrl()}`, + `- Registry URL: ${registryUrl}`, + `- Last result: ${lastResult}`, + "", + "Next step: Review the semantic-release publish logs and npm registry status, then retry the watchdog job.", + ].join("\n"), + ); + return false; +} + +async function main(): Promise { + const { name: packageName } = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf-8")) as { + name: string; + }; + const tag = execFileSync("git", ["describe", "--tags", "--abbrev=0"], { + cwd: ROOT, + encoding: "utf-8", + }).trim(); + const version = tag.replace(/^v/, ""); + if (await waitForNpmVersion({ packageName, version, tag })) { + console.log(`npm now serves ${packageName}@${version}`); + } else { + console.error(`npm did not serve ${packageName}@${version} before the watchdog timed out`); + process.exitCode = 1; + } +} + +if (import.meta.main) { + main().catch((error) => { + console.error(error); + process.exitCode = 1; + }); +} diff --git a/tests/unit/verify-npm-release.test.ts b/tests/unit/verify-npm-release.test.ts new file mode 100644 index 0000000..960048f --- /dev/null +++ b/tests/unit/verify-npm-release.test.ts @@ -0,0 +1,174 @@ +import { expect, test } from "bun:test"; +import { waitForNpmVersion } from "../../scripts/verify-npm-release.js"; + +const packageName = "@brainervirus/opencode-commandcode"; +const version = "1.2.3"; +const title = "[release-stalled] @brainervirus/opencode-commandcode@1.2.3"; + +test("Given open stalled issues for different versions, when npm serves one version, then it comments on and closes only that version's issues", async () => { + const calls: Array<{ args: readonly string[]; body?: string }> = []; + const urls: string[] = []; + const result = await waitForNpmVersion({ + packageName, + version, + fetchImpl: async (url) => { + urls.push(url); + return new Response(null, { status: 200 }); + }, + gh: (args, body) => { + calls.push({ args, body }); + return JSON.stringify([ + [ + { number: 10, title }, + { number: 11, title: "Unrelated issue" }, + { number: 12, title, pull_request: {} }, + ], + [ + { number: 13, title: "[release-stalled] @brainervirus/opencode-commandcode@1.2.30" }, + { number: 14, title }, + ], + ]); + }, + sleep: async () => { + throw new Error("A first-attempt success must not sleep"); + }, + }); + + expect(result).toBe(true); + expect(urls).toEqual(["https://registry.npmjs.org/%40brainervirus%2Fopencode-commandcode/1.2.3"]); + expect(calls.slice(1).map(({ args }) => args)).toEqual([ + ["issue", "comment", "10", "--body-file", "-"], + ["issue", "close", "10", "--reason", "completed"], + ["issue", "comment", "14", "--body-file", "-"], + ["issue", "close", "14", "--reason", "completed"], + ]); + expect(calls[1].body).toContain("npm now serves @brainervirus/opencode-commandcode@1.2.3"); + expect(calls[3].body).toContain("npm now serves @brainervirus/opencode-commandcode@1.2.3"); +}); + +test("Given repeated 404s, when the watchdog times out twice and later sees a 200, then one issue is created, updated and resolved", async () => { + const env = process.env; + const sleepCalls: number[] = []; + const writes: Array<{ args: readonly string[]; body?: string }> = []; + const openIssues = [ + { number: 7, title: "[release-stalled] @brainervirus/opencode-commandcode@1.2.2" }, + ]; + let registryStatus = 404; + let attempts = 0; + const options: Parameters[0] = { + packageName, + version, + intervalMs: 30_000, + timeoutMs: 70_000, + fetchImpl: async () => { + attempts += 1; + return new Response(null, { status: registryStatus }); + }, + sleep: async (ms) => { + sleepCalls.push(ms); + }, + gh: (args, body) => { + if (args[0] === "api") return JSON.stringify([openIssues]); + writes.push({ args, body }); + if (args[1] === "create") { + openIssues.push({ number: 42, title: args[args.indexOf("--title") + 1]! }); + } else if (args[1] === "close") { + const index = openIssues.findIndex(({ number }) => String(number) === args[2]); + if (index >= 0) openIssues.splice(index, 1); + } + return ""; + }, + }; + + try { + process.env = { + ...env, + GITHUB_SERVER_URL: "https://github.com", + GITHUB_REPOSITORY: "BrainerVirus/opencode-commandcode", + GITHUB_RUN_ID: "123", + }; + + expect(await waitForNpmVersion(options)).toBe(false); + expect(attempts).toBe(3); + expect(sleepCalls).toEqual([30_000, 30_000, 10_000]); + expect(writes).toHaveLength(1); + const [created] = writes; + expect(created.args).toEqual([ + "issue", + "create", + "--title", + title, + "--label", + "release-stalled,automation", + "--assignee", + "BrainerVirus", + "--body-file", + "-", + ]); + expect(created.body).toContain("Package: `@brainervirus/opencode-commandcode`"); + expect(created.body).toContain("Version: `1.2.3`"); + expect(created.body).toContain("Tag: `v1.2.3`"); + expect(created.body).toContain( + "https://github.com/BrainerVirus/opencode-commandcode/actions/runs/123", + ); + expect(created.body).toContain("after 70000 ms"); + expect(created.body).toContain("HTTP 404: version not yet visible"); + expect(created.body).toContain("Next step:"); + + process.env.GITHUB_RUN_ID = "456"; + expect(await waitForNpmVersion(options)).toBe(false); + expect(attempts).toBe(6); + expect(writes).toHaveLength(2); + const edited = writes[1]; + expect(edited.args).toEqual([ + "issue", + "edit", + "42", + "--add-label", + "release-stalled,automation", + "--add-assignee", + "BrainerVirus", + "--body-file", + "-", + ]); + expect(edited.body).toContain("/actions/runs/456"); + expect(openIssues.filter((issue) => issue.title === title)).toHaveLength(1); + + registryStatus = 200; + expect(await waitForNpmVersion(options)).toBe(true); + expect(attempts).toBe(7); + expect(openIssues).toEqual([ + { number: 7, title: "[release-stalled] @brainervirus/opencode-commandcode@1.2.2" }, + ]); + expect(writes).toContainEqual({ + args: ["issue", "comment", "42", "--body-file", "-"], + body: "Resolved: npm now serves @brainervirus/opencode-commandcode@1.2.3.", + }); + } finally { + process.env = env; + } +}); + +test("Given a network error and a 503, when a later request succeeds, then it resolves without raising an issue", async () => { + const statuses = [null, 503, 200]; + const calls: Array = []; + expect( + await waitForNpmVersion({ + packageName, + version, + fetchImpl: async () => { + const status = statuses.shift(); + if (status === null) throw new Error("connection reset"); + if (status === undefined) throw new Error("unexpected extra attempt"); + return new Response(null, { status }); + }, + gh: (args) => { + calls.push(args); + return "[[]]"; + }, + sleep: async () => {}, + }), + ).toBe(true); + expect(statuses).toEqual([]); + expect(calls.map(([command]) => command)).toEqual(["api"]); +});