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