From 567a82f8d4feb629a7c10d2cc9180377eb1f6f66 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Fri, 9 Oct 2026 06:29:29 +0800 Subject: [PATCH] fix(update): accept npm 12 release metadata (#1138) * fix(update): accept npm 12 release metadata (cherry picked from commit aa400d18c95e36029c5c654c396ec66924e1358f) * fix(update): classify npm release metadata without a spawn mock Keep the npm 11 string and npm 12 one-element array accepted by the cherry-picked lookup, and separate invalid metadata from a failed registry command. --------- Co-authored-by: Dapo Olaomo --- src/application/Update.test.ts | 37 +++++++- src/application/Update.ts | 33 ++++++- src/application/UpdateRuntime.release.test.ts | 88 +++++++++++++++++++ src/application/UpdateRuntime.ts | 83 ++++++++++++----- src/cliLogging.test.ts | 5 +- 5 files changed, 215 insertions(+), 31 deletions(-) create mode 100644 src/application/UpdateRuntime.release.test.ts diff --git a/src/application/Update.test.ts b/src/application/Update.test.ts index 12b9c0c09..8e1ce0642 100644 --- a/src/application/Update.test.ts +++ b/src/application/Update.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest"; import { err, ok, type Result } from "../domain/result.js"; import { runUpdate, + type ReleaseLookupFailure, type UpdateHost, type UpdateOutput, type NpmInstallation, @@ -14,7 +15,7 @@ import { import type { IntegrationMaintenance } from "./UpdateMaintenance.js"; class FakeUpdateHost implements UpdateHost { - release: Result = ok("3.3.0"); + release: Result = ok("3.3.0"); installationResult: NpmInstallation | undefined = { prefix: "/fixture", packageRoot: "/fixture/lib/node_modules/rea-agents", @@ -35,7 +36,7 @@ class FakeUpdateHost implements UpdateHost { this.installationInspected = true; return Promise.resolve(this.installationResult); }; - latestVersion = (): Promise> => + latestVersion = (): Promise> => Promise.resolve(this.release); installVersion = ( _installation: NpmInstallation, @@ -180,7 +181,10 @@ describe("update failures and version boundaries", () => { it("preserves registry errors without installation", async () => { const host = new FakeUpdateHost(); - host.release = err("npm registry returned HTTP 503"); + host.release = err({ + kind: "unavailable", + detail: "npm registry returned HTTP 503", + }); const result = await runUpdate("3.2.1", host); expect(result).toMatchObject({ status: "failed", @@ -191,6 +195,10 @@ describe("update failures and version boundaries", () => { "remediation", expect.stringContaining("HTTP 503"), ); + expect(result).toHaveProperty( + "remediation", + expect.stringContaining("registry access"), + ); expect(host.installedVersions).toEqual([]); }); @@ -207,6 +215,29 @@ describe("update failures and version boundaries", () => { }, ); + it("describes invalid release metadata without blaming registry access", async () => { + const host = new FakeUpdateHost(); + host.release = err({ + kind: "invalid-metadata", + detail: "expected one version string", + }); + const result = await runUpdate("3.2.1", host); + expect(result).toMatchObject({ + status: "failed", + reason: "version-check", + latestVersion: null, + }); + expect(result).toHaveProperty( + "remediation", + expect.stringContaining("expected one version string"), + ); + expect(result).toHaveProperty( + "remediation", + expect.not.stringContaining("registry access"), + ); + expect(host.installedVersions).toEqual([]); + }); + it.each([ ["3.4.0", "3.3.0"], ["3.3.0", "3.3.0-rc.1"], diff --git a/src/application/Update.ts b/src/application/Update.ts index e0b60b25e..16b4b6a3a 100644 --- a/src/application/Update.ts +++ b/src/application/Update.ts @@ -13,12 +13,17 @@ export interface NpmInstallation { /** Output policy for the package manager subprocess. */ export type UpdateOutput = "human" | "structured"; +/** Why release lookup failed before a version could be compared. */ +export type ReleaseLookupFailure = + | { readonly kind: "unavailable"; readonly detail: string } + | { readonly kind: "invalid-metadata"; readonly detail: string }; + /** Effects used to update and verify one identified REA installation. */ export interface UpdateHost { installation(): Promise; latestVersion( installation: NpmInstallation | undefined, - ): Promise>; + ): Promise>; installVersion( installation: NpmInstallation, version: string, @@ -95,6 +100,28 @@ export const updateInstallCommand = ( `${PRODUCT_IDENTITY.packageName}@${version}`, ]; +const versionCheckRemediation = ( + release: Result, +): string => { + if (release.ok) { + return "REA received invalid version metadata. Check the installed version and npm registry, then rerun rea update."; + } + const failure = release.error; + const kind = failure.kind; + switch (kind) { + case "unavailable": + return `REA could not resolve the latest release: ${failure.detail}. Retry rea update when registry access is available.`; + case "invalid-metadata": + return `REA could not resolve the latest release: ${failure.detail}. Check the npm release metadata, then rerun rea update.`; + default: { + const exhaustive: never = kind; + throw new TypeError( + `Unhandled release lookup failure: ${String(exhaustive)}`, + ); + } + } +}; + /** Identify, resolve, install, and verify REA without applying setup changes. */ export const runUpdate = async ( currentVersion: string, @@ -111,9 +138,7 @@ export const runUpdate = async ( currentVersion, latestVersion, reason: "version-check", - remediation: release.ok - ? "REA received invalid version metadata. Check the installed version and npm registry, then rerun rea update." - : `REA could not resolve the latest release: ${release.error}. Retry rea update when registry access is available.`, + remediation: versionCheckRemediation(release), }; if (!gt(targetVersion, currentVersion)) return { diff --git a/src/application/UpdateRuntime.release.test.ts b/src/application/UpdateRuntime.release.test.ts new file mode 100644 index 000000000..0625d3719 --- /dev/null +++ b/src/application/UpdateRuntime.release.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it } from "vitest"; + +import { err, ok } from "../domain/result.js"; +import { safeParseJson } from "../domain/safeJson.js"; +import { PRODUCT_IDENTITY } from "../identity.js"; +import { + npmLatestVersionCommand, + npmReleaseLookup, + parseNpmLatestVersion, +} from "./UpdateRuntime.js"; + +const installation = { + prefix: "/opt/rea", + packageRoot: "/opt/rea/lib/node_modules/rea-agents", +}; + +describe("npm latest release metadata", () => { + it("accepts npm 11's scalar JSON response", () => { + expect(parseNpmLatestVersion('"6.0.0"')).toEqual(ok("6.0.0")); + }); + + it("accepts npm 12's singleton-array JSON response", () => { + expect(parseNpmLatestVersion('[\n "6.0.0"\n]\n')).toEqual(ok("6.0.0")); + }); + + it.each([ + ["empty array", "[]"], + ["multiple versions", '["6.0.0", "6.0.1"]'], + ["empty version", '[""]'], + ["number", "6"], + ["object", '{"version":"6.0.0"}'], + ["null", "null"], + ])("rejects %s response data", (_description, metadata) => { + expect(parseNpmLatestVersion(metadata)).toEqual( + err( + "Invalid npm release metadata: expected a version string or a single-element version array.", + ), + ); + }); + + it("preserves malformed JSON separately from a wrong metadata shape", () => { + const metadata = '"6.0.0'; + const decoded = safeParseJson(metadata); + expect(decoded.ok).toBe(false); + if (decoded.ok) return; + expect(parseNpmLatestVersion(metadata)).toEqual(err(decoded.error)); + expect(decoded.error).not.toContain("single-element version array"); + }); + + it("keeps command failures distinct from rejected metadata", () => { + expect(npmReleaseLookup(err("npm registry returned HTTP 503"))).toEqual( + err({ kind: "unavailable", detail: "npm registry returned HTTP 503" }), + ); + expect(npmReleaseLookup(ok("[]"))).toEqual( + err({ + kind: "invalid-metadata", + detail: + "Invalid npm release metadata: expected a version string or a single-element version array.", + }), + ); + expect(npmReleaseLookup(ok('["6.0.0"]'))).toEqual(ok("6.0.0")); + }); + + it("keeps the global registry query and adds the owning prefix", () => { + expect(npmLatestVersionCommand(installation)).toEqual([ + "npm", + "view", + "--global", + "--prefix", + installation.prefix, + PRODUCT_IDENTITY.packageName, + "dist-tags.latest", + "--json", + "--fetch-retries=0", + "--fetch-timeout=10000", + ]); + expect(npmLatestVersionCommand(undefined)).toEqual([ + "npm", + "view", + "--global", + PRODUCT_IDENTITY.packageName, + "dist-tags.latest", + "--json", + "--fetch-retries=0", + "--fetch-timeout=10000", + ]); + }); +}); diff --git a/src/application/UpdateRuntime.ts b/src/application/UpdateRuntime.ts index 348607890..caefba91a 100644 --- a/src/application/UpdateRuntime.ts +++ b/src/application/UpdateRuntime.ts @@ -3,13 +3,14 @@ import { homedir } from "node:os"; import { basename, dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import spawn from "cross-spawn"; -import { z } from "zod"; import { PRODUCT_IDENTITY } from "../identity.js"; import { err, ok, type Result } from "../domain/result.js"; +import { safeParseJson } from "../domain/safeJson.js"; import { updateInstallCommand, type NpmInstallation, + type ReleaseLookupFailure, type UpdateHost, type UpdateOutput, } from "./Update.js"; @@ -116,6 +117,60 @@ export const detectNpmInstallation = async ( return { prefix: dirname(library), packageRoot: canonicalPackageRoot }; }; +const INVALID_NPM_RELEASE_METADATA = + "Invalid npm release metadata: expected a version string or a single-element version array."; + +/** npm view arguments for dist-tags.latest, scoped to the owning prefix when known. */ +export const npmLatestVersionCommand = ( + installation: NpmInstallation | undefined, +): readonly string[] => [ + "npm", + "view", + "--global", + ...(installation === undefined ? [] : ["--prefix", installation.prefix]), + PRODUCT_IDENTITY.packageName, + "dist-tags.latest", + "--json", + "--fetch-retries=0", + "--fetch-timeout=10000", +]; + +/** + * Read one latest version from `npm view --json`. + * npm 11 emits a JSON string. npm 12 emits that string as a one-element array. + */ +export const parseNpmLatestVersion = ( + metadata: string, +): Result => { + const decoded = safeParseJson(metadata); + if (!decoded.ok) return err(decoded.error); + const version = readNpmLatestVersion(decoded.value); + return version === undefined + ? err(INVALID_NPM_RELEASE_METADATA) + : ok(version); +}; + +const readNpmLatestVersion = (value: unknown): string | undefined => { + if (typeof value === "string") return nonemptyVersion(value); + if (!Array.isArray(value) || value.length !== 1) return undefined; + const only = value[0]; + return typeof only === "string" ? nonemptyVersion(only) : undefined; +}; + +const nonemptyVersion = (value: string): string | undefined => + value.length === 0 ? undefined : value; + +/** Classify npm view output as a version or a lookup failure. */ +export const npmReleaseLookup = ( + response: Result, +): Result => { + if (!response.ok) return err({ kind: "unavailable", detail: response.error }); + const parsed = parseNpmLatestVersion(response.value); + return parsed.ok + ? ok(parsed.value) + : err({ kind: "invalid-metadata", detail: parsed.error }); +}; + /** Create npm, registry, verification, and read-only maintenance effects. */ export const systemUpdateHost = ( packageRoot = fileURLToPath(new URL("../..", import.meta.url)), @@ -127,28 +182,10 @@ export const systemUpdateHost = ( globalRoot: () => requireCommandOutput(["npm", "root", "--global"]), globalPrefix: () => requireCommandOutput(["npm", "prefix", "--global"]), }), - latestVersion: async (installation) => { - const response = await runUpdateCommand([ - "npm", - "view", - "--global", - ...(installation === undefined ? [] : ["--prefix", installation.prefix]), - PRODUCT_IDENTITY.packageName, - "dist-tags.latest", - "--json", - "--fetch-retries=0", - "--fetch-timeout=10000", - ]); - if (!response.ok) return response; - try { - const parsed = z.string().min(1).safeParse(JSON.parse(response.value)); - return parsed.success - ? ok(parsed.data) - : err(`Invalid npm release metadata: ${parsed.error.message}`); - } catch (cause: unknown) { - return err(cause instanceof Error ? cause.message : String(cause)); - } - }, + latestVersion: async (installation) => + npmReleaseLookup( + await runUpdateCommand(npmLatestVersionCommand(installation)), + ), installVersion: async (installation, version, output) => { const result = await runUpdateCommand( updateInstallCommand(installation, version), diff --git a/src/cliLogging.test.ts b/src/cliLogging.test.ts index b37a6f183..e275519e6 100644 --- a/src/cliLogging.test.ts +++ b/src/cliLogging.test.ts @@ -88,7 +88,10 @@ describe("CLI command outcome classification", () => { }; const updateHost: UpdateHost = { installation: () => Promise.resolve(installation), - latestVersion: () => Promise.resolve(err("registry unavailable")), + latestVersion: () => + Promise.resolve( + err({ kind: "unavailable", detail: "registry unavailable" }), + ), installVersion: () => Promise.resolve(err("not called")), installedVersion: () => Promise.resolve(err("not called")), planMaintenance: () =>