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

maintenanceResolver.test.ts

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