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

providerMaintenance.test.ts

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