Context7 Platform -- Up-to-date docs for AI agents
CTX7-1544: add CLI update notifications and upgrade command (#2477)
Fahreddin Özcan4feee1521ea5
diff --git a/.changeset/fair-foxes-care.md b/.changeset/fair-foxes-care.mdnew file mode 100644index 00000000..130c5229--- /dev/null+++ b/.changeset/fair-foxes-care.md@@ -0,0 +1,5 @@+---+"ctx7": patch+---++Add CLI update notifications and a new `ctx7 upgrade` command. The CLI now checks for newer versions with cached state, shows a non-blocking notice before interactive commands, and provides safer upgrade guidance across npm, pnpm, bun, and ephemeral runner setups.diff --git a/packages/cli/src/__tests__/update-check.test.ts b/packages/cli/src/__tests__/update-check.test.tsnew file mode 100644index 00000000..8c471681--- /dev/null+++ b/packages/cli/src/__tests__/update-check.test.ts@@ -0,0 +1,224 @@+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { mkdir, readFile, rm } from "fs/promises";+import { join } from "path";+import { tmpdir } from "os";++import {+ checkForUpdates,+ compareVersions,+ detectInstallMethod,+ getUpgradePlan,+ markUpdateNotificationShown,+ shouldShowUpdateNotification,+ shouldSkipUpdateNotifier,+} from "../utils/update-check.js";++let tempDir: string;+let stateFile: string;++beforeEach(async () => {+ tempDir = join(tmpdir(), `ctx7-update-${Date.now()}`);+ stateFile = join(tempDir, "cli-state.json");+ await mkdir(tempDir, { recursive: true });+ vi.stubGlobal(+ "fetch",+ vi.fn(() => {+ throw new Error("fetch not mocked");+ })+ );+});++afterEach(async () => {+ await rm(tempDir, { recursive: true, force: true });+ vi.unstubAllGlobals();+ vi.doUnmock("os");+ vi.resetModules();+ vi.restoreAllMocks();+});++describe("compareVersions", () => {+ test("orders semantic versions correctly", () => {+ expect(compareVersions("0.3.14", "0.3.13")).toBeGreaterThan(0);+ expect(compareVersions("0.3.13", "0.3.13")).toBe(0);+ expect(compareVersions("0.3.13", "0.3.14")).toBeLessThan(0);+ });+});++describe("detectInstallMethod", () => {+ test("detects npx and pnpm dlx", () => {+ expect(+ detectInstallMethod({+ npm_execpath: "/usr/local/lib/node_modules/npm/bin/npm-cli.js",+ npm_command: "exec",+ })+ ).toBe("npx");++ expect(+ detectInstallMethod({+ npm_execpath: "/Users/test/Library/pnpm/pnpm.cjs",+ npm_command: "dlx",+ })+ ).toBe("pnpm-dlx");+ });++ test("detects npm, pnpm, bun, and bunx style shells", () => {+ expect(+ detectInstallMethod({+ npm_execpath: "/usr/local/lib/node_modules/npm/bin/npm-cli.js",+ npm_command: "install",+ })+ ).toBe("npm-global");++ expect(+ detectInstallMethod({+ npm_execpath: "/Users/test/Library/pnpm/pnpm.cjs",+ npm_command: "add",+ })+ ).toBe("pnpm-global");++ expect(+ detectInstallMethod({+ npm_execpath: "/Users/test/.bun/bin/bun",+ npm_command: "add",+ })+ ).toBe("bun-global");++ expect(+ detectInstallMethod({+ npm_execpath: "/Users/test/.bun/bin/bun",+ npm_command: "x",+ })+ ).toBe("bunx");+ });++ test("falls back to npm-global for npm user agents", () => {+ expect(detectInstallMethod({ npm_config_user_agent: "npm/10.0.0 node/v22.0.0" })).toBe(+ "npm-global"+ );+ });+});++describe("getUpgradePlan", () => {+ test("returns explicit runner commands for ephemeral installs", () => {+ expect(getUpgradePlan("npx").displayCommand).toBe("npx ctx7@latest <command>");+ expect(getUpgradePlan("pnpm-dlx").displayCommand).toBe("pnpm dlx ctx7@latest <command>");+ });++ test("does not auto-run upgrade plans for unknown installs", () => {+ expect(getUpgradePlan("unknown").canRun).toBe(false);+ });+});++describe("checkForUpdates", () => {+ test("fetches and caches the latest version", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ version: "9.9.9" }),+ })+ );++ const info = await checkForUpdates({+ force: true,+ stateFile,+ now: 123456,+ });++ expect(info?.latestVersion).toBe("9.9.9");+ expect(info?.updateAvailable).toBe(true);+ });++ test("uses cached latest version when the cache is fresh", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ version: "9.9.9" }),+ })+ );++ await checkForUpdates({ force: true, stateFile, now: 1000 });++ const fetchMock = vi.mocked(fetch);+ fetchMock.mockClear();++ const info = await checkForUpdates({+ stateFile,+ now: 2000,+ cacheTtlMs: 10_000,+ });++ expect(info?.latestVersion).toBe("9.9.9");+ expect(fetchMock).not.toHaveBeenCalled();+ });+});++describe("default cli-state persistence", () => {+ test("writes updater state under ~/.context7/cli-state.json when using the default path", async () => {+ const fakeHome = join(tempDir, "fake-home");+ await mkdir(fakeHome, { recursive: true });++ vi.resetModules();+ vi.doMock("os", async () => {+ const actual = await vi.importActual<typeof import("os")>("os");+ return { ...actual, homedir: () => fakeHome };+ });++ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ version: "9.9.9" }),+ })+ );++ const updateCheck = await import("../utils/update-check.js");++ await updateCheck.checkForUpdates({ force: true, now: 1000 });+ await updateCheck.markUpdateNotificationShown("9.9.9", { now: 2000 });++ const persisted = JSON.parse(+ await readFile(join(fakeHome, ".context7", "cli-state.json"), "utf-8")+ ) as {+ latestVersion?: string;+ lastCheckedAt?: number;+ notifiedVersion?: string;+ lastNotifiedAt?: number;+ };++ expect(persisted).toEqual({+ latestVersion: "9.9.9",+ lastCheckedAt: 1000,+ notifiedVersion: "9.9.9",+ lastNotifiedAt: 2000,+ });+ });+});++describe("update notifications", () => {+ test("respects notification cooldown per latest version", async () => {+ const info = {+ currentVersion: "0.3.13",+ latestVersion: "9.9.9",+ updateAvailable: true,+ installMethod: "npm-global" as const,+ upgradePlan: getUpgradePlan("npm-global"),+ };++ expect(await shouldShowUpdateNotification(info, { stateFile, now: 1000 })).toBe(true);++ await markUpdateNotificationShown("9.9.9", { stateFile, now: 1000 });++ expect(await shouldShowUpdateNotification(info, { stateFile, now: 2000 })).toBe(false);+ expect(+ await shouldShowUpdateNotification(info, { stateFile, now: 1000 + 25 * 60 * 60 * 1000 })+ ).toBe(true);+ });++ test("skips notifier for json and version argv", () => {+ expect(shouldSkipUpdateNotifier(["node", "ctx7", "library", "react", "--json"])).toBe(true);+ expect(shouldSkipUpdateNotifier(["node", "ctx7", "--version"])).toBe(true);+ expect(shouldSkipUpdateNotifier(["node", "ctx7", "skills", "list"])).toBe(false);+ });+});diff --git a/packages/cli/src/__tests__/upgrade-command.test.ts b/packages/cli/src/__tests__/upgrade-command.test.tsnew file mode 100644index 00000000..62c17cc3--- /dev/null+++ b/packages/cli/src/__tests__/upgrade-command.test.ts@@ -0,0 +1,319 @@+import { beforeEach, describe, expect, test, vi } from "vitest";+import { Command } from "commander";++const trackEvent = vi.fn();+const checkForUpdates = vi.fn();+const getUpgradePlan = vi.fn();+const markUpdateNotificationShown = vi.fn();+const shouldShowUpdateNotification = vi.fn();+const shouldSkipUpdateNotifier = vi.fn();+const confirm = vi.fn();+const spawn = vi.fn();++vi.mock("../utils/tracking.js", () => ({+ trackEvent: (...args: unknown[]) => trackEvent(...args),+}));++vi.mock("../utils/update-check.js", () => ({+ checkForUpdates: (...args: unknown[]) => checkForUpdates(...args),+ getUpgradePlan: (...args: unknown[]) => getUpgradePlan(...args),+ markUpdateNotificationShown: (...args: unknown[]) => markUpdateNotificationShown(...args),+ shouldShowUpdateNotification: (...args: unknown[]) => shouldShowUpdateNotification(...args),+ shouldSkipUpdateNotifier: (...args: unknown[]) => shouldSkipUpdateNotifier(...args),+}));++vi.mock("@inquirer/prompts", () => ({+ confirm: (...args: unknown[]) => confirm(...args),+}));++vi.mock("child_process", () => ({+ spawn: (...args: unknown[]) => spawn(...args),+}));++import { maybeShowUpgradeNotice, registerUpgradeCommand } from "../commands/upgrade.js";++let logOutput: string[];+const ANSI_PATTERN = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;++function stripAnsi(text: string): string {+ return text.replace(ANSI_PATTERN, "");+}++async function runCommand(...args: string[]): Promise<void> {+ const program = new Command();+ program.exitOverride();+ registerUpgradeCommand(program);+ await program.parseAsync(["node", "test", ...args]);+}++beforeEach(() => {+ vi.clearAllMocks();+ logOutput = [];+ shouldShowUpdateNotification.mockResolvedValue(true);+ shouldSkipUpdateNotifier.mockReturnValue(false);+ vi.spyOn(console, "log").mockImplementation((...args: unknown[]) => {+ logOutput.push(args.join(" "));+ });+ spawn.mockReturnValue({+ on: (event: string, handler: (value?: number) => void) => {+ if (event === "close") handler(0);+ return undefined;+ },+ });+});++function plainLogOutput(): string[] {+ return logOutput.map(stripAnsi);+}++describe("upgrade command", () => {+ test("reports when ctx7 is already up to date", async () => {+ checkForUpdates.mockResolvedValue({+ currentVersion: "0.3.13",+ latestVersion: "0.3.13",+ updateAvailable: false,+ installMethod: "npm-global",+ upgradePlan: {+ displayCommand: "npm install -g ctx7@latest",+ },+ });++ await runCommand("upgrade");++ expect(plainLogOutput().some((line) => line.includes("ctx7 is up to date"))).toBe(true);+ expect(trackEvent).toHaveBeenCalledWith("command", { name: "upgrade" });+ });++ test("prints upgrade instructions in check mode", async () => {+ checkForUpdates.mockResolvedValue({+ currentVersion: "0.3.13",+ latestVersion: "0.3.99",+ updateAvailable: true,+ installMethod: "npm-global",+ upgradePlan: {+ displayCommand: "npm install -g ctx7@latest",+ canRun: true,+ needsExplicitVersion: false,+ },+ });++ await runCommand("upgrade", "--check");++ expect(plainLogOutput().some((line) => line.includes("Update available"))).toBe(true);+ expect(plainLogOutput().some((line) => line.includes("npm install -g ctx7@latest"))).toBe(true);+ expect(spawn).not.toHaveBeenCalled();+ });++ test("explains ephemeral runners instead of trying to self-upgrade", async () => {+ checkForUpdates.mockResolvedValue({+ currentVersion: "0.3.13",+ latestVersion: "0.3.99",+ updateAvailable: true,+ installMethod: "npx",+ upgradePlan: {+ displayCommand: "npx ctx7@latest <command>",+ canRun: false,+ needsExplicitVersion: true,+ },+ });++ await runCommand("upgrade");++ expect(plainLogOutput().some((line) => line.includes("ephemeral runner"))).toBe(true);+ expect(plainLogOutput().some((line) => line.includes("npx ctx7@latest <command>"))).toBe(true);+ expect(spawn).not.toHaveBeenCalled();+ });++ test("runs the upgrade command with --yes when possible", async () => {+ checkForUpdates.mockResolvedValue({+ currentVersion: "0.3.13",+ latestVersion: "0.3.99",+ updateAvailable: true,+ installMethod: "npm-global",+ upgradePlan: {+ command: "npm",+ args: ["install", "-g", "ctx7@latest"],+ displayCommand: "npm install -g ctx7@latest",+ canRun: true,+ needsExplicitVersion: false,+ },+ });++ await runCommand("upgrade", "--yes");++ expect(spawn).toHaveBeenCalledWith(+ "npm",+ ["install", "-g", "ctx7@latest"],+ expect.objectContaining({ stdio: "inherit" })+ );+ });++ test("falls back to getUpgradePlan when update check fails", async () => {+ checkForUpdates.mockResolvedValue(null);+ getUpgradePlan.mockReturnValue({+ displayCommand: "npm install -g ctx7@latest",+ });++ await runCommand("upgrade", "--check");++ expect(plainLogOutput().some((line) => line.includes("Couldn't check for updates"))).toBe(true);+ expect(plainLogOutput().some((line) => line.includes("npm install -g ctx7@latest"))).toBe(true);+ });++ test("shows retry guidance when the upgrade command fails", async () => {+ spawn.mockReturnValue({+ on: (event: string, handler: (value?: number) => void) => {+ if (event === "close") handler(243);+ return undefined;+ },+ });+ checkForUpdates.mockResolvedValue({+ currentVersion: "0.3.13",+ latestVersion: "0.3.99",+ updateAvailable: true,+ installMethod: "npm-global",+ upgradePlan: {+ command: "npm",+ args: ["install", "-g", "ctx7@latest"],+ displayCommand: "npm install -g ctx7@latest",+ canRun: true,+ needsExplicitVersion: false,+ installMethod: "npm-global",+ },+ });++ await runCommand("upgrade", "--yes");++ expect(+ plainLogOutput().some((line) => line.includes("Upgrade command exited with code 243"))+ ).toBe(true);+ expect(plainLogOutput().some((line) => line.includes("Try rerunning:"))).toBe(true);+ expect(plainLogOutput().some((line) => line.includes("permissions"))).toBe(true);+ });++ test("shows permissions guidance when install method is unknown but command is global npm", async () => {+ spawn.mockReturnValue({+ on: (event: string, handler: (value?: number) => void) => {+ if (event === "close") handler(243);+ return undefined;+ },+ });+ checkForUpdates.mockResolvedValue({+ currentVersion: "0.3.13",+ latestVersion: "0.3.99",+ updateAvailable: true,+ installMethod: "unknown",+ upgradePlan: {+ command: "npm",+ args: ["install", "-g", "ctx7@latest"],+ displayCommand: "npm install -g ctx7@latest",+ canRun: false,+ needsExplicitVersion: false,+ installMethod: "unknown",+ },+ });++ await runCommand("upgrade", "--yes");++ expect(spawn).not.toHaveBeenCalled();+ expect(plainLogOutput().some((line) => line.includes("Run npm install -g ctx7@latest"))).toBe(+ true+ );+ });+});++describe("pre-command upgrade notice", () => {+ test("shows a non-blocking notice for upgradeable installs", async () => {+ checkForUpdates.mockResolvedValue({+ currentVersion: "0.3.11",+ latestVersion: "0.3.13",+ updateAvailable: true,+ upgradePlan: {+ command: "npm",+ args: ["install", "-g", "ctx7@latest"],+ displayCommand: "npm install -g ctx7@latest",+ canRun: true,+ needsExplicitVersion: false,+ },+ });+ await maybeShowUpgradeNotice({+ actionName: "library",+ argv: ["node", "ctx7", "library", "react"],+ isInteractive: true,+ });++ expect(plainLogOutput().some((line) => line.includes("Update available:"))).toBe(true);+ expect(plainLogOutput().some((line) => line.includes("Run ctx7 upgrade to update now"))).toBe(+ true+ );+ expect(plainLogOutput().some((line) => line.includes("npm install -g ctx7@latest"))).toBe(true);+ expect(confirm).not.toHaveBeenCalled();+ expect(spawn).not.toHaveBeenCalled();+ expect(markUpdateNotificationShown).toHaveBeenCalledWith("0.3.13");+ });++ test("shows guidance-only notice for unknown installs", async () => {+ checkForUpdates.mockResolvedValue({+ currentVersion: "0.3.11",+ latestVersion: "0.3.13",+ updateAvailable: true,+ upgradePlan: {+ command: "npm",+ args: ["install", "-g", "ctx7@latest"],+ displayCommand: "npm install -g ctx7@latest",+ canRun: false,+ needsExplicitVersion: false,+ },+ });++ await maybeShowUpgradeNotice({+ actionName: "library",+ argv: ["node", "ctx7", "library", "react"],+ isInteractive: true,+ });++ expect(+ plainLogOutput().some((line) => line.includes("Run ctx7 upgrade for update steps"))+ ).toBe(true);+ expect(plainLogOutput().some((line) => line.includes("npm install -g ctx7@latest"))).toBe(true);+ expect(spawn).not.toHaveBeenCalled();+ expect(markUpdateNotificationShown).toHaveBeenCalledWith("0.3.13");+ });++ test("shows runner-specific guidance for ephemeral installs", async () => {+ checkForUpdates.mockResolvedValue({+ currentVersion: "0.3.11",+ latestVersion: "0.3.13",+ updateAvailable: true,+ upgradePlan: {+ displayCommand: "npx ctx7@latest <command>",+ canRun: false,+ needsExplicitVersion: true,+ },+ });++ await maybeShowUpgradeNotice({+ actionName: "library",+ argv: ["node", "ctx7", "library", "react"],+ isInteractive: true,+ });++ expect(plainLogOutput().some((line) => line.includes("Use npx ctx7@latest <command>"))).toBe(+ true+ );+ expect(plainLogOutput().some((line) => line.includes("ctx7 upgrade"))).toBe(false);+ expect(confirm).not.toHaveBeenCalled();+ expect(spawn).not.toHaveBeenCalled();+ expect(markUpdateNotificationShown).toHaveBeenCalledWith("0.3.13");+ });++ test("skips notice for upgrade command", async () => {+ await maybeShowUpgradeNotice({+ actionName: "upgrade",+ argv: ["node", "ctx7", "upgrade"],+ isInteractive: true,+ });++ expect(checkForUpdates).not.toHaveBeenCalled();+ });+});diff --git a/packages/cli/src/commands/upgrade.ts b/packages/cli/src/commands/upgrade.tsnew file mode 100644index 00000000..b0b870c9--- /dev/null+++ b/packages/cli/src/commands/upgrade.ts@@ -0,0 +1,190 @@+import { confirm } from "@inquirer/prompts";+import { spawn } from "child_process";+import { Command } from "commander";+import pc from "picocolors";+import { VERSION } from "../constants.js";+import { log } from "../utils/logger.js";+import { trackEvent } from "../utils/tracking.js";+import {+ checkForUpdates,+ getUpgradePlan,+ markUpdateNotificationShown,+ shouldShowUpdateNotification,+ shouldSkipUpdateNotifier,+ type UpgradePlan,+} from "../utils/update-check.js";++interface UpgradeOptions {+ yes?: boolean;+ check?: boolean;+}++export function registerUpgradeCommand(program: Command): void {+ program+ .command("upgrade")+ .description("Check for a newer ctx7 version and upgrade when possible")+ .option("-y, --yes", "Run the suggested upgrade command without prompting")+ .option("--check", "Only check for updates without running the upgrade command")+ .action(async (options: UpgradeOptions) => {+ await upgradeCommand(options);+ });+}++function runCommand(command: string, args: string[]): Promise<number | null> {+ return new Promise((resolve, reject) => {+ const child = spawn(command, args, {+ stdio: "inherit",+ shell: process.platform === "win32",+ });++ child.on("error", reject);+ child.on("close", (code) => resolve(code));+ });+}++export async function runUpgradePlan(plan: UpgradePlan): Promise<number | null> {+ return runCommand(plan.command, plan.args);+}++function showUpgradeFailureHelp(plan: UpgradePlan): void {+ log.info(`Try rerunning: ${pc.cyan(plan.displayCommand)}`);++ const isGlobalNpmInstall =+ (plan.installMethod === "npm-global" || plan.installMethod === "unknown") &&+ plan.command === "npm" &&+ plan.args.includes("-g");+ const isGlobalAltInstall =+ (plan.installMethod === "pnpm-global" || plan.installMethod === "bun-global") &&+ plan.args.includes("-g");++ if (isGlobalNpmInstall) {+ log.dim(+ "If this failed due to permissions, your global npm directory may require elevated privileges on this machine."+ );+ } else if (isGlobalAltInstall) {+ log.dim(+ "If this failed due to permissions, your global package manager install location may require additional privileges on this machine."+ );+ }+}++export async function maybeShowUpgradeNotice(+ options: {+ actionName?: string;+ argv?: string[];+ isInteractive?: boolean;+ } = {}+): Promise<void> {+ const actionName = options.actionName ?? "";+ const argv = options.argv ?? process.argv;+ const isInteractive =+ options.isInteractive ?? Boolean(process.stdout.isTTY && process.stdin.isTTY);++ if (!isInteractive || shouldSkipUpdateNotifier(argv) || actionName === "upgrade") {+ return;+ }++ const info = await checkForUpdates();+ if (!info || !info.updateAvailable || !(await shouldShowUpdateNotification(info))) {+ return;+ }++ log.blank();+ if (info.upgradePlan.needsExplicitVersion) {+ log.box([+ `${pc.white(pc.bold("Update available:"))} ${pc.green(pc.bold(`v${info.currentVersion}`))} ${pc.dim("->")} ${pc.green(pc.bold(`v${info.latestVersion}`))}`,+ `${pc.white("Use")} ${pc.yellow(pc.bold(info.upgradePlan.displayCommand))} ${pc.white("to run the latest version")}`,+ ]);+ await markUpdateNotificationShown(info.latestVersion);+ log.blank();+ return;+ }++ if (!info.upgradePlan.canRun) {+ log.box([+ `${pc.white(pc.bold("Update available:"))} ${pc.green(pc.bold(`v${info.currentVersion}`))} ${pc.dim("->")} ${pc.green(pc.bold(`v${info.latestVersion}`))}`,+ `${pc.white("Run")} ${pc.yellow(pc.bold("ctx7 upgrade"))} ${pc.white("for update steps")}`,+ `${pc.white("Or run")} ${pc.yellow(info.upgradePlan.displayCommand)}`,+ ]);+ await markUpdateNotificationShown(info.latestVersion);+ log.blank();+ return;+ }++ log.box([+ `${pc.white(pc.bold("Update available:"))} ${pc.green(pc.bold(`v${info.currentVersion}`))} ${pc.dim("->")} ${pc.green(pc.bold(`v${info.latestVersion}`))}`,+ `${pc.white("Run")} ${pc.yellow(pc.bold("ctx7 upgrade"))} ${pc.white("to update now")}`,+ `${pc.white("Or run")} ${pc.yellow(info.upgradePlan.displayCommand)}`,+ ]);+ await markUpdateNotificationShown(info.latestVersion);+ log.blank();+}++async function upgradeCommand(options: UpgradeOptions): Promise<void> {+ trackEvent("command", { name: "upgrade" });++ const info = await checkForUpdates({ force: true });+ const plan = info?.upgradePlan ?? getUpgradePlan();++ if (!info) {+ log.warn("Couldn't check for updates right now.");+ log.info(`Try again later or run ${pc.cyan(plan.displayCommand)} manually.`);+ return;+ }++ if (!info.updateAvailable) {+ log.success(`ctx7 is up to date (${pc.bold(`v${VERSION}`)})`);+ return;+ }++ log.blank();+ log.info(+ `Update available: ${pc.bold(`v${info.currentVersion}`)} ${pc.dim("->")} ${pc.bold(`v${info.latestVersion}`)}`+ );++ if (plan.needsExplicitVersion) {+ log.info(`You're using an ephemeral runner (${plan.installMethod}).`);+ log.info(`Use ${pc.cyan(plan.displayCommand)} to run the latest version immediately.`);+ log.info(`Or install globally with ${pc.cyan("npm install -g ctx7@latest")}.`);+ return;+ }++ if (!plan.canRun) {+ log.info(`Run ${pc.cyan(plan.displayCommand)} to update your installed version.`);+ return;+ }++ log.info(`Upgrade command: ${pc.cyan(plan.displayCommand)}`);++ if (options.check) {+ return;+ }++ let shouldRun = options.yes ?? false;+ if (!shouldRun && process.stdout.isTTY) {+ shouldRun = await confirm({+ message: `Run ${plan.displayCommand} now?`,+ default: true,+ });+ }++ if (!shouldRun) {+ log.dim("Upgrade skipped.");+ return;+ }++ log.blank();+ const exitCode = await runUpgradePlan(plan);++ if (exitCode === 0) {+ log.blank();+ log.success("Upgrade complete.");+ log.info(`Run ${pc.cyan("ctx7 --version")} to verify the installed version.`);+ return;+ }++ log.blank();+ log.error(`Upgrade command exited with code ${exitCode ?? "unknown"}.`);+ showUpgradeFailureHelp(plan);+ process.exitCode = 1;+}diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex 905999a3..dffaafa7 100644--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -5,6 +5,7 @@ import { registerSkillCommands, registerSkillAliases } from "./commands/skill.jsimport { registerAuthCommands, setAuthBaseUrl } from "./commands/auth.js";import { registerSetupCommand } from "./commands/setup.js";import { registerDocsCommands } from "./commands/docs.js";+import { maybeShowUpgradeNotice, registerUpgradeCommand } from "./commands/upgrade.js";import { setBaseUrl } from "./utils/api.js";import { VERSION } from "./constants.js";@@ -27,6 +28,12 @@ programsetAuthBaseUrl(opts.baseUrl);}})+ .hook("preAction", async (_thisCommand, actionCommand) => {+ await maybeShowUpgradeNotice({+ actionName: actionCommand.name(),+ argv: process.argv,+ });+ }).addHelpText("after",`@@ -60,6 +67,7 @@ registerSkillAliases(program);registerAuthCommands(program);registerSetupCommand(program);registerDocsCommands(program);+registerUpgradeCommand(program);program.action(() => {console.log("");@@ -78,4 +86,4 @@ program.action(() => {console.log("");});-program.parse();+await program.parseAsync();diff --git a/packages/cli/src/utils/logger.ts b/packages/cli/src/utils/logger.tsindex 922b7eb5..6b67eca4 100644--- a/packages/cli/src/utils/logger.ts+++ b/packages/cli/src/utils/logger.ts@@ -1,5 +1,28 @@import pc from "picocolors";+const ANSI_PATTERN = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;++function visibleLength(text: string): number {+ return text.replace(ANSI_PATTERN, "").length;+}++function padVisible(text: string, width: number): string {+ const padding = Math.max(0, width - visibleLength(text));+ return text + " ".repeat(padding);+}++export function box(lines: string[], color: (message: string) => string = pc.green): void {+ const contentWidth = Math.max(...lines.map((line) => visibleLength(line)), 0);+ const top = color(`┌${"─".repeat(contentWidth + 2)}┐`);+ const bottom = color(`└${"─".repeat(contentWidth + 2)}┘`);++ console.log(top);+ for (const line of lines) {+ console.log(color("│ ") + padVisible(line, contentWidth) + color(" │"));+ }+ console.log(bottom);+}+export const log = {info: (message: string) => console.log(pc.cyan(message)),success: (message: string) => console.log(pc.green(`✔ ${message}`)),@@ -10,4 +33,5 @@ export const log = {itemAdd: (message: string) => console.log(` ${pc.green("+")} ${message}`),plain: (message: string) => console.log(message),blank: () => console.log(""),+ box,};diff --git a/packages/cli/src/utils/update-check.ts b/packages/cli/src/utils/update-check.tsnew file mode 100644index 00000000..f4ce927b--- /dev/null+++ b/packages/cli/src/utils/update-check.ts@@ -0,0 +1,279 @@+import { homedir } from "os";+import { dirname, join } from "path";+import { mkdir, readFile, writeFile } from "fs/promises";+import { NAME, VERSION } from "../constants.js";++const DEFAULT_CACHE_TTL_MS = 24 * 60 * 60 * 1000;+const UPDATE_STATE_FILE = join(homedir(), ".context7", "cli-state.json");++export type InstallMethod =+ | "npm-global"+ | "pnpm-global"+ | "bun-global"+ | "npx"+ | "pnpm-dlx"+ | "bunx"+ | "unknown";++interface UpdateState {+ latestVersion?: string;+ lastCheckedAt?: number;+ notifiedVersion?: string;+ lastNotifiedAt?: number;+}++export interface UpgradePlan {+ installMethod: InstallMethod;+ command: string;+ args: string[];+ displayCommand: string;+ canRun: boolean;+ needsExplicitVersion: boolean;+}++export interface UpdateInfo {+ currentVersion: string;+ latestVersion: string;+ updateAvailable: boolean;+ installMethod: InstallMethod;+ upgradePlan: UpgradePlan;+}++interface CheckForUpdatesOptions {+ force?: boolean;+ now?: number;+ cacheTtlMs?: number;+ stateFile?: string;+}++function getStateFilePath(stateFile?: string): string {+ return stateFile ?? UPDATE_STATE_FILE;+}++async function readUpdateState(stateFile?: string): Promise<UpdateState> {+ try {+ const raw = await readFile(getStateFilePath(stateFile), "utf-8");+ return JSON.parse(raw) as UpdateState;+ } catch {+ return {};+ }+}++async function writeUpdateState(state: UpdateState, stateFile?: string): Promise<void> {+ const path = getStateFilePath(stateFile);+ await mkdir(dirname(path), { recursive: true });+ await writeFile(path, JSON.stringify(state, null, 2) + "\n", "utf-8");+}++export function compareVersions(a: string, b: string): number {+ const normalize = (version: string): number[] =>+ version+ .split("-", 1)[0]+ .split(".")+ .map((part) => Number.parseInt(part, 10) || 0);++ const left = normalize(a);+ const right = normalize(b);+ const max = Math.max(left.length, right.length);++ for (let i = 0; i < max; i++) {+ const diff = (left[i] ?? 0) - (right[i] ?? 0);+ if (diff !== 0) return diff;+ }++ return 0;+}++export function detectInstallMethod(env: NodeJS.ProcessEnv = process.env): InstallMethod {+ const execPath = env.npm_execpath?.toLowerCase() ?? "";+ const npmCommand = env.npm_command?.toLowerCase() ?? "";+ const userAgent = env.npm_config_user_agent?.toLowerCase() ?? "";++ if (execPath.includes("pnpm") && npmCommand === "dlx") return "pnpm-dlx";+ if (execPath.includes("pnpm")) return "pnpm-global";+ if (execPath.includes("bun") && npmCommand === "x") return "bunx";+ if (execPath.includes("bun")) return "bun-global";+ if (execPath.includes("npm") && npmCommand === "exec") return "npx";+ if (execPath.includes("npm")) return "npm-global";++ if (userAgent.startsWith("pnpm/")) return "pnpm-global";+ if (userAgent.startsWith("bun/")) return "bun-global";+ if (userAgent.startsWith("npm/")) return "npm-global";++ return "unknown";+}++export function getUpgradePlan(+ installMethod = detectInstallMethod(),+ packageName = NAME+): UpgradePlan {+ switch (installMethod) {+ case "pnpm-global":+ return {+ installMethod,+ command: "pnpm",+ args: ["add", "-g", `${packageName}@latest`],+ displayCommand: `pnpm add -g ${packageName}@latest`,+ canRun: true,+ needsExplicitVersion: false,+ };+ case "bun-global":+ return {+ installMethod,+ command: "bun",+ args: ["add", "-g", `${packageName}@latest`],+ displayCommand: `bun add -g ${packageName}@latest`,+ canRun: true,+ needsExplicitVersion: false,+ };+ case "npx":+ return {+ installMethod,+ command: "npx",+ args: [`${packageName}@latest`],+ displayCommand: `npx ${packageName}@latest <command>`,+ canRun: false,+ needsExplicitVersion: true,+ };+ case "pnpm-dlx":+ return {+ installMethod,+ command: "pnpm",+ args: ["dlx", `${packageName}@latest`],+ displayCommand: `pnpm dlx ${packageName}@latest <command>`,+ canRun: false,+ needsExplicitVersion: true,+ };+ case "bunx":+ return {+ installMethod,+ command: "bunx",+ args: [`${packageName}@latest`],+ displayCommand: `bunx ${packageName}@latest <command>`,+ canRun: false,+ needsExplicitVersion: true,+ };+ case "unknown":+ return {+ installMethod,+ command: "npm",+ args: ["install", "-g", `${packageName}@latest`],+ displayCommand: `npm install -g ${packageName}@latest`,+ canRun: false,+ needsExplicitVersion: false,+ };+ case "npm-global":+ default:+ return {+ installMethod: "npm-global",+ command: "npm",+ args: ["install", "-g", `${packageName}@latest`],+ displayCommand: `npm install -g ${packageName}@latest`,+ canRun: true,+ needsExplicitVersion: false,+ };+ }+}++async function fetchLatestVersion(packageName = NAME): Promise<string | null> {+ try {+ const response = await fetch(+ `https://registry.npmjs.org/${encodeURIComponent(packageName)}/latest`,+ {+ headers: { Accept: "application/json" },+ signal: AbortSignal.timeout(1500),+ }+ );++ if (!response.ok) return null;++ const data = (await response.json()) as { version?: unknown };+ return typeof data.version === "string" ? data.version : null;+ } catch {+ return null;+ }+}++export async function checkForUpdates(+ options: CheckForUpdatesOptions = {}+): Promise<UpdateInfo | null> {+ const now = options.now ?? Date.now();+ const cacheTtlMs = options.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;+ const stateFile = options.stateFile;+ const state = await readUpdateState(stateFile);+ const isStale =+ options.force ||+ !state.lastCheckedAt ||+ now - state.lastCheckedAt >= cacheTtlMs ||+ !state.latestVersion;++ let latestVersion = state.latestVersion ?? null;++ if (isStale) {+ const fetchedVersion = await fetchLatestVersion();+ if (fetchedVersion) {+ latestVersion = fetchedVersion;+ await writeUpdateState(+ {+ ...state,+ latestVersion: fetchedVersion,+ lastCheckedAt: now,+ },+ stateFile+ );+ }+ }++ if (!latestVersion) return null;++ const installMethod = detectInstallMethod();++ return {+ currentVersion: VERSION,+ latestVersion,+ updateAvailable: compareVersions(latestVersion, VERSION) > 0,+ installMethod,+ upgradePlan: getUpgradePlan(installMethod),+ };+}++export async function shouldShowUpdateNotification(+ info: UpdateInfo,+ options: { now?: number; stateFile?: string; cooldownMs?: number } = {}+): Promise<boolean> {+ if (!info.updateAvailable) return false;++ const now = options.now ?? Date.now();+ const cooldownMs = options.cooldownMs ?? DEFAULT_CACHE_TTL_MS;+ const state = await readUpdateState(options.stateFile);++ if (+ state.notifiedVersion === info.latestVersion &&+ state.lastNotifiedAt &&+ now - state.lastNotifiedAt < cooldownMs+ ) {+ return false;+ }++ return true;+}++export async function markUpdateNotificationShown(+ latestVersion: string,+ options: { now?: number; stateFile?: string } = {}+): Promise<void> {+ const now = options.now ?? Date.now();+ const state = await readUpdateState(options.stateFile);+ await writeUpdateState(+ {+ ...state,+ notifiedVersion: latestVersion,+ lastNotifiedAt: now,+ },+ options.stateFile+ );+}++export function shouldSkipUpdateNotifier(argv = process.argv): boolean {+ return argv.includes("--json") || argv.includes("-v") || argv.includes("--version");+}diff --git a/packages/cli/tsconfig.json b/packages/cli/tsconfig.jsonindex a5cb69cf..c8192424 100644--- a/packages/cli/tsconfig.json+++ b/packages/cli/tsconfig.json@@ -13,7 +13,8 @@"declaration": true,"declarationMap": true,"sourceMap": true,- "resolveJsonModule": true+ "resolveJsonModule": true,+ "types": ["node"]},"include": ["src/**/*"],"exclude": ["node_modules", "dist"]