Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

providerMaintenance.test.ts

788 lines27.4 KB

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 Effect from "effect/Effect";
12import * as Sink from "effect/Sink";
13import * as Stream from "effect/Stream";
14import { HttpClient } from "effect/unstable/http";
15import { ChildProcessSpawner } from "effect/unstable/process";
16import {
17 createProviderVersionAdvisory,
18 enrichProviderSnapshotWithVersionAdvisory,
19 homebrewOwnershipFromCommandPath,
20 makeCachedProviderMaintenanceResolution,
21 makePackageManagedProviderMaintenanceResolver,
22 makeProviderMaintenanceCapabilities,
23 normalizeCommandPath,
24 npmGlobalPrefixFromCommandPath,
25 parseHomebrewLatestVersion,
26 ProviderVersionCache,
27 resolveLatestProviderVersion,
28 resolvePackageManagedProviderMaintenance,
29 resolveProviderMaintenanceCapabilitiesEffect,
30 type ProviderMaintenanceCapabilities,
31} from "./providerMaintenance.ts";
32import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
33​
34const driver = (value: string) => ProviderDriverKind.make(value);
35// These write `#!/bin/sh` stubs and evaluate them with darwin/linux path
36// semantics; a Windows temp path cannot be split on `:`.
37const windowsHost = HostProcessPlatform.defaultValue() === "win32";
38const makeTempDir = (name: string) =>
39 Crypto.Crypto.pipe(
40 Effect.flatMap((crypto) => crypto.randomUUIDv4),
41 Effect.map((id) => NodePath.join(NodeOS.tmpdir(), `${name}-${id}`)),
42 );
43const isNativeTestCommandPath =
44 (expectedPathSegment: string) =>
45 (commandPath: string): boolean =>
46 normalizeCommandPath(commandPath).includes(expectedPathSegment);
47const packageToolUpdate = makePackageManagedProviderMaintenanceResolver({
48 provider: driver("packageTool"),
49 npmPackageName: "@example/package-tool",
50 nativeUpdate: null,
51});
52const nativePackageToolUpdate = makePackageManagedProviderMaintenanceResolver({
53 provider: driver("nativePackageTool"),
54 npmPackageName: "@example/native-package-tool",
55 nativeUpdate: {
56 args: ["update"],
57 isCommandPath: isNativeTestCommandPath("/.local/bin/native-package-tool"),
58 },
59});
60const installedPackageToolProvider: ServerProvider = {
61 instanceId: ProviderInstanceId.make("packageTool"),
62 driver: driver("packageTool"),
63 enabled: true,
64 installed: true,
65 version: "1.0.0",
66 status: "ready",
67 auth: { status: "authenticated" },
68 checkedAt: "2026-04-10T00:00:00.000Z",
69 models: [],
70 slashCommands: [],
71 skills: [],
72};
73const manualPackageTool: ProviderMaintenanceCapabilities = {
74 provider: driver("packageTool"),
75 packageName: "@example/package-tool",
76 update: null,
77};
78​
79function writeExecutable(path: string) {
80 NodeFS.mkdirSync(NodePath.dirname(path), { recursive: true });
81 NodeFS.writeFileSync(path, "#!/bin/sh\n");
82 NodeFS.chmodSync(path, 0o755);
84​
85/** Symlink `<tempDir>/bin/<name>` into a package entry point, like npm/pnpm do. */
86function linkIntoPackage(tempDir: string, name: string, packageSegments: ReadonlyArray<string>) {
87 const target = NodePath.join(tempDir, ...packageSegments, "bin", `${name}.js`);
88 writeExecutable(target);
89 const link = NodePath.join(tempDir, "bin", name);
90 NodeFS.mkdirSync(NodePath.dirname(link), { recursive: true });
91 NodeFS.symlinkSync(target, link);
92 return link;
94​
95const noSpawn = ChildProcessSpawner.make(() =>
96 Effect.die("maintenance resolution should not spawn a process here"),
97);
98​
99function stdoutSpawner(onSpawn: (command: string, args: ReadonlyArray<string>) => string) {
100 return ChildProcessSpawner.make((command) => {
101 const { command: executable, args } = command as unknown as {
102 readonly command: string;
103 readonly args: ReadonlyArray<string>;
104 };
105 return Effect.succeed(
106 ChildProcessSpawner.makeHandle({
107 pid: ChildProcessSpawner.ProcessId(1),
108 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
109 isRunning: Effect.succeed(false),
110 kill: () => Effect.void,
111 unref: Effect.succeed(Effect.void),
112 stdin: Sink.drain,
113 stdout: Stream.encodeText(Stream.make(onSpawn(executable, args))),
114 stderr: Stream.empty,
115 all: Stream.empty,
116 getInputFd: () => Sink.drain,
117 getOutputFd: () => Stream.empty,
118 }),
119 );
120 });
122​
123it.layer(NodeServices.layer)("providerMaintenance", (it) => {
124 it.effect("reads cached versions through the injectable cache reference", () =>
125 resolveLatestProviderVersion(manualPackageTool).pipe(
126 Effect.provideService(
127 ProviderVersionCache,
128 new Map([
129 [
130 "@example/package-tool",
131 {
132 expiresAt: Number.MAX_SAFE_INTEGER,
133 version: "9.9.9",
134 },
135 ],
136 ]),
137 ),
138 Effect.provideService(
139 HttpClient.HttpClient,
140 HttpClient.make(() =>
141 Effect.die("cached provider version should not make an HTTP request"),
142 ),
143 ),
144 Effect.map((version) => {
145 expect(version).toBe("9.9.9");
146 }),
147 ),
148 );
149​
150 it.effect("prefers the installer's own latest version over the npm registry", () =>
151 resolveLatestProviderVersion({ ...manualPackageTool, latestVersion: "1.2.0" }).pipe(
152 Effect.provideService(ProviderVersionCache, new Map()),
153 Effect.provideService(
154 HttpClient.HttpClient,
155 HttpClient.make(() =>
156 Effect.die("installer-reported latest should not make an HTTP request"),
157 ),
158 ),
159 Effect.map((version) => {
160 expect(version).toBe("1.2.0");
161 }),
162 ),
163 );
164​
165 it.effect("does not fetch latest provider versions when update checks are disabled", () =>
166 enrichProviderSnapshotWithVersionAdvisory(installedPackageToolProvider, manualPackageTool, {
167 enableProviderUpdateChecks: false,
168 }).pipe(
169 Effect.provideService(ProviderVersionCache, new Map()),
170 Effect.provideService(
171 HttpClient.HttpClient,
172 HttpClient.make(() =>
173 Effect.die("disabled provider update checks should not make an HTTP request"),
174 ),
175 ),
176 Effect.map((provider) => {
177 expect(provider.versionAdvisory).toMatchObject({
178 status: "unknown",
179 currentVersion: "1.0.0",
180 latestVersion: null,
181 checkedAt: "2026-04-10T00:00:00.000Z",
182 });
183 }),
184 ),
185 );
186​
187 it("marks providers with unknown current versions as unknown", () => {
188 expect(
189 createProviderVersionAdvisory({
190 driver: driver("packageTool"),
191 currentVersion: null,
192 latestVersion: "9.9.9",
193 }),
194 ).toMatchObject({
195 status: "unknown",
196 currentVersion: null,
197 latestVersion: "9.9.9",
198 });
199 });
200​
201 it("marks providers with unknown latest versions as unknown", () => {
202 expect(
203 createProviderVersionAdvisory({
204 driver: driver("packageTool"),
205 currentVersion: "1.0.0",
206 latestVersion: null,
207 }),
208 ).toMatchObject({
209 status: "unknown",
210 currentVersion: "1.0.0",
211 latestVersion: null,
212 message: null,
213 });
214 });
215​
216 it("keeps the manual update hint when the install is behind but unowned", () => {
217 expect(
218 createProviderVersionAdvisory({
219 driver: driver("packageTool"),
220 currentVersion: "2.1.110",
221 latestVersion: "2.1.117",
222 maintenanceCapabilities: manualPackageTool,
223 }),
224 ).toMatchObject({
225 status: "behind_latest",
226 latestVersion: "2.1.117",
227 updateCommand: null,
228 canUpdate: false,
229 message: "Install the update now or review provider settings.",
230 });
231 });
232​
233 it.effect("stays manual-only when the binary cannot be located", () =>
234 resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
235 binaryPath: "package-tool",
236 env: { PATH: "" },
237 }).pipe(
238 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
239 Effect.map((capabilities) => {
240 expect(capabilities).toEqual(manualPackageTool);
241 }),
242 ),
243 );
244​
245 it.effect.skipIf(!symlinksSupported)(
246 "pins npm updates to the global prefix that owns the package",
247 () =>
248 Effect.gen(function* () {
249 const tempDir = yield* makeTempDir("t3-npm-capabilities");
250 const link = linkIntoPackage(tempDir, "package-tool", [
251 "lib",
252 "node_modules",
253 "@example",
254 "package-tool",
255 ]);
256​
257 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
258 packageToolUpdate,
259 {
260 binaryPath: link,
261 env: { PATH: "" },
262 },
263 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
264​
265 expect(capabilities).toEqual({
266 provider: driver("packageTool"),
267 packageName: "@example/package-tool",
268 update: {
269 command: `npm install -g --prefix ${tempDir} --allow-scripts=@example/package-tool @example/package-tool@latest`,
270 executable: "npm",
271 args: [
272 "install",
273 "-g",
274 "--prefix",
275 tempDir,
276 "--allow-scripts=@example/package-tool",
277 "@example/package-tool@latest",
278 ],
279 lockKey: `npm-global:${normalizeCommandPath(tempDir)}`,
280 },
281 });
282 }),
283 );
284​
285 it("derives the npm prefix only from the global lib/node_modules layout", () => {
286 expect(
287 npmGlobalPrefixFromCommandPath(
288 "/usr/local/lib/node_modules/@openai/codex/bin/codex.js",
289 "@openai/codex",
290 ),
291 ).toBe("/usr/local");
292 // A copy nested inside another package is not a global install.
293 expect(
294 npmGlobalPrefixFromCommandPath(
295 "/usr/local/lib/node_modules/other/node_modules/@openai/codex/bin/codex.js",
296 "@openai/codex",
297 ),
298 ).toBeNull();
299 expect(
300 npmGlobalPrefixFromCommandPath(
301 "/lib/node_modules/@openai/codex/bin/codex.js",
302 "@openai/codex",
303 ),
304 ).toBe("/");
305 // Neither is a project-local dependency.
306 expect(
307 npmGlobalPrefixFromCommandPath(
308 "/work/app/node_modules/@openai/codex/bin/codex.js",
309 "@openai/codex",
310 ),
311 ).toBeNull();
312 });
313​
314 // The Codex Windows installer exposes `%LOCALAPPDATA%\\Programs\\OpenAI\\Codex\\bin`
315 // as a junction into `%CODEX_HOME%\\packages\\standalone\\current\\bin`. Node's
316 // realpath follows junctions, so the real path carries the standalone marker
317 // even though the visible path does not.
318 it.effect("recognizes a Windows standalone install through its junctioned bin dir", () =>
319 Effect.gen(function* () {
320 const visiblePath =
321 "C:\\Users\\Theo\\AppData\\Local\\Programs\\OpenAI\\Codex\\bin\\codex.exe";
322 const realPath =
323 "C:\\Users\\Theo\\.codex\\packages\\standalone\\releases\\0.120.0-x86_64\\bin\\codex.exe";
324 const capabilities = yield* resolvePackageManagedProviderMaintenance(
325 {
326 provider: driver("codex"),
327 npmPackageName: "@openai/codex",
328 nativeUpdate: {
329 args: ["update"],
330 isCommandPath: isNativeTestCommandPath("/packages/standalone/"),
331 },
332 },
333 {
334 binaryPath: "codex",
335 resolvedCommandPath: visiblePath,
336 realCommandPath: realPath,
337 env: {},
338 platform: "win32",
339 },
340 ).pipe(Effect.provideService(HostProcessPlatform, "win32"));
341​
342 expect(capabilities.update).toMatchObject({
343 executable: visiblePath,
344 args: ["update"],
345 lockKey: "codex-native",
346 });
347 }),
348 );
349​
350 it.effect("proves Windows npm ownership from the package manifest beside the shim", () =>
351 Effect.gen(function* () {
352 const tempDir = yield* makeTempDir("t3-npm-windows-capabilities");
353 const shim = NodePath.join(tempDir, "package-tool.cmd");
354 NodeFS.mkdirSync(tempDir, { recursive: true });
355 NodeFS.writeFileSync(shim, "@echo off\r\n");
356 NodeFS.mkdirSync(NodePath.join(tempDir, "node_modules", "@example", "package-tool"), {
357 recursive: true,
358 });
359 NodeFS.writeFileSync(
360 NodePath.join(tempDir, "node_modules", "@example", "package-tool", "package.json"),
361 "{}",
362 );
363​
364 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
365 binaryPath: shim,
366 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
367 }).pipe(
368 Effect.provideService(HostProcessPlatform, "win32"),
369 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
370 );
371​
372 expect(capabilities.update).toMatchObject({
373 executable: "npm",
374 args: ["install", "-g", "--prefix", tempDir, expect.any(String), expect.any(String)],
375 });
376​
377 // The same layout on POSIX is a project checkout, not a global install.
378 const script = NodePath.join(tempDir, "package-tool");
379 writeExecutable(script);
380 const posix = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
381 binaryPath: script,
382 env: { PATH: "" },
383 }).pipe(
384 Effect.provideService(HostProcessPlatform, "linux"),
385 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
386 );
387 expect(posix.update).toBeNull();
388 }),
389 );
390​
391 it.effect.skipIf(!symlinksSupported)(
392 "switches to pnpm updates when the real path lives in pnpm's global store",
393 () =>
394 Effect.gen(function* () {
395 const tempDir = yield* makeTempDir("t3-pnpm-capabilities");
396 const link = linkIntoPackage(tempDir, "package-tool", [
397 ".local",
398 "share",
399 "pnpm",
400 "global",
401 "5",
402 "node_modules",
403 "@example",
404 "package-tool",
405 ]);
406​
407 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
408 packageToolUpdate,
409 {
410 binaryPath: link,
411 env: { PATH: "" },
412 },
413 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
414​
415 expect(capabilities.update).toMatchObject({
416 command: "pnpm add -g @example/package-tool@latest",
417 lockKey: "pnpm-global",
418 });
419 }),
420 );
421​
422 it.effect.skipIf(windowsHost)(
423 "switches to bun updates when the resolved binary lives in bun's global bin",
424 () =>
425 Effect.gen(function* () {
426 const tempDir = yield* makeTempDir("t3-bun-capabilities");
427 const bunBinDir = NodePath.join(tempDir, ".bun", "bin");
428 writeExecutable(NodePath.join(bunBinDir, "package-tool"));
429​
430 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
431 packageToolUpdate,
432 {
433 binaryPath: "package-tool",
434 env: { PATH: bunBinDir },
435 },
436 ).pipe(
437 Effect.provideService(HostProcessPlatform, "darwin"),
438 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
439 );
440​
441 expect(capabilities.update).toMatchObject({
442 command: "bun i -g @example/package-tool@latest",
443 lockKey: "bun-global",
444 });
445 }),
446 );
447​
448 it.effect.skipIf(windowsHost)("switches to native updates and runs the resolved executable", () =>
449 Effect.gen(function* () {
450 const tempDir = yield* makeTempDir("t3-native-capabilities");
451 const nativeBinDir = NodePath.join(tempDir, ".local", "bin");
452 const nativePath = NodePath.join(nativeBinDir, "native-package-tool");
453 writeExecutable(nativePath);
454​
455 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
456 nativePackageToolUpdate,
457 {
458 binaryPath: "native-package-tool",
459 env: { PATH: nativeBinDir },
460 },
461 ).pipe(
462 Effect.provideService(HostProcessPlatform, "darwin"),
463 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
464 );
465​
466 expect(capabilities).toEqual({
467 provider: driver("nativePackageTool"),
468 packageName: "@example/native-package-tool",
469 update: {
470 command: `${nativePath} update`,
471 executable: nativePath,
472 args: ["update"],
473 lockKey: "nativePackageTool-native",
474 },
475 });
476 }),
477 );
478​
479 // Regression for #9850: an explicit native path outside PATH, with spaces,
480 // must be what actually gets spawned.
481 it.effect.skipIf(windowsHost)("runs an explicit native updater outside PATH", () =>
482 Effect.gen(function* () {
483 const tempDir = yield* makeTempDir("t3-native-update");
484 const nativePath = NodePath.join(
485 tempDir,
486 "with spaces",
487 ".local",
488 "bin",
489 "native-package-tool",
490 );
491 NodeFS.mkdirSync(NodePath.dirname(nativePath), { recursive: true });
492 NodeFS.writeFileSync(nativePath, "#!/bin/sh\nprintf '%s' \"$1\"\n");
493 NodeFS.chmodSync(nativePath, 0o755);
494​
495 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
496 nativePackageToolUpdate,
497 { binaryPath: nativePath, env: { PATH: "" } },
498 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
499​
500 expect(capabilities.update?.executable).toBe(nativePath);
501 const result = NodeChildProcess.spawnSync(
502 capabilities.update!.executable,
503 capabilities.update!.args,
504 { env: { PATH: "" }, encoding: "utf8" },
505 );
506 expect(result.status).toBe(0);
507 expect(result.stdout).toBe("update");
508 }),
509 );
510​
511 it.effect.skipIf(!symlinksSupported)(
512 "prefers npm ownership over the Node keg the package lives under",
513 () =>
514 Effect.gen(function* () {
515 // `brew install node` keeps npm globals inside the node keg.
516 const tempDir = yield* makeTempDir("t3-homebrew-node-capabilities");
517 const keg = NodePath.join(tempDir, "Cellar", "node", "22.1.0");
518 const target = NodePath.join(
519 keg,
520 "lib",
521 "node_modules",
522 "@example",
523 "package-tool",
524 "bin",
525 "package-tool.js",
526 );
527 writeExecutable(target);
528 const link = NodePath.join(tempDir, "bin", "package-tool");
529 NodeFS.mkdirSync(NodePath.dirname(link), { recursive: true });
530 NodeFS.symlinkSync(target, link);
531​
532 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
533 packageToolUpdate,
534 {
535 binaryPath: link,
536 env: { PATH: "" },
537 },
538 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
539​
540 expect(capabilities.update).toMatchObject({
541 executable: "npm",
542 args: expect.arrayContaining(["--prefix", keg]),
543 lockKey: `npm-global:${normalizeCommandPath(keg)}`,
544 });
545 }),
546 );
547​
548 it("quotes copyable command words the shell would split", () => {
549 const posix = makeProviderMaintenanceCapabilities({
550 provider: driver("packageTool"),
551 packageName: "@example/package-tool",
552 updateExecutable: "npm",
553 updateArgs: [
554 "install",
555 "-g",
556 "--prefix",
557 "/Users/Jane Doe/.npm-global",
558 "@example/package-tool@latest",
559 ],
560 updateLockKey: "npm-global",
561 platform: "darwin",
562 });
563 expect(posix.update?.command).toBe(
564 "npm install -g --prefix '/Users/Jane Doe/.npm-global' @example/package-tool@latest",
565 );
566 const windows = makeProviderMaintenanceCapabilities({
567 provider: driver("packageTool"),
568 packageName: null,
569 updateExecutable: "C:\\Program Files\\Tool\\tool.exe",
570 updateArgs: ["update"],
571 updateLockKey: "tool",
572 platform: "win32",
573 });
574 expect(windows.update?.command).toBe("& 'C:\\Program Files\\Tool\\tool.exe' update");
575 });
576​
577 it.effect.skipIf(windowsHost)("carries the native updater's environment into the action", () =>
578 Effect.gen(function* () {
579 const tempDir = yield* makeTempDir("t3-native-env");
580 const nativePath = NodePath.join(tempDir, ".local", "bin", "native-package-tool");
581 writeExecutable(nativePath);
582 const resolver = makePackageManagedProviderMaintenanceResolver({
583 provider: driver("nativePackageTool"),
584 npmPackageName: "@example/native-package-tool",
585 nativeUpdate: {
586 args: ["update"],
587 isCommandPath: isNativeTestCommandPath("/.local/bin/native-package-tool"),
588 env: { TOOL_HOME: tempDir },
589 },
590 });
591​
592 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(resolver, {
593 binaryPath: nativePath,
594 env: { PATH: "" },
595 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
596​
597 expect(capabilities.update?.env).toEqual({ TOOL_HOME: tempDir });
598 }),
599 );
600​
601 it("recognizes Homebrew kegs and casks from the real executable path", () => {
602 expect(
603 homebrewOwnershipFromCommandPath("/opt/homebrew/Cellar/claude-code@latest/2.1.0/bin/claude"),
604 ).toEqual({ kind: "formula", name: "claude-code@latest", prefix: "/opt/homebrew" });
605 expect(homebrewOwnershipFromCommandPath("/usr/local/Caskroom/codex/0.148.0/codex")).toEqual({
606 kind: "cask",
607 name: "codex",
608 prefix: "/usr/local",
609 });
610 // A plain /usr/local/bin binary is not evidence of Homebrew (#8832).
611 expect(homebrewOwnershipFromCommandPath("/usr/local/bin/codex")).toBeNull();
612 // A keg elsewhere reports its prefix so the resolver can reject it against
613 // `brew --prefix`.
614 expect(homebrewOwnershipFromCommandPath("/srv/Cellar/claude/1.0.0/bin/claude")).toMatchObject({
615 prefix: "/srv",
616 });
617 });
618​
619 it.effect.skipIf(windowsHost)(
620 "stays manual-only for an explicit binary path that does not exist",
621 () =>
622 Effect.gen(function* () {
623 const tempDir = yield* makeTempDir("t3-missing-native-capabilities");
624 const missingPath = NodePath.join(tempDir, ".local", "bin", "native-package-tool");
625​
626 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
627 nativePackageToolUpdate,
628 { binaryPath: missingPath, env: { PATH: "" } },
629 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
630​
631 expect(capabilities.update).toBeNull();
632 }),
633 );
634​
635 it.effect.each([
636 { directory: "Caskroom", name: "package-tool", kind: "cask" },
637 { directory: "Cellar", name: "package-tool", kind: "formula" },
638 { directory: "Cellar", name: "package-tool@latest", kind: "formula" },
639 ] as const)(
640 "upgrades the owning Homebrew $kind $name through an executable alias",
641 (fixture) =>
642 Effect.gen(function* () {
643 const tempDir = yield* makeTempDir("t3-homebrew-capabilities");
644 const brewBinDir = NodePath.join(tempDir, "brew-bin");
645 const brewPath = NodePath.join(brewBinDir, "brew");
646 writeExecutable(brewPath);
647 const ownedBinary = NodePath.join(
648 tempDir,
649 fixture.directory,
650 fixture.name,
651 "0.148.0",
652 "package-tool-0.148.0",
653 );
654 writeExecutable(ownedBinary);
655 const link = NodePath.join(tempDir, "bin", "custom-package-tool");
656 NodeFS.mkdirSync(NodePath.dirname(link), { recursive: true });
657 NodeFS.symlinkSync(ownedBinary, link);
658 const spawned: Array<ReadonlyArray<string>> = [];
659​
660 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
661 packageToolUpdate,
662 {
663 binaryPath: link,
664 env: { PATH: brewBinDir },
665 },
666 ).pipe(
667 Effect.provideService(HostProcessPlatform, "darwin"),
668 Effect.provideService(
669 ChildProcessSpawner.ChildProcessSpawner,
670 stdoutSpawner((command, args) => {
671 spawned.push([command, ...args]);
672 return args[0] === "--prefix"
673 ? `${tempDir}\n`
674 : JSON.stringify(
675 fixture.kind === "cask"
676 ? { casks: [{ version: "0.148.0,42" }] }
677 : { formulae: [{ versions: { stable: "0.148.0" } }] },
678 );
679 }),
680 ),
681 );
682​
683 expect(spawned).toEqual([
684 [brewPath, "--prefix"],
685 [brewPath, "info", "--json=v2", fixture.name],
686 ]);
687 expect(capabilities).toEqual({
688 provider: driver("packageTool"),
689 packageName: "@example/package-tool",
690 latestVersion: "0.148.0",
691 update: {
692 command:
693 fixture.kind === "cask"
694 ? `brew upgrade --cask ${fixture.name}`
695 : `brew upgrade ${fixture.name}`,
696 executable: brewPath,
697 args:
698 fixture.kind === "cask"
699 ? ["upgrade", "--cask", fixture.name]
700 : ["upgrade", fixture.name],
701 lockKey: "homebrew",
702 },
703 });
704 }),
705 { skip: !symlinksSupported },
706 );
707​
708 it.effect.skipIf(windowsHost)(
709 "stays manual-only when the keg is not under the resolved brew's prefix",
710 () =>
711 Effect.gen(function* () {
712 const tempDir = yield* makeTempDir("t3-homebrew-foreign-prefix");
713 const brewBinDir = NodePath.join(tempDir, "brew-bin");
714 writeExecutable(NodePath.join(brewBinDir, "brew"));
715 const kegBinary = NodePath.join(
716 tempDir,
717 "elsewhere",
718 "Cellar",
719 "package-tool",
720 "1.0.0",
721 "bin",
722 "package-tool",
723 );
724 writeExecutable(kegBinary);
725​
726 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
727 packageToolUpdate,
728 {
729 binaryPath: kegBinary,
730 env: { PATH: brewBinDir },
731 },
732 ).pipe(
733 Effect.provideService(HostProcessPlatform, "darwin"),
734 Effect.provideService(
735 ChildProcessSpawner.ChildProcessSpawner,
736 stdoutSpawner(() => "/opt/homebrew\n"),
737 ),
738 );
739​
740 expect(capabilities).toEqual(manualPackageTool);
741 }),
742 );
743​
744 it("reads the stable formula version from brew info", () => {
745 const info = JSON.stringify({ formulae: [{ versions: { stable: "2.1.5" } }] });
746 const formula = { kind: "formula", name: "claude-code", prefix: "/opt/homebrew" } as const;
747 expect(parseHomebrewLatestVersion(info, formula)).toBe("2.1.5");
748 expect(parseHomebrewLatestVersion("not json", formula)).toBeNull();
749 });
750​
751 it.effect.skipIf(windowsHost)(
752 "disables one-click updates for explicit custom binary paths it cannot safely map",
753 () =>
754 Effect.gen(function* () {
755 const tempDir = yield* makeTempDir("t3-custom-capabilities");
756 const customPath = NodePath.join(tempDir, "tools", "package-tool");
757 writeExecutable(customPath);
758​
759 const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
760 packageToolUpdate,
761 {
762 binaryPath: customPath,
763 env: { PATH: "" },
764 },
765 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));
766​
767 expect(capabilities).toEqual(manualPackageTool);
768 }),
769 );
770​
771 it.effect("caches resolution until a fresh read is requested", () =>
772 Effect.gen(function* () {
773 let resolutions = 0;
774 const resolve = yield* makeCachedProviderMaintenanceResolution(
775 Effect.sync(() => {
776 resolutions += 1;
777 return manualPackageTool;
778 }),
779 );
780 yield* resolve();
781 yield* resolve();
782 expect(resolutions).toBe(1);
783 yield* resolve({ fresh: true });
784 yield* resolve();
785 expect(resolutions).toBe(2);
786 }),
787 );
788});