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"; const dns = vi.hoisted(() => ({ answers: true })); vi.mock("./hostAnswers.js", () => ({ hostAnswers: async () => dns.answers })); describe("isSafeVersion", () => { it("accepts strict semver, incl. prerelease/build metadata", () => { expect(isSafeVersion("1.2.3")).toBe(true); expect(isSafeVersion("0.7.28")).toBe(true); expect(isSafeVersion("1.2.3-beta.1")).toBe(true); expect(isSafeVersion("1.2.3+build.5")).toBe(true); }); it("rejects anything that could carry shell metacharacters or isn't semver", () => { expect(isSafeVersion("")).toBe(false); expect(isSafeVersion("latest")).toBe(false); expect(isSafeVersion("1.2")).toBe(false); expect(isSafeVersion("1.2.3; rm -rf /")).toBe(false); expect(isSafeVersion("1.2.3 && curl evil")).toBe(false); expect(isSafeVersion("$(whoami)")).toBe(false); }); }); /** * Drive printUpdateNotice under controlled mocks. isDevMode() is true under * vitest (the module path ends in .ts), which would suppress the notice, so we * mock ./env.js. detectInstaller and readConfig are mocked to pick the branch. */ async function noticeWith(opts: { installerCommand: string | null; latestVersion?: string; isTTY?: boolean; env?: Record; unattended?: boolean; pendingVersion?: string; }): Promise { vi.resetModules(); vi.doMock("./env.js", () => ({ isDevMode: () => false })); vi.doMock("./attendedTerminal.js", async (importOriginal) => ({ ...(await importOriginal()), isUnattended: () => opts.unattended ?? false, })); vi.doMock("./installerDetection.js", () => ({ detectInstaller: () => ({ kind: opts.installerCommand ? "npm" : "skip", installCommand: () => opts.installerCommand, reason: "test", }), })); vi.doMock("../telemetry/config.js", () => ({ readConfig: () => ({ latestVersion: opts.latestVersion ?? "9.9.9", pendingUpdate: opts.pendingVersion && { version: opts.pendingVersion, command: "npm install -g hyperframes", startedAt: new Date().toISOString(), }, }), writeConfig: () => {}, })); const origEnv = { ...process.env }; for (const [k, v] of Object.entries(opts.env ?? {})) { if (v === undefined) delete process.env[k]; else process.env[k] = v; } // Default to a non-CI interactive terminal unless the test overrides env. for (const name of ["CI", "HYPERFRAMES_NO_UPDATE_CHECK"]) { if (!(name in (opts.env ?? {}))) delete process.env[name]; } const origTTY = process.stderr.isTTY; Object.defineProperty(process.stderr, "isTTY", { value: opts.isTTY ?? true, configurable: true, }); const writes: string[] = []; const origWrite = process.stderr.write.bind(process.stderr); process.stderr.write = ((chunk: unknown) => { writes.push(String(chunk)); return true; }) as typeof process.stderr.write; try { const mod = await import("./updateCheck.js"); mod.printUpdateNotice(); } finally { process.stderr.write = origWrite; Object.defineProperty(process.stderr, "isTTY", { value: origTTY, configurable: true }); process.env = origEnv; } return writes.join(""); } describe("printUpdateNotice — install-method-aware command", () => { afterEach(() => { vi.doUnmock("./env.js"); vi.doUnmock("./attendedTerminal.js"); vi.doUnmock("./installerDetection.js"); vi.doUnmock("../telemetry/config.js"); vi.resetModules(); }); it("shows the detected manager's command for an owned global install", async () => { const out = await noticeWith({ installerCommand: "brew upgrade hyperframes" }); expect(out).toContain("Update available"); expect(out).toContain("brew upgrade hyperframes"); expect(out).not.toContain("npx hyperframes@latest"); }); it("falls back to npx hyperframes@latest when the install method is skip/unknown", async () => { const out = await noticeWith({ installerCommand: null }); expect(out).toContain("npx hyperframes@latest"); }); it("is suppressed on a non-TTY stderr", async () => { const out = await noticeWith({ installerCommand: "brew upgrade hyperframes", isTTY: false }); expect(out).toBe(""); }); it("is suppressed when the run is unattended", async () => { const out = await noticeWith({ installerCommand: "npm i -g hyperframes", unattended: true }); expect(out).toBe(""); }); it("does not tell the user to install a version a background install is already installing", async () => { const out = await noticeWith({ installerCommand: "npm i -g hyperframes", pendingVersion: "9.9.9", }); expect(out).toBe(""); }); it("is suppressed in CI", async () => { const out = await noticeWith({ installerCommand: "brew upgrade hyperframes", env: { CI: "true" }, }); expect(out).toBe(""); }); it("is suppressed by the HYPERFRAMES_NO_UPDATE_CHECK opt-out", async () => { const out = await noticeWith({ installerCommand: "brew upgrade hyperframes", env: { HYPERFRAMES_NO_UPDATE_CHECK: "1" }, }); expect(out).toBe(""); }); it("does not advertise an update from an invalid cached version", async () => { expect(await noticeWith({ installerCommand: null, latestVersion: "not-a-version" })).toBe(""); }); }); /** * The registry-boundary guard: a poisoned or non-string data.version must * never be cached, because it flows into the auto-updater's install command. * This closes the injection class for every downstream consumer at one point. */ async function checkWith( registryVersion: unknown, force = true, ): Promise<{ latest: string; wroteVersion: string | undefined; fetched: boolean; }> { vi.resetModules(); vi.doMock("./env.js", () => ({ isDevMode: () => false })); const writes: Array> = []; vi.doMock("../telemetry/config.js", () => ({ readConfig: () => ({}), readConfigFresh: () => ({}), writeConfig: (c: Record) => writes.push({ ...c }), })); const origFetch = globalThis.fetch; let fetched = false; globalThis.fetch = (async () => { fetched = true; return { ok: true, json: async () => ({ version: registryVersion }) }; }) as unknown as typeof fetch; try { const mod = await import("./updateCheck.js"); const result = await mod.checkForUpdate(force); const lastWrite = writes.at(-1); return { latest: result.latest, wroteVersion: lastWrite ? (lastWrite["latestVersion"] as string | undefined) : undefined, fetched, }; } finally { globalThis.fetch = origFetch; } } async function checkAcrossConcurrentConfigWrite(): Promise> { vi.resetModules(); const initial = { telemetryEnabled: true, anonymousId: "test-install", telemetryNoticeShown: true, commandCount: 0, renderSuccessCount: 0, lastFeedbackPromptAt: 0, }; let persisted: Record = { ...initial }; vi.doMock("../telemetry/config.js", () => ({ readConfig: () => ({ ...initial }), readConfigFresh: () => ({ ...persisted }), writeConfig: (config: Record) => { persisted = { ...config }; return true; }, })); const origFetch = globalThis.fetch; let releaseResponse: (() => void) | undefined; const responseReady = new Promise((resolve) => { releaseResponse = resolve; }); globalThis.fetch = (async () => { await responseReady; return { ok: true, json: async () => ({ version: "9.9.9" }), }; }) as unknown as typeof fetch; try { const mod = await import("./updateCheck.js"); const check = mod.checkForUpdate(true); persisted = { ...persisted, telemetryEnabled: false }; releaseResponse?.(); await check; return persisted; } finally { globalThis.fetch = origFetch; } } /** * U5: validate/inspect/layout are deprecated in favor of `check`. withMeta's * optional `{ deprecated: true }` is the single place that adds `_meta.deprecated` * to a --json envelope; every other command (check, lint, ...) calls withMeta * with no second argument and must never see the key at all — not even `false`. */ describe("withMeta — deprecated flag", () => { it("omits _meta.deprecated entirely when no options are passed (check/lint et al.)", () => { const wrapped = withMeta({ ok: true }); expect("deprecated" in wrapped._meta).toBe(false); }); it("omits _meta.deprecated when options.deprecated is false", () => { const wrapped = withMeta({ ok: true }, { deprecated: false }); expect("deprecated" in wrapped._meta).toBe(false); }); it("sets _meta.deprecated === true when requested (validate/inspect/layout)", () => { const wrapped = withMeta({ ok: true }, { deprecated: true }); expect(wrapped._meta.deprecated).toBe(true); }); it("preserves the rest of the _meta envelope alongside the deprecated flag", () => { const wrapped = withMeta({ ok: true }, { deprecated: true }); expect(wrapped._meta.version).toEqual(expect.any(String)); expect(typeof wrapped._meta.updateAvailable).toBe("boolean"); }); }); /** * The stderr-only deprecation notice: printed once per invocation, never on * stdout, so --json output stays pure JSON while humans still see the notice. */ describe("printDeprecationNotice", () => { it("writes exactly one line to stderr, never stdout", () => { const stderrWrites: string[] = []; const stdoutWrites: string[] = []; const origErrWrite = process.stderr.write.bind(process.stderr); const origOutWrite = process.stdout.write.bind(process.stdout); process.stderr.write = ((chunk: unknown) => { stderrWrites.push(String(chunk)); return true; }) as typeof process.stderr.write; process.stdout.write = ((chunk: unknown) => { stdoutWrites.push(String(chunk)); return true; }) as typeof process.stdout.write; try { printDeprecationNotice("validate"); } finally { process.stderr.write = origErrWrite; process.stdout.write = origOutWrite; } expect(stdoutWrites).toEqual([]); expect(stderrWrites).toHaveLength(1); expect(stderrWrites[0]).toContain("hyperframes validate"); expect(stderrWrites[0]).toContain("hyperframes check"); }); }); describe("checkForUpdate — registry boundary guard", () => { afterEach(() => { vi.doUnmock("../telemetry/config.js"); vi.doUnmock("./env.js"); vi.resetModules(); }); function clearOptOuts(): void { vi.stubEnv("CI", ""); vi.stubEnv("HYPERFRAMES_NO_UPDATE_CHECK", ""); } it("still asks the registry from a run without a terminal", async () => { clearOptOuts(); const origTTY = process.stderr.isTTY; Object.defineProperty(process.stderr, "isTTY", { value: false, configurable: true }); try { expect((await checkWith("99.0.0", false)).fetched).toBe(true); } finally { Object.defineProperty(process.stderr, "isTTY", { value: origTTY, configurable: true }); vi.unstubAllEnvs(); } }); it("skips the background registry request when DNS does not answer", async () => { clearOptOuts(); dns.answers = false; try { expect((await checkWith("99.0.0", false)).fetched).toBe(false); expect((await checkWith("99.0.0")).fetched).toBe(true); } finally { dns.answers = true; vi.unstubAllEnvs(); } }); it.each(["CI", "HYPERFRAMES_NO_UPDATE_CHECK"])( "skips the background registry request when %s=1", async (name) => { clearOptOuts(); vi.stubEnv(name, "1"); try { expect((await checkWith("99.0.0", false)).fetched).toBe(false); expect((await checkWith("99.0.0")).fetched).toBe(true); } finally { vi.unstubAllEnvs(); } }, ); it("caches and returns a valid semver from the registry", async () => { const { latest, wroteVersion } = await checkWith("9.9.9"); expect(latest).toBe("9.9.9"); expect(wroteVersion).toBe("9.9.9"); }); it("rejects a version carrying shell metacharacters (no cache, no surface)", async () => { const { latest, wroteVersion } = await checkWith("1.2.3; rm -rf /"); expect(latest).not.toContain(";"); expect(latest).not.toBe("1.2.3; rm -rf /"); expect(wroteVersion).toBeUndefined(); // never written to config }); it("rejects a non-string data.version", async () => { const { latest, wroteVersion } = await checkWith({ evil: true }); expect(typeof latest).toBe("string"); expect(wroteVersion).toBeUndefined(); }); it("leaves no timer behind when the registry request fails fast", async () => { vi.resetModules(); vi.doMock("../telemetry/config.js", () => ({ readConfig: () => ({}), readConfigFresh: () => ({}), writeConfig: () => {}, })); const origFetch = globalThis.fetch; globalThis.fetch = (async () => { throw new TypeError("fetch failed"); }) as unknown as typeof fetch; vi.useFakeTimers(); try { const mod = await import("./updateCheck.js"); await mod.checkForUpdate(true); expect(vi.getTimerCount()).toBe(0); } finally { vi.useRealTimers(); globalThis.fetch = origFetch; } }); it("merges update metadata into a fresh snapshot without re-enabling telemetry", async () => { const persisted = await checkAcrossConcurrentConfigWrite(); expect(persisted).toMatchObject({ telemetryEnabled: false, latestVersion: "9.9.9", }); }); }); 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: () => {}, })); return import("./updateCheck.js"); } const hoursAgo = (h: number) => new Date(Date.now() - h * 3_600_000).toISOString(); it.each([ ["no cache", {}, true], ["a cache from an hour ago", { lastUpdateCheck: hoursAgo(1), latestVersion: "9.9.9" }, false], ["a cache from 25 hours ago", { lastUpdateCheck: hoursAgo(25), latestVersion: "9.9.9" }, true], ["an unreadable timestamp", { lastUpdateCheck: "garbage", latestVersion: "9.9.9" }, true], [ "an unsafe cached version", { lastUpdateCheck: hoursAgo(1), latestVersion: "1.2.3; rm" }, true, ], ])("with %s, a check is due: %s", async (_, config, due) => { const mod = await load(config); 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 config = behind({ lastUpdateCheck: at(1), lastSkillsCheck: at(1) }); const mod = await loadNotice(config); 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")); config.lastUpdateCheck = new Date().toISOString(); config.lastSkillsCheck = new Date().toISOString(); 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"); expect(mod.updateCheckDue()).toBe(false); }); it("reports a cached newer version, and never surfaces an unsafe one", async () => { expect((await load({ latestVersion: "999.0.0" })).cachedUpdateCheck()).toMatchObject({ latest: "999.0.0", updateAvailable: true, }); const poisoned = (await load({ latestVersion: "999.0.0; rm -rf /" })).cachedUpdateCheck(); expect(poisoned.updateAvailable).toBe(false); expect(poisoned.latest).not.toContain(";"); }); it.each(["not-a-version", "999.0.0; invalid", 999, ["999.0.0"], {}, null, undefined])( "omits invalid cached version %j from JSON metadata", async (latestVersion) => { const mod = await load({ latestVersion }); const wrapped = mod.withMeta({ ok: true }); expect(wrapped._meta).toEqual({ version: mod.cachedUpdateCheck().current, latestVersion: undefined, updateAvailable: false, }); expect(JSON.parse(JSON.stringify(wrapped))).toEqual({ ok: true, _meta: { version: wrapped._meta.version, updateAvailable: false }, }); }, ); // 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(true); expect(mod.getUpdateMeta()).toEqual({ version: "0.9.6", latestVersion: undefined, updateAvailable: false, }); expect(mod.cachedUpdateCheck().latest).toBe("0.9.6"); }); it.each(["999.0.0", "999.0.0+build.5"])( "preserves safe cached version %s and the update-check result in metadata", async (latestVersion) => { const mod = await load({ latestVersion }); expect(mod.getUpdateMeta()).toEqual({ version: mod.cachedUpdateCheck().current, latestVersion, updateAvailable: mod.cachedUpdateCheck().updateAvailable, }); }, ); });