package-command-paths.test.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. import { mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  5. import { ENV_AGENT_DIR, PACKAGE_NAME, VERSION } from "../src/config.ts";
  6. import { ProjectTrustStore } from "../src/core/trust-manager.ts";
  7. import { main } from "../src/main.ts";
  8. describe("package commands", () => {
  9. let tempDir: string;
  10. let agentDir: string;
  11. let projectDir: string;
  12. let packageDir: string;
  13. let originalCwd: string;
  14. let originalAgentDir: string | undefined;
  15. let originalPiPackageDir: string | undefined;
  16. let originalExitCode: typeof process.exitCode;
  17. let originalExecPath: string;
  18. function getNewerPatchVersion(): string {
  19. const [major = "0", minor = "0", patch = "0"] = VERSION.split(".");
  20. return `${major}.${minor}.${Number.parseInt(patch, 10) + 1}`;
  21. }
  22. beforeEach(() => {
  23. tempDir = join(tmpdir(), `pi-package-commands-${Date.now()}-${Math.random().toString(36).slice(2)}`);
  24. agentDir = join(tempDir, "agent");
  25. projectDir = join(tempDir, "project");
  26. packageDir = join(tempDir, "local-package");
  27. mkdirSync(agentDir, { recursive: true });
  28. mkdirSync(projectDir, { recursive: true });
  29. mkdirSync(packageDir, { recursive: true });
  30. originalCwd = process.cwd();
  31. originalAgentDir = process.env[ENV_AGENT_DIR];
  32. originalPiPackageDir = process.env.PI_PACKAGE_DIR;
  33. originalExitCode = process.exitCode;
  34. originalExecPath = process.execPath;
  35. process.exitCode = undefined;
  36. process.env[ENV_AGENT_DIR] = agentDir;
  37. process.chdir(projectDir);
  38. });
  39. afterEach(() => {
  40. vi.unstubAllGlobals();
  41. process.chdir(originalCwd);
  42. process.exitCode = originalExitCode;
  43. if (originalAgentDir === undefined) {
  44. delete process.env[ENV_AGENT_DIR];
  45. } else {
  46. process.env[ENV_AGENT_DIR] = originalAgentDir;
  47. }
  48. if (originalPiPackageDir === undefined) {
  49. delete process.env.PI_PACKAGE_DIR;
  50. } else {
  51. process.env.PI_PACKAGE_DIR = originalPiPackageDir;
  52. }
  53. Object.defineProperty(process, "execPath", { value: originalExecPath, configurable: true });
  54. rmSync(tempDir, { recursive: true, force: true });
  55. });
  56. it("should persist global relative local package paths relative to settings.json", async () => {
  57. const relativePkgDir = join(projectDir, "packages", "local-package");
  58. mkdirSync(relativePkgDir, { recursive: true });
  59. await main(["install", "./packages/local-package"]);
  60. const settingsPath = join(agentDir, "settings.json");
  61. const settings = JSON.parse(readFileSync(settingsPath, "utf-8")) as { packages?: string[] };
  62. expect(settings.packages?.length).toBe(1);
  63. const stored = settings.packages?.[0] ?? "";
  64. const resolvedFromSettings = realpathSync(join(agentDir, stored));
  65. expect(resolvedFromSettings).toBe(realpathSync(relativePkgDir));
  66. });
  67. it("should remove local packages using a path with a trailing slash", async () => {
  68. await main(["install", `${packageDir}/`]);
  69. const settingsPath = join(agentDir, "settings.json");
  70. const installedSettings = JSON.parse(readFileSync(settingsPath, "utf-8")) as { packages?: string[] };
  71. expect(installedSettings.packages?.length).toBe(1);
  72. await main(["remove", `${packageDir}/`]);
  73. const removedSettings = JSON.parse(readFileSync(settingsPath, "utf-8")) as { packages?: string[] };
  74. expect(removedSettings.packages ?? []).toHaveLength(0);
  75. });
  76. it("skips untrusted project package settings", async () => {
  77. mkdirSync(join(projectDir, ".pi"), { recursive: true });
  78. writeFileSync(join(projectDir, ".pi", "settings.json"), JSON.stringify({ packages: ["npm:@project/pkg"] }));
  79. const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  80. try {
  81. await expect(main(["list"])).resolves.toBeUndefined();
  82. const stdout = logSpy.mock.calls.map(([message]) => String(message)).join("\n");
  83. expect(stdout).toContain("No packages installed.");
  84. expect(stdout).not.toContain("Project packages:");
  85. } finally {
  86. logSpy.mockRestore();
  87. }
  88. });
  89. it("uses remembered project trust for list", async () => {
  90. mkdirSync(join(projectDir, ".pi"), { recursive: true });
  91. writeFileSync(join(projectDir, ".pi", "settings.json"), JSON.stringify({ packages: ["npm:@project/pkg"] }));
  92. new ProjectTrustStore(agentDir).set(projectDir, true);
  93. const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  94. try {
  95. await expect(main(["list"])).resolves.toBeUndefined();
  96. const stdout = logSpy.mock.calls.map(([message]) => String(message)).join("\n");
  97. expect(stdout).toContain("Project packages:");
  98. expect(stdout).toContain("npm:@project/pkg");
  99. expect(stdout).not.toContain("No packages installed.");
  100. expect(process.exitCode).toBeUndefined();
  101. } finally {
  102. logSpy.mockRestore();
  103. }
  104. });
  105. it("overrides remembered trust for list with --no-approve", async () => {
  106. mkdirSync(join(projectDir, ".pi"), { recursive: true });
  107. writeFileSync(join(projectDir, ".pi", "settings.json"), JSON.stringify({ packages: ["npm:@project/pkg"] }));
  108. new ProjectTrustStore(agentDir).set(projectDir, true);
  109. const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  110. try {
  111. await expect(main(["list", "--no-approve"])).resolves.toBeUndefined();
  112. const stdout = logSpy.mock.calls.map(([message]) => String(message)).join("\n");
  113. expect(stdout).toContain("No packages installed.");
  114. expect(stdout).not.toContain("Project packages:");
  115. expect(process.exitCode).toBeUndefined();
  116. } finally {
  117. logSpy.mockRestore();
  118. }
  119. });
  120. it("approves project trust for list with --approve", async () => {
  121. mkdirSync(join(projectDir, ".pi"), { recursive: true });
  122. writeFileSync(join(projectDir, ".pi", "settings.json"), JSON.stringify({ packages: ["npm:@project/pkg"] }));
  123. const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  124. try {
  125. await expect(main(["list", "--approve"])).resolves.toBeUndefined();
  126. const stdout = logSpy.mock.calls.map(([message]) => String(message)).join("\n");
  127. expect(stdout).toContain("Project packages:");
  128. expect(stdout).toContain("npm:@project/pkg");
  129. expect(stdout).not.toContain("No packages installed.");
  130. expect(process.exitCode).toBeUndefined();
  131. } finally {
  132. logSpy.mockRestore();
  133. }
  134. });
  135. it("uses default project trust for list", async () => {
  136. mkdirSync(join(projectDir, ".pi"), { recursive: true });
  137. writeFileSync(join(agentDir, "settings.json"), JSON.stringify({ defaultProjectTrust: "always" }));
  138. writeFileSync(join(projectDir, ".pi", "settings.json"), JSON.stringify({ packages: ["npm:@project/pkg"] }));
  139. const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  140. try {
  141. await expect(main(["list"])).resolves.toBeUndefined();
  142. const stdout = logSpy.mock.calls.map(([message]) => String(message)).join("\n");
  143. expect(stdout).toContain("Project packages:");
  144. expect(stdout).toContain("npm:@project/pkg");
  145. expect(stdout).not.toContain("No packages installed.");
  146. expect(process.exitCode).toBeUndefined();
  147. } finally {
  148. logSpy.mockRestore();
  149. }
  150. });
  151. it("uses project_trust extensions for package commands", async () => {
  152. mkdirSync(join(projectDir, ".pi"), { recursive: true });
  153. writeFileSync(join(projectDir, ".pi", "settings.json"), JSON.stringify({ packages: ["npm:@project/pkg"] }));
  154. const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  155. try {
  156. await expect(
  157. main(["list"], {
  158. extensionFactories: [
  159. (pi) => {
  160. pi.on("project_trust", () => ({ trusted: "yes" }));
  161. },
  162. ],
  163. }),
  164. ).resolves.toBeUndefined();
  165. const stdout = logSpy.mock.calls.map(([message]) => String(message)).join("\n");
  166. expect(stdout).toContain("Project packages:");
  167. expect(stdout).toContain("npm:@project/pkg");
  168. expect(stdout).not.toContain("No packages installed.");
  169. expect(process.exitCode).toBeUndefined();
  170. } finally {
  171. logSpy.mockRestore();
  172. }
  173. });
  174. it("lets trust.json override default project trust", async () => {
  175. mkdirSync(join(projectDir, ".pi"), { recursive: true });
  176. writeFileSync(join(agentDir, "settings.json"), JSON.stringify({ defaultProjectTrust: "always" }));
  177. writeFileSync(join(projectDir, ".pi", "settings.json"), JSON.stringify({ packages: ["npm:@project/pkg"] }));
  178. new ProjectTrustStore(agentDir).set(projectDir, false);
  179. const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  180. try {
  181. await expect(main(["list"])).resolves.toBeUndefined();
  182. const stdout = logSpy.mock.calls.map(([message]) => String(message)).join("\n");
  183. expect(stdout).toContain("No packages installed.");
  184. expect(stdout).not.toContain("Project packages:");
  185. expect(process.exitCode).toBeUndefined();
  186. } finally {
  187. logSpy.mockRestore();
  188. }
  189. });
  190. it("blocks local package changes when project is untrusted", async () => {
  191. mkdirSync(join(projectDir, ".pi"), { recursive: true });
  192. const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
  193. try {
  194. await expect(main(["install", "-l", "./local-package"])).resolves.toBeUndefined();
  195. const stderr = errorSpy.mock.calls.map(([message]) => String(message)).join("\n");
  196. expect(stderr).toContain("Project is not trusted. Use --approve to modify local package config.");
  197. expect(process.exitCode).toBe(1);
  198. } finally {
  199. errorSpy.mockRestore();
  200. }
  201. });
  202. it("allows local package install to initialize fresh project settings", async () => {
  203. await main(["install", "-l", packageDir]);
  204. const settingsPath = join(projectDir, ".pi", "settings.json");
  205. const settings = JSON.parse(readFileSync(settingsPath, "utf-8")) as { packages?: string[] };
  206. expect(settings.packages?.length).toBe(1);
  207. const stored = settings.packages?.[0] ?? "";
  208. expect(realpathSync(join(projectDir, ".pi", stored))).toBe(realpathSync(packageDir));
  209. expect(process.exitCode).toBeUndefined();
  210. });
  211. it("shows install subcommand help", async () => {
  212. const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  213. const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
  214. try {
  215. await expect(main(["install", "--help"])).resolves.toBeUndefined();
  216. const stdout = logSpy.mock.calls.map(([message]) => String(message)).join("\n");
  217. expect(stdout).toContain("Usage:");
  218. expect(stdout).toContain("pi install <source> [-l]");
  219. expect(errorSpy).not.toHaveBeenCalled();
  220. expect(process.exitCode).toBeUndefined();
  221. } finally {
  222. logSpy.mockRestore();
  223. errorSpy.mockRestore();
  224. }
  225. });
  226. it("shows a friendly error for unknown install options", async () => {
  227. const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
  228. try {
  229. await expect(main(["install", "--unknown"])).resolves.toBeUndefined();
  230. const stderr = errorSpy.mock.calls.map(([message]) => String(message)).join("\n");
  231. expect(stderr).toContain('Unknown option --unknown for "install".');
  232. expect(stderr).toContain('Use "pi --help" or "pi install <source> [-l] [--approve|--no-approve]".');
  233. expect(process.exitCode).toBe(1);
  234. } finally {
  235. errorSpy.mockRestore();
  236. }
  237. });
  238. it("shows a friendly error for missing install source", async () => {
  239. const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
  240. try {
  241. await expect(main(["install"])).resolves.toBeUndefined();
  242. const stderr = errorSpy.mock.calls.map(([message]) => String(message)).join("\n");
  243. expect(stderr).toContain("Missing install source.");
  244. expect(stderr).toContain("Usage: pi install <source> [-l]");
  245. expect(stderr).not.toContain("at ");
  246. expect(process.exitCode).toBe(1);
  247. } finally {
  248. errorSpy.mockRestore();
  249. }
  250. });
  251. it("uses global npmCommand and current package name for forced self updates without checking the api", async () => {
  252. const globalPrefix = join(tempDir, "global-prefix");
  253. const projectPrefix = join(tempDir, "project-prefix");
  254. const selfPackageDir = join(globalPrefix, "lib", "node_modules", "@earendil-works", "pi-coding-agent");
  255. const fakeNpmPath = join(tempDir, "fake-npm.cjs");
  256. const recordPath = join(tempDir, "self-update.json");
  257. mkdirSync(selfPackageDir, { recursive: true });
  258. mkdirSync(join(projectDir, ".pi"), { recursive: true });
  259. writeFileSync(
  260. fakeNpmPath,
  261. `const fs=require("node:fs"),path=require("node:path"),args=process.argv.slice(2),prefix=args[args.indexOf("--prefix")+1];
  262. if(args.includes("root")) console.log(path.join(prefix,"lib","node_modules"));
  263. else fs.writeFileSync(${JSON.stringify(recordPath)},JSON.stringify(args));
  264. `,
  265. );
  266. writeFileSync(
  267. join(agentDir, "settings.json"),
  268. JSON.stringify({ npmCommand: [originalExecPath, fakeNpmPath, "--prefix", globalPrefix] }, null, 2),
  269. );
  270. writeFileSync(
  271. join(projectDir, ".pi", "settings.json"),
  272. JSON.stringify({ npmCommand: [originalExecPath, fakeNpmPath, "--prefix", projectPrefix] }, null, 2),
  273. );
  274. process.env.PI_PACKAGE_DIR = selfPackageDir;
  275. Object.defineProperty(process, "execPath", {
  276. value: join(selfPackageDir, "dist", "cli.js"),
  277. configurable: true,
  278. });
  279. const fetchMock = vi.fn();
  280. vi.stubGlobal("fetch", fetchMock);
  281. const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  282. const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
  283. try {
  284. await expect(main(["update", "--self", "--force"])).resolves.toBeUndefined();
  285. expect(process.exitCode).toBeUndefined();
  286. expect(errorSpy).not.toHaveBeenCalled();
  287. expect(fetchMock).not.toHaveBeenCalled();
  288. const recordedArgs = JSON.parse(readFileSync(recordPath, "utf-8")) as string[];
  289. expect(recordedArgs).toContain(globalPrefix);
  290. expect(recordedArgs).toContain(PACKAGE_NAME);
  291. expect(recordedArgs).not.toContain(projectPrefix);
  292. } finally {
  293. logSpy.mockRestore();
  294. errorSpy.mockRestore();
  295. }
  296. });
  297. it("uses the current package name when the update check omits packageName", async () => {
  298. const globalPrefix = join(tempDir, "global-prefix");
  299. const selfPackageDir = join(globalPrefix, "lib", "node_modules", "@mariozechner", "pi-coding-agent");
  300. const fakeNpmPath = join(tempDir, "fake-npm.cjs");
  301. const recordPath = join(tempDir, "self-update.json");
  302. mkdirSync(selfPackageDir, { recursive: true });
  303. writeFileSync(
  304. fakeNpmPath,
  305. `const fs=require("node:fs"),path=require("node:path"),args=process.argv.slice(2),prefix=args[args.indexOf("--prefix")+1];
  306. if(args.includes("root")) console.log(path.join(prefix,"lib","node_modules"));
  307. else fs.writeFileSync(${JSON.stringify(recordPath)},JSON.stringify(args));
  308. `,
  309. );
  310. writeFileSync(
  311. join(agentDir, "settings.json"),
  312. JSON.stringify({ npmCommand: [originalExecPath, fakeNpmPath, "--prefix", globalPrefix] }, null, 2),
  313. );
  314. process.env.PI_PACKAGE_DIR = selfPackageDir;
  315. Object.defineProperty(process, "execPath", {
  316. value: join(selfPackageDir, "dist", "cli.js"),
  317. configurable: true,
  318. });
  319. const fetchMock = vi.fn(async () => Response.json({ version: getNewerPatchVersion() }));
  320. vi.stubGlobal("fetch", fetchMock);
  321. const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  322. const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
  323. try {
  324. await expect(main(["update", "--self"])).resolves.toBeUndefined();
  325. expect(process.exitCode).toBeUndefined();
  326. expect(errorSpy).not.toHaveBeenCalled();
  327. expect(fetchMock).toHaveBeenCalledOnce();
  328. const recordedArgs = JSON.parse(readFileSync(recordPath, "utf-8")) as string[];
  329. expect(recordedArgs).toContain(PACKAGE_NAME);
  330. } finally {
  331. logSpy.mockRestore();
  332. errorSpy.mockRestore();
  333. }
  334. });
  335. it("installs the active package name from the update check during self-update", async () => {
  336. const globalPrefix = join(tempDir, "global-prefix");
  337. const selfPackageDir = join(globalPrefix, "lib", "node_modules", "@mariozechner", "pi-coding-agent");
  338. const fakeNpmPath = join(tempDir, "fake-npm.cjs");
  339. const recordPath = join(tempDir, "self-update.json");
  340. mkdirSync(selfPackageDir, { recursive: true });
  341. writeFileSync(
  342. fakeNpmPath,
  343. `const fs=require("node:fs"),path=require("node:path"),args=process.argv.slice(2),prefix=args[args.indexOf("--prefix")+1];
  344. if(args.includes("root")) console.log(path.join(prefix,"lib","node_modules"));
  345. else {
  346. const records=fs.existsSync(${JSON.stringify(recordPath)})?JSON.parse(fs.readFileSync(${JSON.stringify(recordPath)},"utf-8")):[];
  347. records.push(args);
  348. fs.writeFileSync(${JSON.stringify(recordPath)},JSON.stringify(records));
  349. }
  350. `,
  351. );
  352. writeFileSync(
  353. join(agentDir, "settings.json"),
  354. JSON.stringify({ npmCommand: [originalExecPath, fakeNpmPath, "--prefix", globalPrefix] }, null, 2),
  355. );
  356. process.env.PI_PACKAGE_DIR = selfPackageDir;
  357. Object.defineProperty(process, "execPath", {
  358. value: join(selfPackageDir, "dist", "cli.js"),
  359. configurable: true,
  360. });
  361. const activePackageName = PACKAGE_NAME === "@new-scope/pi" ? "@newer-scope/pi" : "@new-scope/pi";
  362. vi.stubGlobal(
  363. "fetch",
  364. vi.fn(async () => Response.json({ packageName: activePackageName, version: "0.73.0" })),
  365. );
  366. const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  367. const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
  368. try {
  369. await expect(main(["update", "--self"])).resolves.toBeUndefined();
  370. expect(process.exitCode).toBeUndefined();
  371. expect(errorSpy).not.toHaveBeenCalled();
  372. const recordedCalls = JSON.parse(readFileSync(recordPath, "utf-8")) as string[][];
  373. expect(recordedCalls).toEqual([
  374. expect.arrayContaining(["uninstall", "-g", PACKAGE_NAME]),
  375. expect.arrayContaining(["install", "-g", activePackageName]),
  376. ]);
  377. } finally {
  378. logSpy.mockRestore();
  379. errorSpy.mockRestore();
  380. }
  381. });
  382. it("fails self-update when renamed npm package installation fails", async () => {
  383. const globalPrefix = join(tempDir, "global-prefix");
  384. const selfPackageDir = join(globalPrefix, "lib", "node_modules", "@mariozechner", "pi-coding-agent");
  385. const fakeNpmPath = join(tempDir, "fake-npm-fail.cjs");
  386. const recordPath = join(tempDir, "self-update-fail.json");
  387. mkdirSync(selfPackageDir, { recursive: true });
  388. writeFileSync(
  389. fakeNpmPath,
  390. `const fs=require("node:fs"),path=require("node:path"),args=process.argv.slice(2),prefix=args[args.indexOf("--prefix")+1];
  391. if(args.includes("root")) {
  392. console.log(path.join(prefix,"lib","node_modules"));
  393. process.exit(0);
  394. }
  395. const records=fs.existsSync(${JSON.stringify(recordPath)})?JSON.parse(fs.readFileSync(${JSON.stringify(recordPath)},"utf-8")):[];
  396. records.push(args);
  397. fs.writeFileSync(${JSON.stringify(recordPath)},JSON.stringify(records));
  398. if(args.includes("install")) process.exit(23);
  399. `,
  400. );
  401. writeFileSync(
  402. join(agentDir, "settings.json"),
  403. JSON.stringify({ npmCommand: [originalExecPath, fakeNpmPath, "--prefix", globalPrefix] }, null, 2),
  404. );
  405. process.env.PI_PACKAGE_DIR = selfPackageDir;
  406. Object.defineProperty(process, "execPath", {
  407. value: join(selfPackageDir, "dist", "cli.js"),
  408. configurable: true,
  409. });
  410. const activePackageName = PACKAGE_NAME === "@new-scope/pi" ? "@newer-scope/pi" : "@new-scope/pi";
  411. vi.stubGlobal(
  412. "fetch",
  413. vi.fn(async () => Response.json({ packageName: activePackageName, version: "0.73.0" })),
  414. );
  415. const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  416. const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
  417. try {
  418. await expect(main(["update", "--self"])).resolves.toBeUndefined();
  419. expect(process.exitCode).toBe(1);
  420. const stdout = logSpy.mock.calls.map(([message]) => String(message)).join("\n");
  421. const stderr = errorSpy.mock.calls.map(([message]) => String(message)).join("\n");
  422. expect(stdout).not.toContain(`Updated pi`);
  423. expect(stderr).toContain("exited with code 23");
  424. const recordedCalls = JSON.parse(readFileSync(recordPath, "utf-8")) as string[][];
  425. expect(recordedCalls).toEqual([
  426. expect.arrayContaining(["uninstall", "-g", PACKAGE_NAME]),
  427. expect.arrayContaining(["install", "-g", activePackageName]),
  428. ]);
  429. } finally {
  430. logSpy.mockRestore();
  431. errorSpy.mockRestore();
  432. }
  433. });
  434. it("suggests the configured source when update input omits the npm prefix", async () => {
  435. const settingsPath = join(agentDir, "settings.json");
  436. writeFileSync(settingsPath, JSON.stringify({ packages: ["npm:pi-formatter"] }, null, 2));
  437. const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
  438. const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  439. try {
  440. await expect(main(["update", "pi-formatter"])).resolves.toBeUndefined();
  441. const stderr = errorSpy.mock.calls.map(([message]) => String(message)).join("\n");
  442. const stdout = logSpy.mock.calls.map(([message]) => String(message)).join("\n");
  443. expect(stderr).toContain("Did you mean npm:pi-formatter?");
  444. expect(stdout).not.toContain("Updated pi-formatter");
  445. expect(process.exitCode).toBe(1);
  446. const settings = JSON.parse(readFileSync(settingsPath, "utf-8")) as { packages?: string[] };
  447. expect(settings.packages).toContain("npm:pi-formatter");
  448. } finally {
  449. errorSpy.mockRestore();
  450. logSpy.mockRestore();
  451. }
  452. });
  453. });