From 7cb6018c6be55979a997b277a59331d330fc1aa6 Mon Sep 17 00:00:00 2001 From: Wenbo Zhu Date: Wed, 4 Nov 2026 09:31:52 +0000 Subject: [PATCH] feat(cli): surface outdated CLI and skills to agents; add hyperframes update --check (#7094) * feat(cli): surface outdated CLI and skills to agents; add hyperframes update Single commit of #7094 on top of main (no merge commits through the signed GraphQL path). Includes: 2h update/skills check interval and stale-cache recheck; `_meta.checkedAt`, `_meta.skillsOutdated`, `_meta.skillsMissing`; `_meta.updateNotice`, one sentence for the agent to relay to the person, at most once a day per project (brew/npx-aware command, omitted under CI, the update-check opt-out and agent plugins); `hyperframes update [--check] [--yes] [--json]` (CLI then skills at the installed CLI's tag; brew version read back); doctor names the running binary and its channel; the hyperframes-cli skill gets one line to pass the notice on, naming no command. Keeps main's install-target skills check (#7120) in updateSkills. Co-Authored-By: Claude Opus 5.5 * fix(cli): update notice names a command that moves this install - `_meta.updateNotice` (and `update --check`'s skills command) now name a command that moves the running install: a global npm/pnpm/bun/brew CLI runs its own `hyperframes update` (or just its manager's command when only the CLI is behind), since `npx hyperframes` would run a project's copy or a fresh npx one; a project-local CLI moves with its project's manager by lockfile (`npm install`/`pnpm add`/`bun add`/`yarn add hyperframes@`), which `update --yes` now names too instead of `npx hyperframes@latest`. - `update`'s confirmation hint states a fact and names no step for the agent: "Updating is the person's call; `update --check` only reports." - `upgrade --json`, `upgrade --project --json` and every `skills` JSON output leave out `_meta.updateNotice` (NO_UPDATE_NOTICE), like `update`. - dailyNotice: a null/non-object file reads as empty and is repaired; a future timestamp is stale; writes go through a 0600 tmp file + rename; withMeta never throws from the notice. - Docs: --json without --yes exits 2; plugin `update` exits 1 (plugin_managed); full `_meta` sample; per-install notice commands. `update --check` says "npm registry not reached" instead of "latest". Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- docs/packages/cli.mdx | 103 +++++- packages/cli/README.md | 9 + packages/cli/src/cli.agentMode.test.ts | 10 + packages/cli/src/cli.ts | 2 + .../cli/src/commands/doctor.install.test.ts | 84 +++++ packages/cli/src/commands/doctor.ts | 18 +- packages/cli/src/commands/skills.ts | 34 +- packages/cli/src/commands/update.test.ts | 346 ++++++++++++++++++ packages/cli/src/commands/update.ts | 298 +++++++++++++++ .../commands/updateNotice.commands.test.ts | 100 +++++ packages/cli/src/commands/upgrade.ts | 104 +++++- packages/cli/src/help.ts | 1 + packages/cli/src/telemetry/config.ts | 5 +- .../cli/src/utils/backgroundChecks.test.ts | 17 + packages/cli/src/utils/dailyNotice.test.ts | 78 ++++ packages/cli/src/utils/dailyNotice.ts | 42 +++ .../cli/src/utils/installerDetection.test.ts | 107 ++++++ packages/cli/src/utils/installerDetection.ts | 100 ++++- .../cli/src/utils/skillsUpdateCheck.test.ts | 56 ++- packages/cli/src/utils/skillsUpdateCheck.ts | 77 ++-- packages/cli/src/utils/updateCheck.test.ts | 293 ++++++++++++++- packages/cli/src/utils/updateCheck.ts | 160 +++++++- scripts/check-core-skills.mjs | 3 +- skills-manifest.json | 2 +- skills/hyperframes-cli/SKILL.md | 2 + 25 files changed, 1956 insertions(+), 95 deletions(-) create mode 100644 packages/cli/src/commands/doctor.install.test.ts create mode 100644 packages/cli/src/commands/update.test.ts create mode 100644 packages/cli/src/commands/update.ts create mode 100644 packages/cli/src/commands/updateNotice.commands.test.ts create mode 100644 packages/cli/src/utils/dailyNotice.test.ts create mode 100644 packages/cli/src/utils/dailyNotice.ts diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx index 8bdec2d8ba..3bbbafbbc9 100644 --- a/docs/packages/cli.mdx +++ b/docs/packages/cli.mdx @@ -32,7 +32,7 @@ npm install -g hyperframes | Edit from the terminal | [`timeline`](#timeline), [`history`](#history) | | Make a file | [`render`](#render), [`benchmark`](#benchmark) | | Render somewhere else | [`cloud`](#hyperframes-cloud), [`lambda`](#hyperframes-lambda), [`cloudrun`](#hyperframes-cloudrun) | -| Fix your setup | [`doctor`](#doctor), [`browser`](#browser), [`upgrade`](#upgrade), [`docs`](#docs), [`info`](#info-and-compositions), [`compositions`](#info-and-compositions), [`clean`](#clean) | +| Fix your setup | [`doctor`](#doctor), [`browser`](#browser), [`update`](#update), [`upgrade`](#upgrade), [`docs`](#docs), [`info`](#info-and-compositions), [`compositions`](#info-and-compositions), [`clean`](#clean) | | Connect other tools | [`auth`](#hyperframes-auth), [`billing`](#billing), [`templates`](#templates), [`skills`](#skills), [`usage`](#usage), [`figma`](#figma-and-events), [`events`](#figma-and-events), [`telemetry`](#telemetry), [`feedback`](#feedback) | `validate`, `inspect`, and `layout` still work but are @@ -59,15 +59,42 @@ second call: "_meta": { "version": "0.1.4", "latestVersion": "0.1.5", - "updateAvailable": true + "updateAvailable": true, + "checkedAt": "2026-11-03T08:00:00.000Z", + "skillsOutdated": 2, + "skillsMissing": 0, + "updateNotice": "For the user: HyperFrames CLI 0.1.5 is available (this run is 0.1.4), and 2 installed HyperFrames skills are out of date. To update both, run: hyperframes update" } } ``` -The version numbers come from a cache refreshed at most once a day, in a +The version numbers come from a cache refreshed at most every two hours, in a background process, and never under CI or `HYPERFRAMES_NO_UPDATE_CHECK=1`. -`--json` never makes a network request of its own. Deprecated commands add -`_meta.deprecated: true`. +`checkedAt` says when npm answered. A cached latest older than the running CLI +is left out and rechecked on the next run. `skillsOutdated` counts the installed +HyperFrames skills that are behind this CLI's release, and `skillsMissing` the +core skills that are not installed, from the same background check; both are +absent until that check has run for this version, once it is more than a day old +(as when `HYPERFRAMES_NO_UPDATE_CHECK=1` stops the checks), and under +`HYPERFRAMES_SKIP_SKILLS=1`. `--json` never makes a network request of its own. +Deprecated commands add `_meta.deprecated: true`. + +`updateNotice` is one sentence for the agent to pass on to the person when the +CLI or the skills are behind: what is newer and the command that updates it. +The person decides whether to run it. The command moves the install that is +running: + +| Install | CLI behind | Skills behind too, or only them | +| --- | --- | --- | +| npm, pnpm, bun or Homebrew global | the manager's command (`npm install -g hyperframes@0.9.8`, `brew upgrade hyperframes`, …) | `hyperframes update` (the global CLI's own; `npx hyperframes` would run a project's copy or a fresh one) | +| project `node_modules` | the project's manager, by lockfile: `npm install`, `pnpm add`, `bun add` or `yarn add hyperframes@0.9.8` | that, then `npx hyperframes update`; skills only: `npx hyperframes update` | +| `npx` | `npx hyperframes@latest update` (npx's cache may hold the old CLI) | the same; skills only: `npx hyperframes update` | + +The skills half is left out when no skill is behind or under +`HYPERFRAMES_SKIP_SKILLS=1`. The notice appears at most once a day per project, +while the numeric fields stay on every result. It is never added under CI, +`HYPERFRAMES_NO_UPDATE_CHECK=1`, or an agent plugin (`HYPERFRAMES_PLUGIN_VERSION`), +and the output of `update`, `upgrade` and `skills` leaves it out. A failure under `--json` always prints one JSON object on stdout, with a machine-readable `code` and, when there is a next step, a `hint`: @@ -127,7 +154,8 @@ notice; `HYPERFRAMES_NO_AUTO_INSTALL=1` turns off only the install. **Skills notice.** When installed HyperFrames skills are out of date or missing, a command ends with one line on stderr naming `npx hyperframes skills update`. It shows at most once a day per project. In an unattended run it shows only when -a core skill is missing. `HYPERFRAMES_SKIP_SKILLS=1` turns it off. No notice +a core skill is missing; outdated skills reach agents as `_meta.skillsOutdated` +and `_meta.updateNotice` instead. `HYPERFRAMES_SKIP_SKILLS=1` turns it off. No notice follows a usage error. ## Create a project @@ -1976,6 +2004,7 @@ npx hyperframes doctor --json hyperframes doctor ✓ Version 0.1.4 (latest) + ✓ CLI binary npm global install · /usr/local/lib/node_modules/hyperframes/dist/cli.js ✓ Node.js v22.x (linux x64) ✓ FFmpeg 7.x ✓ FFprobe 7.x @@ -1986,7 +2015,9 @@ hyperframes doctor ◇ All checks passed ``` -It reports CLI version, Node.js, CPU, memory, disk, the extracted-frame cache, +It reports CLI version, which binary is running and from where (a global npm, +pnpm, bun or Homebrew install, a project's `node_modules`, `npx`, or an agent +plugin) with its path, Node.js, CPU, memory, disk, the extracted-frame cache, the archive extractor, `/dev/shm` on Linux, environment, whisper-cpp, local TTS and BGM models, FFmpeg, FFprobe, Chrome, and Docker. @@ -2037,6 +2068,64 @@ duration, element counts by type, track count, and total size. `npx hyperframes compositions` lists every composition in the project with its ID, duration, resolution, and element count. Both take `--json`. +### `update` + +```bash +npx hyperframes update --check # report the CLI and the skills, install nothing +npx hyperframes update --check --json # the same, for agents +npx hyperframes update --yes # update both without prompting +``` + +`update` asks npm for the latest CLI (past the two-hour cache) and checks the +installed skills against the manifest at this CLI's release tag, in one call. +`--check` only reports. Without it, `update` upgrades the CLI the way +`upgrade --yes` does (an `npx` run gets `npx hyperframes@latest` to run instead, +and a project-local run the project manager's command, such as +`npm install hyperframes@0.9.8`) and then runs `skills update` at the release +tag of the CLI that is now installed. Homebrew installs whatever its formula +has, which can trail npm, so `update` reads the installed version back and +reports `unchanged` when the formula has not moved. Without `--yes` or +`--check`, an unattended run and any `--json` run exit 2, with the hint +"Updating is the person's call; `update --check` only reports." Under an agent +plugin, `update --check` reports, and `update` itself exits 1 with +`plugin_managed`: the plugin manager updates it. `HYPERFRAMES_SKIP_SKILLS=1` +leaves the skills alone. When npm does not answer, the human report says +"npm registry not reached" instead of calling the CLI the latest. +`--check --json` returns: + +```json +{ + "cli": { + "current": "0.9.5", + "latest": "0.9.8", + "updateAvailable": true, + "checkedAt": "2026-11-03T08:00:00.000Z", + "install": { "channel": "npm", "path": "/usr/local/lib/node_modules/hyperframes/dist/cli.js" }, + "command": "npm install -g hyperframes@0.9.8" + }, + "skills": { + "status": "checked", + "ref": "v0.9.5", + "location": "/Users/me/.claude/skills", + "updateAvailable": true, + "outdated": 2, + "missing": 0, + "command": "hyperframes update" + }, + "_meta": { + "version": "0.9.5", + "latestVersion": "0.9.8", + "updateAvailable": true, + "checkedAt": "2026-11-03T08:00:00.000Z", + "skillsOutdated": 2, + "skillsMissing": 0 + } +} +``` + +`cli.checkedAt` is `null` when npm did not answer. `install.channel` is one of +`npm`, `pnpm`, `bun`, `brew`, `npx`, `project`, `workspace`, `plugin` or `unknown`. + ### `upgrade` ```bash diff --git a/packages/cli/README.md b/packages/cli/README.md index 925cb9e6b2..d3fe270e7c 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -194,6 +194,15 @@ npx hyperframes upgrade npx hyperframes upgrade --check --json # machine-readable for agents ``` +### `update` + +Check the CLI and the installed skills for updates in one call, or install both: + +```bash +npx hyperframes update --check --json # report only, machine-readable for agents +npx hyperframes update --yes # upgrade the CLI, then refresh the skills +``` + ## Documentation Full documentation: [hyperframes.heygen.com/packages/cli](https://hyperframes.heygen.com/packages/cli) diff --git a/packages/cli/src/cli.agentMode.test.ts b/packages/cli/src/cli.agentMode.test.ts index e58b4536b1..9687e7045f 100644 --- a/packages/cli/src/cli.agentMode.test.ts +++ b/packages/cli/src/cli.agentMode.test.ts @@ -381,6 +381,16 @@ describe("agent-mode contract", () => { }, ); + // Updating is the person's decision: the hint states that and names no step for the agent. + it("update without --yes refuses to prompt, exits 2, and leaves updating to the person", async () => { + const run = await runAsAgent(["update"]); + expectQuiet(run); + expect(run.code, run.stderr).toBe(2); + expect(run.stdout).toBe(""); + expect(run.stderr).toContain("Updating is the person's call; `update --check` only reports."); + expect(run.stderr).not.toContain("--yes"); + }); + it("only the prompt wrapper loads @clack/prompts, statically or dynamically", () => { const offenders = (readdirSync(srcDir, { recursive: true }) as string[]).filter( (file) => diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index 4a3df9b046..437c705e07 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -166,6 +166,7 @@ const commandLoaders = { doctor: () => import("./commands/doctor.js").then((m) => m.default), clean: () => import("./commands/clean.js").then((m) => m.default), upgrade: () => import("./commands/upgrade.js").then((m) => m.default), + update: () => import("./commands/update.js").then((m) => m.default), skills: () => import("./commands/skills.js").then((m) => m.default), feedback: () => import("./commands/feedback.js").then((m) => m.default), telemetry: () => import("./commands/telemetry.js").then((m) => m.default), @@ -282,6 +283,7 @@ if ( if ( !isHelp && command !== "upgrade" && + command !== "update" && command !== "events" && command !== "telemetry" && command !== "skills" && diff --git a/packages/cli/src/commands/doctor.install.test.ts b/packages/cli/src/commands/doctor.install.test.ts new file mode 100644 index 0000000000..f133466cf1 --- /dev/null +++ b/packages/cli/src/commands/doctor.install.test.ts @@ -0,0 +1,84 @@ +// `doctor` names the binary that is running and where it lives, and its update hint is the +// command for that install: the manager's for a global one, `npx hyperframes@latest` for npx. +// The install detection is real; only the resolved entry path and the cached latest are stubbed. + +import { afterEach, describe, expect, it, vi } from "vitest"; + +const ENTRIES = { + npm: "/usr/local/lib/node_modules/hyperframes/dist/cli.js", + brew: "/opt/homebrew/Cellar/hyperframes/0.9.5/libexec/lib/node_modules/hyperframes/dist/cli.js", + npx: "/home/me/.npm/_npx/4f1c2a/node_modules/hyperframes/dist/cli.js", + project: "/home/me/video/node_modules/hyperframes/dist/cli.js", +} as const; + +const originalArgv1 = process.argv[1]; + +async function doctorAt(entry: string, latestVersion: string | undefined) { + vi.resetModules(); + vi.stubEnv("HYPERFRAMES_PLUGIN_VERSION", ""); + vi.doMock("node:fs", async () => ({ + ...(await vi.importActual("node:fs")), + realpathSync: () => entry, + })); + vi.doMock("../utils/updateCheck.js", async (importOriginal) => ({ + ...(await importOriginal()), + getUpdateMeta: () => ({ + version: "0.9.5", + latestVersion, + updateAvailable: latestVersion !== undefined && latestVersion !== "0.9.5", + }), + })); + vi.doMock("../version.js", async (importOriginal) => ({ + ...(await importOriginal()), + VERSION: "0.9.5", + })); + process.argv[1] = "/usr/local/bin/hyperframes"; + return import("./doctor.js"); +} + +afterEach(() => { + process.argv[1] = originalArgv1 ?? ""; + vi.doUnmock("node:fs"); + vi.doUnmock("../utils/updateCheck.js"); + vi.doUnmock("../version.js"); + vi.unstubAllEnvs(); + vi.resetModules(); +}); + +describe("doctor: the running binary", () => { + it.each([ + ["npm", ENTRIES.npm, "npm global install"], + ["brew", ENTRIES.brew, "Homebrew install"], + ["npx", ENTRIES.npx, "npx"], + ["project", ENTRIES.project, "project-local install"], + ])("names a %s binary and its path", async (_channel, entry, label) => { + const { checkInstall } = await doctorAt(entry, "0.9.5"); + const result = checkInstall(); + expect(result.ok).toBe(true); + expect(result.detail).toContain(label); + expect(result.detail).toContain(entry); + }); + + it("names a plugin run as plugin-pinned", async () => { + const { checkInstall } = await doctorAt(ENTRIES.npx, "0.9.5"); + vi.stubEnv("HYPERFRAMES_PLUGIN_VERSION", "0.9.5"); + expect(checkInstall().detail).toContain("agent plugin"); + }); +}); + +describe("doctor: the update hint fits the install", () => { + it.each([ + ["npm", ENTRIES.npm, "Run: npm install -g hyperframes@0.9.8"], + ["brew", ENTRIES.brew, "Run: brew upgrade hyperframes"], + ["npx", ENTRIES.npx, "Run: npx hyperframes@latest"], + ["project", ENTRIES.project, "Run: npm install hyperframes@0.9.8"], + ])("%s", async (_channel, entry, hint) => { + const { checkVersion } = await doctorAt(entry, "0.9.8"); + expect(checkVersion()).toEqual({ ok: false, detail: "0.9.5 → 0.9.8 available", hint }); + }); + + it("does not claim 'latest' before any check has answered", async () => { + const { checkVersion } = await doctorAt(ENTRIES.npm, undefined); + expect(checkVersion()).toEqual({ ok: true, detail: "0.9.5 (not checked yet)" }); + }); +}); diff --git a/packages/cli/src/commands/doctor.ts b/packages/cli/src/commands/doctor.ts index 97411cee31..a1d57a8b12 100644 --- a/packages/cli/src/commands/doctor.ts +++ b/packages/cli/src/commands/doctor.ts @@ -16,6 +16,11 @@ import { KOKORO_MODULES, KOKORO_PIP, MUSICGEN_MODULES, MUSICGEN_PIP } from "../a import { hasPythonModules, describeRejectedPythonOverride } from "../tts/python.js"; import { VERSION } from "../version.js"; import { getUpdateMeta, withMeta } from "../utils/updateCheck.js"; +import { + installChannelLabel, + runningInstall, + updateCommandFor, +} from "../utils/installerDetection.js"; import { OPTIONAL_PACKAGES, installedOptionalPackageVersion, @@ -82,18 +87,26 @@ function checkDockerRunning(): CheckResult { } } -function checkVersion(): CheckResult { +export function checkVersion(): CheckResult { const meta = getUpdateMeta(); if (meta.updateAvailable && meta.latestVersion) { return { ok: false, detail: `${VERSION} \u2192 ${meta.latestVersion} available`, - hint: "Run: hyperframes upgrade", + hint: `Run: ${updateCommandFor(runningInstall(), meta.latestVersion)}`, }; } + if (!meta.latestVersion) return { ok: true, detail: `${VERSION} (not checked yet)` }; return { ok: true, detail: `${VERSION} (latest)` }; } +/** Which binary is running and from where: a global install per manager, project-local, npx or a plugin. */ +export function checkInstall(): CheckResult { + const install = runningInstall(); + const where = install.path ?? "entry path unknown"; + return { ok: true, detail: `${installChannelLabel(install.channel)} \u00B7 ${where}` }; +} + function checkNode(): CheckResult { return { ok: true, detail: `${process.version} (${process.platform} ${process.arch})` }; } @@ -380,6 +393,7 @@ export default defineCommand({ const environment = await runEnvironmentChecks({ includeBrowser: true }); const checks: Check[] = [ { name: "Version", run: checkVersion }, + { name: "CLI binary", run: checkInstall }, { name: "Node.js", run: checkNode }, { name: "CPU", run: checkCPU }, { name: "Memory", run: checkMemory }, diff --git a/packages/cli/src/commands/skills.ts b/packages/cli/src/commands/skills.ts index 849f8d05b9..1237b6b447 100644 --- a/packages/cli/src/commands/skills.ts +++ b/packages/cli/src/commands/skills.ts @@ -6,7 +6,7 @@ import { c } from "../ui/colors.js"; import { diag } from "../ui/diagnostics.js"; import { buildNpxCommand } from "../utils/npxCommand.js"; import { VERSION } from "../version.js"; -import { withMeta } from "../utils/updateCheck.js"; +import { NO_UPDATE_NOTICE, withMeta } from "../utils/updateCheck.js"; import { checkSkills, FALLBACK_CORE_SKILLS, @@ -328,12 +328,18 @@ export async function updateSkills( all?: boolean; strict?: boolean; cwd?: string; + /** + * The CLI version whose release tag to install from (default: this one). `hyperframes + * update` passes the version it just upgraded to, so the skills match the CLI that runs next. + */ + cliVersion?: string; } = {}, ): Promise { const named = [...new Set(opts.requested ?? [])]; const retired = named.filter((name) => RETIRED_SKILLS.includes(name)); const requested = named.filter((name) => !retired.includes(name)); const strict = opts.strict ?? false; + const cliVersion = opts.cliVersion ?? VERSION; let check: SkillsCheckResult | null = null; try { @@ -350,7 +356,7 @@ export async function updateSkills( check = await checkSkills({ cwd: opts.cwd, canonical: true, - cliVersion: VERSION, + cliVersion, installTarget: true, }); } catch (err) { @@ -378,7 +384,10 @@ export async function updateSkills( ), ); } - return { ...(await updateSkillsOffline(requested, { strict, cwd: opts.cwd })), retired }; + return { + ...(await updateSkillsOffline(requested, { strict, cwd: opts.cwd, cliVersion })), + retired, + }; } const manifestSkills = check.skills; @@ -469,7 +478,7 @@ function verifyInstalled(names: readonly string[], opts: { strict: boolean; cwd? */ async function updateSkillsOffline( requested: readonly string[], - opts: { strict: boolean; cwd?: string }, + opts: { strict: boolean; cwd?: string; cliVersion: string }, ): Promise> { if (requested.length === 0 && opts.strict) { throw new Error( @@ -502,7 +511,7 @@ async function updateSkillsOffline( await installSkills(absent, { cwd: opts.cwd, strict: opts.strict, - ref: cliReleaseTag(VERSION) ?? "main", + ref: cliReleaseTag(opts.cliVersion) ?? "main", }); verifyInstalled(targets, opts); } @@ -599,7 +608,7 @@ const checkCommand = defineCommand({ cliVersion: VERSION, }); - if (args.json) console.log(JSON.stringify(withMeta(result), null, 2)); + if (args.json) console.log(JSON.stringify(withMeta(result, NO_UPDATE_NOTICE), null, 2)); else renderCheck(result); // This check just displayed a fresh verdict, superseding whatever the @@ -622,7 +631,7 @@ const checkCommand = defineCommand({ * the router's trigger-time `skills update ` replaces a pinned install * with the latest upstream skills (GH #5695). */ -function skillsManagedExternally(): boolean { +export function skillsManagedExternally(): boolean { return process.env["HYPERFRAMES_SKIP_SKILLS"] === "1"; } @@ -634,7 +643,10 @@ function reportSkillsManagedExternally(requested: readonly string[], json: boole if (json) { console.log( JSON.stringify( - withMeta({ skipped: true, reason: SKILLS_MANAGED_EXTERNALLY_NOTICE, requested }), + withMeta( + { skipped: true, reason: SKILLS_MANAGED_EXTERNALLY_NOTICE, requested }, + NO_UPDATE_NOTICE, + ), null, 2, ), @@ -669,7 +681,7 @@ function reportUpdate( json: boolean, ): void { if (json) { - console.log(JSON.stringify(withMeta(result), null, 2)); + console.log(JSON.stringify(withMeta(result, NO_UPDATE_NOTICE), null, 2)); return; } for (const name of result.retired) console.log(c.warn(retiredSkillNotice(name))); @@ -699,7 +711,9 @@ function reportUpdate( */ function reportUpdateFailure(message: string, json: boolean): void { if (json) { - console.log(JSON.stringify(withMeta(jsonFailure("runtime_error", message)), null, 2)); + console.log( + JSON.stringify(withMeta(jsonFailure("runtime_error", message), NO_UPDATE_NOTICE), null, 2), + ); return; } clack.log.error(c.error(message)); diff --git a/packages/cli/src/commands/update.test.ts b/packages/cli/src/commands/update.test.ts new file mode 100644 index 0000000000..2eb4257e5a --- /dev/null +++ b/packages/cli/src/commands/update.test.ts @@ -0,0 +1,346 @@ +// `hyperframes update`: one forced check of the CLI and the skills, then the +// install the way `upgrade --yes` and `skills update` do it. Install detection, +// the upgrade argv and the skills install run for real per install channel; +// only spawn, the config file, the manifest fetch/disk and the registry are stubbed. + +import { EventEmitter } from "node:events"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +// The package-manager binaries a CLI upgrade runs; npx (cmd.exe on Windows) and git are the skills tooling. +const INSTALLERS = vi.hoisted(() => new Set(["npm", "pnpm", "bun", "brew"])); + +const state = vi.hoisted(() => ({ + config: {} as Record, + execCalls: [] as { command: string; args: readonly string[]; opts: unknown }[], + spawnCalls: [] as { command: string; args: readonly string[] }[], + installFails: false, + registryLatest: "0.9.8" as string | null, + // What Homebrew's linked binary reports after `brew upgrade` (null: it cannot be read). + brewInstalled: "0.9.8" as string | null, + fetchedUrls: [] as string[], +})); + +vi.mock("../version.js", async (importOriginal) => ({ + ...(await importOriginal()), + VERSION: "0.9.5", +})); + +vi.mock("../telemetry/config.js", () => ({ + CONFIG_PATH: "/nonexistent/hf-update-test/config.json", + readConfig: () => ({ ...state.config }), + readConfigFresh: () => ({ ...state.config }), + writeConfig: (next: Record) => { + state.config = { ...next }; + return true; + }, +})); + +vi.mock("../telemetry/events.js", () => ({ trackSkillsInstallSkipped: vi.fn() })); + +vi.mock("node:child_process", () => ({ + execFile: vi.fn(), + execFileSync: vi.fn((command: string, args: readonly string[], opts: unknown) => { + state.execCalls.push({ command, args, opts }); + if (command === "brew" && args[0] === "--prefix") return "/opt/homebrew/opt/hyperframes\n"; + if (command.replaceAll("\\", "/") === "/opt/homebrew/opt/hyperframes/bin/hyperframes") { + if (state.brewInstalled === null) throw new Error("not linked"); + return `${state.brewInstalled}\n`; + } + if (state.installFails && INSTALLERS.has(command)) throw new Error("boom"); + return Buffer.from("11.0.0"); + }), + spawn: vi.fn((command: string, args: readonly string[]) => { + state.spawnCalls.push({ command, args }); + const child = new EventEmitter(); + setImmediate(() => child.emit("close", 0, null)); + return child; + }), +})); + +const OUTDATED_CHECK = { + location: "/home/user/.claude/skills", + agent: "claude-code", + scope: "global", + updateAvailable: true, + summary: { current: 1, outdated: 2, missing: 0, coreMissing: 0, removed: 0 }, + skills: [ + { name: "hyperframes", status: "outdated" }, + { name: "hyperframes-registry", status: "outdated" }, + { name: "figma", status: "current" }, + ], + foreign: [], + ref: "v0.9.5", +}; + +vi.mock("../utils/skillsManifest.js", async (importOriginal) => ({ + ...(await importOriginal()), + // The manifest is read at the requested CLI version's release tag, as the real check does. + checkSkills: vi.fn(async (opts: { cliVersion?: string }) => ({ + ...OUTDATED_CHECK, + ref: `v${opts.cliVersion}`, + })), + hyperframesSkillNames: vi.fn(() => ["hyperframes"]), + presentSkills: vi.fn((names: readonly string[]) => [...names]), +})); +vi.mock("../utils/skillsMirror.js", () => ({ + mirrorGlobalSkills: vi.fn(() => ({ source: null, mirrored: [], skipped: [] })), +})); + +const ENTRIES = { + npm: "/usr/local/lib/node_modules/hyperframes/dist/cli.js", + pnpm: "/home/me/.local/share/pnpm/global/5/node_modules/hyperframes/dist/cli.js", + bun: "/home/me/.bun/install/global/node_modules/hyperframes/dist/cli.js", + brew: "/opt/homebrew/Cellar/hyperframes/0.9.5/libexec/lib/node_modules/hyperframes/dist/cli.js", + npx: "/home/me/.npm/_npx/4f1c2a/node_modules/hyperframes/dist/cli.js", + project: "/home/me/video/node_modules/hyperframes/dist/cli.js", +} as const; + +const originalArgv = [...process.argv]; +let stdout: string[]; + +async function runUpdate(entry: string, args: Record) { + process.argv = [process.argv[0] ?? "node", entry]; + const { default: cmd } = await import("./update.js"); + await cmd.run?.({ args: { _: [], ...args }, rawArgs: [], cmd } as never); + const { consumeCommandResult } = await import("../utils/commandResult.js"); + return consumeCommandResult().exitCode; +} + +const json = () => JSON.parse(stdout.join("\n")) as Record; +const installs = () => + state.execCalls.filter((c) => INSTALLERS.has(c.command) && c.args[0] !== "--prefix"); +const skillsAdds = () => state.spawnCalls.filter((c) => c.args.includes("add")); + +beforeEach(() => { + vi.resetModules(); + state.config = {}; + state.execCalls = []; + state.spawnCalls = []; + state.installFails = false; + state.registryLatest = "0.9.8"; + state.brewInstalled = "0.9.8"; + state.fetchedUrls = []; + vi.stubGlobal( + "fetch", + vi.fn(async (url: string) => { + state.fetchedUrls.push(String(url)); + return state.registryLatest + ? ({ ok: true, json: async () => ({ version: state.registryLatest }) } as Response) + : ({ ok: false, status: 503 } as Response); + }), + ); + for (const name of [ + "HYPERFRAMES_PLUGIN_VERSION", + "HYPERFRAMES_SKIP_SKILLS", + "HYPERFRAMES_AGENT", + ]) { + vi.stubEnv(name, ""); + } + stdout = []; + vi.spyOn(console, "log").mockImplementation((...a: unknown[]) => void stdout.push(a.join(" "))); + vi.spyOn(console, "error").mockImplementation(() => {}); +}); + +afterEach(() => { + process.argv = [...originalArgv]; + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); + vi.restoreAllMocks(); +}); + +describe("hyperframes update --check", () => { + it("reports the CLI (fresh from npm, past the cache) and the skills in one JSON call, installing nothing", async () => { + // A cache that says "current" and is only minutes old must not answer `update`. + state.config = { latestVersion: "0.9.5", lastUpdateCheck: new Date().toISOString() }; + + expect(await runUpdate(ENTRIES.npm, { check: true, json: true })).toBe(0); + + const out = json(); + expect(state.fetchedUrls).toEqual(["https://registry.npmjs.org/hyperframes/latest"]); + expect(out.cli).toMatchObject({ + current: "0.9.5", + latest: "0.9.8", + updateAvailable: true, + install: { channel: "npm", path: ENTRIES.npm }, + command: "npm install -g hyperframes@0.9.8", + }); + expect(out.cli.checkedAt).toEqual(expect.any(String)); + expect(out.skills).toMatchObject({ + status: "checked", + ref: "v0.9.5", + outdated: 2, + updateAvailable: true, + // The global CLI runs its own update: `npx hyperframes` could run another copy. + command: "hyperframes update", + }); + expect(out._meta).toMatchObject({ + latestVersion: "0.9.8", + updateAvailable: true, + skillsOutdated: 2, + }); + expect(installs()).toEqual([]); + expect(skillsAdds()).toEqual([]); + }); + + it("reads the skills manifest at this CLI's release tag", async () => { + const { checkSkills } = await import("../utils/skillsManifest.js"); + await runUpdate(ENTRIES.npm, { check: true, json: true }); + expect(checkSkills).toHaveBeenCalledWith({ canonical: true, cliVersion: "0.9.5" }); + }); + + it("says when npm was not reached instead of passing the cache off as fresh", async () => { + state.registryLatest = null; + await runUpdate(ENTRIES.npm, { check: true, json: true }); + expect(json().cli).toMatchObject({ updateAvailable: false, checkedAt: null }); + }); + + it("does not call the CLI latest when npm was not reached", async () => { + state.registryLatest = null; + await runUpdate(ENTRIES.npm, { check: true }); + const text = stdout.join("\n"); + expect(text).toContain("(npm registry not reached)"); + expect(text).not.toContain("latest"); + }); + + it.each([ + ["npm", ENTRIES.npm, "npm install -g hyperframes@0.9.8"], + ["pnpm", ENTRIES.pnpm, "pnpm add -g hyperframes@0.9.8"], + ["bun", ENTRIES.bun, "bun add -g hyperframes@0.9.8"], + ["brew", ENTRIES.brew, "brew upgrade hyperframes"], + ["npx", ENTRIES.npx, "npx hyperframes@latest"], + ["project", ENTRIES.project, "npm install hyperframes@0.9.8"], + ])("names the %s install and the command that updates it", async (channel, entry, command) => { + await runUpdate(entry, { check: true, json: true }); + expect(json().cli.install).toEqual({ channel, path: entry }); + expect(json().cli.command).toBe(command); + }); + + it("reports a plugin install as plugin-managed, and does not check its pinned skills", async () => { + vi.stubEnv("HYPERFRAMES_PLUGIN_VERSION", "0.9.5"); + vi.stubEnv("HYPERFRAMES_SKIP_SKILLS", "1"); + const { checkSkills } = await import("../utils/skillsManifest.js"); + vi.mocked(checkSkills).mockClear(); + + expect(await runUpdate(ENTRIES.npx, { check: true, json: true })).toBe(0); + + expect(json().cli.install.channel).toBe("plugin"); + expect(json().cli.command).toMatch(/plugin/); + expect(json().skills.status).toBe("skipped"); + expect(checkSkills).not.toHaveBeenCalled(); + }); +}); + +describe("hyperframes update (install)", () => { + it("asks for --yes in an unattended run instead of installing", async () => { + vi.stubEnv("HYPERFRAMES_AGENT", "1"); + await expect(runUpdate(ENTRIES.npm, { json: true })).rejects.toThrow(/confirmation/); + expect(installs()).toEqual([]); + expect(state.fetchedUrls).toEqual([]); + }); + + it.each([ + ["npm", ENTRIES.npm, "npm", ["install", "-g", "hyperframes@0.9.8"]], + ["pnpm", ENTRIES.pnpm, "pnpm", ["add", "-g", "hyperframes@0.9.8"]], + ["bun", ENTRIES.bun, "bun", ["add", "-g", "hyperframes@0.9.8"]], + // Explicit: the user asked, so brew may move to the formula (unlike auto-update); here it reached npm. + ["brew", ENTRIES.brew, "brew", ["upgrade", "hyperframes"]], + ])( + "%s: upgrades the CLI like upgrade --yes, then installs the skills at the new CLI's tag", + async (_channel, entry, bin, args) => { + expect(await runUpdate(entry, { yes: true, json: true })).toBe(0); + + expect(installs()).toHaveLength(1); + expect(installs()[0]).toMatchObject({ command: bin, args }); + // The child's stdout goes to stderr: a --json stdout stays one parseable object. + expect(installs()[0]!.opts).toMatchObject({ shell: false, stdio: ["inherit", 2, 2] }); + expect(skillsAdds()).toHaveLength(1); + expect(skillsAdds()[0]!.args).toContain("https://github.com/heygen-com/hyperframes#v0.9.8"); + expect(json().updated).toMatchObject({ + cli: { status: "upgraded", version: "0.9.8" }, + skills: { status: "updated" }, + }); + }, + ); + + it.each([ + ["npx", ENTRIES.npx, "npx hyperframes@latest"], + // The project's manager moves its dependency, as `--check` names it. + ["project", ENTRIES.project, "npm install hyperframes@0.9.8"], + ])( + "%s: installs no CLI, names %s, refreshes the skills at its own tag", + async (_channel, entry, command) => { + expect(await runUpdate(entry, { yes: true, json: true })).toBe(0); + expect(installs()).toEqual([]); + expect(json().updated.cli).toMatchObject({ status: "manual", command }); + expect(skillsAdds()[0]!.args).toContain("https://github.com/heygen-com/hyperframes#v0.9.5"); + }, + ); + + // `brew upgrade` installs the formula's version, which lags npm, and exits 0 on a no-op: the + // skills must follow the CLI that is actually installed, never npm's latest. + it("brew staying behind npm: reports the CLI unchanged and keeps the skills at its own tag", async () => { + state.brewInstalled = "0.9.5"; + expect(await runUpdate(ENTRIES.brew, { yes: true, json: true })).toBe(0); + + expect(json().updated.cli).toMatchObject({ status: "unchanged", version: "0.9.5" }); + expect(json().updated.cli.reason).toContain("0.9.8"); + const adds = skillsAdds().flatMap((c) => c.args); + expect(adds).not.toContain("https://github.com/heygen-com/hyperframes#v0.9.8"); + expect(adds).toContain("https://github.com/heygen-com/hyperframes#v0.9.5"); + }); + + it("brew moving to a formula between the two: skills at the version brew installed", async () => { + state.brewInstalled = "0.9.7"; + expect(await runUpdate(ENTRIES.brew, { yes: true, json: true })).toBe(0); + expect(json().updated.cli).toMatchObject({ status: "upgraded", version: "0.9.7" }); + expect(skillsAdds()[0]!.args).toContain("https://github.com/heygen-com/hyperframes#v0.9.7"); + }); + + it("brew whose installed version cannot be read: says so and keeps the skills at this CLI's tag", async () => { + state.brewInstalled = null; + expect(await runUpdate(ENTRIES.brew, { yes: true, json: true })).toBe(0); + expect(json().updated.cli).toMatchObject({ status: "unverified" }); + expect(skillsAdds()[0]!.args).toContain("https://github.com/heygen-com/hyperframes#v0.9.5"); + }); + + it("plugin: refuses, installing neither the CLI nor the skills", async () => { + vi.stubEnv("HYPERFRAMES_PLUGIN_VERSION", "0.9.5"); + vi.stubEnv("HYPERFRAMES_SKIP_SKILLS", "1"); + expect(await runUpdate(ENTRIES.npx, { yes: true, json: true })).toBe(1); + expect(json()).toMatchObject({ ok: false, error: { code: "plugin_managed" } }); + expect(installs()).toEqual([]); + expect(skillsAdds()).toEqual([]); + expect(state.fetchedUrls).toEqual([]); + }); + + it("HYPERFRAMES_SKIP_SKILLS leaves the skills alone while the CLI still updates", async () => { + vi.stubEnv("HYPERFRAMES_SKIP_SKILLS", "1"); + expect(await runUpdate(ENTRIES.npm, { yes: true, json: true })).toBe(0); + expect(installs()).toHaveLength(1); + expect(skillsAdds()).toEqual([]); + expect(json().updated.skills.status).toBe("skipped"); + }); + + it("a failed CLI install exits 1 and says what to run", async () => { + state.installFails = true; + expect(await runUpdate(ENTRIES.npm, { yes: true, json: true })).toBe(1); + expect(json().updated.cli).toMatchObject({ + status: "failed", + command: "npm install -g hyperframes@0.9.8", + }); + }); + + it("installs nothing when the CLI and its skills are current", async () => { + state.registryLatest = "0.9.5"; + const { checkSkills } = await import("../utils/skillsManifest.js"); + vi.mocked(checkSkills).mockResolvedValueOnce({ + ...OUTDATED_CHECK, + updateAvailable: false, + summary: { ...OUTDATED_CHECK.summary, outdated: 0, current: 3 }, + } as never); + expect(await runUpdate(ENTRIES.npm, { yes: true, json: true })).toBe(0); + expect(installs()).toEqual([]); + expect(skillsAdds()).toEqual([]); + expect(json().updated).toEqual({ cli: { status: "current" }, skills: { status: "current" } }); + }); +}); diff --git a/packages/cli/src/commands/update.ts b/packages/cli/src/commands/update.ts new file mode 100644 index 0000000000..ff57d4776a --- /dev/null +++ b/packages/cli/src/commands/update.ts @@ -0,0 +1,298 @@ +import { setCommandExitCode } from "../utils/commandResult.js"; +import { defineCommand } from "../utils/defineCommand.js"; +import type { Example } from "./_examples.js"; +import * as clack from "../ui/prompts.js"; +import { c } from "../ui/colors.js"; +import { readConfigFresh } from "../telemetry/config.js"; +import { isUnattended } from "../utils/attendedTerminal.js"; +import { failureMessage, jsonFailure } from "../utils/jsonError.js"; +import { + installChannelLabel, + runningInstall, + updateCommandFor, + type InstallChannel, +} from "../utils/installerDetection.js"; +import { checkSkills } from "../utils/skillsManifest.js"; +import { recordSkillsCheck } from "../utils/skillsUpdateCheck.js"; +import { + checkForUpdate, + NO_UPDATE_NOTICE, + updateCommandForThisInstall, + withMeta, +} from "../utils/updateCheck.js"; +import { VERSION } from "../version.js"; +import { skillsManagedExternally, updateSkills, type UpdateSkillsResult } from "./skills.js"; +import { upgradeRunningCli, type CliUpgradeOutcome } from "./upgrade.js"; + +export const examples: Example[] = [ + ["Check the CLI and the skills for updates in one call", "hyperframes update --check"], + ["The same check, machine-readable (for agents)", "hyperframes update --check --json"], + ["Update the CLI and the skills without prompting", "hyperframes update --yes"], +]; + +const PLUGIN_REASON = + "This CLI runs from an agent plugin, which pins the CLI and its skills; update the plugin through your agent's plugin manager."; + +interface CliReport { + current: string; + latest: string; + updateAvailable: boolean; + /** When the registry answered this run; null when it did not (latest is then the cached value). */ + checkedAt: string | null; + install: { channel: InstallChannel; path: string | null }; + /** What moves this install to `latest`; null when already current. */ + command: string | null; +} + +type SkillsReport = + | { + status: "checked"; + /** Repo ref the manifest was read at: this CLI's release tag, or main for a dev build. */ + ref: string | null; + location: string | null; + updateAvailable: boolean; + outdated: number; + missing: number; + command: string | null; + } + | { status: "skipped"; reason: string } + | { status: "error"; error: string }; + +interface UpdateOutcome { + cli: CliUpgradeOutcome | { status: "current" }; + skills: + | { status: "updated"; result: UpdateSkillsResult } + | { status: "current" } + | { status: "skipped"; reason: string } + | { status: "failed"; error: string }; +} + +/** One forced registry check (no cache, no opt-out), reported with where this binary runs from. */ +async function checkCli(): Promise { + const startedAt = Date.now(); + const result = await checkForUpdate(true); + const stamp = readConfigFresh().lastUpdateCheck; + const checkedAt = stamp && new Date(stamp).getTime() >= startedAt - 1000 ? stamp : null; + const install = runningInstall(); + return { + current: result.current, + latest: result.latest, + updateAvailable: result.updateAvailable, + checkedAt, + install, + command: result.updateAvailable ? updateCommandFor(install, result.latest) : null, + }; +} + +function skillsSkipReason(channel: InstallChannel): string | null { + if (channel === "plugin") return PLUGIN_REASON; + if (skillsManagedExternally()) { + return "HYPERFRAMES_SKIP_SKILLS=1: skills are managed externally."; + } + return null; +} + +/** The skills check `skills update` would act on (manifest at this CLI's release tag), cached for `_meta`. */ +async function checkInstalledSkills(cli: CliReport): Promise { + const skip = skillsSkipReason(cli.install.channel); + if (skip) return { status: "skipped", reason: skip }; + try { + const result = await checkSkills({ canonical: true, cliVersion: VERSION }); + recordSkillsCheck(result); + return { + status: "checked", + ref: result.ref, + location: result.location, + updateAvailable: result.updateAvailable, + outdated: result.summary.outdated, + missing: result.summary.coreMissing, + // The command `_meta.updateNotice` names, for both halves: it moves this install. + command: result.updateAvailable + ? updateCommandForThisInstall(cli.updateAvailable, true, cli.latest) + : null, + }; + } catch (err) { + return { status: "error", error: failureMessage(err) }; + } +} + +/** The CLI half. A project-local CLI is moved by its project's manager: name that, as `--check` does. */ +function upgradeCli(cli: CliReport): UpdateOutcome["cli"] { + if (!cli.updateAvailable) return { status: "current" }; + const upgrade = upgradeRunningCli(cli.latest); + return upgrade.status === "manual" && cli.command + ? { ...upgrade, command: cli.command } + : upgrade; +} + +/** Upgrade the CLI the way `upgrade --yes` does, then refresh the skills at the tag of the CLI that runs next. */ +async function applyUpdate(cli: CliReport, skills: SkillsReport): Promise { + const cliOutcome = upgradeCli(cli); + if (skills.status === "skipped") return { cli: cliOutcome, skills }; + // Still on this CLI and its skills already match its tag: nothing to install. + if (cliOutcome.status !== "upgraded" && skills.status === "checked" && !skills.updateAvailable) { + return { cli: cliOutcome, skills: { status: "current" } }; + } + // The skills follow the CLI that is installed now, which a brew upgrade may leave short of npm's. + const cliVersion = cliOutcome.status === "upgraded" ? cliOutcome.version : VERSION; + try { + const result = await updateSkills({ refreshInstalled: true, strict: true, cliVersion }); + return { cli: cliOutcome, skills: { status: "updated", result } }; + } catch (err) { + return { cli: cliOutcome, skills: { status: "failed", error: failureMessage(err) } }; + } +} + +function printCheck(cli: CliReport, skills: SkillsReport): void { + const where = `${installChannelLabel(cli.install.channel)}${cli.install.path ? ` · ${cli.install.path}` : ""}`; + console.log(); + console.log(c.bold("hyperframes update")); + console.log(); + const version = cli.updateAvailable + ? c.warn(`${cli.current} → ${cli.latest} available`) + : c.success(`${cli.current} (${cli.checkedAt ? "latest" : "npm registry not reached"})`); + console.log(` ${c.bold("CLI".padEnd(8))}${version}`); + console.log(` ${" ".repeat(8)}${c.dim(where)}`); + if (cli.command) console.log(` ${" ".repeat(8)}${c.accent(`Run: ${cli.command}`)}`); + console.log(` ${c.bold("Skills".padEnd(8))}${skillsLine(skills)}`); + if (skills.status === "checked" && skills.command) { + console.log(` ${" ".repeat(8)}${c.accent(`Run: ${skills.command}`)}`); + } + console.log(); +} + +function skillsLine(skills: SkillsReport): string { + if (skills.status === "skipped") return c.dim(skills.reason); + if (skills.status === "error") return c.warn(`Could not check: ${skills.error}`); + if (!skills.location) return c.warn("No HyperFrames skills installed"); + const at = skills.ref ? ` at ${skills.ref}` : ""; + if (!skills.updateAvailable) return c.success(`Up to date${at} · ${skills.location}`); + return c.warn( + `${skills.outdated} outdated, ${skills.missing} core missing${at} · ${skills.location}`, + ); +} + +function cliOutcomeLine(cli: UpdateOutcome["cli"]): string { + switch (cli.status) { + case "upgraded": + return c.success(`CLI upgraded to v${cli.version}.`); + case "unchanged": + return c.warn(`CLI stays at v${cli.version}: ${cli.reason}.`); + case "unverified": + return c.warn(`CLI: ran ${cli.command}, but ${cli.reason}.`); + case "manual": + return c.warn(`CLI: run ${cli.command} (${cli.reason}).`); + case "failed": + return c.error(`CLI upgrade failed. Run: ${cli.command}`); + default: + return c.success("CLI is up to date."); + } +} + +function printOutcome(outcome: UpdateOutcome): void { + const { skills } = outcome; + console.log(cliOutcomeLine(outcome.cli)); + if (skills.status === "updated") { + const n = skills.result.installed.length; + console.log( + c.success( + n > 0 + ? `Updated ${n} skill(s): ${skills.result.installed.join(", ")}` + : "Skills are up to date.", + ), + ); + } else if (skills.status === "current") { + console.log(c.success("Skills are up to date.")); + } else if (skills.status === "failed") { + console.log(c.error(`Skills update failed: ${skills.error}`)); + } else { + console.log(c.dim(skills.reason)); + } +} + +interface Mode { + json: boolean; + yes: boolean; +} + +/** + * Whether this run may install. A plugin install refuses (exit 1): the plugin pins the CLI and + * its skills. A run that cannot prompt needs --yes, like `upgrade` (exit 2 otherwise). + */ +function installAllowed(channel: InstallChannel, mode: Mode): boolean { + if (channel === "plugin") { + if (mode.json) { + console.log( + JSON.stringify( + withMeta(jsonFailure("plugin_managed", PLUGIN_REASON), NO_UPDATE_NOTICE), + null, + 2, + ), + ); + } else { + clack.log.error(c.error(PLUGIN_REASON)); + } + setCommandExitCode(1); + return false; + } + if (!mode.yes && (mode.json || isUnattended())) { + clack.confirmationRequired( + "hyperframes update", + "Updating is the person's call; `update --check` only reports.", + ); + } + return true; +} + +/** An attended run without --yes confirms first, and only when there is something to install. */ +async function confirmed(cli: CliReport, skills: SkillsReport, mode: Mode): Promise { + const pending = cli.updateAvailable || (skills.status === "checked" && skills.updateAvailable); + if (mode.yes || mode.json || !pending) return true; + const go = await clack.confirm({ message: "Update now?" }); + if (clack.isCancel(go) || go !== true) { + clack.outro(c.dim("Skipped.")); + return false; + } + return true; +} + +async function installUpdates(cli: CliReport, skills: SkillsReport, mode: Mode): Promise { + if (!mode.json) printCheck(cli, skills); + if (!(await confirmed(cli, skills, mode))) return; + const outcome = await applyUpdate(cli, skills); + if (mode.json) + console.log( + JSON.stringify(withMeta({ cli, skills, updated: outcome }, NO_UPDATE_NOTICE), null, 2), + ); + else printOutcome(outcome); + if (outcome.cli.status === "failed" || outcome.skills.status === "failed") { + setCommandExitCode(1); + } +} + +export default defineCommand({ + meta: { + name: "update", + description: "Check the CLI and the skills for updates in one call, and install them", + }, + args: { + check: { type: "boolean", description: "Only report what is outdated; install nothing" }, + yes: { type: "boolean", alias: "y", description: "Update without prompting" }, + json: { type: "boolean", description: "Output as JSON", default: false }, + }, + async run({ args }) { + const mode: Mode = { json: args.json === true, yes: args.yes === true }; + const install = runningInstall(); + if (args.check !== true && !installAllowed(install.channel, mode)) return; + + const cli = await checkCli(); + const skills = await checkInstalledSkills(cli); + if (args.check === true) { + if (mode.json) + console.log(JSON.stringify(withMeta({ cli, skills }, NO_UPDATE_NOTICE), null, 2)); + else printCheck(cli, skills); + return; + } + await installUpdates(cli, skills, mode); + }, +}); diff --git a/packages/cli/src/commands/updateNotice.commands.test.ts b/packages/cli/src/commands/updateNotice.commands.test.ts new file mode 100644 index 0000000000..b15dc985cf --- /dev/null +++ b/packages/cli/src/commands/updateNotice.commands.test.ts @@ -0,0 +1,100 @@ +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +// The commands whose own output is about updating (`upgrade`, `skills`) never add +// `_meta.updateNotice`, as `cli.ts` keeps the stderr notices away from them; a notice there +// would contradict the result it sits on. +const state = vi.hoisted(() => ({ dir: "" })); +const config = () => ({ + lastUpdateCheck: new Date().toISOString(), + latestVersion: "999.0.0", +}); + +vi.mock("../utils/env.js", () => ({ isDevMode: () => false })); +vi.mock("../telemetry/config.js", async (importOriginal) => ({ + ...(await importOriginal()), + get CONFIG_PATH() { + return join(state.dir, "config.json"); + }, + readConfig: () => config(), + readConfigFresh: () => config(), + writeConfig: () => true, +})); +vi.mock("../utils/skillsManifest.js", async (importOriginal) => ({ + ...(await importOriginal()), + checkSkills: vi.fn(async () => ({ + location: "/home/me/.agents/skills", + agent: null, + scope: "global", + foreign: [], + ref: "v0.9.6", + updateAvailable: false, + skills: [], + summary: { outdated: 0, missing: 0, coreMissing: 0, current: 0 }, + })), +})); + +let stdout: string[] = []; + +beforeEach(() => { + state.dir = mkdtempSync(join(tmpdir(), "hf-notice-commands-")); + vi.stubEnv("CI", ""); + vi.stubEnv("HYPERFRAMES_NO_UPDATE_CHECK", ""); + vi.stubEnv("HYPERFRAMES_PLUGIN_VERSION", ""); + vi.stubGlobal( + "fetch", + vi.fn(async () => new Response(JSON.stringify({ version: "999.0.0" }))), + ); + stdout = []; + vi.spyOn(console, "log").mockImplementation((line: unknown) => { + stdout.push(String(line)); + }); +}); + +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); +}); + +const meta = () => (JSON.parse(stdout.join("\n")) as { _meta: Record })._meta; + +/** citty's `Resolvable`: a value, a promise of it, or a function returning either. */ +async function resolve(value: T | Promise | (() => T | Promise)): Promise { + return typeof value === "function" ? (value as () => T | Promise)() : value; +} + +async function run(path: string, args: Record) { + const { default: cmd } = await import(path); + await cmd.run({ args: { _: [], ...args }, rawArgs: [], cmd }); +} + +describe("_meta.updateNotice on update-related commands", () => { + it("is due here: a plain withMeta in the same state carries it", async () => { + const { withMeta } = await import("../utils/updateCheck.js"); + expect(withMeta({ ok: true })._meta.updateNotice).toMatch(/999\.0\.0/); + }); + + it("is absent from upgrade --json, which reports the same update", async () => { + await run("./upgrade.js", { json: true }); + expect(meta()).toMatchObject({ updateAvailable: true, latestVersion: "999.0.0" }); + expect("updateNotice" in meta()).toBe(false); + }); + + it("is absent from upgrade --project --json", async () => { + await run("./upgrade.js", { json: true, project: state.dir, check: true }); + expect("updateNotice" in meta()).toBe(false); + }); + + it("is absent from skills check --json, which reports the skills itself", async () => { + const { default: skills } = await import("./skills.js"); + const subs = await resolve(skills.subCommands); + const check = await resolve(subs?.["check"]); + if (!check) throw new Error("skills check not found"); + await check.run?.({ args: { _: [], json: true }, rawArgs: [], cmd: check } as never); + expect(meta().updateAvailable).toBe(true); + expect("updateNotice" in meta()).toBe(false); + }); +}); diff --git a/packages/cli/src/commands/upgrade.ts b/packages/cli/src/commands/upgrade.ts index 8f6c3691ed..1f9b02b123 100644 --- a/packages/cli/src/commands/upgrade.ts +++ b/packages/cli/src/commands/upgrade.ts @@ -4,7 +4,7 @@ import type { Example } from "./_examples.js"; import * as clack from "../ui/prompts.js"; import { execFileSync } from "node:child_process"; import { existsSync, readFileSync, writeFileSync, renameSync, readdirSync } from "node:fs"; -import { resolve } from "node:path"; +import { join, resolve } from "node:path"; import { c } from "../ui/colors.js"; import { isUnattended } from "../utils/attendedTerminal.js"; import { rewritePinnedHyperframesText, rewriteProjectPinnedScripts } from "../utils/projectPin.js"; @@ -18,11 +18,16 @@ export const examples: Example[] = [ import { VERSION } from "../version.js"; import { checkForUpdate, + NO_UPDATE_NOTICE, withMeta, isSafeVersion, type UpdateCheckResult, } from "../utils/updateCheck.js"; -import { detectInstaller, installInvocation } from "../utils/installerDetection.js"; +import { + detectInstaller, + installInvocation, + type InstallInvocation, +} from "../utils/installerDetection.js"; export default defineCommand({ meta: { name: "upgrade", description: "Check for updates and show upgrade instructions" }, @@ -45,7 +50,7 @@ export default defineCommand({ const p = resolveProjectArgs(args.project, { check: checkOnly, json: useJson }); const res = await upgradeProjectPins(resolve(p.dir), { json: p.json, check: p.check }); if (p.json) { - console.log(JSON.stringify(withMeta(res), null, 2)); + console.log(JSON.stringify(withMeta(res, NO_UPDATE_NOTICE), null, 2)); return; } printProjectPinResult(res, p.check); @@ -55,7 +60,7 @@ export default defineCommand({ // JSON mode: always force-check and output structured data if (useJson) { const result = await checkForUpdate(true); - console.log(JSON.stringify(withMeta(result), null, 2)); + console.log(JSON.stringify(withMeta(result, NO_UPDATE_NOTICE), null, 2)); return; } @@ -124,24 +129,93 @@ function applyUpgrade(result: UpdateCheckResult, autoYes: boolean): void { return; } - const installer = detectInstaller(); - const invocation = installInvocation(installer.kind, result.latest); - const displayCmd = installer.installCommand(result.latest); - const npxFallback = `npx hyperframes@${result.latest}`; - - // Undetectable / ephemeral (npx, bunx) / project-local / workspace: don't - // guess a manager command; point at the universal npx fallback instead. - if (!invocation || !displayCmd) { - printNpxFallback(installer.reason, npxFallback, autoYes); + const plan = upgradePlan(result.latest); + if ("manual" in plan) { + printNpxFallback(plan.reason, plan.manual, autoYes); return; } if (!autoYes) { - printManualCommands(displayCmd, npxFallback); + printManualCommands(plan.displayCmd, `npx hyperframes@${result.latest}`); return; } - runDetectedInstall(invocation, displayCmd, result.latest); + runDetectedInstall(plan.invocation, plan.displayCmd, result.latest); +} + +const NPX_LATEST = "npx hyperframes@latest"; + +/** + * How `upgrade --yes` moves this install to `latest`: the detected manager's argv, or, for an + * install no manager owns (npx/bunx, project-local, workspace, unknown), the npx line to run + * instead of a guessed manager command. + */ +function upgradePlan( + latest: string, +): + | { invocation: InstallInvocation; displayCmd: string; pinsVersion: boolean } + | { manual: string; reason: string } { + const installer = detectInstaller(); + const invocation = installInvocation(installer.kind, latest); + const displayCmd = installer.installCommand(latest); + if (!invocation || !displayCmd) return { manual: NPX_LATEST, reason: installer.reason }; + return { invocation, displayCmd, pinsVersion: installer.kind !== "brew" }; +} + +export type CliUpgradeOutcome = + | { status: "upgraded"; version: string; command: string } + | { status: "unchanged"; version: string; command: string; reason: string } + | { status: "unverified"; command: string; reason: string } + | { status: "manual"; command: string; reason: string } + | { status: "failed"; command: string }; + +/** The version Homebrew's linked `hyperframes` reports, or null when it cannot be read. */ +function brewInstalledVersion(): string | null { + try { + const prefix = execFileSync("brew", ["--prefix", "hyperframes"], { + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + shell: false, + }).trim(); + const version = execFileSync(join(prefix, "bin", "hyperframes"), ["--version"], { + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + shell: false, + env: { ...process.env, HYPERFRAMES_NO_UPDATE_CHECK: "1", HYPERFRAMES_NO_TELEMETRY: "1" }, + }).trim(); + return isSafeVersion(version) ? version : null; + } catch { + return null; + } +} + +/** + * `upgrade --yes` without its prose, for `hyperframes update`: the same plan and argv, and the + * installer's output goes to stderr so a --json stdout stays one parseable object. + */ +export function upgradeRunningCli(latest: string): CliUpgradeOutcome { + if (!isSafeVersion(latest)) return { status: "failed", command: NPX_LATEST }; + const plan = upgradePlan(latest); + if ("manual" in plan) return { status: "manual", command: plan.manual, reason: plan.reason }; + try { + execFileSync(plan.invocation.bin, plan.invocation.args, { + stdio: ["inherit", 2, 2], + shell: false, + }); + } catch { + return { status: "failed", command: plan.displayCmd }; + } + // `brew upgrade` installs whatever the formula pins, which can lag npm, and exits 0 on a no-op. + const installed = plan.pinsVersion ? latest : brewInstalledVersion(); + const command = plan.displayCmd; + if (installed === null) { + return { status: "unverified", command, reason: "the installed version could not be read" }; + } + if (installed === VERSION) { + const reason = `${command} left ${installed} in place; npm has ${latest}`; + return { status: "unchanged", version: installed, command, reason }; + } + return { status: "upgraded", version: installed, command }; } function printNpxFallback(reason: string, npxFallback: string, autoYes: boolean): void { diff --git a/packages/cli/src/help.ts b/packages/cli/src/help.ts index fe5cf6deda..2a0729b37d 100644 --- a/packages/cli/src/help.ts +++ b/packages/cli/src/help.ts @@ -85,6 +85,7 @@ const GROUPS: Group[] = [ ["doctor", "Check system dependencies and environment"], ["clean", "Find and remove what HyperFrames left on disk"], ["upgrade", "Check for updates and show upgrade instructions"], + ["update", "Check the CLI and the skills for updates in one call, and install them"], ], }, { diff --git a/packages/cli/src/telemetry/config.ts b/packages/cli/src/telemetry/config.ts index 430a5e2d85..c6d69fb63d 100644 --- a/packages/cli/src/telemetry/config.ts +++ b/packages/cli/src/telemetry/config.ts @@ -503,8 +503,10 @@ export interface HyperframesConfig { /** True after the result has been surfaced once to the user. */ reported?: boolean; }; - /** ISO timestamp of the last `skills check` freshness check (24h cache). */ + /** ISO timestamp of the last `skills check` freshness check (2h cache). */ lastSkillsCheck?: string; + /** The CLI version that check ran under: it compared against that version's release tag. */ + skillsCheckedVersion?: string; /** Whether installed skills were stale at the last check. */ skillsUpdateAvailable?: boolean; /** How many installed skills were outdated at the last check. */ @@ -739,6 +741,7 @@ function passthroughFields(parsed: Partial): Partial { expect(spawnedChecks()).toEqual(["update", "skills"]); }); + it("refreshes both caches once they are 3 hours old, and leaves 1-hour-old ones alone", () => { + const at = (hours: number) => new Date(Date.now() - hours * 60 * 60 * 1000).toISOString(); + const caches = (hours: number) => ({ + lastUpdateCheck: at(hours), + latestVersion: "1.0.0", + lastSkillsCheck: at(hours), + skillsCheckedVersion: "0.0.0-dev", + }); + disk.config = caches(1); + launchBackgroundChecks(); + expect(spawn).not.toHaveBeenCalled(); + + disk.config = caches(3); + launchBackgroundChecks(); + expect(spawnedChecks()).toEqual(["update", "skills"]); + }); + it("ignores an attempt stamp dated in the future, as after a clock correction", () => { const later = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(); disk.config = { lastUpdateAttemptAt: later, lastSkillsAttemptAt: later }; diff --git a/packages/cli/src/utils/dailyNotice.test.ts b/packages/cli/src/utils/dailyNotice.test.ts new file mode 100644 index 0000000000..fb096a43ea --- /dev/null +++ b/packages/cli/src/utils/dailyNotice.test.ts @@ -0,0 +1,78 @@ +import { chmodSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const state = vi.hoisted(() => ({ dir: "" })); +vi.mock("../telemetry/config.js", () => ({ + get CONFIG_PATH() { + return join(state.dir, "config.json"); + }, +})); + +import { claimDailyNotice } from "./dailyNotice.js"; + +const NOW = Date.parse("2026-11-04T08:00:00Z"); +const HOUR = 3_600_000; +const noticeFile = () => join(state.dir, "update-notice.json"); +const recorded = () => JSON.parse(readFileSync(noticeFile(), "utf-8")) as Record; + +beforeEach(() => { + state.dir = mkdtempSync(join(tmpdir(), "hf-daily-notice-")); +}); + +describe("claimDailyNotice", () => { + it("claims once a day per project, and each project has its own day", () => { + expect(claimDailyNotice("update", "/work/a", NOW)).toBe(true); + expect(claimDailyNotice("update", "/work/a", NOW + HOUR)).toBe(false); + expect(claimDailyNotice("update", "/work/b", NOW + HOUR)).toBe(true); + expect(claimDailyNotice("update", "/work/a", NOW + 25 * HOUR)).toBe(true); + }); + + it("keeps each kind of notice apart", () => { + expect(claimDailyNotice("skills", "/work/a", NOW)).toBe(true); + expect(claimDailyNotice("update", "/work/a", NOW)).toBe(true); + }); + + it.each([["null"], ["[1, 2]"], ['"text"'], ["42"], ["{not json"]])( + "reads a %s file as no showings, and repairs it on write", + (content) => { + writeFileSync(noticeFile(), content); + expect(claimDailyNotice("update", "/work/a", NOW)).toBe(true); + expect(recorded()).toEqual({ "/work/a": NOW }); + }, + ); + + it("drops entries that are not times", () => { + writeFileSync(noticeFile(), JSON.stringify({ "/work/b": "soon", "/work/c": NOW - HOUR })); + expect(claimDailyNotice("update", "/work/a", NOW)).toBe(true); + expect(recorded()).toEqual({ "/work/c": NOW - HOUR, "/work/a": NOW }); + }); + + // A clock that moved back (or a hand-edited file) must not silence the notice for good. + it("treats a showing in the future as stale, and does not keep it", () => { + writeFileSync( + noticeFile(), + JSON.stringify({ "/work/a": NOW + 48 * HOUR, "/work/b": NOW + HOUR }), + ); + expect(claimDailyNotice("update", "/work/a", NOW)).toBe(true); + expect(recorded()).toEqual({ "/work/a": NOW }); + }); + + it.skipIf(process.platform === "win32")("writes the file private to the user", () => { + claimDailyNotice("update", "/work/a", NOW); + expect(statSync(noticeFile()).mode & 0o777).toBe(0o600); + }); + + it.skipIf(process.platform === "win32" || process.getuid?.() === 0)( + "returns false, without throwing, when the directory cannot be written", + () => { + chmodSync(state.dir, 0o500); + try { + expect(claimDailyNotice("update", "/work/a", NOW)).toBe(false); + } finally { + chmodSync(state.dir, 0o700); + } + }, + ); +}); diff --git a/packages/cli/src/utils/dailyNotice.ts b/packages/cli/src/utils/dailyNotice.ts new file mode 100644 index 0000000000..f9e9417ce2 --- /dev/null +++ b/packages/cli/src/utils/dailyNotice.ts @@ -0,0 +1,42 @@ +import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { CONFIG_PATH } from "../telemetry/config.js"; + +const NOTICE_INTERVAL_MS = 24 * 60 * 60 * 1000; + +/** The recorded showings; anything that is not an object of numbers reads as none. */ +function readShown(noticeFile: string): Record { + let parsed: unknown; + try { + parsed = JSON.parse(readFileSync(noticeFile, "utf-8")); + } catch { + return {}; + } + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {}; + return Object.fromEntries( + Object.entries(parsed).filter((entry): entry is [string, number] => Number.isFinite(entry[1])), + ); +} + +/** Shown within the last day. A time ahead of the clock is not trusted, so it reads as stale. */ +const recent = (at: number, now: number) => at <= now && now - at < NOTICE_INTERVAL_MS; + +/** True at most once a day per project for this kind of notice, recorded in `-notice.json`. */ +export function claimDailyNotice(kind: string, project: string, now = Date.now()): boolean { + const noticeFile = join(dirname(CONFIG_PATH), `${kind}-notice.json`); + const shown = readShown(noticeFile); + if (recent(shown[project] ?? 0, now)) return false; + const kept = Object.entries(shown).filter(([, at]) => recent(at, now)); + const tmp = `${noticeFile}.${process.pid}.tmp`; + try { + mkdirSync(dirname(noticeFile), { recursive: true, mode: 0o700 }); + writeFileSync(tmp, JSON.stringify(Object.fromEntries([...kept, [project, now]])), { + mode: 0o600, + }); + renameSync(tmp, noticeFile); + } catch { + rmSync(tmp, { force: true }); + return false; + } + return true; +} diff --git a/packages/cli/src/utils/installerDetection.test.ts b/packages/cli/src/utils/installerDetection.test.ts index 7c7d67f4c6..8161f02e64 100644 --- a/packages/cli/src/utils/installerDetection.test.ts +++ b/packages/cli/src/utils/installerDetection.test.ts @@ -1,3 +1,6 @@ +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; // The module inspects `process.argv[1]` + `realpathSync`. We stub both so @@ -156,3 +159,107 @@ describe("installInvocation", () => { expect(installInvocation("skip", "1.2.3")).toBeNull(); }); }); + +describe("runningInstall: which binary runs, and the command that updates it", () => { + afterEach(() => { + vi.doUnmock("node:fs"); + vi.resetModules(); + vi.unstubAllEnvs(); + }); + + async function runningAt(realPath: string) { + vi.resetModules(); + vi.stubEnv("HYPERFRAMES_PLUGIN_VERSION", ""); + vi.doMock("node:fs", async () => ({ + ...(await vi.importActual("node:fs")), + realpathSync: () => realPath, + })); + const origArgv1 = process.argv[1]; + process.argv[1] = "/usr/local/bin/hyperframes"; + try { + const mod = await import("./installerDetection.js"); + const install = mod.runningInstall(); + return { + install, + command: mod.updateCommandFor(install, "0.9.8"), + label: mod.installChannelLabel(install.channel), + mod, + }; + } finally { + process.argv[1] = origArgv1 ?? ""; + } + } + + it.each([ + [ + "npm", + "/usr/local/lib/node_modules/hyperframes/dist/cli.js", + "npm install -g hyperframes@0.9.8", + ], + [ + "pnpm", + "/home/me/.local/share/pnpm/global/5/node_modules/hyperframes/dist/cli.js", + "pnpm add -g hyperframes@0.9.8", + ], + [ + "bun", + "/home/me/.bun/install/global/node_modules/hyperframes/dist/cli.js", + "bun add -g hyperframes@0.9.8", + ], + [ + "brew", + "/opt/homebrew/Cellar/hyperframes/0.9.5/libexec/lib/node_modules/hyperframes/dist/cli.js", + "brew upgrade hyperframes", + ], + [ + "npx", + "/home/me/.npm/_npx/4f1c2a/node_modules/hyperframes/dist/cli.js", + "npx hyperframes@latest", + ], + [ + "npx", + "/tmp/bunx-1000-hyperframes@latest/node_modules/hyperframes/dist/cli.js", + "npx hyperframes@latest", + ], + [ + "project", + "/home/me/video/node_modules/hyperframes/dist/cli.js", + "npm install hyperframes@0.9.8", + ], + [ + "project", + "/home/me/video/node_modules/.pnpm/hyperframes@0.9.5/node_modules/hyperframes/dist/cli.js", + "npm install hyperframes@0.9.8", + ], + ["workspace", "/home/me/hyperframes/packages/cli/dist/cli.js", "npx hyperframes@latest"], + ["unknown", "/opt/tools/hyperframes/cli.js", "npx hyperframes@latest"], + ])("classifies a %s install at %s; update with: %s", async (channel, path, command) => { + const run = await runningAt(path); + expect(run.install).toEqual({ channel, path }); + expect(run.command).toBe(command); + expect(run.label).toBeTruthy(); + }); + + // `upgrade --project` only rewrites script pins; the dependency moves with the project's manager. + it.each([ + ["bun.lock", "bun add hyperframes@0.9.8"], + ["bun.lockb", "bun add hyperframes@0.9.8"], + ["pnpm-lock.yaml", "pnpm add hyperframes@0.9.8"], + ["yarn.lock", "yarn add hyperframes@0.9.8"], + ["package-lock.json", "npm install hyperframes@0.9.8"], + ])("moves a project-local CLI with the manager its %s names", async (lockfile, command) => { + const project = mkdtempSync(join(tmpdir(), "hf-project-")); + writeFileSync(join(project, lockfile), ""); + const run = await runningAt(join(project, "node_modules", "hyperframes", "dist", "cli.js")); + expect(run.install.channel).toBe("project"); + expect(run.command).toBe(command); + }); + + it("names a plugin install (plugin-cli.mjs marks its pinned npx child) and never an npx command for it", async () => { + const run = await runningAt("/home/me/.npm/_npx/4f1c2a/node_modules/hyperframes/dist/cli.js"); + vi.stubEnv("HYPERFRAMES_PLUGIN_VERSION", "0.9.5"); + const install = run.mod.runningInstall(); + expect(install.channel).toBe("plugin"); + expect(run.mod.updateCommandFor(install, "0.9.8")).toMatch(/plugin/); + }); +}); diff --git a/packages/cli/src/utils/installerDetection.ts b/packages/cli/src/utils/installerDetection.ts index 1ba3bbd340..eb113b7e7e 100644 --- a/packages/cli/src/utils/installerDetection.ts +++ b/packages/cli/src/utils/installerDetection.ts @@ -6,8 +6,9 @@ * in charge. */ -import { realpathSync } from "node:fs"; +import { existsSync, realpathSync } from "node:fs"; import { posix } from "node:path"; +import { isSafeVersion } from "./safeVersion.js"; export type InstallerKind = "npm" | "bun" | "pnpm" | "brew" | "skip"; @@ -59,7 +60,9 @@ function isEphemeralExec(realEntry: string): boolean { return ( normalized.includes("/_npx/") || normalized.includes("/.npm/_npx/") || - posix.basename(posix.dirname(normalized)).startsWith("bunx-") + posix.basename(posix.dirname(normalized)).startsWith("bunx-") || + // bunx installs the package under its temp dir: `/tmp/bunx--/node_modules/…`. + /\/bunx-[^/]+\/node_modules\//.test(normalized) ); } @@ -187,3 +190,96 @@ export function installInvocation(kind: InstallerKind, version: string): Install return null; } } + +/** + * Where the running binary came from, as `doctor` and `update` report it. Unlike + * {@link detectInstaller}, which only answers "can a background install own this?", + * this names every layout, including the ones auto-update leaves alone. + */ +export type InstallChannel = + | "npm" + | "pnpm" + | "bun" + | "brew" + | "npx" + | "project" + | "workspace" + | "plugin" + | "unknown"; + +export interface RunningInstall { + channel: InstallChannel; + /** The resolved entry script that is running, or null when it cannot be resolved. */ + path: string | null; +} + +const CHANNEL_LABELS: Record = { + npm: "npm global install", + pnpm: "pnpm global install", + bun: "bun global install", + brew: "Homebrew install", + npx: "npx / bunx (temporary cache)", + project: "project-local install (node_modules)", + workspace: "workspace link (monorepo dev)", + plugin: "agent plugin (version pinned by the plugin)", + unknown: "unrecognized install layout", +}; + +/** Human label for a channel, e.g. "npm global install". */ +export function installChannelLabel(channel: InstallChannel): string { + return CHANNEL_LABELS[channel]; +} + +/** Classify the running binary: global (per manager), project-local, npx, workspace link or plugin. */ +export function runningInstall(): RunningInstall { + const path = resolveEntry(); + // plugin-cli.mjs runs a pinned `npx hyperframes@` and marks the child with this. + if (process.env["HYPERFRAMES_PLUGIN_VERSION"]) return { channel: "plugin", path }; + const installer = detectInstaller(); + if (installer.kind !== "skip") return { channel: installer.kind, path }; + if (!path) return { channel: "unknown", path }; + if (isWorkspaceLink(path)) return { channel: "workspace", path }; + if (isEphemeralExec(path)) return { channel: "npx", path }; + if (normalizePath(path).includes("/node_modules/hyperframes/")) { + return { channel: "project", path }; + } + return { channel: "unknown", path }; +} + +const PROJECT_LOCKFILES: [string, (spec: string) => string][] = [ + ["bun.lock", (spec) => `bun add ${spec}`], + ["bun.lockb", (spec) => `bun add ${spec}`], + ["pnpm-lock.yaml", (spec) => `pnpm add ${spec}`], + ["yarn.lock", (spec) => `yarn add ${spec}`], +]; + +/** + * What moves a project-local CLI: its project's manager (named by the lockfile beside the + * project's `node_modules`, npm without one) adding `hyperframes@`. Each of the four + * keeps the dependency in the section it is in. `upgrade --project` only rewrites script pins. + */ +function projectInstallCommand(path: string, version: string): string { + const normalized = normalizePath(path); + const root = normalized.slice(0, normalized.indexOf("/node_modules/")); + const spec = `hyperframes@${version}`; + const lockfile = PROJECT_LOCKFILES.find(([name]) => existsSync(posix.join(root, name))); + return lockfile ? lockfile[1](spec) : `npm install ${spec}`; +} + +/** + * The command that moves this install to `latest`: the owning manager's for a global or + * project-local install, `npx hyperframes@latest` everywhere a manager command would not apply. + */ +export function updateCommandFor(install: RunningInstall, latest: string): string { + if (install.channel === "plugin") return "update the HyperFrames plugin in your agent"; + if (install.channel === "brew") return "brew upgrade hyperframes"; + if (install.channel === "project" && install.path && isSafeVersion(latest)) { + return projectInstallCommand(install.path, latest); + } + const kind = install.channel; + if (kind === "npm" || kind === "pnpm" || kind === "bun") { + const invocation = installInvocation(kind, latest); + if (invocation) return `${invocation.bin} ${invocation.args.join(" ")}`; + } + return "npx hyperframes@latest"; +} diff --git a/packages/cli/src/utils/skillsUpdateCheck.test.ts b/packages/cli/src/utils/skillsUpdateCheck.test.ts index 8a93c12e89..4d73b3cc2f 100644 --- a/packages/cli/src/utils/skillsUpdateCheck.test.ts +++ b/packages/cli/src/utils/skillsUpdateCheck.test.ts @@ -69,6 +69,44 @@ describe("skillsUpdateCheck", () => { expect(skillsCheckDue()).toBe(false); }); + describe("cache freshness: 2 hours, and only for this CLI's release tag", () => { + const hoursAgo = (h: number) => new Date(Date.now() - h * 3_600_000).toISOString(); + + it.each([ + [ + "an hour-old check by this CLI", + { lastSkillsCheck: hoursAgo(1), skillsCheckedVersion: "0.0.0-dev" }, + false, + ], + [ + "a 3-hour-old check", + { lastSkillsCheck: hoursAgo(3), skillsCheckedVersion: "0.0.0-dev" }, + true, + ], + [ + "a fresh check taken by another CLI version", + { lastSkillsCheck: hoursAgo(1), skillsCheckedVersion: "0.9.4" }, + true, + ], + ["a fresh check that predates version stamping", { lastSkillsCheck: hoursAgo(1) }, true], + ])("with %s, a background check is due: %s", async (_, cache, due) => { + config = cache; + const { skillsCheckDue } = await import("./skillsUpdateCheck.js"); + expect(skillsCheckDue()).toBe(due); + }); + + it("refreshSkillsCache stamps the CLI version whose tag it compared against", async () => { + mockCheckSkills.mockResolvedValue({ + location: "/home/user/.claude/skills", + updateAvailable: true, + summary: { current: 1, outdated: 2, missing: 0, coreMissing: 0 }, + }); + const { refreshSkillsCache } = await import("./skillsUpdateCheck.js"); + await refreshSkillsCache(); + expect(config).toMatchObject({ skillsCheckedVersion: "0.0.0-dev", skillsOutdatedCount: 2 }); + }); + }); + it("a run without a TTY (an agent) still has its background check due", async () => { gate.noTty = true; const { skillsCheckDue } = await import("./skillsUpdateCheck.js"); @@ -162,6 +200,21 @@ describe("skillsUpdateCheck", () => { expect(await noticeTextFor(stale, "/projects/b")).toContain("2 HyperFrames skills"); }); + // The cache now refreshes every 2 h; the printed nudge must not follow it. + it("still prints at most once a day per project when the cache refreshes 3 hours later", async () => { + vi.useFakeTimers({ now: new Date("2026-11-03T08:00:00Z"), toFake: ["Date"] }); + try { + const stale = { skillsOutdatedCount: 2, skillsMissingCount: 0 }; + expect(await noticeTextFor(stale, "/projects/a")).toContain("2 HyperFrames skills"); + vi.setSystemTime(new Date("2026-11-03T11:00:00Z")); + expect(await noticeTextFor(stale, "/projects/a")).toBeNull(); + vi.setSystemTime(new Date("2026-11-04T08:00:01Z")); + expect(await noticeTextFor(stale, "/projects/a")).toContain("2 HyperFrames skills"); + } finally { + vi.useRealTimers(); + } + }); + it("unattended, says nothing about skills that are only outdated", async () => { gate.unattended = true; expect(await noticeTextFor({ skillsOutdatedCount: 3, skillsMissingCount: 0 })).toBeNull(); @@ -194,7 +247,8 @@ describe("skillsUpdateCheck", () => { // verdict so the next command re-checks for real. describe("invalidateSkillsCache", () => { const PRE_INSTALL_CACHE = { - lastSkillsCheck: new Date().toISOString(), // fresh — inside the 24h TTL + lastSkillsCheck: new Date().toISOString(), // fresh — inside the 2h TTL + skillsCheckedVersion: "0.0.0-dev", // taken by this CLI (the version under test) skillsUpdateAvailable: true, skillsOutdatedCount: 12, skillsMissingCount: 8, diff --git a/packages/cli/src/utils/skillsUpdateCheck.ts b/packages/cli/src/utils/skillsUpdateCheck.ts index e25bb18e49..c9f5b2af55 100644 --- a/packages/cli/src/utils/skillsUpdateCheck.ts +++ b/packages/cli/src/utils/skillsUpdateCheck.ts @@ -1,21 +1,21 @@ // Passive "your skills are stale" nudge. Mirrors updateCheck.ts: a background -// check populates a 24h cache; printSkillsUpdateNotice() reads the cache -// synchronously and prints one line on exit. +// check populates a 2h cache; printSkillsUpdateNotice() reads the cache +// synchronously and prints one line on exit, at most once a day per project. // // Why a passive nudge (not just `skills check`): agents don't reliably run a // check on their own, but they DO run render/lint/validate — so we piggyback // the reminder on the commands they already run. -import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; -import { dirname, join, resolve } from "node:path"; -import { CONFIG_PATH, readConfig, readConfigFresh, writeConfig } from "../telemetry/config.js"; +import { resolve } from "node:path"; +import { readConfig, readConfigFresh, writeConfig } from "../telemetry/config.js"; import { isUnattended } from "./attendedTerminal.js"; +import { claimDailyNotice } from "./dailyNotice.js"; import { hostAnswers } from "./hostAnswers.js"; -import { checkSkills } from "./skillsManifest.js"; +import { checkSkills, type SkillsCheckResult } from "./skillsManifest.js"; import { updateCheckDisabled } from "./updateCheck.js"; import { VERSION } from "../version.js"; -const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours +const CHECK_INTERVAL_MS = 2 * 60 * 60 * 1000; interface SkillsUpdateMeta { updateAvailable: boolean; @@ -33,9 +33,9 @@ function getSkillsUpdateMeta(): SkillsUpdateMeta { }; } -function cacheFresh(lastSkillsCheck: string | undefined, now: number): boolean { - if (!lastSkillsCheck) return false; - return now - new Date(lastSkillsCheck).getTime() < CHECK_INTERVAL_MS; +function cacheFresh(config: ReturnType, now: number): boolean { + if (!config.lastSkillsCheck || config.skillsCheckedVersion !== VERSION) return false; + return now - new Date(config.lastSkillsCheck).getTime() < CHECK_INTERVAL_MS; } /** Run the real check and persist the result to the cache. Skipped when DNS does not answer. */ @@ -44,19 +44,23 @@ export async function refreshSkillsCache(): Promise { // `canonical: true` so this nudge's counts agree with `updateSkills`'s // source of truth — otherwise a stale in-repo skills-manifest.json (e.g. // inside a hyperframes checkout) can produce a false-positive count here. - const result = await checkSkills({ canonical: true, cliVersion: VERSION }); + recordSkillsCheck(await checkSkills({ canonical: true, cliVersion: VERSION })); +} + +/** Cache a canonical skills check (at this CLI's tag) for the nudge and `_meta.skillsOutdated`. */ +export function recordSkillsCheck(result: SkillsCheckResult): void { // Only record a meaningful check when skills were actually found. - if (result.location) { - // Fresh read: this runs in a background child, beside the command's own config writes. - const config = readConfigFresh(); - config.lastSkillsCheck = new Date().toISOString(); - config.skillsUpdateAvailable = result.updateAvailable; - config.skillsOutdatedCount = result.summary.outdated; - // Core-missing only: skills that install on demand (workflows not yet - // triggered on this machine) are not "missing" worth nagging about. - config.skillsMissingCount = result.summary.coreMissing; - writeConfig(config); - } + if (!result.location) return; + // Fresh read: this runs in a background child, beside the command's own config writes. + const config = readConfigFresh(); + config.lastSkillsCheck = new Date().toISOString(); + config.skillsCheckedVersion = VERSION; + config.skillsUpdateAvailable = result.updateAvailable; + config.skillsOutdatedCount = result.summary.outdated; + // Core-missing only: skills that install on demand (workflows not yet + // triggered on this machine) are not "missing" worth nagging about. + config.skillsMissingCount = result.summary.coreMissing; + writeConfig(config); } /** @@ -67,7 +71,7 @@ export async function refreshSkillsCache(): Promise { * the install. Those commands are excluded from the nudge pipeline entirely * (see cli.ts), so nothing else refreshes the cache when they run — without * this, the last background verdict (taken BEFORE the install) keeps printing - * "N skills out of date or missing" on every other command for up to 24h + * "N skills out of date or missing" on every other command for up to 2h * after a successful install/update. * * Counts are cleared along with the timestamp — not left behind — so an @@ -83,6 +87,7 @@ export function invalidateSkillsCache(): void { // running CLI process that wrote other config fields in the meantime. const config = readConfigFresh(); delete config.lastSkillsCheck; + delete config.skillsCheckedVersion; delete config.skillsUpdateAvailable; delete config.skillsOutdatedCount; delete config.skillsMissingCount; @@ -97,30 +102,10 @@ function skillsNoticeOff(): boolean { return process.env["HYPERFRAMES_SKIP_SKILLS"] === "1" || updateCheckDisabled(); } -/** Whether a background skills check is due: this run shows notices and the 24 h cache is stale. */ +/** Whether a background skills check is due: this run shows notices and the 2 h cache is stale. */ export function skillsCheckDue(): boolean { if (skillsNoticeOff()) return false; - return !cacheFresh(readConfig().lastSkillsCheck, Date.now()); -} - -/** True at most once a day per project; records the showing. Unreadable state counts as never shown. */ -function claimDailyNotice(project: string, now = Date.now()): boolean { - const noticeFile = join(dirname(CONFIG_PATH), "skills-notice.json"); - let shown: Record = {}; - try { - shown = JSON.parse(readFileSync(noticeFile, "utf-8")) as Record; - } catch { - // first notice, or a damaged file that the write below replaces - } - if (now - (shown[project] ?? 0) < CHECK_INTERVAL_MS) return false; - const kept = Object.entries(shown).filter(([, at]) => now - at < CHECK_INTERVAL_MS); - try { - mkdirSync(dirname(noticeFile), { recursive: true, mode: 0o700 }); - writeFileSync(noticeFile, JSON.stringify(Object.fromEntries([...kept, [project, now]]))); - } catch { - return false; - } - return true; + return !cacheFresh(readConfig(), Date.now()); } /** The stale-skills nudge text, or null when nothing is outdated or missing. */ @@ -140,5 +125,5 @@ export function printSkillsUpdateNotice(cwd: string = process.cwd()): void { if (skillsNoticeOff()) return; const meta = getSkillsUpdateMeta(); const text = skillsNoticeText(isUnattended() ? { ...meta, outdated: 0 } : meta); - if (text && claimDailyNotice(resolve(cwd))) process.stderr.write(text); + if (text && claimDailyNotice("skills", resolve(cwd))) process.stderr.write(text); } diff --git a/packages/cli/src/utils/updateCheck.test.ts b/packages/cli/src/utils/updateCheck.test.ts index ef6d27ebc6..9052323ded 100644 --- a/packages/cli/src/utils/updateCheck.test.ts +++ b/packages/cli/src/utils/updateCheck.test.ts @@ -1,3 +1,6 @@ +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import { isSafeVersion, printDeprecationNotice, withMeta } from "./updateCheck.js"; @@ -400,20 +403,29 @@ describe("checkForUpdate — registry boundary guard", () => { }); describe("updateCheckDue / cachedUpdateCheck — what the parent reads without fetching", () => { + // The directory that holds the daily notice claims: a fresh one per load(). + let stateDir = ""; + afterEach(() => { vi.doUnmock("../telemetry/config.js"); vi.doUnmock("./env.js"); vi.doUnmock("../version.js"); + vi.doUnmock("./installerDetection.js"); vi.resetModules(); vi.unstubAllEnvs(); + vi.useRealTimers(); }); async function load(config: Record) { vi.resetModules(); vi.stubEnv("CI", ""); vi.stubEnv("HYPERFRAMES_NO_UPDATE_CHECK", ""); + vi.stubEnv("HYPERFRAMES_PLUGIN_VERSION", ""); + vi.stubEnv("HYPERFRAMES_SKIP_SKILLS", ""); + stateDir = mkdtempSync(join(tmpdir(), "hf-update-notice-")); vi.doMock("./env.js", () => ({ isDevMode: () => false })); vi.doMock("../telemetry/config.js", () => ({ + CONFIG_PATH: join(stateDir, "config.json"), readConfig: () => ({ ...config }), readConfigFresh: () => ({ ...config }), writeConfig: () => {}, @@ -438,6 +450,280 @@ describe("updateCheckDue / cachedUpdateCheck — what the parent reads without f expect(mod.updateCheckDue()).toBe(due); }); + // A release reaches agents within hours: the cache answers for 2 h, not a day. + it("re-asks the registry once the cache is 3 hours old", async () => { + const mod = await load({ lastUpdateCheck: hoursAgo(3), latestVersion: "9.9.9" }); + expect(mod.updateCheckDue()).toBe(true); + }); + + it("says in _meta when the cached latest was checked", async () => { + const checkedAt = hoursAgo(1); + const mod = await load({ lastUpdateCheck: checkedAt, latestVersion: "999.0.0" }); + expect(mod.getUpdateMeta()).toMatchObject({ latestVersion: "999.0.0", checkedAt }); + }); + + describe("_meta.skillsOutdated, from the cached background skills check", () => { + const skillsCache = (over: Record = {}) => ({ + lastSkillsCheck: hoursAgo(1), + skillsCheckedVersion: "0.9.6", + skillsOutdatedCount: 3, + skillsMissingCount: 0, + ...over, + }); + const loadAt096 = (config: Record) => { + vi.doMock("../version.js", () => ({ VERSION: "0.9.6", PRODUCER_VERSION: "0.9.6" })); + return load(config); + }; + + it("reports the count without a network call", async () => { + const fetchSpy = vi.fn(); + vi.stubGlobal("fetch", fetchSpy); + try { + const mod = await loadAt096(skillsCache()); + expect(mod.withMeta({ ok: true })._meta.skillsOutdated).toBe(3); + expect(fetchSpy).not.toHaveBeenCalled(); + } finally { + vi.unstubAllGlobals(); + } + }); + + it("still reports a count taken 23 hours ago", async () => { + const mod = await loadAt096(skillsCache({ lastSkillsCheck: hoursAgo(23) })); + expect(mod.getUpdateMeta().skillsOutdated).toBe(3); + }); + + it("reports zero when the check found everything current", async () => { + const mod = await loadAt096(skillsCache({ skillsOutdatedCount: 0 })); + expect(mod.getUpdateMeta().skillsOutdated).toBe(0); + }); + + it.each([ + ["no skills check is cached", {}], + [ + "the check ran under another CLI version (another release tag)", + skillsCache({ skillsCheckedVersion: "0.9.5" }), + ], + ["the cached count is not a count", skillsCache({ skillsOutdatedCount: "3" })], + // Nothing refreshes the count once HYPERFRAMES_NO_UPDATE_CHECK (or CI/dev) stops the checks. + ["the check is over a day old", skillsCache({ lastSkillsCheck: hoursAgo(25) })], + ])("is absent when %s", async (_, config) => { + const mod = await loadAt096(config); + expect("skillsOutdated" in mod.getUpdateMeta()).toBe(false); + }); + + it("is absent when HYPERFRAMES_SKIP_SKILLS hands the skills to something else", async () => { + const mod = await loadAt096(skillsCache()); + vi.stubEnv("HYPERFRAMES_SKIP_SKILLS", "1"); + expect("skillsOutdated" in mod.getUpdateMeta()).toBe(false); + }); + + it("reports missing core skills as skillsMissing, beside skillsOutdated", async () => { + const mod = await loadAt096(skillsCache({ skillsMissingCount: 2 })); + expect(mod.getUpdateMeta()).toMatchObject({ skillsOutdated: 3, skillsMissing: 2 }); + }); + + it.each([ + [ + "the check is over a day old", + skillsCache({ skillsMissingCount: 2, lastSkillsCheck: hoursAgo(25) }), + ], + [ + "the check ran under another CLI version", + skillsCache({ skillsMissingCount: 2, skillsCheckedVersion: "0.9.5" }), + ], + ["the cached count is not a count", skillsCache({ skillsMissingCount: -1 })], + ])("leaves skillsMissing out when %s", async (_, config) => { + const mod = await loadAt096(config); + expect("skillsMissing" in mod.getUpdateMeta()).toBe(false); + }); + + it("leaves skillsMissing out under HYPERFRAMES_SKIP_SKILLS", async () => { + const mod = await loadAt096(skillsCache({ skillsMissingCount: 2 })); + vi.stubEnv("HYPERFRAMES_SKIP_SKILLS", "1"); + expect("skillsMissing" in mod.getUpdateMeta()).toBe(false); + }); + }); + + // The agent relays this sentence to the person, who decides whether to update; no skill text + // tells the agent to run an update itself. + describe("_meta.updateNotice, for the agent to pass on to the person", () => { + const behind = (over: Record = {}) => ({ + lastUpdateCheck: hoursAgo(1), + latestVersion: "0.9.8", + lastSkillsCheck: hoursAgo(1), + skillsCheckedVersion: "0.9.6", + skillsOutdatedCount: 3, + skillsMissingCount: 0, + ...over, + }); + const loadNotice = ( + config: Record, + channel = "npm", + path = "/test/lib/node_modules/hyperframes/dist/cli.js", + ) => { + vi.doMock("../version.js", () => ({ VERSION: "0.9.6", PRODUCER_VERSION: "0.9.6" })); + vi.doMock("./installerDetection.js", async (importOriginal) => ({ + ...(await importOriginal()), + runningInstall: () => ({ channel, path }), + })); + return load(config); + }; + + it("names the newer CLI, the skills behind, and the one command that updates both", async () => { + const mod = await loadNotice(behind()); + expect(mod.withMeta({ ok: true })._meta.updateNotice).toBe( + "For the user: HyperFrames CLI 0.9.8 is available (this run is 0.9.6), and 3 installed HyperFrames skills are out of date. To update both, run: hyperframes update", + ); + }); + + it("counts missing core skills in the skills half", async () => { + const mod = await loadNotice(behind({ skillsOutdatedCount: 1, skillsMissingCount: 2 })); + expect(mod.withMeta({ ok: true })._meta.updateNotice).toContain( + "1 installed HyperFrames skill is out of date and 2 core skills are missing.", + ); + }); + + it("speaks of the skills alone when the CLI is current", async () => { + const mod = await loadNotice(behind({ latestVersion: "0.9.6" })); + expect(mod.withMeta({ ok: true })._meta.updateNotice).toBe( + "For the user: 3 installed HyperFrames skills are out of date (this run is HyperFrames CLI 0.9.6). To update them, run: hyperframes update", + ); + }); + + it("leaves out the skills half when no skill is behind", async () => { + const mod = await loadNotice(behind({ skillsOutdatedCount: 0 })); + expect(mod.withMeta({ ok: true })._meta.updateNotice).toBe( + "For the user: HyperFrames CLI 0.9.8 is available (this run is 0.9.6). To update, run: npm install -g hyperframes@0.9.8", + ); + }); + + it("leaves out the skills half under HYPERFRAMES_SKIP_SKILLS", async () => { + const mod = await loadNotice(behind()); + vi.stubEnv("HYPERFRAMES_SKIP_SKILLS", "1"); + const notice = mod.withMeta({ ok: true })._meta.updateNotice; + expect(notice).toBe( + "For the user: HyperFrames CLI 0.9.8 is available (this run is 0.9.6). To update, run: npm install -g hyperframes@0.9.8", + ); + }); + + // Each command moves the install that is running: a global CLI's own `update` (npx would run a + // project's copy or a fresh one), a project's manager for a project-local CLI. + const PROJECT = "/test/video/node_modules/hyperframes/dist/cli.js"; + it.each([ + [ + "npm", + undefined, + "hyperframes update", + "npm install -g hyperframes@0.9.8", + "hyperframes update", + ], + [ + "pnpm", + undefined, + "hyperframes update", + "pnpm add -g hyperframes@0.9.8", + "hyperframes update", + ], + [ + "bun", + undefined, + "hyperframes update", + "bun add -g hyperframes@0.9.8", + "hyperframes update", + ], + ["brew", undefined, "hyperframes update", "brew upgrade hyperframes", "hyperframes update"], + [ + "project", + PROJECT, + "npm install hyperframes@0.9.8, then npx hyperframes update", + "npm install hyperframes@0.9.8", + "npx hyperframes update", + ], + [ + "npx", + undefined, + "npx hyperframes@latest update", + "npx hyperframes@latest update", + "npx hyperframes update", + ], + [ + "unknown", + undefined, + "npx hyperframes update", + "npx hyperframes update", + "npx hyperframes update", + ], + ])( + "%s: names a command that moves this install", + async (channel, path, both, cliOnly, skillsOnly) => { + const cases: [Record, string][] = [ + [behind(), both], + [behind({ skillsOutdatedCount: 0 }), cliOnly], + [behind({ latestVersion: "0.9.6" }), skillsOnly], + ]; + for (const [config, command] of cases) { + const mod = await loadNotice(config, channel, path); + expect(mod.withMeta({ ok: true })._meta.updateNotice).toMatch( + new RegExp(`run: ${command.replaceAll(".", "\\.")}$`), + ); + } + }, + ); + + it.each([ + ["the update check is off", { HYPERFRAMES_NO_UPDATE_CHECK: "1" }], + ["CI runs it", { CI: "1" }], + ["an agent plugin pins the CLI", { HYPERFRAMES_PLUGIN_VERSION: "0.9.6" }], + ])("is absent when %s", async (_, env) => { + const mod = await loadNotice(behind()); + for (const [k, v] of Object.entries(env)) vi.stubEnv(k, v); + expect("updateNotice" in mod.withMeta({ ok: true })._meta).toBe(false); + }); + + it("is absent when nothing is behind", async () => { + const mod = await loadNotice(behind({ latestVersion: "0.9.6", skillsOutdatedCount: 0 })); + expect("updateNotice" in mod.withMeta({ ok: true })._meta).toBe(false); + }); + + it("is absent when the caller opts out (`update` names its own command)", async () => { + const mod = await loadNotice(behind()); + expect("updateNotice" in mod.withMeta({ ok: true }, { updateNotice: false })._meta).toBe( + false, + ); + }); + + it("shows once a day per project; the numeric fields stay on every result", async () => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(new Date("2026-11-03T08:00:00Z")); + const at = (h: number) => + new Date(Date.parse("2026-11-03T08:00:00Z") - h * 3_600_000).toISOString(); + const mod = await loadNotice(behind({ lastUpdateCheck: at(1), lastSkillsCheck: at(1) })); + + const first = mod.withMeta({ ok: true })._meta; + expect(first.updateNotice).toEqual(expect.any(String)); + const again = mod.withMeta({ ok: true })._meta; + expect("updateNotice" in again).toBe(false); + expect(again).toMatchObject({ + updateAvailable: true, + latestVersion: "0.9.8", + skillsOutdated: 3, + }); + expect(again.checkedAt).toEqual(expect.any(String)); + + vi.setSystemTime(new Date("2026-11-04T08:30:00Z")); + expect(mod.withMeta({ ok: true })._meta.updateNotice).toEqual(expect.any(String)); + }); + + it("keeps its own daily claim, apart from the stderr skills nudge", async () => { + const mod = await loadNotice(behind()); + writeFileSync( + join(stateDir, "skills-notice.json"), + JSON.stringify({ [resolve(process.cwd())]: Date.now() }), + ); + expect(mod.withMeta({ ok: true })._meta.updateNotice).toEqual(expect.any(String)); + }); + }); + it("is never due under CI", async () => { const mod = await load({}); vi.stubEnv("CI", "1"); @@ -471,10 +757,13 @@ describe("updateCheckDue / cachedUpdateCheck — what the parent reads without f }, ); - it("treats a cached latest older than the running CLI as unknown, without re-checking sooner than the daily cadence", async () => { + // The cache predates this install (an upgrade happened since), so however recent, it is + // stale: the next background check asks the registry (launchBackgroundChecks' 1 h + // failure backoff still bounds how often). + it("treats a cached latest older than the running CLI as unknown, and as due for a recheck now", async () => { vi.doMock("../version.js", () => ({ VERSION: "0.9.6", PRODUCER_VERSION: "0.9.6" })); const mod = await load({ lastUpdateCheck: hoursAgo(1), latestVersion: "0.9.5" }); - expect(mod.updateCheckDue()).toBe(false); + expect(mod.updateCheckDue()).toBe(true); expect(mod.getUpdateMeta()).toEqual({ version: "0.9.6", latestVersion: undefined, diff --git a/packages/cli/src/utils/updateCheck.ts b/packages/cli/src/utils/updateCheck.ts index e36b37a967..74de0042f4 100644 --- a/packages/cli/src/utils/updateCheck.ts +++ b/packages/cli/src/utils/updateCheck.ts @@ -1,5 +1,5 @@ import { existsSync, readFileSync } from "node:fs"; -import { join } from "node:path"; +import { join, resolve } from "node:path"; import { compareVersions } from "compare-versions"; import { readConfig, readConfigFresh, writeConfig } from "../telemetry/config.js"; import { VERSION } from "../version.js"; @@ -7,14 +7,22 @@ import { isCI, isUnattended } from "./attendedTerminal.js"; import { isDevMode } from "./env.js"; import { asNotice } from "./jsonError.js"; import { hostAnswers } from "./hostAnswers.js"; -import { detectInstaller } from "./installerDetection.js"; +import { claimDailyNotice } from "./dailyNotice.js"; +import { + detectInstaller, + runningInstall, + updateCommandFor, + type InstallChannel, + type RunningInstall, +} from "./installerDetection.js"; import { readPinnedHyperframesVersions } from "./projectPin.js"; import { isSafeVersion } from "./safeVersion.js"; export { isSafeVersion } from "./safeVersion.js"; const NPM_REGISTRY_URL = "https://registry.npmjs.org/hyperframes/latest"; -const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours +const CHECK_INTERVAL_MS = 2 * 60 * 60 * 1000; +const SKILLS_COUNT_MAX_AGE_MS = 24 * 60 * 60 * 1000; const FETCH_TIMEOUT_MS = 3000; /** Returns true if `a` is newer than `b` per semver (handles alpha, beta, rc). */ @@ -36,12 +44,23 @@ export interface UpdateMeta { version: string; latestVersion?: string; updateAvailable: boolean; + /** When the registry gave `latestVersion` (ISO). Absent when no usable answer is cached. */ + checkedAt?: string; + /** Installed skills behind this CLI's release tag, per the cached background check. */ + skillsOutdated?: number; + /** Core skills not installed, from the same cached check and under the same rules as `skillsOutdated`. */ + skillsMissing?: number; + /** + * One sentence for the agent to pass on to the person: a newer CLI or skills, and the command + * that updates them. Added by `withMeta` at most once a day per project; absent otherwise. + */ + updateNotice?: string; /** Present (and true) only for commands superseded by `check`; absent otherwise. */ deprecated?: boolean; } /** - * Check npm registry for the latest version. Uses a 24h cache to avoid + * Check npm registry for the latest version. Uses a 2h cache to avoid * hitting the registry on every invocation. * * @param force - Skip the cache, opt-outs and DNS probe: the caller waits for the registry @@ -93,10 +112,14 @@ export async function checkForUpdate(force?: boolean): Promise, + count: unknown, +): number | undefined { + if (process.env["HYPERFRAMES_SKIP_SKILLS"] === "1") return undefined; + if (!config.lastSkillsCheck || config.skillsCheckedVersion !== VERSION) return undefined; + const age = Date.now() - new Date(config.lastSkillsCheck).getTime(); + if (!(age >= 0 && age < SKILLS_COUNT_MAX_AGE_MS)) return undefined; + return typeof count === "number" && Number.isInteger(count) && count >= 0 ? count : undefined; +} + +/** "3 installed HyperFrames skills are out of date and 1 core skill is missing", or null. */ +function skillsBehindPhrase(meta: UpdateMeta): string | null { + const outdated = meta.skillsOutdated ?? 0; + const missing = meta.skillsMissing ?? 0; + const parts: string[] = []; + if (outdated > 0) { + parts.push( + `${outdated} installed HyperFrames ${outdated === 1 ? "skill is" : "skills are"} out of date`, + ); + } + if (missing > 0) { + const which = outdated > 0 ? "core" : "core HyperFrames"; + parts.push(`${missing} ${which} ${missing === 1 ? "skill is" : "skills are"} missing`); + } + return parts.length > 0 ? parts.join(" and ") : null; +} + +const GLOBAL_CHANNELS: ReadonlySet = new Set(["npm", "pnpm", "bun", "brew"]); + +/** A project-local CLI moves with its project's manager; `update` there then only does the skills. */ +function projectNoticeCommand( + install: RunningInstall, + cliBehind: boolean, + skillsBehind: boolean, + latest: string, +): string { + if (!cliBehind) return "npx hyperframes update"; + const bump = updateCommandFor(install, latest); + return skillsBehind ? `${bump}, then npx hyperframes update` : bump; +} + +/** + * A command that moves THIS install. A global CLI runs its own `hyperframes update` (or just its + * manager's command when only the CLI is behind): `npx hyperframes` would run a project's copy or + * a fresh npx one instead. An npx run pins `@latest`, since npx's cache can hold the old CLI. + */ +export function updateCommandForThisInstall( + cliBehind: boolean, + skillsBehind: boolean, + latest: string, +): string { + const install = runningInstall(); + if (GLOBAL_CHANNELS.has(install.channel)) { + return skillsBehind ? "hyperframes update" : updateCommandFor(install, latest); + } + if (install.channel === "project") { + return projectNoticeCommand(install, cliBehind, skillsBehind, latest); + } + return install.channel === "npx" && cliBehind + ? "npx hyperframes@latest update" + : "npx hyperframes update"; +} + +/** The sentence itself: the newer CLI, the skills behind, or both, and the command. */ +function noticeSentence( + version: string, + latest: string | null, + skills: string | null, + command: string, +): string { + const cli = latest ? `HyperFrames CLI ${latest} is available (this run is ${version})` : null; + if (cli && skills) return `For the user: ${cli}, and ${skills}. To update both, run: ${command}`; + if (cli) return `For the user: ${cli}. To update, run: ${command}`; + return `For the user: ${skills} (this run is HyperFrames CLI ${version}). To update them, run: ${command}`; +} + +/** The update notice for this run's `_meta`, before the once-a-day gate; null when there is nothing to say. */ +function updateNoticeText(meta: UpdateMeta): string | null { + if (updateCheckDisabled() || process.env["HYPERFRAMES_PLUGIN_VERSION"]) return null; + const latest = meta.updateAvailable ? (meta.latestVersion ?? null) : null; + const skills = skillsBehindPhrase(meta); + if (!latest && !skills) return null; + const command = updateCommandForThisInstall( + latest !== null, + skills !== null, + latest ?? meta.version, + ); + return noticeSentence(meta.version, latest, skills, command); +} + +/** The notice when it is due for this project today; a failure here never fails the command. */ +function noticeOrNull(meta: UpdateMeta): string | null { + try { + const notice = updateNoticeText(meta); + return notice && claimDailyNotice("update", resolve(process.cwd())) ? notice : null; + } catch { + return null; + } +} + +/** + * For `withMeta` in commands whose own output is about updating (`update`, `upgrade`, `skills`): + * the same commands `cli.ts` keeps the stderr notices away from. + */ +export const NO_UPDATE_NOTICE = { updateNotice: false }; + /** * Wrap a JSON payload with the _meta version envelope. * Use this in all --json command outputs for consistent agent-friendly metadata. @@ -143,12 +281,20 @@ export function getUpdateMeta(): UpdateMeta { * Pass `{ deprecated: true }` from a command superseded by `check` (validate, * inspect, layout) to add `_meta.deprecated: true`; every other call site is * unaffected — the key is only ever added, never set to `false`. + * + * `_meta.updateNotice` is added when the CLI or the skills are behind, at most once a day per + * project (the numeric fields stay on every result). `{ updateNotice: false }` leaves it out, + * for `update`, whose own result already says what to run. */ export function withMeta( data: T, - options?: { deprecated?: boolean }, + options?: { deprecated?: boolean; updateNotice?: boolean }, ): T & { _meta: UpdateMeta } { const meta = getUpdateMeta(); + if (options?.updateNotice !== false) { + const notice = noticeOrNull(meta); + if (notice) meta.updateNotice = notice; + } if (options?.deprecated) meta.deprecated = true; return { ...data, _meta: meta }; } diff --git a/scripts/check-core-skills.mjs b/scripts/check-core-skills.mjs index 42d994797b..5dba43757d 100644 --- a/scripts/check-core-skills.mjs +++ b/scripts/check-core-skills.mjs @@ -13,7 +13,8 @@ const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), ".."); export const DESCRIPTION_MAX = 320; export const CORE_SKILLS = { hyperframes: 7168, - "hyperframes-cli": 7168, + // +256 B for the `_meta.updateNotice` line: the agent relays it, the person updates. + "hyperframes-cli": 7424, "hyperframes-registry": 5120, "media-use": 5120, figma: 7168, diff --git a/skills-manifest.json b/skills-manifest.json index 3568e01fba..40bcdf07dd 100644 --- a/skills-manifest.json +++ b/skills-manifest.json @@ -10,7 +10,7 @@ "files": 77 }, "hyperframes-cli": { - "hash": "aeb9494dee6777a7", + "hash": "ce9f4c1ff4fcb4ee", "files": 13 }, "hyperframes-registry": { diff --git a/skills/hyperframes-cli/SKILL.md b/skills/hyperframes-cli/SKILL.md index d180c732bd..4f03d3f132 100644 --- a/skills/hyperframes-cli/SKILL.md +++ b/skills/hyperframes-cli/SKILL.md @@ -9,6 +9,8 @@ description: The HyperFrames CLI by job - scaffold, check, look at frames, edit Run `npx hyperframes ` unless the project gives a wrapper; then use the wrapper. It needs Node.js 22+ and FFmpeg. Every command has `--help`; most take `--json`, and a failure prints `✗ …`, a `Fix:` line and exits non-zero. +A `--json` result may carry `_meta.updateNotice`: a newer HyperFrames release is out. Pass it to the person once per conversation, in your own words, at a natural pause; updating is theirs to decide. + ## Commands by job | Job | Commands |