@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 2,676 lines 99.1 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off
2 import { expect, it } from "@effect/vitest";
3 import * as NodeFS from "node:fs";
4 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
5 import * as NodeServices from "@effect/platform-node/NodeServices";
6 import * as NodeOS from "node:os";
7 import * as NodePath from "node:path";
8 import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
9 import * as HostProcess from "@t3tools/shared/HostProcess";
10 import * as SecureRandom from "effect/crypto/SecureRandom";
11 import * as Deferred from "effect/Deferred";
12 import * as Effect from "effect/Effect";
13 import * as Fiber from "effect/Fiber";
14 import * as Layer from "effect/Layer";
15 import * as Sink from "effect/Sink";
16 import * as Stream from "effect/Stream";
17 import * as TestClock from "effect/testing/TestClock";
18 import * as HttpClient from "effect/http/HttpClient";
19 import * as HttpClientResponse from "effect/http/HttpClientResponse";
20 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
21 import * as ProviderLatestVersions from "./ProviderLatestVersions.ts";
22 import {
23 createProviderVersionAdvisory,
24 makeTargetedProviderUpdateAction,
25 enrichProviderSnapshotWithVersionAdvisory,
26 homebrewOwnershipFromCommandPath,
27 invalidateLatestProviderVersion,
28 makeCachedProviderMaintenanceResolution,
29 makeManualOnlyProviderMaintenanceCapabilities,
30 makePackageManagedProviderMaintenanceResolver,
31 makeProviderMaintenanceCapabilities,
32 normalizeCommandPath,
33 npmGlobalPrefixFromCommandPath,
34 parseChocolateyLatestVersion,
35 parseHomebrewLatestVersion,
36 resolveLatestProviderVersion,
37 resolvePackageManagedProviderMaintenance,
38 resolveProviderMaintenanceCapabilitiesEffect,
39 type PackageManagedProviderMaintenanceDefinition,
40 type ProviderMaintenanceCapabilities,
41 } from "./maintenanceResolver.ts";
42 import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
43
44 const driver = (value: string) => ProviderDriverKind.make(value);
45 // Shell stubs use POSIX paths; Windows temp paths cannot split on colon.
46 const windowsHost = HostProcess.Platform.defaultValue() === "win32";
47 const makeTempDir = (name: string) =>
48 SecureRandom.SecureRandom.pipe(
49 Effect.flatMap((random) => random.uuidV4()),
50 Effect.map((id) => NodePath.join(NodeFS.realpathSync(NodeOS.tmpdir()), `${name}-${id}`)),
51 );
52 const isNativeTestCommandPath =
53 (expectedPathSegment: string) =>
54 (commandPath: string): boolean =>
55 normalizeCommandPath(commandPath).includes(expectedPathSegment);
56 const packageToolUpdate = makePackageManagedProviderMaintenanceResolver({
57 provider: driver("packageTool"),
58 npmPackageName: "@example/package-tool",
59 nativeUpdate: null,
60 });
61 const nativePackageToolUpdate = makePackageManagedProviderMaintenanceResolver({
62 provider: driver("nativePackageTool"),
63 npmPackageName: "@example/native-package-tool",
64 nativeUpdate: {
65 args: ["update"],
66 isCommandPath: isNativeTestCommandPath("/.local/bin/native-package-tool"),
67 },
68 });
69 const bunOutdatedTable = (row: string) => [
70 "|-------------------------------------------------------|",
71 "| Package | Current | Update | Latest |",
72 "|-----------------------|---------|--------|----------|",
73 row,
74 "|-------------------------------------------------------|",
75 "Note: The * indicates that version isn't true latest due to minimum release age",
76 ];
77 const miseToolUpdate = makePackageManagedProviderMaintenanceResolver({
78 provider: driver("packageTool"),
79 npmPackageName: "@example/package-tool",
80 mise: { tool: "package-tool" },
81 nativeUpdate: null,
82 });
83 const installedPackageToolProvider: ServerProvider = {
84 instanceId: ProviderInstanceId.make("packageTool"),
85 driver: driver("packageTool"),
86 enabled: true,
87 installed: true,
88 version: "1.0.0",
89 status: "ready",
90 auth: { status: "authenticated" },
91 checkedAt: "2026-04-10T00:00:00.000Z",
92 models: [],
93 slashCommands: [],
94 skills: [],
95 };
96 const manualPackageTool: ProviderMaintenanceCapabilities = {
97 provider: driver("packageTool"),
98 packageName: "@example/package-tool",
99 update: null,
100 };
101
102 function writeExecutable(path: string) {
103 NodeFS.mkdirSync(NodePath.dirname(path), { recursive: true });
104 NodeFS.writeFileSync(path, "#!/bin/sh\n");
105 NodeFS.chmodSync(path, 0o755);
106 }
107
108 function linkIntoPackage(tempDir: string, name: string, packageSegments: ReadonlyArray<string>) {
109 const target = NodePath.join(tempDir, ...packageSegments, "bin", `${name}.js`);
110 writeExecutable(target);
111 const link = NodePath.join(tempDir, "bin", name);
112 NodeFS.mkdirSync(NodePath.dirname(link), { recursive: true });
113 NodeFS.symlinkSync(target, link);
114 return link;
115 }
116
117 const noSpawn = ChildProcessSpawner.make(() =>
118 Effect.die("maintenance resolution should not spawn a process here"),
119 );
120
121 function stdoutSpawner(
122 onSpawn: (command: string, args: ReadonlyArray<string>) => string,
123 exitCodeOf: (args: ReadonlyArray<string>) => number = () => 0,
124 ) {
125 return ChildProcessSpawner.make((command) => {
126 const { command: executable, args } = command as unknown as {
127 readonly command: string;
128 readonly args: ReadonlyArray<string>;
129 };
130 return Effect.succeed(
131 ChildProcessSpawner.makeHandle({
132 pid: ChildProcessSpawner.ProcessId(1),
133 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCodeOf(args))),
134 isRunning: Effect.succeed(false),
135 kill: () => Effect.void,
136 unref: Effect.succeed(Effect.void),
137 stdin: Sink.drain,
138 stdout: Stream.encodeText(Stream.make(onSpawn(executable, args))),
139 stderr: Stream.empty,
140 all: Stream.empty,
141 getInputFd: () => Sink.drain,
142 getOutputFd: () => Stream.empty,
143 }),
144 );
145 });
146 }
147
148 type MiseLatestAnswer = string | { readonly stdout?: string; readonly exitCode?: number } | "hang";
149
150 /** A `mise` answering `which`, `ls --json --installed [tool]`, and `latest`, recording each call. */
151 function miseSpawner(
152 answers: {
153 readonly which: string;
154 readonly latest?: MiseLatestAnswer;
155 readonly installed: Record<string, ReadonlyArray<unknown>>;
156 },
157 spawned: Array<ReadonlyArray<string>>,
158 ) {
159 return ChildProcessSpawner.make((command) => {
160 const { command: executable, args } = command as unknown as {
161 readonly command: string;
162 readonly args: ReadonlyArray<string>;
163 };
164 spawned.push([executable, ...args]);
165 const latest = answers.latest ?? "";
166 const hang = args[0] === "latest" && latest === "hang";
167 let stdout = "";
168 let exitCode = 0;
169 if (args[0] === "which") {
170 stdout = `${answers.which}\n`;
171 } else if (args[0] === "latest" && typeof latest === "string") {
172 stdout = latest === "hang" ? "" : `${latest}\n`;
173 } else if (args[0] === "latest" && typeof latest !== "string") {
174 stdout = latest.stdout ?? "";
175 exitCode = latest.exitCode ?? 0;
176 } else if (args[0] === "ls") {
177 // `mise ls --json <tool>` lists one tool's installs; without a tool, every tool's.
178 // A registry short name also lists installs configured under a backend, like `npm:<pkg>`.
179 const tool = args.slice(1).find((arg) => !arg.startsWith("-"));
180 const configured = tool
181 ? Object.keys(answers.installed).find((name) => name.replace(/^[^:]+:/, "") === tool)
182 : undefined;
183 stdout = JSON.stringify(
184 tool
185 ? (answers.installed[tool] ?? answers.installed[configured ?? ""] ?? [])
186 : answers.installed,
187 );
188 } else {
189 exitCode = 1;
190 }
191 return Effect.succeed(
192 ChildProcessSpawner.makeHandle({
193 pid: ChildProcessSpawner.ProcessId(1),
194 exitCode: hang ? Effect.never : Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
195 isRunning: Effect.succeed(hang),
196 kill: () => Effect.void,
197 unref: Effect.succeed(Effect.void),
198 stdin: Sink.drain,
199 stdout: hang ? Stream.never : Stream.encodeText(Stream.make(stdout)),
200 stderr: Stream.empty,
201 all: Stream.empty,
202 getInputFd: () => Sink.drain,
203 getOutputFd: () => Stream.empty,
204 }),
205 );
206 });
207 }
208
209 /**
210 * A mise binary on its own PATH dir and an install of `package-tool` 1.0.0 in its data dir,
211 * with the `latest` link mise keeps pointing at the newest install.
212 */
213 function miseFixture(
214 tempDir: string,
215 options: {
216 readonly misePresent?: boolean;
217 readonly tool?: string;
218 readonly dataDir?: string;
219 /** The backend name the config requests the tool by, such as `npm:package-tool`. */
220 readonly backend?: string;
221 } = {},
222 ) {
223 const miseBinDir = NodePath.join(tempDir, "mise-bin");
224 const misePath = NodePath.join(miseBinDir, "mise");
225 if (options.misePresent !== false) writeExecutable(misePath);
226 const toolDir = NodePath.join(
227 options.dataDir ?? NodePath.join(tempDir, "mise"),
228 "installs",
229 options.backend ? options.backend.replace(/[:@/]+/g, "-") : "package-tool",
230 );
231 if (options.backend) {
232 NodeFS.mkdirSync(toolDir, { recursive: true });
233 NodeFS.writeFileSync(
234 NodePath.join(toolDir, ".mise.backend.toml"),
235 `short = "${options.backend}"\nfull = "${options.backend}"\nexplicit_backend = true\n`,
236 );
237 }
238 const latestDir = NodePath.join(toolDir, "latest");
239 let installPath = "";
240 let binaryPath = "";
241 /** Installs `version` and points `latest` at it, as `mise upgrade` does. */
242 const install = (version: string) => {
243 installPath = NodePath.join(toolDir, version);
244 binaryPath = NodePath.join(installPath, "bin", "package-tool");
245 writeExecutable(binaryPath);
246 if (symlinksSupported) {
247 NodeFS.rmSync(latestDir, { force: true });
248 NodeFS.symlinkSync(installPath, latestDir);
249 }
250 return binaryPath;
251 };
252 install("1.0.0");
253 const installed = (
254 install: { readonly requested_version?: string; readonly active?: boolean } = {},
255 ) => ({
256 [options.tool ?? options.backend ?? "package-tool"]: [
257 { install_path: installPath, requested_version: "latest", active: true, ...install },
258 ],
259 });
260 return {
261 miseBinDir,
262 misePath,
263 get binaryPath() {
264 return binaryPath;
265 },
266 latestBinaryPath: NodePath.join(latestDir, "bin", "package-tool"),
267 install,
268 installed,
269 };
270 }
271
272 /** A mise shim: a link named for the tool that points at mise itself. */
273 function linkShim(tempDir: string, misePath: string, name: string) {
274 const shimPath = NodePath.join(tempDir, "mise", "shims", name);
275 NodeFS.mkdirSync(NodePath.dirname(shimPath), { recursive: true });
276 NodeFS.symlinkSync(misePath, shimPath);
277 return shimPath;
278 }
279
280 it.layer(
281 Layer.mergeAll(
282 NodeServices.layer,
283 NodeCrypto.layer,
284 Layer.succeed(HostProcess.Environment, { PATH: "" }),
285 ),
286 )("providerMaintenance", (it) => {
287 it.effect("prefers the installer's own latest version over the npm registry", () =>
288 resolveLatestProviderVersion({ ...manualPackageTool, latestVersion: "1.2.0" }).pipe(
289 Effect.provide(ProviderLatestVersions.layer),
290 Effect.provideService(
291 HttpClient.HttpClient,
292 HttpClient.make(() =>
293 Effect.die("installer-reported latest should not make an HTTP request"),
294 ),
295 ),
296 Effect.map((version) => {
297 expect(version).toBe("1.2.0");
298 }),
299 ),
300 );
301
302 it.effect("reads the latest version from the npm registry", () =>
303 resolveLatestProviderVersion(manualPackageTool).pipe(
304 Effect.provide(ProviderLatestVersions.layer),
305 Effect.provideService(
306 HttpClient.HttpClient,
307 HttpClient.make((request) =>
308 Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ version: "1.2.3" }))),
309 ),
310 ),
311 Effect.map((version) => {
312 expect(version).toBe("1.2.3");
313 }),
314 ),
315 );
316
317 it.effect("gives up on a registry body that stalls after the headers", () =>
318 Effect.gen(function* () {
319 const lookup = yield* resolveLatestProviderVersion(manualPackageTool).pipe(
320 Effect.provide(ProviderLatestVersions.layer),
321 Effect.provideService(
322 HttpClient.HttpClient,
323 HttpClient.make((request) =>
324 Effect.succeed(HttpClientResponse.fromWeb(request, new Response(new ReadableStream()))),
325 ),
326 ),
327 Effect.forkChild({ startImmediately: true }),
328 );
329 yield* TestClock.adjust("4 seconds");
330 expect(lookup.pollUnsafe()).toBeDefined();
331 expect(yield* Fiber.join(lookup)).toBeNull();
332 }),
333 );
334
335 it.effect("does not fetch latest provider versions when update checks are disabled", () =>
336 enrichProviderSnapshotWithVersionAdvisory(
337 { ...installedPackageToolProvider, installedVersion: "1.1.0" },
338 manualPackageTool,
339 { enableProviderUpdateChecks: false },
340 ).pipe(
341 Effect.provide(ProviderLatestVersions.layer),
342 Effect.provideService(
343 HttpClient.HttpClient,
344 HttpClient.make(() =>
345 Effect.die("disabled provider update checks should not make an HTTP request"),
346 ),
347 ),
348 Effect.map((provider) => {
349 expect(provider.versionAdvisory).toMatchObject({
350 status: "unknown",
351 currentVersion: "1.1.0",
352 latestVersion: null,
353 checkedAt: "2026-04-10T00:00:00.000Z",
354 });
355 }),
356 ),
357 );
358
359 // npm-global installs ask `npm outdated` instead; see the npm-global cases below.
360 it.effect.each([
361 { install: "native", stdout: '"1.2.0"', exitCode: 0, latest: "1.2.0" },
362 { install: "manual", stdout: '["1.2.0"]', exitCode: 0, latest: "1.2.0" },
363 { install: "native", stdout: "", exitCode: 1, latest: null },
364 { install: "native", stdout: "not json", exitCode: 0, latest: null },
365 { install: "manual", stdout: '["1.2.0", "1.3.0"]', exitCode: 0, latest: null },
366 { install: "manual", stdout: '""', exitCode: 0, latest: null },
367 ])(
368 "uses npm's registry for $install installs (exit $exitCode, output $stdout)",
369 (fixture) =>
370 Effect.gen(function* () {
371 const tempDir = yield* makeTempDir("t3-registry-version");
372 const npmBinDir = NodePath.join(tempDir, "npm-bin");
373 writeExecutable(NodePath.join(npmBinDir, "npm"));
374 const binaryPath = NodePath.join(tempDir, ".local/bin/native-package-tool");
375 writeExecutable(binaryPath);
376 let probes = 0;
377 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
378 fixture.install === "native" ? nativePackageToolUpdate : packageToolUpdate,
379 { binaryPath, env: { PATH: "" } },
380 ).pipe(
381 Effect.provideService(HostProcess.Environment, { PATH: npmBinDir }),
382 Effect.provideService(
383 ChildProcessSpawner.ChildProcessSpawner,
384 stdoutSpawner(
385 (command, args) => {
386 probes++;
387 expect(command).toBe(NodePath.join(npmBinDir, "npm"));
388 expect(args).toEqual([
389 "view",
390 "--global",
391 "--json",
392 `${capabilities.packageName}@latest`,
393 "version",
394 ]);
395 return fixture.stdout;
396 },
397 () => fixture.exitCode,
398 ),
399 ),
400 );
401 const program = Effect.gen(function* () {
402 yield* enrichProviderSnapshotWithVersionAdvisory(
403 installedPackageToolProvider,
404 capabilities,
405 { enableProviderUpdateChecks: false },
406 );
407 expect(probes).toBe(0);
408 const snapshot = yield* enrichProviderSnapshotWithVersionAdvisory(
409 installedPackageToolProvider,
410 capabilities,
411 );
412 expect(snapshot.versionAdvisory?.latestVersion).toBe(fixture.latest);
413 expect(probes).toBe(1);
414 expect(yield* resolveLatestProviderVersion(capabilities)).toBe(fixture.latest);
415 expect(probes).toBe(1);
416 yield* invalidateLatestProviderVersion(capabilities);
417 expect(yield* resolveLatestProviderVersion(capabilities)).toBe(fixture.latest);
418 expect(probes).toBe(2);
419 });
420 yield* program.pipe(
421 Effect.provideServiceEffect(
422 ProviderLatestVersions.ProviderLatestVersions,
423 ProviderLatestVersions.make([
424 ["@example/package-tool", "9.9.9"],
425 ["@example/native-package-tool", "9.9.9"],
426 ]),
427 ),
428 Effect.provideService(
429 HttpClient.HttpClient,
430 HttpClient.make(() =>
431 Effect.die("a configured npm lookup must not fall back to public npm"),
432 ),
433 ),
434 );
435 }),
436 { skip: !symlinksSupported || windowsHost },
437 );
438
439 it.effect.skipIf(windowsHost)(
440 "does not offer a Vite+ update npm's release-age policy will not install",
441 () =>
442 Effect.gen(function* () {
443 const tempDir = yield* makeTempDir("t3-release-age");
444 const npmBinDir = NodePath.join(tempDir, "npm-bin");
445 const npmPath = NodePath.join(npmBinDir, "npm");
446 writeExecutable(npmPath);
447 const vitePlusNodePath = NodePath.join(tempDir, "vite-plus-node/bin/node");
448 const binaryPath = NodePath.join(tempDir, ".vite-plus/bin/package-tool");
449 writeExecutable(binaryPath);
450 const advise = (env: NodeJS.ProcessEnv, vitePlusPacks: string, nodeSource = "lts") =>
451 resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
452 binaryPath,
453 env: { PATH: npmBinDir, ...env },
454 }).pipe(
455 Effect.provideService(
456 ChildProcessSpawner.ChildProcessSpawner,
457 // `vp i -g` runs the npm beside Vite+'s Node; `npm view` ignores min-release-age.
458 stdoutSpawner((command, args) => {
459 if (command === "vp") {
460 return JSON.stringify({
461 node: { source: nodeSource, bin_path: vitePlusNodePath, installed: true },
462 });
463 }
464 if (command === npmPath) {
465 return args[0] === "view" ? '"1.2.0"' : "example-package-tool-1.2.0.tgz\n";
466 }
467 return command === NodePath.join(NodePath.dirname(vitePlusNodePath), "npm") &&
468 args[0] === "pack"
469 ? `example-package-tool-${vitePlusPacks}.tgz\n`
470 : "";
471 }),
472 ),
473 Effect.flatMap((capabilities) =>
474 enrichProviderSnapshotWithVersionAdvisory(
475 { ...installedPackageToolProvider, version: "1.1.0" },
476 capabilities,
477 ),
478 ),
479 Effect.map((snapshot) => snapshot.versionAdvisory),
480 );
481
482 expect(yield* advise({ npm_config_min_release_age: "7" }, "1.1.0")).toMatchObject({
483 status: "current",
484 currentVersion: "1.1.0",
485 latestVersion: "1.1.0",
486 });
487 expect((yield* advise({}, "1.2.0"))?.latestVersion).toBe("1.2.0");
488 // Install never uses the system Node `vp env off` reports, so this falls back to `npm view`.
489 expect(
490 (yield* advise(
491 { npm_config_min_release_age: "7", VP_HOME: "system-first" },
492 "1.1.0",
493 "system PATH",
494 ))?.latestVersion,
495 ).toBe("1.2.0");
496 }).pipe(
497 Effect.provide(ProviderLatestVersions.layer),
498 Effect.provideService(
499 HttpClient.HttpClient,
500 HttpClient.make(() =>
501 Effect.die("a configured npm lookup must not fall back to public npm"),
502 ),
503 ),
504 ),
505 );
506
507 it.effect.skipIf(!symlinksSupported || windowsHost)(
508 "keeps configured npm registries' latest versions apart for one install",
509 () =>
510 Effect.gen(function* () {
511 const tempDir = yield* makeTempDir("t3-npm-registry-isolation");
512 yield* Effect.addFinalizer(() =>
513 Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true })),
514 );
515 const npmBinDir = NodePath.join(tempDir, "npm-bin");
516 writeExecutable(NodePath.join(npmBinDir, "npm"));
517 const binaryPath = linkIntoPackage(tempDir, "package-tool", [
518 "lib",
519 "node_modules",
520 "@example",
521 "package-tool",
522 ]);
523 let probes = 0;
524 const latest = (registry: string, version: string) =>
525 resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
526 binaryPath,
527 env: { PATH: npmBinDir, NPM_CONFIG_REGISTRY: registry },
528 }).pipe(
529 Effect.provideService(
530 ChildProcessSpawner.ChildProcessSpawner,
531 stdoutSpawner(() => {
532 probes++;
533 return JSON.stringify({ "@example/package-tool": { latest: version } });
534 }),
535 ),
536 Effect.tap((capabilities) =>
537 Effect.sync(() => {
538 expect(capabilities.latestVersionCacheKey ?? "").not.toContain("private-token");
539 }),
540 ),
541 Effect.flatMap(resolveLatestProviderVersion),
542 );
543 const first = "https://user:private-token@first.example.test";
544 const second = "https://second.example.test";
545 expect(yield* latest(first, "1.1.0")).toBe("1.1.0");
546 expect(yield* latest(second, "2.0.0")).toBe("2.0.0");
547 expect(yield* latest(first, "1.2.0")).toBe("1.1.0");
548 expect(probes).toBe(2);
549 }).pipe(
550 Effect.provide(ProviderLatestVersions.layer),
551 Effect.provideService(
552 HttpClient.HttpClient,
553 HttpClient.make(() => Effect.die("configured registries must not use public npm")),
554 ),
555 ),
556 );
557
558 it("pins the advertised stable version in a pnpm-global update command", () => {
559 const advisoryFor = (
560 maintenanceCapabilities: ReturnType<typeof makeProviderMaintenanceCapabilities>,
561 latestVersion: string,
562 ) =>
563 createProviderVersionAdvisory({
564 driver: driver("packageTool"),
565 currentVersion: "1.0.0",
566 latestVersion,
567 maintenanceCapabilities,
568 }).updateCommand;
569 const pnpmTool = makeProviderMaintenanceCapabilities({
570 provider: driver("packageTool"),
571 packageName: "@example/package-tool",
572 updateExecutable: "pnpm",
573 updateArgs: [
574 "add",
575 "-g",
576 "--allow-build=@example/package-tool",
577 "@example/package-tool@latest",
578 ],
579 updateLockKey: "pnpm-global",
580 });
581
582 expect(advisoryFor(pnpmTool, "1.1.0")).toBe(
583 "pnpm add -g --allow-build=@example/package-tool @example/package-tool@1.1.0",
584 );
585 // A prerelease cannot be pinned safely, so pnpm keeps @latest.
586 expect(advisoryFor(pnpmTool, "1.1.0-beta.1")).toBe(
587 "pnpm add -g --allow-build=@example/package-tool @example/package-tool@latest",
588 );
589 // npm keeps @latest; its outdated probe already reports what that resolves to.
590 expect(
591 advisoryFor(
592 makeProviderMaintenanceCapabilities({
593 provider: driver("packageTool"),
594 packageName: "@example/package-tool",
595 updateExecutable: "npm",
596 updateArgs: ["install", "-g", "@example/package-tool@latest"],
597 updateLockKey: "npm-global:/opt/node",
598 }),
599 "1.1.0",
600 ),
601 ).toBe("npm install -g @example/package-tool@latest");
602 });
603
604 it("names the install to update when it is behind but unowned", () => {
605 expect(
606 createProviderVersionAdvisory({
607 driver: driver("packageTool"),
608 currentVersion: "2.1.110",
609 latestVersion: "2.1.117",
610 maintenanceCapabilities: {
611 ...manualPackageTool,
612 installPath: "/Applications/Tool.app/Contents/Resources/bin/package-tool",
613 },
614 }),
615 ).toMatchObject({
616 status: "behind_latest",
617 latestVersion: "2.1.117",
618 updateCommand: null,
619 canUpdate: false,
620 message:
621 "Version 2.1.117 is out. T3 Code runs /Applications/Tool.app/Contents/Resources/bin/package-tool; update it with the app or tool that installed it.",
622 });
623 });
624
625 it("offers the update when an owned install is behind", () => {
626 expect(
627 createProviderVersionAdvisory({
628 driver: driver("packageTool"),
629 currentVersion: "2.1.110",
630 latestVersion: "2.1.117",
631 maintenanceCapabilities: makeProviderMaintenanceCapabilities({
632 provider: driver("packageTool"),
633 packageName: "@example/package-tool",
634 updateExecutable: "npm",
635 updateArgs: ["install", "-g", "@example/package-tool@latest"],
636 updateLockKey: "npm-global:/usr/local",
637 }),
638 }),
639 ).toMatchObject({
640 status: "behind_latest",
641 canUpdate: true,
642 message: "Install the update now or review provider settings.",
643 });
644 });
645
646 it("shows the Chocolatey upgrade command without offering to run it", () => {
647 expect(
648 createProviderVersionAdvisory({
649 driver: driver("claudeAgent"),
650 currentVersion: "2.1.304",
651 latestVersion: "2.1.306",
652 maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
653 provider: driver("claudeAgent"),
654 packageName: "@anthropic-ai/claude-code",
655 installPath: "C:\\ProgramData\\chocolatey\\bin\\claude.exe",
656 manualCommand: "choco upgrade claude-code",
657 }),
658 }),
659 ).toMatchObject({
660 canUpdate: false,
661 canInstallVersion: false,
662 updateCommand: "choco upgrade claude-code",
663 });
664 });
665
666 it.effect("stays manual-only when the binary cannot be located", () =>
667 resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
668 binaryPath: "package-tool",
669 env: { PATH: "" },
670 }).pipe(
671 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
672 Effect.map((capabilities) => {
673 expect(capabilities).toEqual(manualPackageTool);
674 }),
675 ),
676 );
677
678 it.effect.skipIf(!symlinksSupported)(
679 "pins npm updates to the global prefix that owns the package and the provider's PATH",
680 () =>
681 Effect.gen(function* () {
682 const tempDir = yield* makeTempDir("t3-npm-capabilities");
683 const link = linkIntoPackage(tempDir, "package-tool", [
684 "lib",
685 "node_modules",
686 "@example",
687 "package-tool",
688 ]);
689 // A version manager's Node, which only the provider's settings put on PATH.
690 const providerEnv = { PATH: NodePath.join(tempDir, "bin") };
691
692 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
693 packageToolUpdate,
694 {
695 binaryPath: link,
696 env: providerEnv,
697 },
698 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
699
700 expect(capabilities).toEqual({
701 provider: driver("packageTool"),
702 packageName: "@example/package-tool",
703 latestVersion: null,
704 lookupLatestVersion: expect.anything(),
705 latestVersionCacheKey: expect.any(String),
706 update: {
707 command: `npm install -g --prefix ${tempDir} --allow-scripts=@example/package-tool @example/package-tool@latest`,
708 executable: "npm",
709 args: [
710 "install",
711 "-g",
712 "--prefix",
713 tempDir,
714 "--allow-scripts=@example/package-tool",
715 "@example/package-tool@latest",
716 ],
717 lockKey: `npm-global:${normalizeCommandPath(tempDir)}`,
718 env: providerEnv,
719 },
720 });
721 }),
722 );
723
724 it("derives the npm prefix only from the global lib/node_modules layout", () => {
725 expect(
726 npmGlobalPrefixFromCommandPath(
727 "/usr/local/lib/node_modules/@openai/codex/bin/codex.js",
728 "@openai/codex",
729 ),
730 ).toBe("/usr/local");
731 expect(
732 npmGlobalPrefixFromCommandPath(
733 "/usr/local/lib/node_modules/other/node_modules/@openai/codex/bin/codex.js",
734 "@openai/codex",
735 ),
736 ).toBeNull();
737 expect(
738 npmGlobalPrefixFromCommandPath(
739 "/lib/node_modules/@openai/codex/bin/codex.js",
740 "@openai/codex",
741 ),
742 ).toBe("/");
743 expect(
744 npmGlobalPrefixFromCommandPath(
745 "/work/app/node_modules/@openai/codex/bin/codex.js",
746 "@openai/codex",
747 ),
748 ).toBeNull();
749 });
750
751 // The Windows Codex bin junction resolves into CODEX_HOME/packages/standalone/current/bin.
752 it.effect("recognizes a Windows standalone install through its junctioned bin dir", () =>
753 Effect.gen(function* () {
754 const visiblePath =
755 "C:\\Users\\Theo\\AppData\\Local\\Programs\\OpenAI\\Codex\\bin\\codex.exe";
756 const realPath =
757 "C:\\Users\\Theo\\.codex\\packages\\standalone\\releases\\0.120.0-x86_64\\bin\\codex.exe";
758 const capabilities = yield* resolvePackageManagedProviderMaintenance(
759 {
760 provider: driver("codex"),
761 npmPackageName: "@openai/codex",
762 nativeUpdate: {
763 args: ["update"],
764 isCommandPath: isNativeTestCommandPath("/packages/standalone/"),
765 },
766 },
767 {
768 binaryPath: "codex",
769 resolvedCommandPath: visiblePath,
770 realCommandPath: realPath,
771 env: {},
772 platform: "win32",
773 },
774 ).pipe(Effect.provideService(HostProcess.Platform, "win32"));
775
776 expect(capabilities.update).toMatchObject({
777 executable: visiblePath,
778 args: ["update"],
779 lockKey: "codex-native",
780 });
781 }),
782 );
783
784 it.effect(
785 "keeps an unrecognized install manual-only when the native updater requires its path",
786 () =>
787 Effect.gen(function* () {
788 const systemPath =
789 "/usr/local/lib/codex/releases/rust-v0.162.1-x86_64-unknown-linux-musl/bin/codex";
790 const capabilities = yield* resolvePackageManagedProviderMaintenance(
791 {
792 provider: driver("codex"),
793 npmPackageName: "@openai/codex",
794 nativeUpdate: {
795 args: ["update"],
796 isCommandPath: isNativeTestCommandPath("/packages/standalone/"),
797 requiresCommandPath: true,
798 },
799 },
800 {
801 binaryPath: "codex",
802 resolvedCommandPath: "/usr/local/bin/codex",
803 realCommandPath: systemPath,
804 env: {},
805 platform: "linux",
806 },
807 ).pipe(
808 Effect.provideService(HostProcess.Platform, "linux"),
809 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
810 );
811
812 expect(capabilities.update).toBeNull();
813 expect(capabilities.installPath).toBe(systemPath);
814 }),
815 );
816
817 const claudeUpdate = {
818 provider: driver("claudeAgent"),
819 npmPackageName: "@anthropic-ai/claude-code",
820 nativeUpdate: {
821 args: ["update"],
822 isCommandPath: isNativeTestCommandPath("/.local/bin/claude"),
823 },
824 };
825 const otherProviderUpdate = {
826 provider: driver("nativePackageTool"),
827 npmPackageName: "@example/native-package-tool",
828 nativeUpdate: {
829 args: ["update"],
830 isCommandPath: isNativeTestCommandPath("/.local/bin/native-package-tool"),
831 },
832 };
833 const resolveInstall = (input: {
834 readonly definition: PackageManagedProviderMaintenanceDefinition;
835 readonly resolved: string;
836 readonly real: string;
837 readonly platform?: NodeJS.Platform;
838 readonly env?: NodeJS.ProcessEnv;
839 }) =>
840 resolvePackageManagedProviderMaintenance(input.definition, {
841 binaryPath: "claude",
842 resolvedCommandPath: input.resolved,
843 realCommandPath: input.real,
844 env: input.env ?? {},
845 platform: input.platform ?? "win32",
846 }).pipe(
847 Effect.provideService(HostProcess.Platform, input.platform ?? "win32"),
848 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
849 );
850 const userWinGetLink = "C:\\Users\\me\\AppData\\Local\\Microsoft\\WinGet\\Links\\claude.exe";
851 const userWinGetPackage =
852 "C:\\Users\\me\\AppData\\Local\\Microsoft\\WinGet\\Packages\\Anthropic.ClaudeCode_Microsoft.Winget.Source_8wekyb3d8bbwe\\claude.exe";
853 const machineWinGetLink = "C:\\Program Files\\WinGet\\Links\\claude.exe";
854 const machineWinGetPackage =
855 "C:\\Program Files\\WinGet\\Packages\\Anthropic.ClaudeCode_Microsoft.Winget.Source_8wekyb3d8bbwe\\claude.exe";
856 const nativeClaude = "C:\\Users\\me\\.local\\bin\\claude.exe";
857
858 it.effect.each([
859 { name: "a user-scope link", resolved: userWinGetLink, real: userWinGetPackage },
860 { name: "a user-scope package", resolved: userWinGetPackage, real: userWinGetPackage },
861 { name: "a machine-scope package", resolved: machineWinGetPackage, real: machineWinGetPackage },
862 { name: "a machine-scope link alone", resolved: machineWinGetLink, real: machineWinGetLink },
863 {
864 name: "a mixed-case link",
865 resolved: "c:\\USERS\\me\\appdata\\local\\MICROSOFT\\winget\\links\\Claude.EXE",
866 real: userWinGetPackage.toUpperCase(),
867 },
868 { name: "a native-looking alias", resolved: nativeClaude, real: userWinGetPackage },
869 ] as const)("keeps a WinGet Claude install manual-only through $name", (fixture) =>
870 Effect.gen(function* () {
871 const capabilities = yield* resolveInstall({ definition: claudeUpdate, ...fixture });
872
873 expect(capabilities.update).toBeNull();
874 }),
875 );
876
877 const chocolateyShim = "C:\\ProgramData\\chocolatey\\bin\\claude.exe";
878 const chocolateyPackage = "C:\\ProgramData\\chocolatey\\lib\\claude-code\\tools\\claude.exe";
879
880 it.effect.each([
881 { name: "the shimgen shim", resolved: chocolateyShim, real: chocolateyShim },
882 { name: "the package binary", resolved: chocolateyPackage, real: chocolateyPackage },
883 {
884 name: "a custom root",
885 resolved: "D:\\Tools\\Choco\\bin\\claude.exe",
886 real: "D:\\Tools\\Choco\\bin\\claude.exe",
887 env: { ChocolateyInstall: "D:\\Tools\\Choco" },
888 },
889 {
890 name: "a custom root package",
891 resolved: "D:\\Tools\\Choco\\lib\\claude-code\\tools\\claude.exe",
892 real: "D:\\Tools\\Choco\\lib\\claude-code\\tools\\claude.exe",
893 env: { ChocolateyInstall: "D:\\Tools\\Choco" },
894 },
895 {
896 name: "a mixed-case custom root with a trailing separator",
897 resolved: "D:\\Tools\\Choco\\bin\\Claude.EXE",
898 real: "D:\\Tools\\Choco\\bin\\Claude.EXE",
899 env: { ChocolateyInstall: "d:/tools/choco/" },
900 },
901 { name: "a native-looking alias", resolved: nativeClaude, real: chocolateyPackage },
902 ] as const)("keeps a Chocolatey Claude install manual-only through $name", (fixture) =>
903 Effect.gen(function* () {
904 const capabilities = yield* resolveInstall({ definition: claudeUpdate, ...fixture });
905
906 expect(capabilities.update).toBeNull();
907 expect(capabilities.installPath).toBe(fixture.real);
908 expect(capabilities.latestVersion).toBeNull();
909 expect(capabilities.lookupLatestVersion).toBeDefined();
910 expect(capabilities.manualCommand).toBe("choco upgrade claude-code");
911 }),
912 );
913
914 it.effect("keeps a Chocolatey-shaped path off Windows on the native updater", () =>
915 Effect.gen(function* () {
916 const commandPath = "/home/me/chocolatey/bin/claude.exe";
917 const capabilities = yield* resolveInstall({
918 definition: claudeUpdate,
919 resolved: commandPath,
920 real: commandPath,
921 platform: "linux",
922 });
923
924 expect(capabilities.update).toMatchObject({ lockKey: "claudeAgent-native" });
925 }),
926 );
927
928 // Chocolatey publishes behind npm, so comparing against the registry would
929 // report an update `choco upgrade` cannot install yet.
930 it.effect("compares a Chocolatey Claude install against choco search", () =>
931 Effect.gen(function* () {
932 const probes: Array<{ command: string; args: ReadonlyArray<string> }> = [];
933 const capabilities = yield* resolvePackageManagedProviderMaintenance(claudeUpdate, {
934 binaryPath: "claude",
935 resolvedCommandPath: chocolateyShim,
936 realCommandPath: chocolateyShim,
937 env: {},
938 platform: "win32",
939 }).pipe(
940 Effect.provideService(HostProcess.Platform, "win32"),
941 Effect.provideService(
942 ChildProcessSpawner.ChildProcessSpawner,
943 stdoutSpawner((command, args) => {
944 probes.push({ command, args });
945 return "claude-code|2.1.304\r\n";
946 }),
947 ),
948 );
949 expect(probes).toEqual([]);
950
951 const latest = yield* resolveLatestProviderVersion(capabilities).pipe(
952 Effect.provide(ProviderLatestVersions.layer),
953 Effect.provideService(
954 HttpClient.HttpClient,
955 HttpClient.make(() => Effect.die("the installer's latest should not come from npm")),
956 ),
957 );
958
959 expect(latest).toBe("2.1.304");
960 expect(probes.map(({ command }) => NodePath.basename(command).replace(/\.\w+$/, ""))).toEqual(
961 ["choco"],
962 );
963 expect(probes[0]?.args).toEqual(["search", "claude-code", "--exact", "--limit-output"]);
964 expect(
965 createProviderVersionAdvisory({
966 driver: driver("claudeAgent"),
967 currentVersion: "2.1.304",
968 latestVersion: latest,
969 maintenanceCapabilities: capabilities,
970 }),
971 ).toMatchObject({ status: "current", canUpdate: false, canInstallVersion: false });
972 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
973 );
974
975 it.effect("stays unknown when choco search fails instead of asking npm", () =>
976 Effect.gen(function* () {
977 const capabilities = yield* resolvePackageManagedProviderMaintenance(claudeUpdate, {
978 binaryPath: "claude",
979 resolvedCommandPath: chocolateyShim,
980 realCommandPath: chocolateyShim,
981 env: {},
982 platform: "win32",
983 }).pipe(
984 Effect.provideService(HostProcess.Platform, "win32"),
985 Effect.provideService(
986 ChildProcessSpawner.ChildProcessSpawner,
987 stdoutSpawner(
988 () => "",
989 () => 1,
990 ),
991 ),
992 );
993
994 const latest = yield* resolveLatestProviderVersion(capabilities).pipe(
995 Effect.provide(ProviderLatestVersions.layer),
996 Effect.provideService(
997 HttpClient.HttpClient,
998 HttpClient.make(() => Effect.die("a failed choco search should not fall back to npm")),
999 ),
1000 );
1001
1002 expect(latest).toBeNull();
1003 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
1004 );
1005
1006 it.effect.each([
1007 {
1008 name: "a native install",
1009 definition: claudeUpdate,
1010 resolved: nativeClaude,
1011 real: nativeClaude,
1012 },
1013 {
1014 name: "a WinGet-shaped path off Windows",
1015 definition: claudeUpdate,
1016 resolved: "/home/me/winget/links/claude.exe",
1017 real: "/home/me/winget/links/claude.exe",
1018 platform: "linux",
1019 },
1020 {
1021 name: "a WinGet-named folder outside the WinGet roots",
1022 definition: claudeUpdate,
1023 resolved: "C:\\Work\\WinGet\\Links\\claude.exe",
1024 real: "C:\\Work\\WinGet\\Links\\claude.exe",
1025 },
1026 {
1027 name: "a WinGet-named folder inside another directory",
1028 definition: claudeUpdate,
1029 resolved: "C:\\Work\\Microsoft\\WinGet\\Links\\claude.exe",
1030 real: "C:\\Work\\Microsoft\\WinGet\\Links\\claude.exe",
1031 },
1032 {
1033 name: "another provider in WinGet",
1034 definition: otherProviderUpdate,
1035 resolved: userWinGetLink,
1036 real: userWinGetPackage,
1037 },
1038 {
1039 name: "a claude-code tools path outside Chocolatey",
1040 definition: claudeUpdate,
1041 resolved: "C:\\Work\\lib\\claude-code\\tools\\claude.exe",
1042 real: "C:\\Work\\lib\\claude-code\\tools\\claude.exe",
1043 },
1044 {
1045 name: "another WinGet package",
1046 definition: claudeUpdate,
1047 resolved: userWinGetPackage.replace("ClaudeCode_", "ClaudeCodeOther_"),
1048 real: userWinGetPackage.replace("ClaudeCode_", "ClaudeCodeOther_"),
1049 },
1050 ] as const)("keeps the native updater for $name", (fixture) =>
1051 Effect.gen(function* () {
1052 const capabilities = yield* resolveInstall(fixture);
1053
1054 expect(capabilities.update).toMatchObject({
1055 executable: fixture.resolved,
1056 args: ["update"],
1057 lockKey: `${fixture.definition.provider}-native`,
1058 });
1059 }),
1060 );
1061
1062 it.effect.each([
1063 {
1064 name: "the default home",
1065 resolved: "/Users/theo/.vite-plus/bin/claude",
1066 real: "/Users/theo/.vite-plus/current/bin/vp",
1067 platform: "darwin",
1068 },
1069 {
1070 name: "the XDG home",
1071 resolved: "/home/theo/.local/share/vite-plus/bin/claude",
1072 real: "/home/theo/.local/share/vite-plus/current/bin/vp",
1073 platform: "linux",
1074 },
1075 {
1076 name: "the Windows home",
1077 resolved: "C:\\Users\\Theo\\AppData\\Local\\vite-plus\\bin\\claude.cmd",
1078 real: "C:\\Users\\Theo\\AppData\\Local\\vite-plus\\packages\\@anthropic-ai\\claude-code\\lib\\node_modules\\@anthropic-ai\\claude-code\\cli.js",
1079 platform: "win32",
1080 },
1081 ] as const)("updates a Vite+ global install in $name with vp", (fixture) =>
1082 Effect.gen(function* () {
1083 const capabilities = yield* resolveInstall({ definition: claudeUpdate, ...fixture });
1084
1085 expect(capabilities.update).toMatchObject({
1086 command: "vp i -g @anthropic-ai/claude-code",
1087 lockKey: "vite-plus-global",
1088 });
1089 }),
1090 );
1091
1092 // `vp env off` makes each shim run the next matching executable on PATH instead.
1093 it.effect.each([
1094 {
1095 name: "a system_first shim (VP_HOME layout) to a later install",
1096 vpHome: ".vite-plus",
1097 setVpHome: true,
1098 configs: { ".vite-plus": "system_first" },
1099 vitePlus: false,
1100 },
1101 {
1102 name: "a system_first shim (XDG layout) to a later install",
1103 vpHome: ".local/share/vite-plus",
1104 setVpHome: false,
1105 configs: { ".config/vite-plus": "system_first" },
1106 vitePlus: false,
1107 },
1108 {
1109 name: "a managed VP_HOME shim despite a system_first XDG config",
1110 vpHome: ".local/share/vite-plus",
1111 setVpHome: true,
1112 configs: { ".local/share/vite-plus": "managed", ".config/vite-plus": "system_first" },
1113 vitePlus: true,
1114 },
1115 ] as const)("updates through vp only for the install the shim runs: $name", (fixture) =>
1116 Effect.gen(function* () {
1117 const tempDir = yield* makeTempDir("vite-plus-system-first");
1118 const vpHome = NodePath.join(tempDir, fixture.vpHome);
1119 for (const [dir, shimMode] of Object.entries(fixture.configs)) {
1120 NodeFS.mkdirSync(NodePath.join(tempDir, dir), { recursive: true });
1121 NodeFS.writeFileSync(
1122 NodePath.join(tempDir, dir, "config.json"),
1123 JSON.stringify({ shimMode }),
1124 );
1125 }
1126 const shim = NodePath.join(vpHome, "bin", "package-tool");
1127 writeExecutable(shim);
1128 const otherInstall = linkIntoPackage(NodePath.join(tempDir, "npm"), "package-tool", [
1129 "lib",
1130 "node_modules",
1131 "@example",
1132 "package-tool",
1133 ]);
1134
1135 const capabilities = yield* packageToolUpdate
1136 .resolve({
1137 binaryPath: "package-tool",
1138 resolvedCommandPath: shim,
1139 realCommandPath: NodePath.join(vpHome, "current", "bin", "vp"),
1140 env: {
1141 ...(fixture.setVpHome ? { VP_HOME: vpHome } : {}),
1142 PATH: [NodePath.dirname(shim), NodePath.dirname(otherInstall)].join(":"),
1143 },
1144 platform: "linux",
1145 })
1146 .pipe(
1147 Effect.provideService(HostProcess.Platform, "linux"),
1148 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
1149 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
1150 );
1151
1152 expect(capabilities.update?.lockKey === "vite-plus-global").toBe(fixture.vitePlus);
1153 }),
1154 );
1155
1156 it.effect("keeps a project folder named vite-plus manual-only", () =>
1157 Effect.gen(function* () {
1158 const capabilities = yield* resolveInstall({
1159 definition: claudeUpdate,
1160 resolved: "/work/vite-plus/bin/claude",
1161 real: "/work/vite-plus/node_modules/@anthropic-ai/claude-code/cli.js",
1162 platform: "linux",
1163 });
1164
1165 expect(capabilities.update).toBeNull();
1166 }),
1167 );
1168
1169 it.effect.each([
1170 {
1171 name: "a home-manager link in the native location",
1172 definition: claudeUpdate,
1173 resolved: "/home/me/.local/bin/claude",
1174 real: "/nix/store/0c2kbzqz3m0m4hcx2g7hq1n5wfs9a6xd-claude-code-with-bun/bin/claude",
1175 },
1176 {
1177 name: "another provider's profile link",
1178 definition: otherProviderUpdate,
1179 resolved: "/etc/profiles/per-user/me/bin/native-package-tool",
1180 real: "/nix/store/0c2kbzqz3m0m4hcx2g7hq1n5wfs9a6xd-native-package-tool-1.0.0/bin/native-package-tool",
1181 },
1182 ] as const)("keeps a Nix store install manual-only through $name", (fixture) =>
1183 Effect.gen(function* () {
1184 const capabilities = yield* resolveInstall({ ...fixture, platform: "linux" });
1185
1186 expect(capabilities.update).toBeNull();
1187 }),
1188 );
1189
1190 it.effect.skipIf(windowsHost)("upgrades a mise tool through a shim of a Nix-installed mise", () =>
1191 Effect.gen(function* () {
1192 const tempDir = yield* makeTempDir("t3-nix-mise-shim");
1193 const mise = miseFixture(tempDir, { misePresent: false });
1194 const nixMise = "/nix/store/0c2kbzqz3m0m4hcx2g7hq1n5wfs9a6xd-mise-2026.1.0/bin/mise";
1195 const spawned: Array<ReadonlyArray<string>> = [];
1196
1197 const capabilities = yield* resolvePackageManagedProviderMaintenance(
1198 {
1199 provider: driver("packageTool"),
1200 npmPackageName: "@example/package-tool",
1201 mise: { tool: "package-tool" },
1202 nativeUpdate: null,
1203 },
1204 {
1205 binaryPath: "package-tool",
1206 resolvedCommandPath: NodePath.join(tempDir, "mise", "shims", "package-tool"),
1207 realCommandPath: nixMise,
1208 env: { PATH: "" },
1209 platform: "linux",
1210 },
1211 ).pipe(
1212 Effect.provideService(HostProcess.Platform, "linux"),
1213 Effect.provideService(
1214 ChildProcessSpawner.ChildProcessSpawner,
1215 miseSpawner({ which: mise.binaryPath, installed: mise.installed() }, spawned),
1216 ),
1217 );
1218
1219 expect(capabilities.update).toMatchObject({
1220 executable: nixMise,
1221 args: ["upgrade", "package-tool"],
1222 });
1223 }),
1224 );
1225
1226 it.effect("proves Windows npm ownership from the package manifest beside the shim", () =>
1227 Effect.gen(function* () {
1228 const tempDir = yield* makeTempDir("t3-npm-windows-capabilities");
1229 const shim = NodePath.join(tempDir, "package-tool.cmd");
1230 NodeFS.mkdirSync(tempDir, { recursive: true });
1231 NodeFS.writeFileSync(shim, "@echo off\r\n");
1232 NodeFS.mkdirSync(NodePath.join(tempDir, "node_modules", "@example", "package-tool"), {
1233 recursive: true,
1234 });
1235 NodeFS.writeFileSync(
1236 NodePath.join(tempDir, "node_modules", "@example", "package-tool", "package.json"),
1237 "{}",
1238 );
1239
1240 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
1241 binaryPath: shim,
1242 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
1243 }).pipe(
1244 Effect.provideService(HostProcess.Platform, "win32"),
1245 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
1246 );
1247
1248 expect(capabilities.update).toMatchObject({
1249 executable: "npm",
1250 args: ["install", "-g", "--prefix", tempDir, expect.any(String), expect.any(String)],
1251 });
1252
1253 const script = NodePath.join(tempDir, "package-tool");
1254 writeExecutable(script);
1255 const posix = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
1256 binaryPath: script,
1257 env: { PATH: "" },
1258 }).pipe(
1259 Effect.provideService(HostProcess.Platform, "linux"),
1260 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
1261 );
1262 expect(posix.update).toBeNull();
1263 }),
1264 );
1265
1266 it.effect.skipIf(!symlinksSupported)(
1267 "switches to pnpm updates when the real path lives in pnpm's global store",
1268 () =>
1269 Effect.gen(function* () {
1270 const tempDir = yield* makeTempDir("t3-pnpm-capabilities");
1271 const link = linkIntoPackage(tempDir, "package-tool", [
1272 ".local",
1273 "share",
1274 "pnpm",
1275 "global",
1276 "5",
1277 "node_modules",
1278 "@example",
1279 "package-tool",
1280 ]);
1281
1282 const updateCommand = (spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]) =>
1283 resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
1284 binaryPath: link,
1285 env: { PATH: "" },
1286 }).pipe(
1287 Effect.map((capabilities) => capabilities.update),
1288 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1289 );
1290 const pnpmVersion = (version: string) =>
1291 stdoutSpawner((command, args) => {
1292 expect([command, ...args].join(" ")).toMatch(/pnpm(\.cmd)?"? --version$/);
1293 return `${version}
1294 `;
1295 });
1296
1297 expect(yield* updateCommand(pnpmVersion("11.1.3"))).toMatchObject({
1298 command: "pnpm add -g --allow-build=@example/package-tool @example/package-tool@latest",
1299 lockKey: "pnpm-global",
1300 });
1301 expect((yield* updateCommand(pnpmVersion("10.3.0")))?.command).toBe(
1302 "pnpm add -g @example/package-tool@latest",
1303 );
1304 expect((yield* updateCommand(noSpawn))?.command).toBe(
1305 "pnpm add -g @example/package-tool@latest",
1306 );
1307 }),
1308 );
1309
1310 it.effect.each([
1311 {
1312 case: "the eligible release with an inherited PATH",
1313 inheritPath: true,
1314 outdated: { "@example/package-tool": { current: "1.0.0", latest: "1.1.0" } },
1315 exitCode: 1,
1316 npmOutput: '"1.2.0"',
1317 expected: "1.1.0",
1318 },
1319 {
1320 case: "no update during cooldown",
1321 outdated: {},
1322 exitCode: 0,
1323 npmOutput: '"1.2.0"',
1324 expected: "1.0.0",
1325 },
1326 {
1327 case: "the public registry fallback when pnpm fails and npm is unavailable",
1328 outdated: { "@example/package-tool": { current: "1.0.0", latest: "1.1.0" } },
1329 exitCode: 2,
1330 expected: "9.9.9",
1331 },
1332 {
1333 case: "the configured npm registry when the pnpm probe fails",
1334 outdated: {},
1335 exitCode: 2,
1336 npmOutput: '"1.2.0"',
1337 expected: "1.2.0",
1338 },
1339 {
1340 case: "an unknown version when both configured lookups fail",
1341 outdated: {},
1342 exitCode: 2,
1343 npmOutput: "not json",
1344 expected: null,
1345 },
1346 ])(
1347 "advertises $case for pnpm-global installs",
1348 (fixture) =>
1349 Effect.gen(function* () {
1350 const tempDir = yield* makeTempDir("t3-pnpm-latest");
1351 const pnpmBinDir = NodePath.join(tempDir, "pnpm-bin");
1352 writeExecutable(NodePath.join(pnpmBinDir, "pnpm"));
1353 if (fixture.npmOutput !== undefined) writeExecutable(NodePath.join(pnpmBinDir, "npm"));
1354 const link = linkIntoPackage(tempDir, "package-tool", [
1355 ".local",
1356 "share",
1357 "pnpm",
1358 "global",
1359 "5",
1360 "node_modules",
1361 "@example",
1362 "package-tool",
1363 ]);
1364
1365 let npmProbes = 0;
1366 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
1367 packageToolUpdate,
1368 { binaryPath: link, env: fixture.inheritPath ? {} : { PATH: pnpmBinDir } },
1369 ).pipe(
1370 Effect.provideService(HostProcess.Environment, {
1371 PATH: fixture.inheritPath ? pnpmBinDir : "",
1372 }),
1373 Effect.provideService(
1374 ChildProcessSpawner.ChildProcessSpawner,
1375 stdoutSpawner(
1376 (_command, args) => {
1377 if (args[0] === "view") {
1378 npmProbes++;
1379 return fixture.npmOutput ?? "";
1380 }
1381 return args[0] === "outdated"
1382 ? JSON.stringify(fixture.outdated)
1383 : JSON.stringify([
1384 { dependencies: { "@example/package-tool": { version: "1.0.0" } } },
1385 ]);
1386 },
1387 (args) => (args[0] === "outdated" ? fixture.exitCode : 0),
1388 ),
1389 ),
1390 );
1391
1392 const provider = yield* enrichProviderSnapshotWithVersionAdvisory(
1393 installedPackageToolProvider,
1394 capabilities,
1395 ).pipe(
1396 Effect.provideServiceEffect(
1397 ProviderLatestVersions.ProviderLatestVersions,
1398 ProviderLatestVersions.make([["@example/package-tool", "9.9.9"]]),
1399 ),
1400 Effect.provideService(
1401 HttpClient.HttpClient,
1402 HttpClient.make(() => Effect.die("the npm version is already cached")),
1403 ),
1404 );
1405 expect(provider.versionAdvisory).toMatchObject({
1406 status:
1407 fixture.expected === null
1408 ? "unknown"
1409 : fixture.expected === "1.0.0"
1410 ? "current"
1411 : "behind_latest",
1412 currentVersion: "1.0.0",
1413 latestVersion: fixture.expected,
1414 });
1415 expect(npmProbes).toBe(fixture.exitCode === 2 && fixture.npmOutput !== undefined ? 1 : 0);
1416 }),
1417 { skip: !symlinksSupported || windowsHost },
1418 );
1419
1420 it.effect.each([
1421 {
1422 case: "the eligible release",
1423 outdated: { "@example/package-tool": { current: "1.0.0", wanted: "1.1.0", latest: "1.1.0" } },
1424 exitCode: 1,
1425 status: "behind_latest",
1426 latestVersion: "1.1.0",
1427 },
1428 {
1429 case: "no update during cooldown",
1430 outdated: {},
1431 exitCode: 0,
1432 status: "current",
1433 latestVersion: "1.0.0",
1434 },
1435 {
1436 case: "no update during cooldown beside a broken global",
1437 outdated: {},
1438 exitCode: 0,
1439 listExitCode: 1,
1440 status: "current",
1441 latestVersion: "1.0.0",
1442 },
1443 {
1444 case: "no registry version when npm cannot reach the registry",
1445 outdated: { error: { code: "ECONNREFUSED" } },
1446 exitCode: 1,
1447 status: "unknown",
1448 latestVersion: null,
1449 },
1450 ])(
1451 "advertises $case for npm-global installs",
1452 (fixture) =>
1453 Effect.gen(function* () {
1454 const tempDir = yield* makeTempDir("t3-npm-latest");
1455 const npmBinDir = NodePath.join(tempDir, "npm-bin");
1456 const npmPath = NodePath.join(npmBinDir, "npm");
1457 writeExecutable(npmPath);
1458 const link = linkIntoPackage(tempDir, "package-tool", [
1459 "lib",
1460 "node_modules",
1461 "@example",
1462 "package-tool",
1463 ]);
1464
1465 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
1466 packageToolUpdate,
1467 { binaryPath: link, env: { PATH: npmBinDir } },
1468 ).pipe(
1469 // The updater's npm comes from the provider's PATH.
1470 Effect.provideService(HostProcess.Environment, { PATH: "" }),
1471 Effect.provideService(
1472 ChildProcessSpawner.ChildProcessSpawner,
1473 stdoutSpawner(
1474 (command, args) => {
1475 expect(command).toBe(npmPath);
1476 expect(args.slice(1, 4)).toEqual(["-g", "--prefix", tempDir]);
1477 return JSON.stringify(
1478 args[0] === "outdated"
1479 ? fixture.outdated
1480 : {
1481 dependencies: { "@example/package-tool": { version: "1.0.0" } },
1482 },
1483 );
1484 },
1485 (args) => (args[0] === "outdated" ? fixture.exitCode : (fixture.listExitCode ?? 0)),
1486 ),
1487 ),
1488 );
1489
1490 const provider = yield* enrichProviderSnapshotWithVersionAdvisory(
1491 installedPackageToolProvider,
1492 capabilities,
1493 ).pipe(
1494 Effect.provideServiceEffect(
1495 ProviderLatestVersions.ProviderLatestVersions,
1496 ProviderLatestVersions.make([["@example/package-tool", "9.9.9"]]),
1497 ),
1498 Effect.provideService(
1499 HttpClient.HttpClient,
1500 HttpClient.make(() => Effect.die("the npm version is already cached")),
1501 ),
1502 );
1503 expect(provider.versionAdvisory).toMatchObject({
1504 status: fixture.status,
1505 currentVersion: "1.0.0",
1506 latestVersion: fixture.latestVersion,
1507 updateCommand: expect.stringMatching(/@example\/package-tool@latest$/),
1508 });
1509 }),
1510 { skip: !symlinksSupported || windowsHost },
1511 );
1512
1513 it.effect.each([
1514 {
1515 case: "the eligible release under minimumReleaseAge",
1516 row: "| @example/package-tool | 1.0.0 | 1.0.0 | 1.1.0 * |",
1517 expected: "1.1.0",
1518 },
1519 {
1520 case: "no update when the installed version is the eligible release",
1521 row: "| @example/package-tool | 1.0.0 | 1.0.0 * | 1.0.0 * |",
1522 expected: "1.0.0",
1523 },
1524 {
1525 // bun prints only its banner both when nothing is outdated and when the registry fails.
1526 case: "the npm fallback when bun reports no row",
1527 row: null,
1528 expected: "1.2.0",
1529 },
1530 ])(
1531 "advertises $case for bun-global installs",
1532 (fixture) =>
1533 Effect.gen(function* () {
1534 const tempDir = yield* makeTempDir("t3-bun-latest");
1535 const bunBinDir = NodePath.join(tempDir, ".bun", "bin");
1536 writeExecutable(NodePath.join(bunBinDir, "bun"));
1537 writeExecutable(NodePath.join(bunBinDir, "package-tool"));
1538 const outdated = [
1539 "bun outdated v1.3.3 (274e01c7)",
1540 ...(fixture.row === null ? [] : bunOutdatedTable(fixture.row)),
1541 "",
1542 ].join("\n");
1543
1544 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
1545 packageToolUpdate,
1546 { binaryPath: "package-tool", env: { PATH: bunBinDir } },
1547 ).pipe(
1548 Effect.provideService(HostProcess.Platform, "darwin"),
1549 Effect.provideService(HostProcess.Environment, { PATH: "" }),
1550 Effect.provideService(
1551 ChildProcessSpawner.ChildProcessSpawner,
1552 stdoutSpawner((_command, args) =>
1553 args[0] === "outdated"
1554 ? outdated
1555 : `${tempDir} node_modules (1)\n└── @example/package-tool@1.0.0\n`,
1556 ),
1557 ),
1558 );
1559
1560 const provider = yield* enrichProviderSnapshotWithVersionAdvisory(
1561 installedPackageToolProvider,
1562 capabilities,
1563 ).pipe(
1564 Effect.provideServiceEffect(
1565 ProviderLatestVersions.ProviderLatestVersions,
1566 ProviderLatestVersions.make([["@example/package-tool", "1.2.0"]]),
1567 ),
1568 Effect.provideService(
1569 HttpClient.HttpClient,
1570 HttpClient.make(() => Effect.die("the npm version is already cached")),
1571 ),
1572 );
1573 expect(provider.versionAdvisory).toMatchObject({
1574 status: fixture.expected === "1.0.0" ? "current" : "behind_latest",
1575 currentVersion: "1.0.0",
1576 latestVersion: fixture.expected,
1577 });
1578 }),
1579 { skip: windowsHost },
1580 );
1581
1582 it.effect.skipIf(windowsHost)(
1583 "switches to bun updates when the resolved binary lives in bun's global bin",
1584 () =>
1585 Effect.gen(function* () {
1586 const tempDir = yield* makeTempDir("t3-bun-capabilities");
1587 const bunBinDir = NodePath.join(tempDir, ".bun", "bin");
1588 writeExecutable(NodePath.join(bunBinDir, "package-tool"));
1589
1590 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
1591 packageToolUpdate,
1592 {
1593 binaryPath: "package-tool",
1594 env: { PATH: bunBinDir },
1595 },
1596 ).pipe(
1597 Effect.provideService(HostProcess.Platform, "darwin"),
1598 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
1599 );
1600
1601 expect(capabilities.update).toMatchObject({
1602 command: "bun i -g @example/package-tool@latest",
1603 lockKey: "bun-global",
1604 });
1605 }),
1606 );
1607
1608 it.effect.skipIf(windowsHost)("switches to native updates and runs the resolved executable", () =>
1609 Effect.gen(function* () {
1610 const tempDir = yield* makeTempDir("t3-native-capabilities");
1611 const nativeBinDir = NodePath.join(tempDir, ".local", "bin");
1612 const nativePath = NodePath.join(nativeBinDir, "native-package-tool");
1613 writeExecutable(nativePath);
1614
1615 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
1616 nativePackageToolUpdate,
1617 {
1618 binaryPath: "native-package-tool",
1619 env: {
1620 PATH: nativeBinDir,
1621 MISE_SHIMS_DIR: nativeBinDir,
1622 MISE_SYSTEM_SHIMS_DIR: nativeBinDir,
1623 },
1624 },
1625 ).pipe(
1626 Effect.provideService(HostProcess.Platform, "darwin"),
1627 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
1628 );
1629
1630 expect(capabilities).toEqual({
1631 provider: driver("nativePackageTool"),
1632 packageName: "@example/native-package-tool",
1633 update: {
1634 command: `${nativePath} update`,
1635 executable: nativePath,
1636 args: ["update"],
1637 lockKey: "nativePackageTool-native",
1638 },
1639 });
1640 }),
1641 );
1642
1643 it.effect.each(["wrapper", "symlink", "custom-data"])(
1644 "keeps a mise-owned %s in a native install location manual-only",
1645 (launcher, { skip }) => {
1646 if (windowsHost || (launcher !== "wrapper" && !symlinksSupported)) skip();
1647 return Effect.gen(function* () {
1648 const tempDir = yield* makeTempDir("t3-native-mise");
1649 const nativePath = NodePath.join(tempDir, ".local", "bin", "native-package-tool");
1650 if (launcher === "wrapper") {
1651 writeExecutable(nativePath);
1652 NodeFS.writeFileSync(
1653 nativePath,
1654 '#!/bin/sh\nexec mise x native-package-tool -- native-package-tool "$@"\n',
1655 );
1656 } else {
1657 const target = NodePath.join(
1658 tempDir,
1659 launcher === "custom-data" ? "managed-tools" : "mise",
1660 "installs",
1661 "native-package-tool",
1662 "1.0.0",
1663 "native-package-tool",
1664 );
1665 writeExecutable(target);
1666 NodeFS.mkdirSync(NodePath.dirname(nativePath), { recursive: true });
1667 NodeFS.symlinkSync(target, nativePath);
1668 }
1669
1670 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
1671 nativePackageToolUpdate,
1672 {
1673 binaryPath: nativePath,
1674 env: {
1675 PATH: "",
1676 ...(launcher === "custom-data"
1677 ? { MISE_DATA_DIR: NodePath.join(tempDir, "managed-tools") }
1678 : {}),
1679 },
1680 },
1681 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
1682
1683 expect(capabilities.update).toBeNull();
1684 });
1685 },
1686 );
1687
1688 it.effect.skipIf(!symlinksSupported || windowsHost)(
1689 "updates an npm-owned launcher in a native install location with npm",
1690 () =>
1691 Effect.gen(function* () {
1692 const tempDir = yield* makeTempDir("t3-native-npm");
1693 const prefix = NodePath.join(tempDir, ".local");
1694 const packageBin = NodePath.join("node_modules", "@example", "native-package-tool", "bin");
1695 writeExecutable(NodePath.join(prefix, "lib", packageBin, "native-package-tool.exe"));
1696 const launcher = NodePath.join(prefix, "bin", "native-package-tool");
1697 NodeFS.mkdirSync(NodePath.dirname(launcher), { recursive: true });
1698 NodeFS.symlinkSync(
1699 NodePath.join("..", "lib", packageBin, "native-package-tool.exe"),
1700 launcher,
1701 );
1702
1703 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
1704 nativePackageToolUpdate,
1705 { binaryPath: launcher, env: { PATH: "" } },
1706 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
1707
1708 expect(capabilities.update).toMatchObject({
1709 executable: "npm",
1710 args: expect.arrayContaining(["--prefix", prefix]),
1711 lockKey: `npm-global:${normalizeCommandPath(prefix)}`,
1712 });
1713 }),
1714 );
1715
1716 it.effect.skipIf(!symlinksSupported)(
1717 "prefers npm ownership over the Node keg the package lives under",
1718 () =>
1719 Effect.gen(function* () {
1720 const tempDir = yield* makeTempDir("t3-homebrew-node-capabilities");
1721 const keg = NodePath.join(tempDir, "Cellar", "node", "22.1.0");
1722 const target = NodePath.join(
1723 keg,
1724 "lib",
1725 "node_modules",
1726 "@example",
1727 "package-tool",
1728 "bin",
1729 "package-tool.js",
1730 );
1731 writeExecutable(target);
1732 const link = NodePath.join(tempDir, "bin", "package-tool");
1733 NodeFS.mkdirSync(NodePath.dirname(link), { recursive: true });
1734 NodeFS.symlinkSync(target, link);
1735
1736 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
1737 packageToolUpdate,
1738 {
1739 binaryPath: link,
1740 env: { PATH: "" },
1741 },
1742 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
1743
1744 expect(capabilities.update).toMatchObject({
1745 executable: "npm",
1746 args: expect.arrayContaining(["--prefix", keg]),
1747 lockKey: `npm-global:${normalizeCommandPath(keg)}`,
1748 });
1749 }),
1750 );
1751
1752 for (const fixture of [
1753 {
1754 name: "an npm-shaped package",
1755 definition: packageToolUpdate,
1756 target: ["lib", "node_modules", "@example", "package-tool", "bin", "package-tool.exe"],
1757 },
1758 {
1759 name: "a launcher script",
1760 definition: nativePackageToolUpdate,
1761 target: ["share", "native-package-tool", "native-package-tool"],
1762 },
1763 ]) {
1764 it.effect.skipIf(!symlinksSupported || windowsHost)(
1765 `leaves ${fixture.name} owned by MacPorts to MacPorts`,
1766 () =>
1767 Effect.gen(function* () {
1768 const prefix = yield* makeTempDir("t3-macports");
1769 writeExecutable(NodePath.join(prefix, "bin", "port"));
1770 const target = NodePath.join(prefix, ...fixture.target);
1771 writeExecutable(target);
1772 const launcher = NodePath.join(prefix, "bin", NodePath.basename(target, ".exe"));
1773 NodeFS.symlinkSync(target, launcher);
1774
1775 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
1776 fixture.definition,
1777 { binaryPath: launcher, env: { PATH: NodePath.join(prefix, "bin") } },
1778 ).pipe(
1779 Effect.provideService(HostProcess.Platform, "darwin"),
1780 Effect.provideService(
1781 ChildProcessSpawner.ChildProcessSpawner,
1782 stdoutSpawner((command, args) =>
1783 NodePath.basename(command) === "port" && args.includes("provides")
1784 ? args.includes("-q")
1785 ? "package-tool\n"
1786 : args
1787 .filter((arg) => arg.startsWith("/"))
1788 .map((file) => `${file} is provided by: package-tool\n`)
1789 .join("")
1790 : "",
1791 ),
1792 ),
1793 );
1794
1795 expect(capabilities.update).toBeNull();
1796 expect(capabilities.manualCommand).toBe("sudo port upgrade package-tool");
1797 }),
1798 );
1799 }
1800
1801 it("quotes copyable command words the shell would split", () => {
1802 const posix = makeProviderMaintenanceCapabilities({
1803 provider: driver("packageTool"),
1804 packageName: "@example/package-tool",
1805 updateExecutable: "npm",
1806 updateArgs: [
1807 "install",
1808 "-g",
1809 "--prefix",
1810 "/Users/Jane Doe/.npm-global",
1811 "@example/package-tool@latest",
1812 ],
1813 updateLockKey: "npm-global",
1814 platform: "darwin",
1815 });
1816 expect(posix.update?.command).toBe(
1817 "npm install -g --prefix '/Users/Jane Doe/.npm-global' @example/package-tool@latest",
1818 );
1819 const windows = makeProviderMaintenanceCapabilities({
1820 provider: driver("packageTool"),
1821 packageName: null,
1822 updateExecutable: "C:\\Program Files\\Tool\\tool.exe",
1823 updateArgs: ["update"],
1824 updateLockKey: "tool",
1825 platform: "win32",
1826 });
1827 expect(windows.update?.command).toBe("& 'C:\\Program Files\\Tool\\tool.exe' update");
1828 });
1829
1830 it.effect.skipIf(windowsHost)("carries the native updater's environment into the action", () =>
1831 Effect.gen(function* () {
1832 const tempDir = yield* makeTempDir("t3-native-env");
1833 const nativePath = NodePath.join(tempDir, ".local", "bin", "native-package-tool");
1834 writeExecutable(nativePath);
1835 const resolver = makePackageManagedProviderMaintenanceResolver({
1836 provider: driver("nativePackageTool"),
1837 npmPackageName: "@example/native-package-tool",
1838 nativeUpdate: {
1839 args: ["update"],
1840 isCommandPath: isNativeTestCommandPath("/.local/bin/native-package-tool"),
1841 env: { TOOL_HOME: tempDir },
1842 },
1843 });
1844
1845 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(resolver, {
1846 binaryPath: nativePath,
1847 env: { PATH: "" },
1848 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
1849
1850 expect(capabilities.update?.env).toEqual({ TOOL_HOME: tempDir });
1851 }),
1852 );
1853
1854 it("reads the Chocolatey package version from choco search --limit-output", () => {
1855 expect(parseChocolateyLatestVersion("claude-code|2.1.304\r\n", "claude-code")).toBe("2.1.304");
1856 expect(parseChocolateyLatestVersion("Claude-Code|2.1.304\r\n", "claude-code")).toBe("2.1.304");
1857 expect(parseChocolateyLatestVersion("claude-code-other|9.9.9\r\n", "claude-code")).toBeNull();
1858 expect(parseChocolateyLatestVersion("", "claude-code")).toBeNull();
1859 });
1860
1861 it("recognizes Homebrew kegs and casks from the real executable path", () => {
1862 expect(
1863 homebrewOwnershipFromCommandPath("/opt/homebrew/Cellar/claude-code@latest/2.1.0/bin/claude"),
1864 ).toEqual({ kind: "formula", name: "claude-code@latest", prefix: "/opt/homebrew" });
1865 expect(homebrewOwnershipFromCommandPath("/usr/local/Caskroom/codex/0.148.0/codex")).toEqual({
1866 kind: "cask",
1867 name: "codex",
1868 prefix: "/usr/local",
1869 });
1870 expect(homebrewOwnershipFromCommandPath("/usr/local/bin/codex")).toBeNull();
1871 expect(homebrewOwnershipFromCommandPath("/srv/Cellar/claude/1.0.0/bin/claude")).toMatchObject({
1872 prefix: "/srv",
1873 });
1874 });
1875
1876 it.effect("shares installer lookups only for the same executable and update target", () =>
1877 Effect.gen(function* () {
1878 let lookups = 0;
1879 const capabilities = (executable: string, args: ReadonlyArray<string>, version: string) =>
1880 makeProviderMaintenanceCapabilities({
1881 provider: driver("packageTool"),
1882 packageName: "@example/package-tool",
1883 updateExecutable: executable,
1884 updateArgs: args,
1885 updateLockKey: "homebrew",
1886 latestVersion: null,
1887 lookupLatestVersion: Effect.sync(() => {
1888 lookups += 1;
1889 return version;
1890 }),
1891 });
1892
1893 const formula = capabilities("/opt/homebrew/bin/brew", ["upgrade", "package-tool"], "2.0.0");
1894 const cask = capabilities(
1895 "/opt/homebrew/bin/brew",
1896 ["upgrade", "--cask", "package-tool"],
1897 "3.0.0",
1898 );
1899 const otherBrew = capabilities("/usr/local/bin/brew", ["upgrade", "package-tool"], "4.0.0");
1900
1901 expect(yield* resolveLatestProviderVersion(formula)).toBe("2.0.0");
1902 expect(yield* resolveLatestProviderVersion(cask)).toBe("3.0.0");
1903 expect(yield* resolveLatestProviderVersion(otherBrew)).toBe("4.0.0");
1904 const refreshed = capabilities(
1905 "/opt/homebrew/bin/brew",
1906 ["upgrade", "package-tool"],
1907 "5.0.0",
1908 );
1909 expect(yield* resolveLatestProviderVersion(refreshed)).toBe("2.0.0");
1910 expect(lookups).toBe(3);
1911
1912 yield* invalidateLatestProviderVersion(refreshed);
1913 expect(yield* resolveLatestProviderVersion(refreshed)).toBe("5.0.0");
1914 expect(yield* resolveLatestProviderVersion(cask)).toBe("3.0.0");
1915 expect(yield* resolveLatestProviderVersion(otherBrew)).toBe("4.0.0");
1916 expect(lookups).toBe(4);
1917 }).pipe(
1918 Effect.provide(ProviderLatestVersions.layer),
1919 Effect.provideService(
1920 HttpClient.HttpClient,
1921 HttpClient.make(() => Effect.die("Homebrew's latest should not come from npm")),
1922 ),
1923 ),
1924 );
1925
1926 it.effect(
1927 "refreshes installer versions without letting an older lookup overwrite the result",
1928 () =>
1929 Effect.gen(function* () {
1930 const started = yield* Deferred.make<void>();
1931 const release = yield* Deferred.make<string>();
1932 let lookups = 0;
1933 const capabilities = makeProviderMaintenanceCapabilities({
1934 provider: driver("packageTool"),
1935 packageName: "@example/package-tool",
1936 updateExecutable: "/opt/homebrew/bin/brew",
1937 updateArgs: ["upgrade", "package-tool"],
1938 updateLockKey: "homebrew",
1939 latestVersion: null,
1940 lookupLatestVersion: Effect.suspend(() =>
1941 ++lookups === 1
1942 ? Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(release)))
1943 : Effect.succeed("2.0.0"),
1944 ),
1945 });
1946 const pending = yield* resolveLatestProviderVersion(capabilities).pipe(Effect.forkChild);
1947 yield* Deferred.await(started);
1948 yield* invalidateLatestProviderVersion(capabilities);
1949 expect(yield* resolveLatestProviderVersion(capabilities)).toBe("2.0.0");
1950
1951 yield* Deferred.succeed(release, "1.0.0");
1952 expect(yield* Fiber.join(pending)).toBe("1.0.0");
1953 expect(yield* resolveLatestProviderVersion(capabilities)).toBe("2.0.0");
1954 expect(lookups).toBe(2);
1955 }).pipe(
1956 Effect.provide(ProviderLatestVersions.layer),
1957 Effect.provideService(
1958 HttpClient.HttpClient,
1959 HttpClient.make(() => Effect.die("Homebrew's latest should not come from npm")),
1960 ),
1961 ),
1962 );
1963
1964 it.effect.skipIf(windowsHost)(
1965 "stays manual-only when the keg is not under the resolved brew's prefix",
1966 () =>
1967 Effect.gen(function* () {
1968 const tempDir = yield* makeTempDir("t3-homebrew-foreign-prefix");
1969 const brewBinDir = NodePath.join(tempDir, "brew-bin");
1970 writeExecutable(NodePath.join(brewBinDir, "brew"));
1971 const kegBinary = NodePath.join(
1972 tempDir,
1973 "elsewhere",
1974 "Cellar",
1975 "package-tool",
1976 "1.0.0",
1977 "bin",
1978 "package-tool",
1979 );
1980 writeExecutable(kegBinary);
1981
1982 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
1983 packageToolUpdate,
1984 {
1985 binaryPath: kegBinary,
1986 env: { PATH: brewBinDir },
1987 },
1988 ).pipe(
1989 Effect.provideService(HostProcess.Platform, "darwin"),
1990 Effect.provideService(
1991 ChildProcessSpawner.ChildProcessSpawner,
1992 stdoutSpawner(() => "/opt/homebrew\n"),
1993 ),
1994 );
1995
1996 expect(capabilities).toEqual({
1997 ...manualPackageTool,
1998 installPath: NodeFS.realpathSync(kegBinary),
1999 });
2000 }),
2001 );
2002
2003 it("reads the stable formula version from brew info", () => {
2004 const info = JSON.stringify({ formulae: [{ versions: { stable: "2.1.5" } }] });
2005 const formula = { kind: "formula", name: "claude-code", prefix: "/opt/homebrew" } as const;
2006 expect(parseHomebrewLatestVersion(info, formula)).toBe("2.1.5");
2007 expect(parseHomebrewLatestVersion("not json", formula)).toBeNull();
2008 });
2009
2010 it("treats Homebrew's latest cask version as unknown", () => {
2011 const info = JSON.stringify({ casks: [{ version: "latest" }] });
2012 const cask = { kind: "cask", name: "package-tool", prefix: "/opt/homebrew" } as const;
2013 expect(parseHomebrewLatestVersion(info, cask)).toBeNull();
2014 });
2015
2016 it.effect.skipIf(windowsHost)(
2017 "disables one-click updates for explicit custom binary paths it cannot safely map",
2018 () =>
2019 Effect.gen(function* () {
2020 const tempDir = yield* makeTempDir("t3-custom-capabilities");
2021 const customPath = NodePath.join(tempDir, "tools", "package-tool");
2022 writeExecutable(customPath);
2023
2024 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
2025 packageToolUpdate,
2026 {
2027 binaryPath: customPath,
2028 env: { PATH: "" },
2029 },
2030 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
2031
2032 expect(capabilities).toEqual({
2033 ...manualPackageTool,
2034 installPath: NodeFS.realpathSync(customPath),
2035 });
2036 }),
2037 );
2038
2039 it.effect.skipIf(windowsHost)(
2040 "falls back to the provider's own updater when no installer is proven",
2041 () =>
2042 Effect.gen(function* () {
2043 const tempDir = yield* makeTempDir("t3-self-update-fallback");
2044 const customPath = NodePath.join(tempDir, "tools", "package-tool");
2045 writeExecutable(customPath);
2046 const selfUpdating = makePackageManagedProviderMaintenanceResolver({
2047 provider: driver("packageTool"),
2048 npmPackageName: "@example/package-tool",
2049 nativeUpdate: { args: ["update", "--self"] },
2050 });
2051
2052 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(selfUpdating, {
2053 binaryPath: customPath,
2054 env: { PATH: "" },
2055 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
2056 expect(capabilities.update).toMatchObject({
2057 executable: customPath,
2058 args: ["update", "--self"],
2059 lockKey: "packageTool-native",
2060 });
2061
2062 const misePath = NodePath.join(tempDir, "mise", "installs", "package-tool", "1.0.0", "bin");
2063 writeExecutable(NodePath.join(misePath, "package-tool"));
2064 const mise = yield* resolveProviderMaintenanceCapabilitiesEffect(selfUpdating, {
2065 binaryPath: NodePath.join(misePath, "package-tool"),
2066 env: { PATH: "" },
2067 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
2068 expect(mise.update).toBeNull();
2069
2070 // A mise command wrapper is a symlink to the mise binary, not to the tool.
2071 const miseBinary = NodePath.join(tempDir, "usr", "bin", "mise");
2072 writeExecutable(miseBinary);
2073 const wrapper = NodePath.join(
2074 tempDir,
2075 ".local",
2076 "share",
2077 "mise",
2078 "command-wrappers",
2079 "bin",
2080 "package-tool",
2081 );
2082 NodeFS.mkdirSync(NodePath.dirname(wrapper), { recursive: true });
2083 NodeFS.symlinkSync(miseBinary, wrapper);
2084 const viaWrapper = yield* resolveProviderMaintenanceCapabilitiesEffect(selfUpdating, {
2085 binaryPath: wrapper,
2086 env: { PATH: "" },
2087 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
2088 expect(viaWrapper.update).toBeNull();
2089 }),
2090 );
2091
2092 it.effect.each([
2093 { name: "its latest link", via: "latest" },
2094 { name: "a latest link in a custom data dir", via: "latest", dataDir: "data" },
2095 { name: "a shim", via: "shim" },
2096 // `mise upgrade package-tool` skips a tool configured by its backend name.
2097 { name: "a shim to a backend-configured install", via: "shim", backend: "npm:package-tool" },
2098 ])(
2099 "upgrades the mapped mise tool through $name requested as latest",
2100 (fixture) =>
2101 Effect.gen(function* () {
2102 const tempDir = yield* makeTempDir("t3-mise-upgrade");
2103 const mise = miseFixture(tempDir, {
2104 ...(fixture.dataDir ? { dataDir: NodePath.join(tempDir, fixture.dataDir) } : {}),
2105 ...(fixture.backend ? { backend: fixture.backend } : {}),
2106 });
2107 const upgradeTool = fixture.backend ?? "package-tool";
2108 const binaryPath =
2109 fixture.via === "latest"
2110 ? mise.latestBinaryPath
2111 : linkShim(tempDir, mise.misePath, "package-tool");
2112 const spawned: Array<ReadonlyArray<string>> = [];
2113
2114 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(miseToolUpdate, {
2115 binaryPath,
2116 env: { PATH: mise.miseBinDir },
2117 }).pipe(
2118 Effect.provideService(
2119 ChildProcessSpawner.ChildProcessSpawner,
2120 miseSpawner({ which: mise.binaryPath, installed: mise.installed() }, spawned),
2121 ),
2122 );
2123
2124 expect(capabilities.update).toMatchObject({
2125 command: `mise upgrade ${upgradeTool}`,
2126 executable: mise.misePath,
2127 args: ["upgrade", upgradeTool],
2128 });
2129 expect(spawned).toContainEqual([mise.misePath, "which", "package-tool"]);
2130 // Resolution proves ownership but never asks mise for releases.
2131 expect(spawned.some((args) => args[1] === "latest")).toBe(false);
2132 }),
2133 { skip: !symlinksSupported || windowsHost },
2134 );
2135
2136 it.effect.each([
2137 { name: "a pinned version", installed: { requested_version: "1.0.0" } },
2138 { name: "an inactive install", installed: { active: false } },
2139 { name: "an install of another mise tool", tool: "other-tool" },
2140 { name: "an install mise which does not run", which: "elsewhere" },
2141 { name: "an install without mise on PATH", misePresent: false },
2142 { name: "a provider with no mise tool", definition: "unmapped" },
2143 { name: "a mise x wrapper", via: "wrapper" },
2144 { name: "a fixed version path", via: "versioned" },
2145 { name: "a version mise activate put on PATH", via: "activated" },
2146 ] as const)(
2147 "leaves $name manual-only",
2148 (fixture) =>
2149 Effect.gen(function* () {
2150 const tempDir = yield* makeTempDir("t3-mise-manual");
2151 const mise = miseFixture(tempDir, {
2152 misePresent: !("misePresent" in fixture),
2153 tool: "tool" in fixture ? fixture.tool : "package-tool",
2154 });
2155 let binaryPath = symlinksSupported ? mise.latestBinaryPath : mise.binaryPath;
2156 let path = mise.miseBinDir;
2157 if ("via" in fixture && fixture.via === "versioned") {
2158 binaryPath = mise.binaryPath;
2159 } else if ("via" in fixture && fixture.via === "activated") {
2160 binaryPath = "package-tool";
2161 path = [NodePath.dirname(mise.binaryPath), mise.miseBinDir].join(NodePath.delimiter);
2162 } else if ("via" in fixture) {
2163 binaryPath = NodePath.join(tempDir, "bin", "package-tool");
2164 NodeFS.mkdirSync(NodePath.dirname(binaryPath), { recursive: true });
2165 NodeFS.writeFileSync(
2166 binaryPath,
2167 '#!/bin/sh\nexec mise x package-tool -- package-tool "$@"\n',
2168 );
2169 NodeFS.chmodSync(binaryPath, 0o755);
2170 }
2171 const which =
2172 "which" in fixture
2173 ? NodePath.join(tempDir, "elsewhere", "package-tool")
2174 : mise.binaryPath;
2175
2176 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
2177 "definition" in fixture ? packageToolUpdate : miseToolUpdate,
2178 { binaryPath, env: { PATH: path } },
2179 ).pipe(
2180 Effect.provideService(
2181 ChildProcessSpawner.ChildProcessSpawner,
2182 miseSpawner(
2183 {
2184 which,
2185 installed: mise.installed("installed" in fixture ? fixture.installed : {}),
2186 },
2187 [],
2188 ),
2189 ),
2190 );
2191
2192 expect(capabilities.update).toBeNull();
2193 expect(capabilities.lookupLatestVersion).toBeUndefined();
2194 }),
2195 { skip: windowsHost },
2196 );
2197
2198 it.effect.skipIf(windowsHost)(
2199 "keeps the provider's own updater for an install mise does not own",
2200 () =>
2201 Effect.gen(function* () {
2202 const tempDir = yield* makeTempDir("t3-mise-native");
2203 const nativePath = NodePath.join(tempDir, ".local", "bin", "native-package-tool");
2204 writeExecutable(nativePath);
2205 const miseMappedNative = makePackageManagedProviderMaintenanceResolver({
2206 provider: driver("nativePackageTool"),
2207 npmPackageName: "@example/native-package-tool",
2208 mise: { tool: "native-package-tool" },
2209 nativeUpdate: {
2210 args: ["update"],
2211 isCommandPath: isNativeTestCommandPath("/.local/bin/native-package-tool"),
2212 },
2213 });
2214
2215 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(miseMappedNative, {
2216 binaryPath: nativePath,
2217 env: { PATH: "" },
2218 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
2219
2220 expect(capabilities.update).toEqual({
2221 command: `${nativePath} update`,
2222 executable: nativePath,
2223 args: ["update"],
2224 lockKey: "nativePackageTool-native",
2225 });
2226 }),
2227 );
2228
2229 it.effect.each([
2230 {
2231 name: "a mise tool whose upgrades are disabled",
2232 mise: { tool: "package-tool", upgrade: false },
2233 },
2234 { name: "a pinned mise tool", mise: { tool: "package-tool" }, pinned: true },
2235 {
2236 name: "an inactive version of a mise tool",
2237 mise: { tool: "package-tool" },
2238 inactive: true,
2239 },
2240 {
2241 name: "an inactive version of a mise tool whose upgrades are disabled",
2242 mise: { tool: "package-tool", upgrade: false },
2243 inactive: true,
2244 },
2245 ] as const)(
2246 "keeps $name in a custom data dir manual-only instead of running its own updater",
2247 (fixture) =>
2248 Effect.gen(function* () {
2249 const tempDir = yield* makeTempDir("t3-mise-custom-manual");
2250 const mise = miseFixture(tempDir, { dataDir: NodePath.join(tempDir, "data") });
2251 let binaryPath = mise.latestBinaryPath;
2252 let installed = mise.installed("pinned" in fixture ? { requested_version: "1.0.0" } : {});
2253 if ("inactive" in fixture) {
2254 // Configured to 1.0.0 while mise resolves its active 2.0.0 instead.
2255 binaryPath = mise.binaryPath;
2256 const inactive = { ...installed["package-tool"]![0]!, active: false };
2257 mise.install("2.0.0");
2258 installed = { "package-tool": [inactive, ...mise.installed()["package-tool"]!] };
2259 }
2260 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
2261 makePackageManagedProviderMaintenanceResolver({
2262 provider: driver("packageTool"),
2263 npmPackageName: "@example/package-tool",
2264 mise: fixture.mise,
2265 nativeUpdate: { args: ["upgrade"] },
2266 }),
2267 { binaryPath, env: { PATH: mise.miseBinDir } },
2268 ).pipe(
2269 Effect.provideService(
2270 ChildProcessSpawner.ChildProcessSpawner,
2271 miseSpawner({ which: mise.binaryPath, installed }, []),
2272 ),
2273 );
2274
2275 expect(capabilities.update).toBeNull();
2276 }),
2277 { skip: !symlinksSupported || windowsHost },
2278 );
2279
2280 it.effect.skipIf(!symlinksSupported || windowsHost)(
2281 "updates an npm global under mise's Node with npm even when mise runs it",
2282 () =>
2283 Effect.gen(function* () {
2284 const tempDir = yield* makeTempDir("t3-mise-node-npm");
2285 const mise = miseFixture(tempDir);
2286 const nodePrefix = NodePath.join(tempDir, "mise", "installs", "node", "22.0.0");
2287 const binaryPath = NodePath.join(nodePrefix, "bin", "package-tool");
2288 const target = NodePath.join(
2289 nodePrefix,
2290 "lib",
2291 "node_modules",
2292 "@example",
2293 "package-tool",
2294 "bin",
2295 "package-tool.js",
2296 );
2297 writeExecutable(target);
2298 NodeFS.mkdirSync(NodePath.dirname(binaryPath), { recursive: true });
2299 NodeFS.symlinkSync(target, binaryPath);
2300
2301 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(miseToolUpdate, {
2302 binaryPath,
2303 env: { PATH: mise.miseBinDir },
2304 }).pipe(
2305 Effect.provideService(
2306 ChildProcessSpawner.ChildProcessSpawner,
2307 // mise resolves the npm global through its Node; no `package-tool` tool is installed.
2308 miseSpawner({ which: binaryPath, installed: {} }, []),
2309 ),
2310 );
2311
2312 expect(capabilities.update?.args).toEqual([
2313 "install",
2314 "-g",
2315 "--prefix",
2316 NodeFS.realpathSync(nodePrefix),
2317 "--allow-scripts=@example/package-tool",
2318 "@example/package-tool@latest",
2319 ]);
2320 }),
2321 );
2322
2323 it.effect.skipIf(!symlinksSupported || windowsHost)(
2324 "asks mise for its latest release only while update checks are enabled",
2325 () =>
2326 Effect.gen(function* () {
2327 const tempDir = yield* makeTempDir("t3-mise-latest");
2328 const mise = miseFixture(tempDir);
2329 const spawned: Array<ReadonlyArray<string>> = [];
2330 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(miseToolUpdate, {
2331 binaryPath: mise.latestBinaryPath,
2332 env: { PATH: mise.miseBinDir },
2333 }).pipe(
2334 Effect.provideService(
2335 ChildProcessSpawner.ChildProcessSpawner,
2336 miseSpawner(
2337 // mise's `minimum_release_age` can hold it behind npm's 1.2.0.
2338 { which: mise.binaryPath, latest: "1.1.0", installed: mise.installed() },
2339 spawned,
2340 ),
2341 ),
2342 );
2343 const advise = (enableProviderUpdateChecks: boolean) =>
2344 enrichProviderSnapshotWithVersionAdvisory(installedPackageToolProvider, capabilities, {
2345 enableProviderUpdateChecks,
2346 });
2347
2348 expect((yield* advise(false)).versionAdvisory).toMatchObject({
2349 status: "unknown",
2350 latestVersion: null,
2351 });
2352 expect(spawned.filter((args) => args[1] === "latest")).toEqual([]);
2353
2354 expect((yield* advise(true)).versionAdvisory).toMatchObject({
2355 status: "behind_latest",
2356 latestVersion: "1.1.0",
2357 });
2358 expect((yield* advise(true)).versionAdvisory?.latestVersion).toBe("1.1.0");
2359 expect(spawned.filter((args) => args[1] === "latest")).toEqual([
2360 [mise.misePath, "latest", "package-tool"],
2361 ]);
2362 }).pipe(
2363 Effect.provide(ProviderLatestVersions.layer),
2364 Effect.provideService(
2365 HttpClient.HttpClient,
2366 HttpClient.make(() => Effect.die("mise answers for its own installs")),
2367 ),
2368 ),
2369 );
2370
2371 it.effect.skipIf(!symlinksSupported || windowsHost)(
2372 "keeps each mise environment's latest release apart",
2373 () =>
2374 Effect.gen(function* () {
2375 const tempDir = yield* makeTempDir("t3-mise-latest-env");
2376 const mise = miseFixture(tempDir);
2377 const advise = (env: NodeJS.ProcessEnv, latest: string) =>
2378 resolveProviderMaintenanceCapabilitiesEffect(miseToolUpdate, {
2379 binaryPath: mise.latestBinaryPath,
2380 env: { PATH: mise.miseBinDir, ...env },
2381 }).pipe(
2382 Effect.provideService(
2383 ChildProcessSpawner.ChildProcessSpawner,
2384 miseSpawner({ which: mise.binaryPath, latest, installed: mise.installed() }, []),
2385 ),
2386 Effect.flatMap((capabilities) =>
2387 enrichProviderSnapshotWithVersionAdvisory(
2388 installedPackageToolProvider,
2389 capabilities,
2390 {
2391 enableProviderUpdateChecks: true,
2392 },
2393 ),
2394 ),
2395 Effect.map((snapshot) => snapshot.versionAdvisory?.latestVersion),
2396 );
2397
2398 expect(yield* advise({ MISE_MINIMUM_RELEASE_AGE: "7d" }, "1.1.0")).toBe("1.1.0");
2399 expect(yield* advise({}, "1.2.0")).toBe("1.2.0");
2400 expect(yield* advise({ MISE_MINIMUM_RELEASE_AGE: "7d" }, "1.2.0")).toBe("1.1.0");
2401 }).pipe(
2402 Effect.provide(ProviderLatestVersions.layer),
2403 Effect.provideService(
2404 HttpClient.HttpClient,
2405 HttpClient.make(() => Effect.die("mise answers for its own installs")),
2406 ),
2407 ),
2408 );
2409
2410 it.effect.each([
2411 { name: "fails", latest: { exitCode: 1 } },
2412 { name: "prints nothing", latest: { stdout: "" } },
2413 { name: "never answers", latest: "hang" },
2414 ] as const)(
2415 "reports an unknown latest version when mise latest $name",
2416 (fixture) =>
2417 Effect.gen(function* () {
2418 const tempDir = yield* makeTempDir("t3-mise-latest-unknown");
2419 const mise = miseFixture(tempDir);
2420 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(miseToolUpdate, {
2421 binaryPath: mise.latestBinaryPath,
2422 env: { PATH: mise.miseBinDir },
2423 }).pipe(
2424 Effect.provideService(
2425 ChildProcessSpawner.ChildProcessSpawner,
2426 miseSpawner(
2427 { which: mise.binaryPath, latest: fixture.latest, installed: mise.installed() },
2428 [],
2429 ),
2430 ),
2431 );
2432 expect(capabilities.update).toMatchObject({ args: ["upgrade", "package-tool"] });
2433
2434 const advisory = yield* enrichProviderSnapshotWithVersionAdvisory(
2435 installedPackageToolProvider,
2436 capabilities,
2437 { enableProviderUpdateChecks: true },
2438 ).pipe(Effect.forkChild);
2439 yield* TestClock.adjust("1 minute");
2440
2441 expect((yield* Fiber.join(advisory)).versionAdvisory).toMatchObject({
2442 status: "unknown",
2443 latestVersion: null,
2444 });
2445 }).pipe(
2446 Effect.provide(ProviderLatestVersions.layer),
2447 Effect.provideService(
2448 HttpClient.HttpClient,
2449 HttpClient.make(() => Effect.die("an offline mise must not fall back to npm")),
2450 ),
2451 ),
2452 { skip: !symlinksSupported || windowsHost },
2453 );
2454
2455 it.effect.skipIf(!symlinksSupported)("updates Yarn global installs with yarn", () =>
2456 Effect.gen(function* () {
2457 const tempDir = yield* makeTempDir("t3-yarn-capabilities");
2458 const link = linkIntoPackage(tempDir, "package-tool", [
2459 ".config",
2460 "yarn",
2461 "global",
2462 "node_modules",
2463 "@example",
2464 "package-tool",
2465 ]);
2466
2467 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
2468 binaryPath: link,
2469 env: { PATH: "" },
2470 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
2471
2472 expect(capabilities.update).toMatchObject({
2473 command: "yarn global add @example/package-tool@latest",
2474 lockKey: "yarn-global",
2475 });
2476 expect(makeTargetedProviderUpdateAction(capabilities, "2.0.0")?.args).toEqual([
2477 "global",
2478 "add",
2479 "@example/package-tool@2.0.0",
2480 ]);
2481 }),
2482 );
2483
2484 it.effect.skipIf(!symlinksSupported)(
2485 "updates Volta installs only when Volta has the package",
2486 () =>
2487 Effect.gen(function* () {
2488 const voltaHome = NodePath.join(yield* makeTempDir("t3-volta-capabilities"), ".volta");
2489 const shim = NodePath.join(voltaHome, "bin", "volta-shim");
2490 writeExecutable(shim);
2491 const link = NodePath.join(voltaHome, "bin", "package-tool");
2492 NodeFS.symlinkSync(shim, link);
2493 const resolve = resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
2494 binaryPath: link,
2495 env: { PATH: "" },
2496 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
2497
2498 expect((yield* resolve).update).toBeNull();
2499 NodeFS.mkdirSync(
2500 NodePath.join(voltaHome, "tools", "image", "packages", "@example", "package-tool"),
2501 { recursive: true },
2502 );
2503 expect((yield* resolve).update).toMatchObject({
2504 command: "volta install @example/package-tool@latest",
2505 lockKey: "volta",
2506 });
2507 }),
2508 );
2509
2510 it.effect.each([
2511 { name: "Volta's script shim", script: "@echo off\r\nvolta run %~n0 %*\r\n", owned: true },
2512 {
2513 name: "a fixed-target wrapper",
2514 script: '#!/bin/bash\nvolta run node /other/opencode/index.js "$@"\n',
2515 owned: false,
2516 },
2517 {
2518 name: "an unreachable forwarding line",
2519 script: "@echo off\r\nexit /b 0\r\nvolta run %~n0 %*\r\n",
2520 owned: false,
2521 },
2522 {
2523 name: "Volta's bash shim without a final newline",
2524 script: '#!/bin/bash\nvolta run "$(basename $0)" "$@"',
2525 owned: true,
2526 },
2527 ])(
2528 "updates Windows Volta installs from $name only when Volta has the package",
2529 ({ script, owned }) =>
2530 Effect.gen(function* () {
2531 const voltaHome = NodePath.join(yield* makeTempDir("t3-volta-windows"), "Volta");
2532 const shim = NodePath.join(voltaHome, "bin", "package-tool.CMD");
2533 NodeFS.mkdirSync(NodePath.dirname(shim), { recursive: true });
2534 NodeFS.writeFileSync(shim, script);
2535 const resolve = resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
2536 binaryPath: shim,
2537 env: { PATH: "" },
2538 }).pipe(
2539 Effect.provideService(HostProcess.Platform, "win32"),
2540 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
2541 );
2542
2543 expect((yield* resolve).update).toBeNull();
2544 NodeFS.mkdirSync(
2545 NodePath.join(voltaHome, "tools", "image", "packages", "@example", "package-tool"),
2546 { recursive: true },
2547 );
2548 expect((yield* resolve).update).toEqual(
2549 owned
2550 ? expect.objectContaining({
2551 command: "volta install @example/package-tool@latest",
2552 lockKey: "volta",
2553 })
2554 : null,
2555 );
2556 }),
2557 );
2558
2559 it.effect.skipIf(windowsHost)("upgrades with the keg's own brew when brew is not on PATH", () =>
2560 Effect.gen(function* () {
2561 const tempDir = yield* makeTempDir("t3-homebrew-keg-brew");
2562 const brewPath = NodePath.join(tempDir, "bin", "brew");
2563 writeExecutable(brewPath);
2564 const kegBinary = NodePath.join(tempDir, "Cellar", "package-tool", "1.0.0", "bin", "tool");
2565 writeExecutable(kegBinary);
2566
2567 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
2568 binaryPath: kegBinary,
2569 env: { PATH: "" },
2570 }).pipe(
2571 Effect.provideService(HostProcess.Platform, "darwin"),
2572 Effect.provideService(
2573 ChildProcessSpawner.ChildProcessSpawner,
2574 stdoutSpawner((_command, args) => (args[0] === "--prefix" ? `${tempDir}\n` : "{}")),
2575 ),
2576 );
2577
2578 expect(capabilities.update).toMatchObject({
2579 executable: brewPath,
2580 args: ["upgrade", "package-tool"],
2581 lockKey: "homebrew",
2582 });
2583 }),
2584 );
2585
2586 it.effect("starts a fresh read instead of joining the resolution already running", () =>
2587 Effect.gen(function* () {
2588 const releaseStale = yield* Deferred.make<void>();
2589 let resolutions = 0;
2590 const resolve = yield* makeCachedProviderMaintenanceResolution(
2591 Effect.suspend(() => {
2592 resolutions += 1;
2593 return resolutions === 1
2594 ? Deferred.await(releaseStale).pipe(Effect.as(manualPackageTool))
2595 : Effect.succeed(manualPackageTool);
2596 }),
2597 );
2598
2599 const advisory = yield* Effect.forkChild(resolve(), { startImmediately: true });
2600 const fresh = yield* Effect.forkChild(resolve({ fresh: true }), { startImmediately: true });
2601 expect(resolutions).toBe(2);
2602 expect(fresh.pollUnsafe()).toBeDefined();
2603 yield* Deferred.succeed(releaseStale, undefined);
2604 expect(yield* Fiber.join(fresh)).toEqual(manualPackageTool);
2605 yield* Fiber.join(advisory);
2606 }),
2607 );
2608
2609 it.effect("resolves again after the first read is interrupted", () =>
2610 Effect.gen(function* () {
2611 const release = yield* Deferred.make<void>();
2612 let resolutions = 0;
2613 const resolve = yield* makeCachedProviderMaintenanceResolution(
2614 Effect.suspend(() => {
2615 resolutions += 1;
2616 return resolutions === 1
2617 ? Effect.never
2618 : Deferred.await(release).pipe(Effect.as(manualPackageTool));
2619 }),
2620 );
2621
2622 const first = yield* Effect.forkChild(resolve(), { startImmediately: true });
2623 yield* Fiber.interrupt(first);
2624
2625 const owner = yield* Effect.forkChild(resolve(), { startImmediately: true });
2626 const waiter = yield* Effect.forkChild(resolve(), { startImmediately: true });
2627 yield* Fiber.interrupt(owner);
2628 yield* Deferred.succeed(release, undefined);
2629 expect(yield* Fiber.join(waiter)).toEqual(manualPackageTool);
2630 expect(yield* resolve()).toEqual(manualPackageTool);
2631 expect(resolutions).toBe(2);
2632 }),
2633 );
2634 });
2635
2636 it("pins only owned package-manager installs and preserves their execution context", () => {
2637 const capabilities = makeProviderMaintenanceCapabilities({
2638 provider: driver("codex"),
2639 packageName: "@openai/codex",
2640 updateExecutable: "npm",
2641 updateLockKey: "npm-global:/opt/node",
2642 updateArgs: [
2643 "install",
2644 "-g",
2645 "--prefix",
2646 "/opt/node",
2647 "--allow-scripts=@openai/codex",
2648 "@openai/codex@latest",
2649 ],
2650 env: { PATH: "/opt/node/bin" },
2651 });
2652 const pinned = makeTargetedProviderUpdateAction(capabilities, "2.0.0");
2653 expect(pinned).toMatchObject({
2654 executable: "npm",
2655 lockKey: capabilities.update?.lockKey,
2656 env: capabilities.update?.env,
2657 args: [
2658 "install",
2659 "-g",
2660 "--prefix",
2661 "/opt/node",
2662 "--allow-scripts=@openai/codex",
2663 "@openai/codex@2.0.0",
2664 ],
2665 });
2666 expect(pinned?.command).toContain("@openai/codex@2.0.0");
2667 for (const lockKey of ["codex-native", "homebrew", "manual"]) {
2668 expect(
2669 makeTargetedProviderUpdateAction(
2670 { ...capabilities, update: { ...capabilities.update!, lockKey } },
2671 "2.0.0",
2672 ),
2673 ).toBeNull();
2674 }
2675 expect(makeTargetedProviderUpdateAction(capabilities, "2.0.0; rm -rf /")).toBeNull();
2676 });