Files
hyperframes/packages/cli/src/utils/backgroundChecks.test.ts
T
Wenbo ZhuandClaude Opus 5.5 7cb6018c6b 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 <noreply@anthropic.com>

* 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@<v>`), 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 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:31:52 +00:00

147 lines
5.7 KiB
TypeScript

import { existsSync, readFileSync } from "node:fs";
import { basename } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const env = vi.hoisted(() => ({ dev: false }));
vi.mock("./env.js", () => ({ isDevMode: () => env.dev }));
const disk = vi.hoisted(() => ({ config: {} as Record<string, unknown> }));
vi.mock("../telemetry/config.js", () => ({
readConfig: () => ({ ...disk.config }),
readConfigFresh: () => ({ ...disk.config }),
writeConfig: (next: Record<string, unknown>) => {
disk.config = { ...next };
return true;
},
}));
const child = vi.hoisted(() => ({ on: vi.fn(), unref: vi.fn() }));
const spawn = vi.hoisted(() => vi.fn(() => child));
vi.mock("node:child_process", async (importOriginal) => ({
...(await importOriginal<typeof import("node:child_process")>()),
spawn,
}));
const { launchBackgroundChecks } = await import("./backgroundChecks.js");
/** The checks handed to the child, or null when none was spawned. */
function spawnedChecks(): string[] | null {
const call = spawn.mock.calls[0] as unknown as [string, string[]] | undefined;
return call ? call[1].slice(1) : null;
}
/** tsup entry name -> source file, as the package build declares them. */
function buildEntries(): Map<string, string> {
const config = readFileSync(new URL("../../tsup.config.ts", import.meta.url), "utf8");
const block = config.slice(config.indexOf("entry: {"));
const entries = block.slice(0, block.indexOf("},"));
return new Map([...entries.matchAll(/"?([\w/]+)"?: "([^"]+)"/g)].map((m) => [m[1]!, m[2]!]));
}
describe("launchBackgroundChecks", () => {
let origTTY: boolean | undefined;
beforeEach(() => {
spawn.mockClear();
disk.config = {};
env.dev = false;
for (const name of ["CI", "HYPERFRAMES_NO_UPDATE_CHECK", "HYPERFRAMES_SKIP_SKILLS"]) {
vi.stubEnv(name, "");
}
origTTY = process.stderr.isTTY;
Object.defineProperty(process.stderr, "isTTY", { value: true, configurable: true });
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllEnvs();
Object.defineProperty(process.stderr, "isTTY", { value: origTTY, configurable: true });
});
it("runs both stale checks in one detached child the parent does not wait for", () => {
launchBackgroundChecks();
expect(spawn).toHaveBeenCalledTimes(1);
const [execPath, , opts] = spawn.mock.calls[0] as unknown as [
string,
string[],
Record<string, unknown>,
];
expect(execPath).toBe(process.execPath);
expect(spawnedChecks()).toEqual(["update", "skills"]);
expect(opts).toMatchObject({ detached: true, stdio: "ignore", windowsHide: true });
expect(child.unref).toHaveBeenCalled();
expect(child.on).toHaveBeenCalledWith("error", expect.any(Function));
});
it("spawns the file the package build emits", () => {
launchBackgroundChecks();
const worker = (spawn.mock.calls[0] as unknown as [string, string[]])[1][0]!;
const source = buildEntries().get(basename(worker, ".js"));
expect(source, `${basename(worker)} is not a tsup entry`).toBeDefined();
expect(existsSync(fileURLToPath(new URL(`../../${source}`, import.meta.url)))).toBe(true);
});
it("retries a check that did not refresh its cache at most once an hour", () => {
vi.useFakeTimers({ toFake: ["Date"] });
launchBackgroundChecks();
expect(spawnedChecks()).toEqual(["update", "skills"]);
// The child failed (offline): no cache written. The next command within the hour starts nothing.
spawn.mockClear();
vi.advanceTimersByTime(59 * 60 * 1000);
launchBackgroundChecks();
expect(spawn).not.toHaveBeenCalled();
vi.advanceTimersByTime(2 * 60 * 1000);
launchBackgroundChecks();
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 };
launchBackgroundChecks();
expect(spawnedChecks()).toEqual(["update", "skills"]);
});
it("does not start a second skills check while one started this hour", () => {
disk.config = { lastUpdateCheck: new Date().toISOString(), latestVersion: "1.0.0" };
launchBackgroundChecks();
expect(spawnedChecks()).toEqual(["skills"]);
spawn.mockClear();
launchBackgroundChecks();
expect(spawn).not.toHaveBeenCalled();
});
it.each([
["dev mode", () => (env.dev = true), null],
["CI=1", () => vi.stubEnv("CI", "1"), null],
["CI=true", () => vi.stubEnv("CI", "true"), null],
["HYPERFRAMES_NO_UPDATE_CHECK=1", () => vi.stubEnv("HYPERFRAMES_NO_UPDATE_CHECK", "1"), null],
["HYPERFRAMES_SKIP_SKILLS=1", () => vi.stubEnv("HYPERFRAMES_SKIP_SKILLS", "1"), ["update"]],
[
"no terminal",
() => Object.defineProperty(process.stderr, "isTTY", { value: false, configurable: true }),
["update", "skills"],
],
])("with %s, hands the child only what the parent used to check", (_, arrange, checks) => {
arrange();
launchBackgroundChecks();
expect(spawnedChecks()).toEqual(checks);
});
});