Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import { expect, it } from "@effect/vitest";
3import * as NodeFS from "node:fs";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import * as NodeOS from "node:os";
6import * as NodePath from "node:path";
7import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
8import * as HostProcess from "@t3tools/shared/HostProcess";
9import * as Crypto from "effect/Crypto";
10import * as Deferred from "effect/Deferred";
11import * as Effect from "effect/Effect";
12import * as Fiber from "effect/Fiber";
13import * as Layer from "effect/Layer";
14import * as Sink from "effect/Sink";
15import * as Stream from "effect/Stream";
16import * as HttpClient from "effect/http/HttpClient";
17import * as HttpClientResponse from "effect/http/HttpClientResponse";
18import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
19import * as TestClock from "effect/testing/TestClock";
20import * as ProviderLatestVersions from "./ProviderLatestVersions.ts";
21import {
22 createProviderVersionAdvisory,
23 makeTargetedProviderUpdateAction,
24 enrichProviderSnapshotWithVersionAdvisory,
25 homebrewOwnershipFromCommandPath,
26 invalidateLatestProviderVersion,
27 makeCachedProviderMaintenanceResolution,
28 makePackageManagedProviderMaintenanceResolver,
29 makeProviderMaintenanceCapabilities,
30 normalizeCommandPath,
31 npmGlobalPrefixFromCommandPath,
32 parseHomebrewLatestVersion,
33 resolveLatestProviderVersion,
34 resolvePackageManagedProviderMaintenance,
35 resolveProviderMaintenanceCapabilitiesEffect,
36 type PackageManagedProviderMaintenanceDefinition,
37 type ProviderMaintenanceCapabilities,
38} from "./maintenanceResolver.ts";
39import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
40
41const driver = (value: string) => ProviderDriverKind.make(value);
42// Shell stubs use POSIX paths; Windows temp paths cannot split on colon.
43const windowsHost = HostProcess.Platform.defaultValue() === "win32";
44const makeTempDir = (name: string) =>
45 Crypto.Crypto.pipe(
46 Effect.flatMap((crypto) => crypto.randomUUIDv4()),
47 Effect.map((id) => NodePath.join(NodeFS.realpathSync(NodeOS.tmpdir()), `${name}-${id}`)),
48 );
49const isNativeTestCommandPath =
50 (expectedPathSegment: string) =>
51 (commandPath: string): boolean =>
52 normalizeCommandPath(commandPath).includes(expectedPathSegment);
53const packageToolUpdate = makePackageManagedProviderMaintenanceResolver({
54 provider: driver("packageTool"),
55 npmPackageName: "@example/package-tool",
56 nativeUpdate: null,
57});
58const nativePackageToolUpdate = makePackageManagedProviderMaintenanceResolver({
59 provider: driver("nativePackageTool"),
60 npmPackageName: "@example/native-package-tool",
61 nativeUpdate: {
62 args: ["update"],
63 isCommandPath: isNativeTestCommandPath("/.local/bin/native-package-tool"),
64 },
65});
66const installedPackageToolProvider: ServerProvider = {
67 instanceId: ProviderInstanceId.make("packageTool"),
68 driver: driver("packageTool"),
69 enabled: true,
70 installed: true,
71 version: "1.0.0",
72 status: "ready",
73 auth: { status: "authenticated" },
74 checkedAt: "2026-04-10T00:00:00.000Z",
75 models: [],
76 slashCommands: [],
77 skills: [],
78};
79const manualPackageTool: ProviderMaintenanceCapabilities = {
80 provider: driver("packageTool"),
81 packageName: "@example/package-tool",
82 update: null,
83};
84
85function writeExecutable(path: string) {
86 NodeFS.mkdirSync(NodePath.dirname(path), { recursive: true });
87 NodeFS.writeFileSync(path, "#!/bin/sh\n");
88 NodeFS.chmodSync(path, 0o755);
89}
90
91function linkIntoPackage(tempDir: string, name: string, packageSegments: ReadonlyArray<string>) {
92 const target = NodePath.join(tempDir, ...packageSegments, "bin", `${name}.js`);
93 writeExecutable(target);
94 const link = NodePath.join(tempDir, "bin", name);
95 NodeFS.mkdirSync(NodePath.dirname(link), { recursive: true });
96 NodeFS.symlinkSync(target, link);
97 return link;
98}
99
100const noSpawn = ChildProcessSpawner.make(() =>
101 Effect.die("maintenance resolution should not spawn a process here"),
102);
103
104function stdoutSpawner(
105 onSpawn: (command: string, args: ReadonlyArray<string>) => string,
106 exitCodeOf: (args: ReadonlyArray<string>) => number = () => 0,
107) {
108 return ChildProcessSpawner.make((command) => {
109 const { command: executable, args } = command as unknown as {
110 readonly command: string;
111 readonly args: ReadonlyArray<string>;
112 };
113 return Effect.succeed(
114 ChildProcessSpawner.makeHandle({
115 pid: ChildProcessSpawner.ProcessId(1),
116 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCodeOf(args))),
117 isRunning: Effect.succeed(false),
118 kill: () => Effect.void,
119 unref: Effect.succeed(Effect.void),
120 stdin: Sink.drain,
121 stdout: Stream.encodeText(Stream.make(onSpawn(executable, args))),
122 stderr: Stream.empty,
123 all: Stream.empty,
124 getInputFd: () => Sink.drain,
125 getOutputFd: () => Stream.empty,
126 }),
127 );
128 });
129}
130
131it.layer(
132 NodeServices.layer.pipe(Layer.merge(Layer.succeed(HostProcess.Environment, { PATH: "" }))),
133)("providerMaintenance", (it) => {
134 it.effect("prefers the installer's own latest version over the npm registry", () =>
135 resolveLatestProviderVersion({ ...manualPackageTool, latestVersion: "1.2.0" }).pipe(
136 Effect.provide(ProviderLatestVersions.layer),
137 Effect.provideService(
138 HttpClient.HttpClient,
139 HttpClient.make(() =>
140 Effect.die("installer-reported latest should not make an HTTP request"),
141 ),
142 ),
143 Effect.map((version) => {
144 expect(version).toBe("1.2.0");
145 }),
146 ),
147 );
148
149 it.effect("reads the latest version from the npm registry", () =>
150 resolveLatestProviderVersion(manualPackageTool).pipe(
151 Effect.provide(ProviderLatestVersions.layer),
152 Effect.provideService(
153 HttpClient.HttpClient,
154 HttpClient.make((request) =>
155 Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ version: "1.2.3" }))),
156 ),
157 ),
158 Effect.map((version) => {
159 expect(version).toBe("1.2.3");
160 }),
161 ),
162 );
163
164 it.effect("gives up on a registry body that stalls after the headers", () =>
165 Effect.gen(function* () {
166 const lookup = yield* resolveLatestProviderVersion(manualPackageTool).pipe(
167 Effect.provide(ProviderLatestVersions.layer),
168 Effect.provideService(
169 HttpClient.HttpClient,
170 HttpClient.make((request) =>
171 Effect.succeed(HttpClientResponse.fromWeb(request, new Response(new ReadableStream()))),
172 ),
173 ),
174 Effect.forkChild({ startImmediately: true }),
175 );
176 yield* TestClock.adjust("4 seconds");
177 expect(lookup.pollUnsafe()).toBeDefined();
178 expect(yield* Fiber.join(lookup)).toBeNull();
179 }),
180 );
181
182 it.effect("does not fetch latest provider versions when update checks are disabled", () =>
183 enrichProviderSnapshotWithVersionAdvisory(
184 { ...installedPackageToolProvider, installedVersion: "1.1.0" },
185 manualPackageTool,
186 { enableProviderUpdateChecks: false },
187 ).pipe(
188 Effect.provide(ProviderLatestVersions.layer),
189 Effect.provideService(
190 HttpClient.HttpClient,
191 HttpClient.make(() =>
192 Effect.die("disabled provider update checks should not make an HTTP request"),
193 ),
194 ),
195 Effect.map((provider) => {
196 expect(provider.versionAdvisory).toMatchObject({
197 status: "unknown",
198 currentVersion: "1.1.0",
199 latestVersion: null,
200 checkedAt: "2026-04-10T00:00:00.000Z",
201 });
202 }),
203 ),
204 );
205
206 it.effect.each([
207 { install: "native", stdout: '"1.2.0"', exitCode: 0, latest: "1.2.0" },
208 { install: "manual", stdout: '["1.2.0"]', exitCode: 0, latest: "1.2.0" },
209 { install: "npm", stdout: '"1.2.0"', exitCode: 0, latest: "1.2.0" },
210 { install: "native", stdout: "", exitCode: 1, latest: null },
211 { install: "npm", stdout: '"1.2.0"', exitCode: 1, latest: null },
212 { install: "native", stdout: "not json", exitCode: 0, latest: null },
213 { install: "manual", stdout: '["1.2.0", "1.3.0"]', exitCode: 0, latest: null },
214 { install: "manual", stdout: '""', exitCode: 0, latest: null },
215 ])(
216 "uses npm's registry for $install installs (exit $exitCode, output $stdout)",
217 (fixture) =>
218 Effect.gen(function* () {
219 const tempDir = yield* makeTempDir("t3-registry-version");
220 const npmBinDir = NodePath.join(tempDir, "npm-bin");
221 writeExecutable(NodePath.join(npmBinDir, "npm"));
222 const binaryPath =
223 fixture.install === "npm"
224 ? linkIntoPackage(tempDir, "package-tool", [
225 "lib",
226 "node_modules",
227 "@example",
228 "package-tool",
229 ])
230 : NodePath.join(tempDir, ".local/bin/native-package-tool");
231 if (fixture.install !== "npm") writeExecutable(binaryPath);
232 let probes = 0;
233 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
234 fixture.install === "native" ? nativePackageToolUpdate : packageToolUpdate,
235 { binaryPath, env: { PATH: "" } },
236 ).pipe(
237 Effect.provideService(HostProcess.Environment, { PATH: npmBinDir }),
238 Effect.provideService(
239 ChildProcessSpawner.ChildProcessSpawner,
240 stdoutSpawner(
241 (command, args) => {
242 probes++;
243 expect(command).toBe(NodePath.join(npmBinDir, "npm"));
244 expect(args).toEqual([
245 "view",
246 "--global",
247 ...(fixture.install === "npm" ? ["--prefix", tempDir] : []),
248 "--json",
249 `${capabilities.packageName}@latest`,
250 "version",
251 ]);
252 return fixture.stdout;
253 },
254 () => fixture.exitCode,
255 ),
256 ),
257 );
258 const program = Effect.gen(function* () {
259 yield* enrichProviderSnapshotWithVersionAdvisory(
260 installedPackageToolProvider,
261 capabilities,
262 { enableProviderUpdateChecks: false },
263 );
264 expect(probes).toBe(0);
265 const snapshot = yield* enrichProviderSnapshotWithVersionAdvisory(
266 installedPackageToolProvider,
267 capabilities,
268 );
269 expect(snapshot.versionAdvisory?.latestVersion).toBe(fixture.latest);
270 expect(probes).toBe(1);
271 expect(yield* resolveLatestProviderVersion(capabilities)).toBe(fixture.latest);
272 expect(probes).toBe(1);
273 yield* invalidateLatestProviderVersion(capabilities);
274 expect(yield* resolveLatestProviderVersion(capabilities)).toBe(fixture.latest);
275 expect(probes).toBe(2);
276 });
277 yield* program.pipe(
278 Effect.provideServiceEffect(
279 ProviderLatestVersions.ProviderLatestVersions,
280 ProviderLatestVersions.make([
281 ["@example/package-tool", "9.9.9"],
282 ["@example/native-package-tool", "9.9.9"],
283 ]),
284 ),
285 Effect.provideService(
286 HttpClient.HttpClient,
287 HttpClient.make(() =>
288 Effect.die("a configured npm lookup must not fall back to public npm"),
289 ),
290 ),
291 );
292 }),
293 { skip: !symlinksSupported || windowsHost },
294 );
295
296 it("pins the advertised stable version in a pnpm-global update command", () => {
297 const advisoryFor = (
298 maintenanceCapabilities: ReturnType<typeof makeProviderMaintenanceCapabilities>,
299 latestVersion: string,
300 ) =>
301 createProviderVersionAdvisory({
302 driver: driver("packageTool"),
303 currentVersion: "1.0.0",
304 latestVersion,
305 maintenanceCapabilities,
306 }).updateCommand;
307 const pnpmTool = makeProviderMaintenanceCapabilities({
308 provider: driver("packageTool"),
309 packageName: "@example/package-tool",
310 updateExecutable: "pnpm",
311 updateArgs: [
312 "add",
313 "-g",
314 "--allow-build=@example/package-tool",
315 "@example/package-tool@latest",
316 ],
317 updateLockKey: "pnpm-global",
318 });
319
320 expect(advisoryFor(pnpmTool, "1.1.0")).toBe(
321 "pnpm add -g --allow-build=@example/package-tool @example/package-tool@1.1.0",
322 );
323 // A prerelease cannot be pinned safely, so pnpm keeps @latest.
324 expect(advisoryFor(pnpmTool, "1.1.0-beta.1")).toBe(
325 "pnpm add -g --allow-build=@example/package-tool @example/package-tool@latest",
326 );
327 // Only pnpm's minimumReleaseAge skips fresh releases; npm keeps @latest.
328 expect(
329 advisoryFor(
330 makeProviderMaintenanceCapabilities({
331 provider: driver("packageTool"),
332 packageName: "@example/package-tool",
333 updateExecutable: "npm",
334 updateArgs: ["install", "-g", "@example/package-tool@latest"],
335 updateLockKey: "npm-global:/opt/node",
336 }),
337 "1.1.0",
338 ),
339 ).toBe("npm install -g @example/package-tool@latest");
340 });
341
342 it("names the install to update when it is behind but unowned", () => {
343 expect(
344 createProviderVersionAdvisory({
345 driver: driver("packageTool"),
346 currentVersion: "2.1.110",
347 latestVersion: "2.1.117",
348 maintenanceCapabilities: {
349 ...manualPackageTool,
350 installPath: "/Applications/Tool.app/Contents/Resources/bin/package-tool",
351 },
352 }),
353 ).toMatchObject({
354 status: "behind_latest",
355 latestVersion: "2.1.117",
356 updateCommand: null,
357 canUpdate: false,
358 message:
359 "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.",
360 });
361 });
362
363 it("offers the update when an owned install is behind", () => {
364 expect(
365 createProviderVersionAdvisory({
366 driver: driver("packageTool"),
367 currentVersion: "2.1.110",
368 latestVersion: "2.1.117",
369 maintenanceCapabilities: makeProviderMaintenanceCapabilities({
370 provider: driver("packageTool"),
371 packageName: "@example/package-tool",
372 updateExecutable: "npm",
373 updateArgs: ["install", "-g", "@example/package-tool@latest"],
374 updateLockKey: "npm-global:/usr/local",
375 }),
376 }),
377 ).toMatchObject({
378 status: "behind_latest",
379 canUpdate: true,
380 message: "Install the update now or review provider settings.",
381 });
382 });
383
384 it.effect("stays manual-only when the binary cannot be located", () =>
385 resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
386 binaryPath: "package-tool",
387 env: { PATH: "" },
388 }).pipe(
389 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
390 Effect.map((capabilities) => {
391 expect(capabilities).toEqual(manualPackageTool);
392 }),
393 ),
394 );
395
396 it.effect.skipIf(!symlinksSupported)(
397 "pins npm updates to the global prefix that owns the package",
398 () =>
399 Effect.gen(function* () {
400 const tempDir = yield* makeTempDir("t3-npm-capabilities");
401 const link = linkIntoPackage(tempDir, "package-tool", [
402 "lib",
403 "node_modules",
404 "@example",
405 "package-tool",
406 ]);
407
408 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
409 packageToolUpdate,
410 {
411 binaryPath: link,
412 env: { PATH: "" },
413 },
414 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
415
416 expect(capabilities).toEqual({
417 provider: driver("packageTool"),
418 packageName: "@example/package-tool",
419 update: {
420 command: `npm install -g --prefix ${tempDir} --allow-scripts=@example/package-tool @example/package-tool@latest`,
421 executable: "npm",
422 args: [
423 "install",
424 "-g",
425 "--prefix",
426 tempDir,
427 "--allow-scripts=@example/package-tool",
428 "@example/package-tool@latest",
429 ],
430 lockKey: `npm-global:${normalizeCommandPath(tempDir)}`,
431 },
432 });
433 }),
434 );
435
436 it("derives the npm prefix only from the global lib/node_modules layout", () => {
437 expect(
438 npmGlobalPrefixFromCommandPath(
439 "/usr/local/lib/node_modules/@openai/codex/bin/codex.js",
440 "@openai/codex",
441 ),
442 ).toBe("/usr/local");
443 expect(
444 npmGlobalPrefixFromCommandPath(
445 "/usr/local/lib/node_modules/other/node_modules/@openai/codex/bin/codex.js",
446 "@openai/codex",
447 ),
448 ).toBeNull();
449 expect(
450 npmGlobalPrefixFromCommandPath(
451 "/lib/node_modules/@openai/codex/bin/codex.js",
452 "@openai/codex",
453 ),
454 ).toBe("/");
455 expect(
456 npmGlobalPrefixFromCommandPath(
457 "/work/app/node_modules/@openai/codex/bin/codex.js",
458 "@openai/codex",
459 ),
460 ).toBeNull();
461 });
462
463 // The Windows Codex bin junction resolves into CODEX_HOME/packages/standalone/current/bin.
464 it.effect("recognizes a Windows standalone install through its junctioned bin dir", () =>
465 Effect.gen(function* () {
466 const visiblePath =
467 "C:\\Users\\Theo\\AppData\\Local\\Programs\\OpenAI\\Codex\\bin\\codex.exe";
468 const realPath =
469 "C:\\Users\\Theo\\.codex\\packages\\standalone\\releases\\0.120.0-x86_64\\bin\\codex.exe";
470 const capabilities = yield* resolvePackageManagedProviderMaintenance(
471 {
472 provider: driver("codex"),
473 npmPackageName: "@openai/codex",
474 nativeUpdate: {
475 args: ["update"],
476 isCommandPath: isNativeTestCommandPath("/packages/standalone/"),
477 },
478 },
479 {
480 binaryPath: "codex",
481 resolvedCommandPath: visiblePath,
482 realCommandPath: realPath,
483 env: {},
484 platform: "win32",
485 },
486 ).pipe(Effect.provideService(HostProcess.Platform, "win32"));
487
488 expect(capabilities.update).toMatchObject({
489 executable: visiblePath,
490 args: ["update"],
491 lockKey: "codex-native",
492 });
493 }),
494 );
495
496 it.effect(
497 "keeps an unrecognized install manual-only when the native updater requires its path",
498 () =>
499 Effect.gen(function* () {
500 const systemPath =
501 "/usr/local/lib/codex/releases/rust-v0.162.1-x86_64-unknown-linux-musl/bin/codex";
502 const capabilities = yield* resolvePackageManagedProviderMaintenance(
503 {
504 provider: driver("codex"),
505 npmPackageName: "@openai/codex",
506 nativeUpdate: {
507 args: ["update"],
508 isCommandPath: isNativeTestCommandPath("/packages/standalone/"),
509 requiresCommandPath: true,
510 },
511 },
512 {
513 binaryPath: "codex",
514 resolvedCommandPath: "/usr/local/bin/codex",
515 realCommandPath: systemPath,
516 env: {},
517 platform: "linux",
518 },
519 ).pipe(
520 Effect.provideService(HostProcess.Platform, "linux"),
521 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
522 );
523
524 expect(capabilities.update).toBeNull();
525 expect(capabilities.installPath).toBe(systemPath);
526 }),
527 );
528
529 const claudeUpdate = {
530 provider: driver("claudeAgent"),
531 npmPackageName: "@anthropic-ai/claude-code",
532 nativeUpdate: {
533 args: ["update"],
534 isCommandPath: isNativeTestCommandPath("/.local/bin/claude"),
535 },
536 };
537 const otherProviderUpdate = {
538 provider: driver("nativePackageTool"),
539 npmPackageName: "@example/native-package-tool",
540 nativeUpdate: {
541 args: ["update"],
542 isCommandPath: isNativeTestCommandPath("/.local/bin/native-package-tool"),
543 },
544 };
545 const resolveInstall = (input: {
546 readonly definition: PackageManagedProviderMaintenanceDefinition;
547 readonly resolved: string;
548 readonly real: string;
549 readonly platform?: NodeJS.Platform;
550 }) =>
551 resolvePackageManagedProviderMaintenance(input.definition, {
552 binaryPath: "claude",
553 resolvedCommandPath: input.resolved,
554 realCommandPath: input.real,
555 env: {},
556 platform: input.platform ?? "win32",
557 }).pipe(
558 Effect.provideService(HostProcess.Platform, input.platform ?? "win32"),
559 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
560 );
561 const userWinGetLink = "C:\\Users\\me\\AppData\\Local\\Microsoft\\WinGet\\Links\\claude.exe";
562 const userWinGetPackage =
563 "C:\\Users\\me\\AppData\\Local\\Microsoft\\WinGet\\Packages\\Anthropic.ClaudeCode_Microsoft.Winget.Source_8wekyb3d8bbwe\\claude.exe";
564 const machineWinGetLink = "C:\\Program Files\\WinGet\\Links\\claude.exe";
565 const machineWinGetPackage =
566 "C:\\Program Files\\WinGet\\Packages\\Anthropic.ClaudeCode_Microsoft.Winget.Source_8wekyb3d8bbwe\\claude.exe";
567 const nativeClaude = "C:\\Users\\me\\.local\\bin\\claude.exe";
568
569 it.effect.each([
570 { name: "a user-scope link", resolved: userWinGetLink, real: userWinGetPackage },
571 { name: "a user-scope package", resolved: userWinGetPackage, real: userWinGetPackage },
572 { name: "a machine-scope package", resolved: machineWinGetPackage, real: machineWinGetPackage },
573 { name: "a machine-scope link alone", resolved: machineWinGetLink, real: machineWinGetLink },
574 {
575 name: "a mixed-case link",
576 resolved: "c:\\USERS\\me\\appdata\\local\\MICROSOFT\\winget\\links\\Claude.EXE",
577 real: userWinGetPackage.toUpperCase(),
578 },
579 { name: "a native-looking alias", resolved: nativeClaude, real: userWinGetPackage },
580 ] as const)("keeps a WinGet Claude install manual-only through $name", (fixture) =>
581 Effect.gen(function* () {
582 const capabilities = yield* resolveInstall({ definition: claudeUpdate, ...fixture });
583
584 expect(capabilities.update).toBeNull();
585 }),
586 );
587
588 it.effect.each([
589 {
590 name: "a native install",
591 definition: claudeUpdate,
592 resolved: nativeClaude,
593 real: nativeClaude,
594 },
595 {
596 name: "a WinGet-shaped path off Windows",
597 definition: claudeUpdate,
598 resolved: "/home/me/winget/links/claude.exe",
599 real: "/home/me/winget/links/claude.exe",
600 platform: "linux",
601 },
602 {
603 name: "a WinGet-named folder outside the WinGet roots",
604 definition: claudeUpdate,
605 resolved: "C:\\Work\\WinGet\\Links\\claude.exe",
606 real: "C:\\Work\\WinGet\\Links\\claude.exe",
607 },
608 {
609 name: "a WinGet-named folder inside another directory",
610 definition: claudeUpdate,
611 resolved: "C:\\Work\\Microsoft\\WinGet\\Links\\claude.exe",
612 real: "C:\\Work\\Microsoft\\WinGet\\Links\\claude.exe",
613 },
614 {
615 name: "another provider in WinGet",
616 definition: otherProviderUpdate,
617 resolved: userWinGetLink,
618 real: userWinGetPackage,
619 },
620 {
621 name: "another WinGet package",
622 definition: claudeUpdate,
623 resolved: userWinGetPackage.replace("ClaudeCode_", "ClaudeCodeOther_"),
624 real: userWinGetPackage.replace("ClaudeCode_", "ClaudeCodeOther_"),
625 },
626 ] as const)("keeps the native updater for $name", (fixture) =>
627 Effect.gen(function* () {
628 const capabilities = yield* resolveInstall(fixture);
629
630 expect(capabilities.update).toMatchObject({
631 executable: fixture.resolved,
632 args: ["update"],
633 lockKey: `${fixture.definition.provider}-native`,
634 });
635 }),
636 );
637
638 it.effect.each([
639 {
640 name: "the default home",
641 resolved: "/Users/theo/.vite-plus/bin/claude",
642 real: "/Users/theo/.vite-plus/current/bin/vp",
643 platform: "darwin",
644 },
645 {
646 name: "the XDG home",
647 resolved: "/home/theo/.local/share/vite-plus/bin/claude",
648 real: "/home/theo/.local/share/vite-plus/current/bin/vp",
649 platform: "linux",
650 },
651 {
652 name: "the Windows home",
653 resolved: "C:\\Users\\Theo\\AppData\\Local\\vite-plus\\bin\\claude.cmd",
654 real: "C:\\Users\\Theo\\AppData\\Local\\vite-plus\\packages\\@anthropic-ai\\claude-code\\lib\\node_modules\\@anthropic-ai\\claude-code\\cli.js",
655 platform: "win32",
656 },
657 ] as const)("updates a Vite+ global install in $name with vp", (fixture) =>
658 Effect.gen(function* () {
659 const capabilities = yield* resolveInstall({ definition: claudeUpdate, ...fixture });
660
661 expect(capabilities.update).toMatchObject({
662 command: "vp i -g @anthropic-ai/claude-code",
663 lockKey: "vite-plus-global",
664 });
665 }),
666 );
667
668 it.effect("keeps a project folder named vite-plus manual-only", () =>
669 Effect.gen(function* () {
670 const capabilities = yield* resolveInstall({
671 definition: claudeUpdate,
672 resolved: "/work/vite-plus/bin/claude",
673 real: "/work/vite-plus/node_modules/@anthropic-ai/claude-code/cli.js",
674 platform: "linux",
675 });
676
677 expect(capabilities.update).toBeNull();
678 }),
679 );
680
681 it.effect("proves Windows npm ownership from the package manifest beside the shim", () =>
682 Effect.gen(function* () {
683 const tempDir = yield* makeTempDir("t3-npm-windows-capabilities");
684 const shim = NodePath.join(tempDir, "package-tool.cmd");
685 NodeFS.mkdirSync(tempDir, { recursive: true });
686 NodeFS.writeFileSync(shim, "@echo off\r\n");
687 NodeFS.mkdirSync(NodePath.join(tempDir, "node_modules", "@example", "package-tool"), {
688 recursive: true,
689 });
690 NodeFS.writeFileSync(
691 NodePath.join(tempDir, "node_modules", "@example", "package-tool", "package.json"),
692 "{}",
693 );
694
695 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
696 binaryPath: shim,
697 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
698 }).pipe(
699 Effect.provideService(HostProcess.Platform, "win32"),
700 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
701 );
702
703 expect(capabilities.update).toMatchObject({
704 executable: "npm",
705 args: ["install", "-g", "--prefix", tempDir, expect.any(String), expect.any(String)],
706 });
707
708 const script = NodePath.join(tempDir, "package-tool");
709 writeExecutable(script);
710 const posix = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
711 binaryPath: script,
712 env: { PATH: "" },
713 }).pipe(
714 Effect.provideService(HostProcess.Platform, "linux"),
715 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
716 );
717 expect(posix.update).toBeNull();
718 }),
719 );
720
721 it.effect.skipIf(!symlinksSupported)(
722 "switches to pnpm updates when the real path lives in pnpm's global store",
723 () =>
724 Effect.gen(function* () {
725 const tempDir = yield* makeTempDir("t3-pnpm-capabilities");
726 const link = linkIntoPackage(tempDir, "package-tool", [
727 ".local",
728 "share",
729 "pnpm",
730 "global",
731 "5",
732 "node_modules",
733 "@example",
734 "package-tool",
735 ]);
736
737 const updateCommand = (spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]) =>
738 resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
739 binaryPath: link,
740 env: { PATH: "" },
741 }).pipe(
742 Effect.map((capabilities) => capabilities.update),
743 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
744 );
745 const pnpmVersion = (version: string) =>
746 stdoutSpawner((command, args) => {
747 expect([command, ...args].join(" ")).toMatch(/pnpm(\.cmd)?"? --version$/);
748 return `${version}
749`;
750 });
751
752 expect(yield* updateCommand(pnpmVersion("11.1.3"))).toMatchObject({
753 command: "pnpm add -g --allow-build=@example/package-tool @example/package-tool@latest",
754 lockKey: "pnpm-global",
755 });
756 expect((yield* updateCommand(pnpmVersion("10.3.0")))?.command).toBe(
757 "pnpm add -g @example/package-tool@latest",
758 );
759 expect((yield* updateCommand(noSpawn))?.command).toBe(
760 "pnpm add -g @example/package-tool@latest",
761 );
762 }),
763 );
764
765 it.effect.each([
766 {
767 case: "the eligible release",
768 outdated: { "@example/package-tool": { current: "1.0.0", latest: "1.1.0" } },
769 exitCode: 1,
770 npmOutput: '"1.2.0"',
771 expected: "1.1.0",
772 },
773 {
774 case: "no update during cooldown",
775 outdated: {},
776 exitCode: 0,
777 npmOutput: '"1.2.0"',
778 expected: "1.0.0",
779 },
780 {
781 case: "the public registry fallback when pnpm fails and npm is unavailable",
782 outdated: { "@example/package-tool": { current: "1.0.0", latest: "1.1.0" } },
783 exitCode: 2,
784 expected: "9.9.9",
785 },
786 {
787 case: "the configured npm registry when the pnpm probe fails",
788 outdated: {},
789 exitCode: 2,
790 npmOutput: '"1.2.0"',
791 expected: "1.2.0",
792 },
793 {
794 case: "an unknown version when both configured lookups fail",
795 outdated: {},
796 exitCode: 2,
797 npmOutput: "not json",
798 expected: null,
799 },
800 ])(
801 "advertises $case for pnpm-global installs",
802 (fixture) =>
803 Effect.gen(function* () {
804 const tempDir = yield* makeTempDir("t3-pnpm-latest");
805 const pnpmBinDir = NodePath.join(tempDir, "pnpm-bin");
806 writeExecutable(NodePath.join(pnpmBinDir, "pnpm"));
807 if (fixture.npmOutput !== undefined) writeExecutable(NodePath.join(pnpmBinDir, "npm"));
808 const link = linkIntoPackage(tempDir, "package-tool", [
809 ".local",
810 "share",
811 "pnpm",
812 "global",
813 "5",
814 "node_modules",
815 "@example",
816 "package-tool",
817 ]);
818
819 let npmProbes = 0;
820 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
821 packageToolUpdate,
822 { binaryPath: link, env: { PATH: "" } },
823 ).pipe(
824 Effect.provideService(HostProcess.Environment, { PATH: pnpmBinDir }),
825 Effect.provideService(
826 ChildProcessSpawner.ChildProcessSpawner,
827 stdoutSpawner(
828 (_command, args) => {
829 if (args[0] === "view") {
830 npmProbes++;
831 return fixture.npmOutput ?? "";
832 }
833 return args[0] === "outdated"
834 ? JSON.stringify(fixture.outdated)
835 : JSON.stringify([
836 { dependencies: { "@example/package-tool": { version: "1.0.0" } } },
837 ]);
838 },
839 (args) => (args[0] === "outdated" ? fixture.exitCode : 0),
840 ),
841 ),
842 );
843
844 const provider = yield* enrichProviderSnapshotWithVersionAdvisory(
845 installedPackageToolProvider,
846 capabilities,
847 ).pipe(
848 Effect.provideServiceEffect(
849 ProviderLatestVersions.ProviderLatestVersions,
850 ProviderLatestVersions.make([["@example/package-tool", "9.9.9"]]),
851 ),
852 Effect.provideService(
853 HttpClient.HttpClient,
854 HttpClient.make(() => Effect.die("the npm version is already cached")),
855 ),
856 );
857 expect(provider.versionAdvisory).toMatchObject({
858 status:
859 fixture.expected === null
860 ? "unknown"
861 : fixture.expected === "1.0.0"
862 ? "current"
863 : "behind_latest",
864 currentVersion: "1.0.0",
865 latestVersion: fixture.expected,
866 });
867 expect(npmProbes).toBe(fixture.exitCode === 2 && fixture.npmOutput !== undefined ? 1 : 0);
868 }),
869 { skip: !symlinksSupported || windowsHost },
870 );
871
872 it.effect.skipIf(windowsHost)(
873 "switches to bun updates when the resolved binary lives in bun's global bin",
874 () =>
875 Effect.gen(function* () {
876 const tempDir = yield* makeTempDir("t3-bun-capabilities");
877 const bunBinDir = NodePath.join(tempDir, ".bun", "bin");
878 writeExecutable(NodePath.join(bunBinDir, "package-tool"));
879
880 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
881 packageToolUpdate,
882 {
883 binaryPath: "package-tool",
884 env: { PATH: bunBinDir },
885 },
886 ).pipe(
887 Effect.provideService(HostProcess.Platform, "darwin"),
888 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
889 );
890
891 expect(capabilities.update).toMatchObject({
892 command: "bun i -g @example/package-tool@latest",
893 lockKey: "bun-global",
894 });
895 }),
896 );
897
898 it.effect.skipIf(windowsHost)("switches to native updates and runs the resolved executable", () =>
899 Effect.gen(function* () {
900 const tempDir = yield* makeTempDir("t3-native-capabilities");
901 const nativeBinDir = NodePath.join(tempDir, ".local", "bin");
902 const nativePath = NodePath.join(nativeBinDir, "native-package-tool");
903 writeExecutable(nativePath);
904
905 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
906 nativePackageToolUpdate,
907 {
908 binaryPath: "native-package-tool",
909 env: { PATH: nativeBinDir },
910 },
911 ).pipe(
912 Effect.provideService(HostProcess.Platform, "darwin"),
913 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
914 );
915
916 expect(capabilities).toEqual({
917 provider: driver("nativePackageTool"),
918 packageName: "@example/native-package-tool",
919 update: {
920 command: `${nativePath} update`,
921 executable: nativePath,
922 args: ["update"],
923 lockKey: "nativePackageTool-native",
924 },
925 });
926 }),
927 );
928
929 it.effect.each(["wrapper", "symlink"])(
930 "keeps a mise-owned %s in a native install location manual-only",
931 (launcher, { skip }) => {
932 if (windowsHost || (launcher === "symlink" && !symlinksSupported)) skip();
933 return Effect.gen(function* () {
934 const tempDir = yield* makeTempDir("t3-native-mise");
935 const nativePath = NodePath.join(tempDir, ".local", "bin", "native-package-tool");
936 if (launcher === "wrapper") {
937 writeExecutable(nativePath);
938 NodeFS.writeFileSync(
939 nativePath,
940 '#!/bin/sh\nexec mise x native-package-tool -- native-package-tool "$@"\n',
941 );
942 } else {
943 const target = NodePath.join(
944 tempDir,
945 "mise",
946 "installs",
947 "native-package-tool",
948 "1.0.0",
949 "native-package-tool",
950 );
951 writeExecutable(target);
952 NodeFS.mkdirSync(NodePath.dirname(nativePath), { recursive: true });
953 NodeFS.symlinkSync(target, nativePath);
954 }
955
956 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
957 nativePackageToolUpdate,
958 { binaryPath: nativePath, env: { PATH: "" } },
959 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
960
961 expect(capabilities.update).toBeNull();
962 });
963 },
964 );
965
966 it.effect.skipIf(!symlinksSupported)(
967 "prefers npm ownership over the Node keg the package lives under",
968 () =>
969 Effect.gen(function* () {
970 const tempDir = yield* makeTempDir("t3-homebrew-node-capabilities");
971 const keg = NodePath.join(tempDir, "Cellar", "node", "22.1.0");
972 const target = NodePath.join(
973 keg,
974 "lib",
975 "node_modules",
976 "@example",
977 "package-tool",
978 "bin",
979 "package-tool.js",
980 );
981 writeExecutable(target);
982 const link = NodePath.join(tempDir, "bin", "package-tool");
983 NodeFS.mkdirSync(NodePath.dirname(link), { recursive: true });
984 NodeFS.symlinkSync(target, link);
985
986 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
987 packageToolUpdate,
988 {
989 binaryPath: link,
990 env: { PATH: "" },
991 },
992 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
993
994 expect(capabilities.update).toMatchObject({
995 executable: "npm",
996 args: expect.arrayContaining(["--prefix", keg]),
997 lockKey: `npm-global:${normalizeCommandPath(keg)}`,
998 });
999 }),
1000 );
1001
1002 it("quotes copyable command words the shell would split", () => {
1003 const posix = makeProviderMaintenanceCapabilities({
1004 provider: driver("packageTool"),
1005 packageName: "@example/package-tool",
1006 updateExecutable: "npm",
1007 updateArgs: [
1008 "install",
1009 "-g",
1010 "--prefix",
1011 "/Users/Jane Doe/.npm-global",
1012 "@example/package-tool@latest",
1013 ],
1014 updateLockKey: "npm-global",
1015 platform: "darwin",
1016 });
1017 expect(posix.update?.command).toBe(
1018 "npm install -g --prefix '/Users/Jane Doe/.npm-global' @example/package-tool@latest",
1019 );
1020 const windows = makeProviderMaintenanceCapabilities({
1021 provider: driver("packageTool"),
1022 packageName: null,
1023 updateExecutable: "C:\\Program Files\\Tool\\tool.exe",
1024 updateArgs: ["update"],
1025 updateLockKey: "tool",
1026 platform: "win32",
1027 });
1028 expect(windows.update?.command).toBe("& 'C:\\Program Files\\Tool\\tool.exe' update");
1029 });
1030
1031 it.effect.skipIf(windowsHost)("carries the native updater's environment into the action", () =>
1032 Effect.gen(function* () {
1033 const tempDir = yield* makeTempDir("t3-native-env");
1034 const nativePath = NodePath.join(tempDir, ".local", "bin", "native-package-tool");
1035 writeExecutable(nativePath);
1036 const resolver = makePackageManagedProviderMaintenanceResolver({
1037 provider: driver("nativePackageTool"),
1038 npmPackageName: "@example/native-package-tool",
1039 nativeUpdate: {
1040 args: ["update"],
1041 isCommandPath: isNativeTestCommandPath("/.local/bin/native-package-tool"),
1042 env: { TOOL_HOME: tempDir },
1043 },
1044 });
1045
1046 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(resolver, {
1047 binaryPath: nativePath,
1048 env: { PATH: "" },
1049 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
1050
1051 expect(capabilities.update?.env).toEqual({ TOOL_HOME: tempDir });
1052 }),
1053 );
1054
1055 it("recognizes Homebrew kegs and casks from the real executable path", () => {
1056 expect(
1057 homebrewOwnershipFromCommandPath("/opt/homebrew/Cellar/claude-code@latest/2.1.0/bin/claude"),
1058 ).toEqual({ kind: "formula", name: "claude-code@latest", prefix: "/opt/homebrew" });
1059 expect(homebrewOwnershipFromCommandPath("/usr/local/Caskroom/codex/0.148.0/codex")).toEqual({
1060 kind: "cask",
1061 name: "codex",
1062 prefix: "/usr/local",
1063 });
1064 expect(homebrewOwnershipFromCommandPath("/usr/local/bin/codex")).toBeNull();
1065 expect(homebrewOwnershipFromCommandPath("/srv/Cellar/claude/1.0.0/bin/claude")).toMatchObject({
1066 prefix: "/srv",
1067 });
1068 });
1069
1070 it.effect("shares installer lookups only for the same executable and update target", () =>
1071 Effect.gen(function* () {
1072 let lookups = 0;
1073 const capabilities = (executable: string, args: ReadonlyArray<string>, version: string) =>
1074 makeProviderMaintenanceCapabilities({
1075 provider: driver("packageTool"),
1076 packageName: "@example/package-tool",
1077 updateExecutable: executable,
1078 updateArgs: args,
1079 updateLockKey: "homebrew",
1080 latestVersion: null,
1081 lookupLatestVersion: Effect.sync(() => {
1082 lookups += 1;
1083 return version;
1084 }),
1085 });
1086
1087 const formula = capabilities("/opt/homebrew/bin/brew", ["upgrade", "package-tool"], "2.0.0");
1088 const cask = capabilities(
1089 "/opt/homebrew/bin/brew",
1090 ["upgrade", "--cask", "package-tool"],
1091 "3.0.0",
1092 );
1093 const otherBrew = capabilities("/usr/local/bin/brew", ["upgrade", "package-tool"], "4.0.0");
1094
1095 expect(yield* resolveLatestProviderVersion(formula)).toBe("2.0.0");
1096 expect(yield* resolveLatestProviderVersion(cask)).toBe("3.0.0");
1097 expect(yield* resolveLatestProviderVersion(otherBrew)).toBe("4.0.0");
1098 const refreshed = capabilities(
1099 "/opt/homebrew/bin/brew",
1100 ["upgrade", "package-tool"],
1101 "5.0.0",
1102 );
1103 expect(yield* resolveLatestProviderVersion(refreshed)).toBe("2.0.0");
1104 expect(lookups).toBe(3);
1105
1106 yield* invalidateLatestProviderVersion(refreshed);
1107 expect(yield* resolveLatestProviderVersion(refreshed)).toBe("5.0.0");
1108 expect(yield* resolveLatestProviderVersion(cask)).toBe("3.0.0");
1109 expect(yield* resolveLatestProviderVersion(otherBrew)).toBe("4.0.0");
1110 expect(lookups).toBe(4);
1111 }).pipe(
1112 Effect.provide(ProviderLatestVersions.layer),
1113 Effect.provideService(
1114 HttpClient.HttpClient,
1115 HttpClient.make(() => Effect.die("Homebrew's latest should not come from npm")),
1116 ),
1117 ),
1118 );
1119
1120 it.effect(
1121 "refreshes installer versions without letting an older lookup overwrite the result",
1122 () =>
1123 Effect.gen(function* () {
1124 const started = yield* Deferred.make<void>();
1125 const release = yield* Deferred.make<string>();
1126 let lookups = 0;
1127 const capabilities = makeProviderMaintenanceCapabilities({
1128 provider: driver("packageTool"),
1129 packageName: "@example/package-tool",
1130 updateExecutable: "/opt/homebrew/bin/brew",
1131 updateArgs: ["upgrade", "package-tool"],
1132 updateLockKey: "homebrew",
1133 latestVersion: null,
1134 lookupLatestVersion: Effect.suspend(() =>
1135 ++lookups === 1
1136 ? Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(release)))
1137 : Effect.succeed("2.0.0"),
1138 ),
1139 });
1140 const pending = yield* resolveLatestProviderVersion(capabilities).pipe(Effect.forkChild);
1141 yield* Deferred.await(started);
1142 yield* invalidateLatestProviderVersion(capabilities);
1143 expect(yield* resolveLatestProviderVersion(capabilities)).toBe("2.0.0");
1144
1145 yield* Deferred.succeed(release, "1.0.0");
1146 expect(yield* Fiber.join(pending)).toBe("1.0.0");
1147 expect(yield* resolveLatestProviderVersion(capabilities)).toBe("2.0.0");
1148 expect(lookups).toBe(2);
1149 }).pipe(
1150 Effect.provide(ProviderLatestVersions.layer),
1151 Effect.provideService(
1152 HttpClient.HttpClient,
1153 HttpClient.make(() => Effect.die("Homebrew's latest should not come from npm")),
1154 ),
1155 ),
1156 );
1157
1158 it.effect.skipIf(windowsHost)(
1159 "stays manual-only when the keg is not under the resolved brew's prefix",
1160 () =>
1161 Effect.gen(function* () {
1162 const tempDir = yield* makeTempDir("t3-homebrew-foreign-prefix");
1163 const brewBinDir = NodePath.join(tempDir, "brew-bin");
1164 writeExecutable(NodePath.join(brewBinDir, "brew"));
1165 const kegBinary = NodePath.join(
1166 tempDir,
1167 "elsewhere",
1168 "Cellar",
1169 "package-tool",
1170 "1.0.0",
1171 "bin",
1172 "package-tool",
1173 );
1174 writeExecutable(kegBinary);
1175
1176 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
1177 packageToolUpdate,
1178 {
1179 binaryPath: kegBinary,
1180 env: { PATH: brewBinDir },
1181 },
1182 ).pipe(
1183 Effect.provideService(HostProcess.Platform, "darwin"),
1184 Effect.provideService(
1185 ChildProcessSpawner.ChildProcessSpawner,
1186 stdoutSpawner(() => "/opt/homebrew\n"),
1187 ),
1188 );
1189
1190 expect(capabilities).toEqual({
1191 ...manualPackageTool,
1192 installPath: NodeFS.realpathSync(kegBinary),
1193 });
1194 }),
1195 );
1196
1197 it("reads the stable formula version from brew info", () => {
1198 const info = JSON.stringify({ formulae: [{ versions: { stable: "2.1.5" } }] });
1199 const formula = { kind: "formula", name: "claude-code", prefix: "/opt/homebrew" } as const;
1200 expect(parseHomebrewLatestVersion(info, formula)).toBe("2.1.5");
1201 expect(parseHomebrewLatestVersion("not json", formula)).toBeNull();
1202 });
1203
1204 it("treats Homebrew's latest cask version as unknown", () => {
1205 const info = JSON.stringify({ casks: [{ version: "latest" }] });
1206 const cask = { kind: "cask", name: "package-tool", prefix: "/opt/homebrew" } as const;
1207 expect(parseHomebrewLatestVersion(info, cask)).toBeNull();
1208 });
1209
1210 it.effect.skipIf(windowsHost)(
1211 "disables one-click updates for explicit custom binary paths it cannot safely map",
1212 () =>
1213 Effect.gen(function* () {
1214 const tempDir = yield* makeTempDir("t3-custom-capabilities");
1215 const customPath = NodePath.join(tempDir, "tools", "package-tool");
1216 writeExecutable(customPath);
1217
1218 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
1219 packageToolUpdate,
1220 {
1221 binaryPath: customPath,
1222 env: { PATH: "" },
1223 },
1224 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
1225
1226 expect(capabilities).toEqual({
1227 ...manualPackageTool,
1228 installPath: NodeFS.realpathSync(customPath),
1229 });
1230 }),
1231 );
1232
1233 it.effect.skipIf(windowsHost)(
1234 "falls back to the provider's own updater when no installer is proven",
1235 () =>
1236 Effect.gen(function* () {
1237 const tempDir = yield* makeTempDir("t3-self-update-fallback");
1238 const customPath = NodePath.join(tempDir, "tools", "package-tool");
1239 writeExecutable(customPath);
1240 const selfUpdating = makePackageManagedProviderMaintenanceResolver({
1241 provider: driver("packageTool"),
1242 npmPackageName: "@example/package-tool",
1243 nativeUpdate: { args: ["update", "--self"] },
1244 });
1245
1246 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(selfUpdating, {
1247 binaryPath: customPath,
1248 env: { PATH: "" },
1249 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
1250 expect(capabilities.update).toMatchObject({
1251 executable: customPath,
1252 args: ["update", "--self"],
1253 lockKey: "packageTool-native",
1254 });
1255
1256 const misePath = NodePath.join(tempDir, "mise", "installs", "package-tool", "1.0.0", "bin");
1257 writeExecutable(NodePath.join(misePath, "package-tool"));
1258 const mise = yield* resolveProviderMaintenanceCapabilitiesEffect(selfUpdating, {
1259 binaryPath: NodePath.join(misePath, "package-tool"),
1260 env: { PATH: "" },
1261 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
1262 expect(mise.update).toBeNull();
1263 }),
1264 );
1265
1266 it.effect.skipIf(!symlinksSupported)("updates Yarn global installs with yarn", () =>
1267 Effect.gen(function* () {
1268 const tempDir = yield* makeTempDir("t3-yarn-capabilities");
1269 const link = linkIntoPackage(tempDir, "package-tool", [
1270 ".config",
1271 "yarn",
1272 "global",
1273 "node_modules",
1274 "@example",
1275 "package-tool",
1276 ]);
1277
1278 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
1279 binaryPath: link,
1280 env: { PATH: "" },
1281 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
1282
1283 expect(capabilities.update).toMatchObject({
1284 command: "yarn global add @example/package-tool@latest",
1285 lockKey: "yarn-global",
1286 });
1287 expect(makeTargetedProviderUpdateAction(capabilities, "2.0.0")?.args).toEqual([
1288 "global",
1289 "add",
1290 "@example/package-tool@2.0.0",
1291 ]);
1292 }),
1293 );
1294
1295 it.effect.skipIf(!symlinksSupported)(
1296 "updates Volta installs only when Volta has the package",
1297 () =>
1298 Effect.gen(function* () {
1299 const voltaHome = NodePath.join(yield* makeTempDir("t3-volta-capabilities"), ".volta");
1300 const shim = NodePath.join(voltaHome, "bin", "volta-shim");
1301 writeExecutable(shim);
1302 const link = NodePath.join(voltaHome, "bin", "package-tool");
1303 NodeFS.symlinkSync(shim, link);
1304 const resolve = resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
1305 binaryPath: link,
1306 env: { PATH: "" },
1307 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
1308
1309 expect((yield* resolve).update).toBeNull();
1310 NodeFS.mkdirSync(
1311 NodePath.join(voltaHome, "tools", "image", "packages", "@example", "package-tool"),
1312 { recursive: true },
1313 );
1314 expect((yield* resolve).update).toMatchObject({
1315 command: "volta install @example/package-tool@latest",
1316 lockKey: "volta",
1317 });
1318 }),
1319 );
1320
1321 it.effect.skipIf(windowsHost)("upgrades with the keg's own brew when brew is not on PATH", () =>
1322 Effect.gen(function* () {
1323 const tempDir = yield* makeTempDir("t3-homebrew-keg-brew");
1324 const brewPath = NodePath.join(tempDir, "bin", "brew");
1325 writeExecutable(brewPath);
1326 const kegBinary = NodePath.join(tempDir, "Cellar", "package-tool", "1.0.0", "bin", "tool");
1327 writeExecutable(kegBinary);
1328
1329 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
1330 binaryPath: kegBinary,
1331 env: { PATH: "" },
1332 }).pipe(
1333 Effect.provideService(HostProcess.Platform, "darwin"),
1334 Effect.provideService(
1335 ChildProcessSpawner.ChildProcessSpawner,
1336 stdoutSpawner((_command, args) => (args[0] === "--prefix" ? `${tempDir}\n` : "{}")),
1337 ),
1338 );
1339
1340 expect(capabilities.update).toMatchObject({
1341 executable: brewPath,
1342 args: ["upgrade", "package-tool"],
1343 lockKey: "homebrew",
1344 });
1345 }),
1346 );
1347
1348 it.effect("starts a fresh read instead of joining the resolution already running", () =>
1349 Effect.gen(function* () {
1350 const releaseStale = yield* Deferred.make<void>();
1351 let resolutions = 0;
1352 const resolve = yield* makeCachedProviderMaintenanceResolution(
1353 Effect.suspend(() => {
1354 resolutions += 1;
1355 return resolutions === 1
1356 ? Deferred.await(releaseStale).pipe(Effect.as(manualPackageTool))
1357 : Effect.succeed(manualPackageTool);
1358 }),
1359 );
1360
1361 const advisory = yield* Effect.forkChild(resolve(), { startImmediately: true });
1362 const fresh = yield* Effect.forkChild(resolve({ fresh: true }), { startImmediately: true });
1363 expect(resolutions).toBe(2);
1364 expect(fresh.pollUnsafe()).toBeDefined();
1365 yield* Deferred.succeed(releaseStale, undefined);
1366 expect(yield* Fiber.join(fresh)).toEqual(manualPackageTool);
1367 yield* Fiber.join(advisory);
1368 }),
1369 );
1370
1371 it.effect("resolves again after the first read is interrupted", () =>
1372 Effect.gen(function* () {
1373 const release = yield* Deferred.make<void>();
1374 let resolutions = 0;
1375 const resolve = yield* makeCachedProviderMaintenanceResolution(
1376 Effect.suspend(() => {
1377 resolutions += 1;
1378 return resolutions === 1
1379 ? Effect.never
1380 : Deferred.await(release).pipe(Effect.as(manualPackageTool));
1381 }),
1382 );
1383
1384 const first = yield* Effect.forkChild(resolve(), { startImmediately: true });
1385 yield* Fiber.interrupt(first);
1386
1387 const owner = yield* Effect.forkChild(resolve(), { startImmediately: true });
1388 const waiter = yield* Effect.forkChild(resolve(), { startImmediately: true });
1389 yield* Fiber.interrupt(owner);
1390 yield* Deferred.succeed(release, undefined);
1391 expect(yield* Fiber.join(waiter)).toEqual(manualPackageTool);
1392 expect(yield* resolve()).toEqual(manualPackageTool);
1393 expect(resolutions).toBe(2);
1394 }),
1395 );
1396});
1397
1398it("pins only owned package-manager installs and preserves their execution context", () => {
1399 const capabilities = makeProviderMaintenanceCapabilities({
1400 provider: driver("codex"),
1401 packageName: "@openai/codex",
1402 updateExecutable: "npm",
1403 updateLockKey: "npm-global:/opt/node",
1404 updateArgs: [
1405 "install",
1406 "-g",
1407 "--prefix",
1408 "/opt/node",
1409 "--allow-scripts=@openai/codex",
1410 "@openai/codex@latest",
1411 ],
1412 env: { PATH: "/opt/node/bin" },
1413 });
1414 const pinned = makeTargetedProviderUpdateAction(capabilities, "2.0.0");
1415 expect(pinned).toMatchObject({
1416 executable: "npm",
1417 lockKey: capabilities.update?.lockKey,
1418 env: capabilities.update?.env,
1419 args: [
1420 "install",
1421 "-g",
1422 "--prefix",
1423 "/opt/node",
1424 "--allow-scripts=@openai/codex",
1425 "@openai/codex@2.0.0",
1426 ],
1427 });
1428 expect(pinned?.command).toContain("@openai/codex@2.0.0");
1429 for (const lockKey of ["codex-native", "homebrew", "manual"]) {
1430 expect(
1431 makeTargetedProviderUpdateAction(
1432 { ...capabilities, update: { ...capabilities.update!, lockKey } },
1433 "2.0.0",
1434 ),
1435 ).toBeNull();
1436 }
1437 expect(makeTargetedProviderUpdateAction(capabilities, "2.0.0; rm -rf /")).toBeNull();
1438});