Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import { expect, it } from "@effect/vitest";
3import * as NodeChildProcess from "node:child_process";
4import * as NodeFS from "node:fs";
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import * as NodeOS from "node:os";
7import * as NodePath from "node:path";
8import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
9import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
10import * as Crypto from "effect/Crypto";
11import * as Deferred from "effect/Deferred";
12import * as Effect from "effect/Effect";
13import * as Fiber from "effect/Fiber";
14import * as Sink from "effect/Sink";
15import * as Stream from "effect/Stream";
16import { HttpClient } from "effect/http";
17import { ChildProcessSpawner } from "effect/process";
18import {
19 createProviderVersionAdvisory,
20 makeTargetedProviderUpdateAction,
21 enrichProviderSnapshotWithVersionAdvisory,
22 homebrewOwnershipFromCommandPath,
23 makeCachedProviderMaintenanceResolution,
24 makePackageManagedProviderMaintenanceResolver,
25 makeProviderMaintenanceCapabilities,
26 normalizeCommandPath,
27 npmGlobalPrefixFromCommandPath,
28 parseHomebrewLatestVersion,
29 ProviderVersionCache,
30 resolveLatestProviderVersion,
31 resolvePackageManagedProviderMaintenance,
32 resolveProviderMaintenanceCapabilitiesEffect,
33 type ProviderMaintenanceCapabilities,
34} from "./providerMaintenance.ts";
35import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
36
37const driver = (value: string) => ProviderDriverKind.make(value);
38// These write `#!/bin/sh` stubs and evaluate them with darwin/linux path
39// semantics; a Windows temp path cannot be split on `:`.
40const windowsHost = HostProcessPlatform.defaultValue() === "win32";
41const makeTempDir = (name: string) =>
42 Crypto.Crypto.pipe(
43 Effect.flatMap((crypto) => crypto.randomUUIDv4),
44 Effect.map((id) => NodePath.join(NodeFS.realpathSync(NodeOS.tmpdir()), `${name}-${id}`)),
45 );
46const isNativeTestCommandPath =
47 (expectedPathSegment: string) =>
48 (commandPath: string): boolean =>
49 normalizeCommandPath(commandPath).includes(expectedPathSegment);
50const packageToolUpdate = makePackageManagedProviderMaintenanceResolver({
51 provider: driver("packageTool"),
52 npmPackageName: "@example/package-tool",
53 nativeUpdate: null,
54});
55const nativePackageToolUpdate = makePackageManagedProviderMaintenanceResolver({
56 provider: driver("nativePackageTool"),
57 npmPackageName: "@example/native-package-tool",
58 nativeUpdate: {
59 args: ["update"],
60 isCommandPath: isNativeTestCommandPath("/.local/bin/native-package-tool"),
61 },
62});
63const installedPackageToolProvider: ServerProvider = {
64 instanceId: ProviderInstanceId.make("packageTool"),
65 driver: driver("packageTool"),
66 enabled: true,
67 installed: true,
68 version: "1.0.0",
69 status: "ready",
70 auth: { status: "authenticated" },
71 checkedAt: "2026-04-10T00:00:00.000Z",
72 models: [],
73 slashCommands: [],
74 skills: [],
75};
76const manualPackageTool: ProviderMaintenanceCapabilities = {
77 provider: driver("packageTool"),
78 packageName: "@example/package-tool",
79 update: null,
80};
81
82function writeExecutable(path: string) {
83 NodeFS.mkdirSync(NodePath.dirname(path), { recursive: true });
84 NodeFS.writeFileSync(path, "#!/bin/sh\n");
85 NodeFS.chmodSync(path, 0o755);
86}
87
88/** Symlink `<tempDir>/bin/<name>` into a package entry point, like npm/pnpm do. */
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(onSpawn: (command: string, args: ReadonlyArray<string>) => string) {
103 return ChildProcessSpawner.make((command) => {
104 const { command: executable, args } = command as unknown as {
105 readonly command: string;
106 readonly args: ReadonlyArray<string>;
107 };
108 return Effect.succeed(
109 ChildProcessSpawner.makeHandle({
110 pid: ChildProcessSpawner.ProcessId(1),
111 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
112 isRunning: Effect.succeed(false),
113 kill: () => Effect.void,
114 unref: Effect.succeed(Effect.void),
115 stdin: Sink.drain,
116 stdout: Stream.encodeText(Stream.make(onSpawn(executable, args))),
117 stderr: Stream.empty,
118 all: Stream.empty,
119 getInputFd: () => Sink.drain,
120 getOutputFd: () => Stream.empty,
121 }),
122 );
123 });
124}
125
126it.layer(NodeServices.layer)("providerMaintenance", (it) => {
127 it.effect("reads cached versions through the injectable cache reference", () =>
128 resolveLatestProviderVersion(manualPackageTool).pipe(
129 Effect.provideService(
130 ProviderVersionCache,
131 new Map([
132 [
133 "@example/package-tool",
134 {
135 expiresAt: Number.MAX_SAFE_INTEGER,
136 version: "9.9.9",
137 },
138 ],
139 ]),
140 ),
141 Effect.provideService(
142 HttpClient.HttpClient,
143 HttpClient.make(() =>
144 Effect.die("cached provider version should not make an HTTP request"),
145 ),
146 ),
147 Effect.map((version) => {
148 expect(version).toBe("9.9.9");
149 }),
150 ),
151 );
152
153 it.effect("prefers the installer's own latest version over the npm registry", () =>
154 resolveLatestProviderVersion({ ...manualPackageTool, latestVersion: "1.2.0" }).pipe(
155 Effect.provideService(ProviderVersionCache, new Map()),
156 Effect.provideService(
157 HttpClient.HttpClient,
158 HttpClient.make(() =>
159 Effect.die("installer-reported latest should not make an HTTP request"),
160 ),
161 ),
162 Effect.map((version) => {
163 expect(version).toBe("1.2.0");
164 }),
165 ),
166 );
167
168 it.effect("does not fetch latest provider versions when update checks are disabled", () =>
169 enrichProviderSnapshotWithVersionAdvisory(installedPackageToolProvider, manualPackageTool, {
170 enableProviderUpdateChecks: false,
171 }).pipe(
172 Effect.provideService(ProviderVersionCache, new Map()),
173 Effect.provideService(
174 HttpClient.HttpClient,
175 HttpClient.make(() =>
176 Effect.die("disabled provider update checks should not make an HTTP request"),
177 ),
178 ),
179 Effect.map((provider) => {
180 expect(provider.versionAdvisory).toMatchObject({
181 status: "unknown",
182 currentVersion: "1.0.0",
183 latestVersion: null,
184 checkedAt: "2026-04-10T00:00:00.000Z",
185 });
186 }),
187 ),
188 );
189
190 it("marks providers with unknown current versions as unknown", () => {
191 expect(
192 createProviderVersionAdvisory({
193 driver: driver("packageTool"),
194 currentVersion: null,
195 latestVersion: "9.9.9",
196 }),
197 ).toMatchObject({
198 status: "unknown",
199 currentVersion: null,
200 latestVersion: "9.9.9",
201 });
202 });
203
204 it("marks providers with unknown latest versions as unknown", () => {
205 expect(
206 createProviderVersionAdvisory({
207 driver: driver("packageTool"),
208 currentVersion: "1.0.0",
209 latestVersion: null,
210 }),
211 ).toMatchObject({
212 status: "unknown",
213 currentVersion: "1.0.0",
214 latestVersion: null,
215 message: null,
216 });
217 });
218
219 it("keeps the manual update hint when the install is behind but unowned", () => {
220 expect(
221 createProviderVersionAdvisory({
222 driver: driver("packageTool"),
223 currentVersion: "2.1.110",
224 latestVersion: "2.1.117",
225 maintenanceCapabilities: manualPackageTool,
226 }),
227 ).toMatchObject({
228 status: "behind_latest",
229 latestVersion: "2.1.117",
230 updateCommand: null,
231 canUpdate: false,
232 message: "Install the update now or review provider settings.",
233 });
234 });
235
236 it.effect("stays manual-only when the binary cannot be located", () =>
237 resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
238 binaryPath: "package-tool",
239 env: { PATH: "" },
240 }).pipe(
241 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
242 Effect.map((capabilities) => {
243 expect(capabilities).toEqual(manualPackageTool);
244 }),
245 ),
246 );
247
248 it.effect.skipIf(!symlinksSupported)(
249 "pins npm updates to the global prefix that owns the package",
250 () =>
251 Effect.gen(function* () {
252 const tempDir = yield* makeTempDir("t3-npm-capabilities");
253 const link = linkIntoPackage(tempDir, "package-tool", [
254 "lib",
255 "node_modules",
256 "@example",
257 "package-tool",
258 ]);
259
260 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
261 packageToolUpdate,
262 {
263 binaryPath: link,
264 env: { PATH: "" },
265 },
266 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
267
268 expect(capabilities).toEqual({
269 provider: driver("packageTool"),
270 packageName: "@example/package-tool",
271 update: {
272 command: `npm install -g --prefix ${tempDir} --allow-scripts=@example/package-tool @example/package-tool@latest`,
273 executable: "npm",
274 args: [
275 "install",
276 "-g",
277 "--prefix",
278 tempDir,
279 "--allow-scripts=@example/package-tool",
280 "@example/package-tool@latest",
281 ],
282 lockKey: `npm-global:${normalizeCommandPath(tempDir)}`,
283 },
284 });
285 }),
286 );
287
288 it("derives the npm prefix only from the global lib/node_modules layout", () => {
289 expect(
290 npmGlobalPrefixFromCommandPath(
291 "/usr/local/lib/node_modules/@openai/codex/bin/codex.js",
292 "@openai/codex",
293 ),
294 ).toBe("/usr/local");
295 // A copy nested inside another package is not a global install.
296 expect(
297 npmGlobalPrefixFromCommandPath(
298 "/usr/local/lib/node_modules/other/node_modules/@openai/codex/bin/codex.js",
299 "@openai/codex",
300 ),
301 ).toBeNull();
302 expect(
303 npmGlobalPrefixFromCommandPath(
304 "/lib/node_modules/@openai/codex/bin/codex.js",
305 "@openai/codex",
306 ),
307 ).toBe("/");
308 // Neither is a project-local dependency.
309 expect(
310 npmGlobalPrefixFromCommandPath(
311 "/work/app/node_modules/@openai/codex/bin/codex.js",
312 "@openai/codex",
313 ),
314 ).toBeNull();
315 });
316
317 // The Codex Windows installer exposes `%LOCALAPPDATA%\\Programs\\OpenAI\\Codex\\bin`
318 // as a junction into `%CODEX_HOME%\\packages\\standalone\\current\\bin`. Node's
319 // realpath follows junctions, so the real path carries the standalone marker
320 // even though the visible path does not.
321 it.effect("recognizes a Windows standalone install through its junctioned bin dir", () =>
322 Effect.gen(function* () {
323 const visiblePath =
324 "C:\\Users\\Theo\\AppData\\Local\\Programs\\OpenAI\\Codex\\bin\\codex.exe";
325 const realPath =
326 "C:\\Users\\Theo\\.codex\\packages\\standalone\\releases\\0.120.0-x86_64\\bin\\codex.exe";
327 const capabilities = yield* resolvePackageManagedProviderMaintenance(
328 {
329 provider: driver("codex"),
330 npmPackageName: "@openai/codex",
331 nativeUpdate: {
332 args: ["update"],
333 isCommandPath: isNativeTestCommandPath("/packages/standalone/"),
334 },
335 },
336 {
337 binaryPath: "codex",
338 resolvedCommandPath: visiblePath,
339 realCommandPath: realPath,
340 env: {},
341 platform: "win32",
342 },
343 ).pipe(Effect.provideService(HostProcessPlatform, "win32"));
344
345 expect(capabilities.update).toMatchObject({
346 executable: visiblePath,
347 args: ["update"],
348 lockKey: "codex-native",
349 });
350 }),
351 );
352
353 it.effect("proves Windows npm ownership from the package manifest beside the shim", () =>
354 Effect.gen(function* () {
355 const tempDir = yield* makeTempDir("t3-npm-windows-capabilities");
356 const shim = NodePath.join(tempDir, "package-tool.cmd");
357 NodeFS.mkdirSync(tempDir, { recursive: true });
358 NodeFS.writeFileSync(shim, "@echo off\r\n");
359 NodeFS.mkdirSync(NodePath.join(tempDir, "node_modules", "@example", "package-tool"), {
360 recursive: true,
361 });
362 NodeFS.writeFileSync(
363 NodePath.join(tempDir, "node_modules", "@example", "package-tool", "package.json"),
364 "{}",
365 );
366
367 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
368 binaryPath: shim,
369 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
370 }).pipe(
371 Effect.provideService(HostProcessPlatform, "win32"),
372 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
373 );
374
375 expect(capabilities.update).toMatchObject({
376 executable: "npm",
377 args: ["install", "-g", "--prefix", tempDir, expect.any(String), expect.any(String)],
378 });
379
380 // The same layout on POSIX is a project checkout, not a global install.
381 const script = NodePath.join(tempDir, "package-tool");
382 writeExecutable(script);
383 const posix = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
384 binaryPath: script,
385 env: { PATH: "" },
386 }).pipe(
387 Effect.provideService(HostProcessPlatform, "linux"),
388 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
389 );
390 expect(posix.update).toBeNull();
391 }),
392 );
393
394 it.effect.skipIf(!symlinksSupported)(
395 "switches to pnpm updates when the real path lives in pnpm's global store",
396 () =>
397 Effect.gen(function* () {
398 const tempDir = yield* makeTempDir("t3-pnpm-capabilities");
399 const link = linkIntoPackage(tempDir, "package-tool", [
400 ".local",
401 "share",
402 "pnpm",
403 "global",
404 "5",
405 "node_modules",
406 "@example",
407 "package-tool",
408 ]);
409
410 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
411 packageToolUpdate,
412 {
413 binaryPath: link,
414 env: { PATH: "" },
415 },
416 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
417
418 expect(capabilities.update).toMatchObject({
419 command: "pnpm add -g @example/package-tool@latest",
420 lockKey: "pnpm-global",
421 });
422 }),
423 );
424
425 it.effect.skipIf(windowsHost)(
426 "switches to bun updates when the resolved binary lives in bun's global bin",
427 () =>
428 Effect.gen(function* () {
429 const tempDir = yield* makeTempDir("t3-bun-capabilities");
430 const bunBinDir = NodePath.join(tempDir, ".bun", "bin");
431 writeExecutable(NodePath.join(bunBinDir, "package-tool"));
432
433 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
434 packageToolUpdate,
435 {
436 binaryPath: "package-tool",
437 env: { PATH: bunBinDir },
438 },
439 ).pipe(
440 Effect.provideService(HostProcessPlatform, "darwin"),
441 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
442 );
443
444 expect(capabilities.update).toMatchObject({
445 command: "bun i -g @example/package-tool@latest",
446 lockKey: "bun-global",
447 });
448 }),
449 );
450
451 it.effect.skipIf(windowsHost)("switches to native updates and runs the resolved executable", () =>
452 Effect.gen(function* () {
453 const tempDir = yield* makeTempDir("t3-native-capabilities");
454 const nativeBinDir = NodePath.join(tempDir, ".local", "bin");
455 const nativePath = NodePath.join(nativeBinDir, "native-package-tool");
456 writeExecutable(nativePath);
457
458 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
459 nativePackageToolUpdate,
460 {
461 binaryPath: "native-package-tool",
462 env: { PATH: nativeBinDir },
463 },
464 ).pipe(
465 Effect.provideService(HostProcessPlatform, "darwin"),
466 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
467 );
468
469 expect(capabilities).toEqual({
470 provider: driver("nativePackageTool"),
471 packageName: "@example/native-package-tool",
472 update: {
473 command: `${nativePath} update`,
474 executable: nativePath,
475 args: ["update"],
476 lockKey: "nativePackageTool-native",
477 },
478 });
479 }),
480 );
481
482 // Regression for #9850: an explicit native path outside PATH, with spaces,
483 // must be what actually gets spawned.
484 it.effect.skipIf(windowsHost)("runs an explicit native updater outside PATH", () =>
485 Effect.gen(function* () {
486 const tempDir = yield* makeTempDir("t3-native-update");
487 const nativePath = NodePath.join(
488 tempDir,
489 "with spaces",
490 ".local",
491 "bin",
492 "native-package-tool",
493 );
494 NodeFS.mkdirSync(NodePath.dirname(nativePath), { recursive: true });
495 NodeFS.writeFileSync(nativePath, "#!/bin/sh\nprintf '%s' \"$1\"\n");
496 NodeFS.chmodSync(nativePath, 0o755);
497
498 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
499 nativePackageToolUpdate,
500 { binaryPath: nativePath, env: { PATH: "" } },
501 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
502
503 expect(capabilities.update?.executable).toBe(nativePath);
504 const result = NodeChildProcess.spawnSync(
505 capabilities.update!.executable,
506 capabilities.update!.args,
507 { env: { PATH: "" }, encoding: "utf8" },
508 );
509 expect(result.status).toBe(0);
510 expect(result.stdout).toBe("update");
511 }),
512 );
513
514 it.effect.skipIf(!symlinksSupported)(
515 "prefers npm ownership over the Node keg the package lives under",
516 () =>
517 Effect.gen(function* () {
518 // `brew install node` keeps npm globals inside the node keg.
519 const tempDir = yield* makeTempDir("t3-homebrew-node-capabilities");
520 const keg = NodePath.join(tempDir, "Cellar", "node", "22.1.0");
521 const target = NodePath.join(
522 keg,
523 "lib",
524 "node_modules",
525 "@example",
526 "package-tool",
527 "bin",
528 "package-tool.js",
529 );
530 writeExecutable(target);
531 const link = NodePath.join(tempDir, "bin", "package-tool");
532 NodeFS.mkdirSync(NodePath.dirname(link), { recursive: true });
533 NodeFS.symlinkSync(target, link);
534
535 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
536 packageToolUpdate,
537 {
538 binaryPath: link,
539 env: { PATH: "" },
540 },
541 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
542
543 expect(capabilities.update).toMatchObject({
544 executable: "npm",
545 args: expect.arrayContaining(["--prefix", keg]),
546 lockKey: `npm-global:${normalizeCommandPath(keg)}`,
547 });
548 }),
549 );
550
551 it("quotes copyable command words the shell would split", () => {
552 const posix = makeProviderMaintenanceCapabilities({
553 provider: driver("packageTool"),
554 packageName: "@example/package-tool",
555 updateExecutable: "npm",
556 updateArgs: [
557 "install",
558 "-g",
559 "--prefix",
560 "/Users/Jane Doe/.npm-global",
561 "@example/package-tool@latest",
562 ],
563 updateLockKey: "npm-global",
564 platform: "darwin",
565 });
566 expect(posix.update?.command).toBe(
567 "npm install -g --prefix '/Users/Jane Doe/.npm-global' @example/package-tool@latest",
568 );
569 const windows = makeProviderMaintenanceCapabilities({
570 provider: driver("packageTool"),
571 packageName: null,
572 updateExecutable: "C:\\Program Files\\Tool\\tool.exe",
573 updateArgs: ["update"],
574 updateLockKey: "tool",
575 platform: "win32",
576 });
577 expect(windows.update?.command).toBe("& 'C:\\Program Files\\Tool\\tool.exe' update");
578 });
579
580 it.effect.skipIf(windowsHost)("carries the native updater's environment into the action", () =>
581 Effect.gen(function* () {
582 const tempDir = yield* makeTempDir("t3-native-env");
583 const nativePath = NodePath.join(tempDir, ".local", "bin", "native-package-tool");
584 writeExecutable(nativePath);
585 const resolver = makePackageManagedProviderMaintenanceResolver({
586 provider: driver("nativePackageTool"),
587 npmPackageName: "@example/native-package-tool",
588 nativeUpdate: {
589 args: ["update"],
590 isCommandPath: isNativeTestCommandPath("/.local/bin/native-package-tool"),
591 env: { TOOL_HOME: tempDir },
592 },
593 });
594
595 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(resolver, {
596 binaryPath: nativePath,
597 env: { PATH: "" },
598 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
599
600 expect(capabilities.update?.env).toEqual({ TOOL_HOME: tempDir });
601 }),
602 );
603
604 it("recognizes Homebrew kegs and casks from the real executable path", () => {
605 expect(
606 homebrewOwnershipFromCommandPath("/opt/homebrew/Cellar/claude-code@latest/2.1.0/bin/claude"),
607 ).toEqual({ kind: "formula", name: "claude-code@latest", prefix: "/opt/homebrew" });
608 expect(homebrewOwnershipFromCommandPath("/usr/local/Caskroom/codex/0.148.0/codex")).toEqual({
609 kind: "cask",
610 name: "codex",
611 prefix: "/usr/local",
612 });
613 // A plain /usr/local/bin binary is not evidence of Homebrew (#8832).
614 expect(homebrewOwnershipFromCommandPath("/usr/local/bin/codex")).toBeNull();
615 // A keg elsewhere reports its prefix so the resolver can reject it against
616 // `brew --prefix`.
617 expect(homebrewOwnershipFromCommandPath("/srv/Cellar/claude/1.0.0/bin/claude")).toMatchObject({
618 prefix: "/srv",
619 });
620 });
621
622 it.effect.skipIf(windowsHost)(
623 "stays manual-only for an explicit binary path that does not exist",
624 () =>
625 Effect.gen(function* () {
626 const tempDir = yield* makeTempDir("t3-missing-native-capabilities");
627 const missingPath = NodePath.join(tempDir, ".local", "bin", "native-package-tool");
628
629 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
630 nativePackageToolUpdate,
631 { binaryPath: missingPath, env: { PATH: "" } },
632 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
633
634 expect(capabilities.update).toBeNull();
635 }),
636 );
637
638 it.effect.each([
639 { directory: "Caskroom", name: "package-tool", kind: "cask" },
640 { directory: "Cellar", name: "package-tool", kind: "formula" },
641 { directory: "Cellar", name: "package-tool@latest", kind: "formula" },
642 ] as const)(
643 "upgrades the owning Homebrew $kind $name through an executable alias",
644 (fixture) =>
645 Effect.gen(function* () {
646 const tempDir = yield* makeTempDir("t3-homebrew-capabilities");
647 const brewBinDir = NodePath.join(tempDir, "brew-bin");
648 const brewPath = NodePath.join(brewBinDir, "brew");
649 writeExecutable(brewPath);
650 const ownedBinary = NodePath.join(
651 tempDir,
652 fixture.directory,
653 fixture.name,
654 "0.148.0",
655 "package-tool-0.148.0",
656 );
657 writeExecutable(ownedBinary);
658 const link = NodePath.join(tempDir, "bin", "custom-package-tool");
659 NodeFS.mkdirSync(NodePath.dirname(link), { recursive: true });
660 NodeFS.symlinkSync(ownedBinary, link);
661 const spawned: Array<ReadonlyArray<string>> = [];
662
663 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
664 packageToolUpdate,
665 {
666 binaryPath: link,
667 env: { PATH: brewBinDir },
668 },
669 ).pipe(
670 Effect.provideService(HostProcessPlatform, "darwin"),
671 Effect.provideService(
672 ChildProcessSpawner.ChildProcessSpawner,
673 stdoutSpawner((command, args) => {
674 spawned.push([command, ...args]);
675 return args[0] === "--prefix"
676 ? `${tempDir}\n`
677 : JSON.stringify(
678 fixture.kind === "cask"
679 ? { casks: [{ version: "0.148.0,42" }] }
680 : { formulae: [{ versions: { stable: "0.148.0" } }] },
681 );
682 }),
683 ),
684 );
685
686 expect(spawned).toEqual([
687 [brewPath, "--prefix"],
688 [brewPath, "info", "--json=v2", fixture.name],
689 ]);
690 expect(capabilities).toEqual({
691 provider: driver("packageTool"),
692 packageName: "@example/package-tool",
693 latestVersion: "0.148.0",
694 update: {
695 command:
696 fixture.kind === "cask"
697 ? `brew upgrade --cask ${fixture.name}`
698 : `brew upgrade ${fixture.name}`,
699 executable: brewPath,
700 args:
701 fixture.kind === "cask"
702 ? ["upgrade", "--cask", fixture.name]
703 : ["upgrade", fixture.name],
704 lockKey: "homebrew",
705 },
706 });
707 }),
708 { skip: !symlinksSupported },
709 );
710
711 it.effect.skipIf(windowsHost)(
712 "stays manual-only when the keg is not under the resolved brew's prefix",
713 () =>
714 Effect.gen(function* () {
715 const tempDir = yield* makeTempDir("t3-homebrew-foreign-prefix");
716 const brewBinDir = NodePath.join(tempDir, "brew-bin");
717 writeExecutable(NodePath.join(brewBinDir, "brew"));
718 const kegBinary = NodePath.join(
719 tempDir,
720 "elsewhere",
721 "Cellar",
722 "package-tool",
723 "1.0.0",
724 "bin",
725 "package-tool",
726 );
727 writeExecutable(kegBinary);
728
729 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
730 packageToolUpdate,
731 {
732 binaryPath: kegBinary,
733 env: { PATH: brewBinDir },
734 },
735 ).pipe(
736 Effect.provideService(HostProcessPlatform, "darwin"),
737 Effect.provideService(
738 ChildProcessSpawner.ChildProcessSpawner,
739 stdoutSpawner(() => "/opt/homebrew\n"),
740 ),
741 );
742
743 expect(capabilities).toEqual(manualPackageTool);
744 }),
745 );
746
747 it("reads the stable formula version from brew info", () => {
748 const info = JSON.stringify({ formulae: [{ versions: { stable: "2.1.5" } }] });
749 const formula = { kind: "formula", name: "claude-code", prefix: "/opt/homebrew" } as const;
750 expect(parseHomebrewLatestVersion(info, formula)).toBe("2.1.5");
751 expect(parseHomebrewLatestVersion("not json", formula)).toBeNull();
752 });
753
754 it.effect.skipIf(windowsHost)(
755 "disables one-click updates for explicit custom binary paths it cannot safely map",
756 () =>
757 Effect.gen(function* () {
758 const tempDir = yield* makeTempDir("t3-custom-capabilities");
759 const customPath = NodePath.join(tempDir, "tools", "package-tool");
760 writeExecutable(customPath);
761
762 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
763 packageToolUpdate,
764 {
765 binaryPath: customPath,
766 env: { PATH: "" },
767 },
768 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
769
770 expect(capabilities).toEqual(manualPackageTool);
771 }),
772 );
773
774 it.effect.skipIf(windowsHost)(
775 "falls back to the provider's own updater when no installer is proven",
776 () =>
777 Effect.gen(function* () {
778 const tempDir = yield* makeTempDir("t3-self-update-fallback");
779 const customPath = NodePath.join(tempDir, "tools", "package-tool");
780 writeExecutable(customPath);
781 const selfUpdating = makePackageManagedProviderMaintenanceResolver({
782 provider: driver("packageTool"),
783 npmPackageName: "@example/package-tool",
784 nativeUpdate: { args: ["update", "--self"] },
785 });
786
787 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(selfUpdating, {
788 binaryPath: customPath,
789 env: { PATH: "" },
790 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
791 expect(capabilities.update).toMatchObject({
792 executable: customPath,
793 args: ["update", "--self"],
794 lockKey: "packageTool-native",
795 });
796
797 // A mise install is pinned in mise's config, so it stays manual.
798 const misePath = NodePath.join(tempDir, "mise", "installs", "package-tool", "1.0.0", "bin");
799 writeExecutable(NodePath.join(misePath, "package-tool"));
800 const mise = yield* resolveProviderMaintenanceCapabilitiesEffect(selfUpdating, {
801 binaryPath: NodePath.join(misePath, "package-tool"),
802 env: { PATH: "" },
803 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
804 expect(mise.update).toBeNull();
805 }),
806 );
807
808 it.effect.skipIf(!symlinksSupported)("updates Yarn global installs with yarn", () =>
809 Effect.gen(function* () {
810 const tempDir = yield* makeTempDir("t3-yarn-capabilities");
811 const link = linkIntoPackage(tempDir, "package-tool", [
812 ".config",
813 "yarn",
814 "global",
815 "node_modules",
816 "@example",
817 "package-tool",
818 ]);
819
820 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
821 binaryPath: link,
822 env: { PATH: "" },
823 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
824
825 expect(capabilities.update).toMatchObject({
826 command: "yarn global add @example/package-tool@latest",
827 lockKey: "yarn-global",
828 });
829 expect(makeTargetedProviderUpdateAction(capabilities, "2.0.0")?.args).toEqual([
830 "global",
831 "add",
832 "@example/package-tool@2.0.0",
833 ]);
834 }),
835 );
836
837 it.effect.skipIf(!symlinksSupported)(
838 "updates Volta installs only when Volta has the package",
839 () =>
840 Effect.gen(function* () {
841 const voltaHome = NodePath.join(yield* makeTempDir("t3-volta-capabilities"), ".volta");
842 const shim = NodePath.join(voltaHome, "bin", "volta-shim");
843 writeExecutable(shim);
844 const link = NodePath.join(voltaHome, "bin", "package-tool");
845 NodeFS.symlinkSync(shim, link);
846 const resolve = resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
847 binaryPath: link,
848 env: { PATH: "" },
849 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
850
851 expect((yield* resolve).update).toBeNull();
852 NodeFS.mkdirSync(
853 NodePath.join(voltaHome, "tools", "image", "packages", "@example", "package-tool"),
854 { recursive: true },
855 );
856 expect((yield* resolve).update).toMatchObject({
857 command: "volta install @example/package-tool@latest",
858 lockKey: "volta",
859 });
860 }),
861 );
862
863 it.effect.skipIf(windowsHost)("upgrades with the keg's own brew when brew is not on PATH", () =>
864 Effect.gen(function* () {
865 const tempDir = yield* makeTempDir("t3-homebrew-keg-brew");
866 const brewPath = NodePath.join(tempDir, "bin", "brew");
867 writeExecutable(brewPath);
868 const kegBinary = NodePath.join(tempDir, "Cellar", "package-tool", "1.0.0", "bin", "tool");
869 writeExecutable(kegBinary);
870
871 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
872 binaryPath: kegBinary,
873 env: { PATH: "" },
874 }).pipe(
875 Effect.provideService(HostProcessPlatform, "darwin"),
876 Effect.provideService(
877 ChildProcessSpawner.ChildProcessSpawner,
878 stdoutSpawner((_command, args) => (args[0] === "--prefix" ? `${tempDir}\n` : "{}")),
879 ),
880 );
881
882 expect(capabilities.update).toMatchObject({
883 executable: brewPath,
884 args: ["upgrade", "package-tool"],
885 lockKey: "homebrew",
886 });
887 }),
888 );
889
890 it.effect("caches resolution until a fresh read is requested", () =>
891 Effect.gen(function* () {
892 let resolutions = 0;
893 const resolve = yield* makeCachedProviderMaintenanceResolution(
894 Effect.sync(() => {
895 resolutions += 1;
896 return manualPackageTool;
897 }),
898 );
899 yield* resolve();
900 yield* resolve();
901 expect(resolutions).toBe(1);
902 yield* resolve({ fresh: true });
903 yield* resolve();
904 expect(resolutions).toBe(2);
905 }),
906 );
907
908 it.effect("starts a fresh read instead of joining the resolution already running", () =>
909 Effect.gen(function* () {
910 const releaseStale = yield* Deferred.make<void>();
911 let resolutions = 0;
912 const resolve = yield* makeCachedProviderMaintenanceResolution(
913 Effect.suspend(() => {
914 resolutions += 1;
915 return resolutions === 1
916 ? Deferred.await(releaseStale).pipe(Effect.as(manualPackageTool))
917 : Effect.succeed(manualPackageTool);
918 }),
919 );
920
921 // An advisory read starts a resolution that is still running when the
922 // user clicks Update; the fresh read must not wait on or reuse it.
923 const advisory = yield* Effect.forkChild(resolve(), { startImmediately: true });
924 const fresh = yield* Effect.forkChild(resolve({ fresh: true }), { startImmediately: true });
925 // The fresh read runs its own resolution, so it finishes while the stale
926 // one is still waiting.
927 expect(resolutions).toBe(2);
928 expect(fresh.pollUnsafe()).toBeDefined();
929 yield* Deferred.succeed(releaseStale, undefined);
930 expect(yield* Fiber.join(fresh)).toEqual(manualPackageTool);
931 yield* Fiber.join(advisory);
932 }),
933 );
934
935 it.effect("resolves again after the first read is interrupted", () =>
936 Effect.gen(function* () {
937 const release = yield* Deferred.make<void>();
938 let resolutions = 0;
939 const resolve = yield* makeCachedProviderMaintenanceResolution(
940 Effect.suspend(() => {
941 resolutions += 1;
942 return resolutions === 1
943 ? Effect.never
944 : Deferred.await(release).pipe(Effect.as(manualPackageTool));
945 }),
946 );
947
948 const first = yield* Effect.forkChild(resolve(), { startImmediately: true });
949 yield* Fiber.interrupt(first);
950
951 // The next read resolves again, and a reader that joined it keeps it
952 // running when the reader that started it goes away.
953 const owner = yield* Effect.forkChild(resolve(), { startImmediately: true });
954 const waiter = yield* Effect.forkChild(resolve(), { startImmediately: true });
955 yield* Fiber.interrupt(owner);
956 yield* Deferred.succeed(release, undefined);
957 expect(yield* Fiber.join(waiter)).toEqual(manualPackageTool);
958 expect(yield* resolve()).toEqual(manualPackageTool);
959 expect(resolutions).toBe(2);
960 }),
961 );
962});
963
964it("pins only owned package-manager installs and preserves their execution context", () => {
965 const capabilities = makeProviderMaintenanceCapabilities({
966 provider: driver("codex"),
967 packageName: "@openai/codex",
968 updateExecutable: "npm",
969 updateLockKey: "npm-global:/opt/node",
970 updateArgs: [
971 "install",
972 "-g",
973 "--prefix",
974 "/opt/node",
975 "--allow-scripts=@openai/codex",
976 "@openai/codex@latest",
977 ],
978 env: { PATH: "/opt/node/bin" },
979 });
980 const pinned = makeTargetedProviderUpdateAction(capabilities, "2.0.0");
981 expect(pinned).toMatchObject({
982 executable: "npm",
983 lockKey: capabilities.update?.lockKey,
984 env: capabilities.update?.env,
985 args: [
986 "install",
987 "-g",
988 "--prefix",
989 "/opt/node",
990 "--allow-scripts=@openai/codex",
991 "@openai/codex@2.0.0",
992 ],
993 });
994 expect(pinned?.command).toContain("@openai/codex@2.0.0");
995 for (const lockKey of ["codex-native", "homebrew", "manual"]) {
996 expect(
997 makeTargetedProviderUpdateAction(
998 { ...capabilities, update: { ...capabilities.update!, lockKey } },
999 "2.0.0",
1000 ),
1001 ).toBeNull();
1002 }
1003 expect(makeTargetedProviderUpdateAction(capabilities, "2.0.0; rm -rf /")).toBeNull();
1004});