diff --git a/apps/server/src/provider/Drivers/ClaudeMaintenance.test.ts b/apps/server/src/provider/Drivers/ClaudeMaintenance.test.ts index eccf421dd7c18..33f9f901c8731 100644 --- a/apps/server/src/provider/Drivers/ClaudeMaintenance.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeMaintenance.test.ts @@ -24,6 +24,8 @@ import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import * as HttpClient from "effect/http/HttpClient"; import * as HttpClientResponse from "effect/http/HttpClientResponse"; +import * as Sink from "effect/Sink"; +import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import { makeClaudeMaintenanceResolution } from "./ClaudeMaintenance.ts"; @@ -77,6 +79,13 @@ const fixture = Effect.fn("ClaudeMaintenance.test.fixture")(function* ( : platform === "darwin" ? "/Library/Application Support/ClaudeCode" : "/etc/claude-code"; + const npmPath = path.join(directory, "bin/npm"); + if (install === "npm") { + yield* fs.makeDirectory(path.dirname(npmPath), { recursive: true }); + yield* fs.writeFileString(npmPath, "#!/bin/sh\n"); + yield* fs.chmod(npmPath, 0o755); + } + const npmProbes: Array> = []; let installationReads = 0; const testFs = FileSystem.makeNoop({ ...fs, @@ -105,11 +114,37 @@ const fixture = Effect.fn("ClaudeMaintenance.test.fixture")(function* ( managed, managedDirectory, settingsPath, + npmProbes, installationReads: () => installationReads, - makeResolution: makeClaudeMaintenanceResolution({ binaryPath, env: { PATH: "" } }).pipe( + makeResolution: makeClaudeMaintenanceResolution({ + binaryPath, + env: { PATH: install === "npm" ? path.dirname(npmPath) : "" }, + }).pipe( Effect.provideService( ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => Effect.die("version checks must not run a subprocess")), + ChildProcessSpawner.make((command) => { + if (!ChildProcess.isStandardCommand(command) || command.command !== npmPath) { + return Effect.die("version checks may only ask npm"); + } + npmProbes.push(command.args.map(String)); + return Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.encodeText( + Stream.make(JSON.stringify({ "@anthropic-ai/claude-code": { latest: "2.1.316" } })), + ), + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }), + ); + }), ), Effect.provideService(FileSystem.FileSystem, testFs), Effect.provideService(HostProcess.Platform, platform), @@ -233,12 +268,17 @@ it.layer(NodeServices.layer)("ClaudeMaintenance", (it) => { status: row.advisory, latestVersion: row.expected, }); - expect(requests).toHaveLength(1); - expect(requests[0]).toMatch( - row.npm ? /registry\.npmjs\.org/ : new RegExp(`claude-code-releases/${row.channel}$`), - ); + // npm installs ask `npm outdated`, which applies npm's release-age settings. + const lookups = row.npm ? f.npmProbes : requests; + expect(lookups).toHaveLength(1); + if (row.npm) { + expect(requests).toEqual([]); + expect(f.npmProbes[0]?.[0]).toBe("outdated"); + } else { + expect(requests[0]).toMatch(new RegExp(`claude-code-releases/${row.channel}$`)); + } yield* enrich; - expect(requests).toHaveLength(1); + expect(lookups).toHaveLength(1); }), ); diff --git a/apps/server/src/provider/Drivers/CodexDriver.test.ts b/apps/server/src/provider/Drivers/CodexDriver.test.ts index 01d44f3d3d1e8..1462d051346f1 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.test.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.test.ts @@ -729,6 +729,7 @@ it.layer(layerTest)("CodexDriver", (it) => { const shimDir = NodePath.join(tempDir, fixture.dataRoot, "shims"); const npmPrefix = NodePath.join(tempDir, "mise", "installs", "node", "24.13.0"); const npmBin = NodePath.join(npmPrefix, "bin"); + const npmPath = NodePath.join(npmBin, "npm"); const npmEntry = NodePath.join( npmPrefix, "lib", @@ -738,7 +739,7 @@ it.layer(layerTest)("CodexDriver", (it) => { "bin", "codex.js", ); - for (const file of [brewPath, misePath, npmEntry]) { + for (const file of [brewPath, misePath, npmPath, npmEntry]) { yield* fs.makeDirectory(NodePath.dirname(file), { recursive: true }); yield* fs.writeFileString(file, "#!/bin/sh\n"); yield* fs.chmod(file, 0o755); @@ -753,12 +754,20 @@ it.layer(layerTest)("CodexDriver", (it) => { ].join(NodePath.delimiter); const probes: Array> = []; const metadataSpawner = ChildProcessSpawner.make((command) => { - if (!ChildProcess.isStandardCommand(command) || command.command !== brewPath) { + const isNpmOutdated = + ChildProcess.isStandardCommand(command) && + command.command === npmPath && + command.args[0] === "outdated"; + if ( + !ChildProcess.isStandardCommand(command) || + (command.command !== brewPath && !isNpmOutdated) + ) { return Effect.die("Provider resolution must not execute a provider or updater"); } - probes.push(command.args.map(String)); - const stdout = - command.args[0] === "--prefix" + if (!isNpmOutdated) probes.push(command.args.map(String)); + const stdout = isNpmOutdated + ? JSON.stringify({ "@openai/codex": { latest: "0.153.4" } }) + : command.args[0] === "--prefix" ? brewPrefix : JSON.stringify({ formulae: [{ versions: { stable: "2026.9.1" } }] }); return Effect.succeed( diff --git a/packages/provider-core/src/server/maintenanceResolver.test.ts b/packages/provider-core/src/server/maintenanceResolver.test.ts index 0899713ed9602..c9fcc71d9c66d 100644 --- a/packages/provider-core/src/server/maintenanceResolver.test.ts +++ b/packages/provider-core/src/server/maintenanceResolver.test.ts @@ -356,12 +356,11 @@ it.layer( ), ); + // npm-global installs ask `npm outdated` instead; see the npm-global cases below. it.effect.each([ { install: "native", stdout: '"1.2.0"', exitCode: 0, latest: "1.2.0" }, { install: "manual", stdout: '["1.2.0"]', exitCode: 0, latest: "1.2.0" }, - { install: "npm", stdout: '"1.2.0"', exitCode: 0, latest: "1.2.0" }, { install: "native", stdout: "", exitCode: 1, latest: null }, - { install: "npm", stdout: '"1.2.0"', exitCode: 1, latest: null }, { install: "native", stdout: "not json", exitCode: 0, latest: null }, { install: "manual", stdout: '["1.2.0", "1.3.0"]', exitCode: 0, latest: null }, { install: "manual", stdout: '""', exitCode: 0, latest: null }, @@ -372,20 +371,12 @@ it.layer( const tempDir = yield* makeTempDir("t3-registry-version"); const npmBinDir = NodePath.join(tempDir, "npm-bin"); writeExecutable(NodePath.join(npmBinDir, "npm")); - const binaryPath = - fixture.install === "npm" - ? linkIntoPackage(tempDir, "package-tool", [ - "lib", - "node_modules", - "@example", - "package-tool", - ]) - : NodePath.join(tempDir, ".local/bin/native-package-tool"); - if (fixture.install !== "npm") writeExecutable(binaryPath); + const binaryPath = NodePath.join(tempDir, ".local/bin/native-package-tool"); + writeExecutable(binaryPath); let probes = 0; const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect( fixture.install === "native" ? nativePackageToolUpdate : packageToolUpdate, - { binaryPath, env: { PATH: fixture.install === "npm" ? npmBinDir : "" } }, + { binaryPath, env: { PATH: "" } }, ).pipe( Effect.provideService(HostProcess.Environment, { PATH: npmBinDir }), Effect.provideService( @@ -397,7 +388,6 @@ it.layer( expect(args).toEqual([ "view", "--global", - ...(fixture.install === "npm" ? ["--prefix", tempDir] : []), "--json", `${capabilities.packageName}@latest`, "version", @@ -540,7 +530,7 @@ it.layer( ChildProcessSpawner.ChildProcessSpawner, stdoutSpawner(() => { probes++; - return JSON.stringify(version); + return JSON.stringify({ "@example/package-tool": { latest: version } }); }), ), Effect.tap((capabilities) => @@ -596,7 +586,7 @@ it.layer( expect(advisoryFor(pnpmTool, "1.1.0-beta.1")).toBe( "pnpm add -g --allow-build=@example/package-tool @example/package-tool@latest", ); - // Only pnpm's minimumReleaseAge skips fresh releases; npm keeps @latest. + // npm keeps @latest; its outdated probe already reports what that resolves to. expect( advisoryFor( makeProviderMaintenanceCapabilities({ @@ -710,6 +700,9 @@ it.layer( expect(capabilities).toEqual({ provider: driver("packageTool"), packageName: "@example/package-tool", + latestVersion: null, + lookupLatestVersion: expect.anything(), + latestVersionCacheKey: expect.any(String), update: { command: `npm install -g --prefix ${tempDir} --allow-scripts=@example/package-tool @example/package-tool@latest`, executable: "npm", @@ -1424,6 +1417,99 @@ it.layer( { skip: !symlinksSupported || windowsHost }, ); + it.effect.each([ + { + case: "the eligible release", + outdated: { "@example/package-tool": { current: "1.0.0", wanted: "1.1.0", latest: "1.1.0" } }, + exitCode: 1, + status: "behind_latest", + latestVersion: "1.1.0", + }, + { + case: "no update during cooldown", + outdated: {}, + exitCode: 0, + status: "current", + latestVersion: "1.0.0", + }, + { + case: "no update during cooldown beside a broken global", + outdated: {}, + exitCode: 0, + listExitCode: 1, + status: "current", + latestVersion: "1.0.0", + }, + { + case: "no registry version when npm cannot reach the registry", + outdated: { error: { code: "ECONNREFUSED" } }, + exitCode: 1, + status: "unknown", + latestVersion: null, + }, + ])( + "advertises $case for npm-global installs", + (fixture) => + Effect.gen(function* () { + const tempDir = yield* makeTempDir("t3-npm-latest"); + const npmBinDir = NodePath.join(tempDir, "npm-bin"); + const npmPath = NodePath.join(npmBinDir, "npm"); + writeExecutable(npmPath); + const link = linkIntoPackage(tempDir, "package-tool", [ + "lib", + "node_modules", + "@example", + "package-tool", + ]); + + const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect( + packageToolUpdate, + { binaryPath: link, env: { PATH: npmBinDir } }, + ).pipe( + // The updater's npm comes from the provider's PATH. + Effect.provideService(HostProcess.Environment, { PATH: "" }), + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + stdoutSpawner( + (command, args) => { + expect(command).toBe(npmPath); + expect(args.slice(1, 4)).toEqual(["-g", "--prefix", tempDir]); + return JSON.stringify( + args[0] === "outdated" + ? fixture.outdated + : { + dependencies: { "@example/package-tool": { version: "1.0.0" } }, + }, + ); + }, + (args) => (args[0] === "outdated" ? fixture.exitCode : (fixture.listExitCode ?? 0)), + ), + ), + ); + + const provider = yield* enrichProviderSnapshotWithVersionAdvisory( + installedPackageToolProvider, + capabilities, + ).pipe( + Effect.provideServiceEffect( + ProviderLatestVersions.ProviderLatestVersions, + ProviderLatestVersions.make([["@example/package-tool", "9.9.9"]]), + ), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("the npm version is already cached")), + ), + ); + expect(provider.versionAdvisory).toMatchObject({ + status: fixture.status, + currentVersion: "1.0.0", + latestVersion: fixture.latestVersion, + updateCommand: expect.stringMatching(/@example\/package-tool@latest$/), + }); + }), + { skip: !symlinksSupported || windowsHost }, + ); + it.effect.each([ { case: "the eligible release under minimumReleaseAge", diff --git a/packages/provider-core/src/server/maintenanceResolver.ts b/packages/provider-core/src/server/maintenanceResolver.ts index 96645fd1685fd..d83d7375cf646 100644 --- a/packages/provider-core/src/server/maintenanceResolver.ts +++ b/packages/provider-core/src/server/maintenanceResolver.ts @@ -431,24 +431,22 @@ const runProbe = Effect.fn("runProbe")(function* ( ); }); -const decodePnpmOutdated = Schema.decodeUnknownOption( +const decodeOutdated = Schema.decodeUnknownOption( Schema.fromJsonString( Schema.Record(Schema.String, Schema.Struct({ latest: Schema.optional(Schema.String) })), ), ); -const decodePnpmList = Schema.decodeUnknownOption( - Schema.fromJsonString( - Schema.Array( - Schema.Struct({ - dependencies: Schema.optional( - Schema.Record(Schema.String, Schema.Struct({ version: Schema.optional(Schema.String) })), - ), - }), - ), +const GlobalPackageList = Schema.Struct({ + dependencies: Schema.optional( + Schema.Record(Schema.String, Schema.Struct({ version: Schema.optional(Schema.String) })), ), +}); +const decodePnpmList = Schema.decodeUnknownOption( + Schema.fromJsonString(Schema.Array(GlobalPackageList)), ); +const decodeNpmList = Schema.decodeUnknownOption(Schema.fromJsonString(GlobalPackageList)); -// Unlike npm's latest tag, pnpm outdated respects minimumReleaseAge and its excludes. +// Unlike the registry's latest tag, pnpm outdated respects minimumReleaseAge and its excludes. const resolvePnpmGlobalLatestVersion = Effect.fn("resolvePnpmGlobalLatestVersion")(function* ( packageName: string, env: NodeJS.ProcessEnv, @@ -466,9 +464,7 @@ const resolvePnpmGlobalLatestVersion = Effect.fn("resolvePnpmGlobalLatestVersion // pnpm outdated exits 1 when updates are available. [0, 1], ); - const outdatedEntries = outdated - ? Option.getOrUndefined(decodePnpmOutdated(outdated)) - : undefined; + const outdatedEntries = outdated ? Option.getOrUndefined(decodeOutdated(outdated)) : undefined; if (!outdatedEntries) return null; const latest = nonEmptyString(outdatedEntries[packageName]?.latest); if (latest) return latest; @@ -482,6 +478,41 @@ const resolvePnpmGlobalLatestVersion = Effect.fn("resolvePnpmGlobalLatestVersion return nonEmptyString(listedEntries?.[0]?.dependencies?.[packageName]?.version); }); +// Unlike `npm view`, `outdated` applies min-release-age, before and their excludes. +const resolveNpmGlobalLatestVersion = Effect.fn("resolveNpmGlobalLatestVersion")(function* ( + packageName: string, + npmPrefix: string, + env: NodeJS.ProcessEnv, +) { + // Match the updater's npm and environment. + const npmPath = yield* resolveCommandPath("npm", { + env: { ...(yield* HostProcess.Environment), ...env }, + }); + if (!npmPath) return null; + const outdated = yield* runProbe( + npmPath, + ["outdated", "-g", "--prefix", npmPrefix, "--json", packageName], + env, + // npm outdated exits 1 when updates are available. + [0, 1], + ); + const outdatedEntries = outdated ? Option.getOrUndefined(decodeOutdated(outdated)) : undefined; + // npm prints failures such as an unreachable registry as `{"error": ...}`, also exiting 1. + if (!outdatedEntries || "error" in outdatedEntries) return null; + const latest = nonEmptyString(outdatedEntries[packageName]?.latest); + if (latest) return latest; + // An empty result means the installed version is still the eligible release. + const listed = yield* runProbe( + npmPath, + ["ls", "-g", "--prefix", npmPrefix, "--depth", "0", "--json", packageName], + env, + // npm ls still prints the tree but exits 1 when other globals have problems. + [0, 1], + ); + const listedEntries = listed ? Option.getOrUndefined(decodeNpmList(listed)) : undefined; + return nonEmptyString(listedEntries?.dependencies?.[packageName]?.version); +}); + // npm names the tarball `${name}-${version}.tgz`, dropping a scope's `@` and its `/`. function parseNpmPackVersion(stdout: string, packageName: string): string | null { const prefix = `${packageName.replace(/^@/, "").replace("/", "-")}-`; @@ -933,8 +964,9 @@ export const resolvePackageManagedProviderMaintenance = Effect.fn( // npm proof outranks a containing Homebrew keg; Homebrew Node globals still belong to npm. const npmPrefix = yield* resolveNpmGlobalPrefix(context, packageName); if (npmPrefix) { + const services = yield* Effect.context(); // npm 12 requires script approval to install native binaries; older npm only warns about the flag. - return makeProviderMaintenanceCapabilities({ + const capabilities = makeProviderMaintenanceCapabilities({ provider: definition.provider, packageName, updateExecutable: "npm", @@ -948,7 +980,22 @@ export const resolvePackageManagedProviderMaintenance = Effect.fn( ], updateLockKey: `npm-global:${normalizeCommandPath(npmPrefix)}`, env: context.env, + // Inside min-release-age `@latest` installs an older release than the + // registry's tag, so only npm's own answer is worth advertising. + latestVersion: null, + lookupLatestVersion: resolveNpmGlobalLatestVersion(packageName, npmPrefix, context.env).pipe( + Effect.provideContext(services), + ), }); + return { + ...capabilities, + latestVersionCacheKey: [ + "npm-global", + normalizeCommandPath(npmPrefix), + packageName, + environmentCacheKey(context.env), + ].join("\0"), + }; } const homebrew = homebrewOwnershipFromCommandPath(context.realCommandPath); @@ -1146,21 +1193,9 @@ const withConfiguredNpmVersionLookup = Effect.fn("withConfiguredNpmVersionLookup const npmPath = yield* resolveCommandPath("npm", { env }); if (!npmPath) return capabilities; const services = yield* Effect.context(); - const update = capabilities.update; - const prefixIndex = update?.lockKey.startsWith("npm-global:") - ? update.args.indexOf("--prefix") - : -1; - const prefix = prefixIndex >= 0 ? update?.args[prefixIndex + 1] : undefined; const lookup = runProbe( npmPath, - [ - "view", - "--global", - ...(prefix ? ["--prefix", prefix] : []), - "--json", - `${packageName}@latest`, - "version", - ], + ["view", "--global", "--json", `${packageName}@latest`, "version"], env, ).pipe( Effect.map((stdout) => { @@ -1182,7 +1217,6 @@ const withConfiguredNpmVersionLookup = Effect.fn("withConfiguredNpmVersionLookup "configured-npm", npmPath, packageName, - prefix ?? "", environmentCacheKey(env), installerLatestVersionKey(capabilities) ?? "", ].join("\0"),