From b02fe6506e476d41f3bd924ae5248fa26381d720 Mon Sep 17 00:00:00 2001 From: James Russo Date: Wed, 4 Nov 2026 01:45:59 +0000 Subject: [PATCH] fix(cli): check skill freshness at the install destination (#7120) * fix(cli): check skill freshness at the install destination * fix(cli): report foreign skill requests while offline --- docs/guides/skills.mdx | 9 + .../src/commands/skills.installTarget.test.ts | 262 ++++++++++++++++++ packages/cli/src/commands/skills.ts | 29 +- packages/cli/src/utils/skillsManifest.ts | 31 ++- 4 files changed, 320 insertions(+), 11 deletions(-) create mode 100644 packages/cli/src/commands/skills.installTarget.test.ts diff --git a/docs/guides/skills.mdx b/docs/guides/skills.mdx index aab6d8a082..d97f64e93b 100644 --- a/docs/guides/skills.mdx +++ b/docs/guides/skills.mdx @@ -50,6 +50,15 @@ npx hyperframes skills update This installs or refreshes the core set and any HyperFrames skills already present in the global install, then links those bundles into compatible installed agents. It does not add every optional skill. +Updates check the Claude global store (`~/.claude/skills`, or the `skills/` folder +under `CLAUDE_CONFIG_DIR`) that the installer writes to. Skills found only in +another agent's directory do not make a missing core skill count as installed +there, and optional skills in that other directory are not automatically added +to the managed store. Name an optional skill explicitly to add it. The install +record's publisher attribution is respected even before the managed store exists. +An explicit update request for a skill owned by another publisher fails without +overwriting it, including when the freshness check is unavailable offline. + Check freshness without changing anything: ```bash diff --git a/packages/cli/src/commands/skills.installTarget.test.ts b/packages/cli/src/commands/skills.installTarget.test.ts new file mode 100644 index 0000000000..1135b07582 --- /dev/null +++ b/packages/cli/src/commands/skills.installTarget.test.ts @@ -0,0 +1,262 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { EventEmitter } from "node:events"; +import { + cpSync, + existsSync, + lstatSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { buildManifest, FALLBACK_CORE_SKILLS } from "../utils/skillsManifest.js"; +import { updateSkills } from "./skills.js"; +import { log } from "../ui/prompts.js"; + +const installer = vi.hoisted(() => ({ run: vi.fn<(args: readonly string[]) => void>() })); + +vi.mock("node:child_process", () => ({ + execFile: vi.fn( + (_cmd: string, _args: readonly string[], _opts: unknown, callback: (err: Error) => void) => + callback(new Error("git unavailable in test")), + ), + execFileSync: vi.fn(() => Buffer.from("22.0.0")), + spawn: vi.fn((_cmd: string, args: readonly string[]) => { + const child = new EventEmitter(); + setImmediate(() => { + installer.run(args); + child.emit("close", 0, null); + }); + return child; + }), +})); + +vi.mock("../telemetry/events.js", () => ({ trackSkillsInstallSkipped: vi.fn() })); +vi.mock("../utils/skillsUpdateCheck.js", () => ({ invalidateSkillsCache: vi.fn() })); + +let fixture: string; +let home: string; +let cwd: string; +let source: string; +let store: string; +let cursor: string; +let manifest: ReturnType; + +function write(path: string, content: string): void { + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, content); +} + +function selected(args: readonly string[]): string[] { + return args.filter((_, index) => args[index - 1] === "--skill"); +} + +function seedCore(target: string): void { + mkdirSync(target, { recursive: true }); + for (const name of FALLBACK_CORE_SKILLS) + cpSync(join(source, name), join(target, name), { recursive: true }); +} + +function install(args: readonly string[], omit: readonly string[] = []): void { + const lockPath = join(home, ".agents", ".skill-lock.json"); + const lock: { skills: Record } = existsSync(lockPath) + ? JSON.parse(readFileSync(lockPath, "utf8")) + : { skills: {} }; + for (const name of selected(args)) { + if (omit.includes(name)) continue; + for (const target of [store, join(home, ".agents", "skills")]) { + mkdirSync(target, { recursive: true }); + cpSync(join(source, name), join(target, name), { recursive: true }); + } + lock.skills[name] = { source: "heygen-com/hyperframes" }; + } + write(lockPath, JSON.stringify(lock)); +} + +beforeEach(() => { + fixture = mkdtempSync(join(tmpdir(), "hf-install-target-")); + home = join(fixture, "home"); + cwd = join(fixture, "project"); + source = join(fixture, "source"); + store = join(home, ".claude", "skills"); + cursor = join(home, ".cursor", "skills"); + mkdirSync(cwd, { recursive: true }); + for (const name of [...FALLBACK_CORE_SKILLS, "reverse-any-video", "slideshow"]) { + write(join(source, name, "SKILL.md"), `# ${name}\nCurrent release\n`); + } + manifest = buildManifest(source, { source: "heygen-com/hyperframes" }); + vi.stubEnv("HOME", home); + vi.stubEnv("USERPROFILE", home); + for (const name of ["CLAUDE_CONFIG_DIR", "XDG_STATE_HOME", "XDG_CONFIG_HOME"]) + vi.stubEnv(name, ""); + vi.stubGlobal( + "fetch", + vi.fn(async () => new Response(JSON.stringify(manifest))), + ); + installer.run.mockReset(); + installer.run.mockImplementation(install); +}); + +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); + rmSync(fixture, { recursive: true, force: true }); +}); + +describe("skills update install destination", () => { + it.each([false, true])( + "reports a requested foreign skill while offline (strict: %s)", + async (strict) => { + seedCore(store); + const path = join(store, "reverse-any-video", "SKILL.md"); + write(path, "# Another publisher\n"); + write( + join(home, ".agents", ".skill-lock.json"), + JSON.stringify({ + skills: { "reverse-any-video": { source: "another/publisher" } }, + }), + ); + vi.stubGlobal( + "fetch", + vi.fn(async () => { + throw new Error("offline"); + }), + ); + const warning = vi.spyOn(log, "warn").mockImplementation(() => {}); + + const update = updateSkills({ cwd, requested: ["reverse-any-video"], strict }); + + if (strict) { + await expect(update).rejects.toThrow( + "Skill(s) owned by another publisher: reverse-any-video", + ); + } else { + const result = await update; + expect(result.unknown).toEqual(["reverse-any-video"]); + expect(warning).toHaveBeenCalledWith( + expect.stringContaining("owned by another publisher: reverse-any-video"), + ); + } + expect(installer.run).not.toHaveBeenCalled(); + expect(readFileSync(path, "utf8")).toBe("# Another publisher\n"); + }, + ); + + it("installs the core in one run with only Cursor skills present, then becomes a no-op", async () => { + seedCore(cursor); + rmSync(join(cursor, "media-use"), { recursive: true }); + const optional = join(cursor, "reverse-any-video", "SKILL.md"); + write(optional, "# Existing Cursor-only workflow\n"); + + const first = await updateSkills({ cwd, refreshInstalled: true, strict: true }); + + expect(first.installed.sort()).toEqual([...FALLBACK_CORE_SKILLS].sort()); + for (const name of FALLBACK_CORE_SKILLS) { + expect(readFileSync(join(store, name, "SKILL.md"), "utf8")).toBe( + readFileSync(join(source, name, "SKILL.md"), "utf8"), + ); + } + expect(existsSync(join(store, "reverse-any-video"))).toBe(false); + expect(readFileSync(optional, "utf8")).toBe("# Existing Cursor-only workflow\n"); + if (process.platform !== "win32") + expect(lstatSync(join(cursor, "hyperframes")).isSymbolicLink()).toBe(true); + + const second = await updateSkills({ cwd, refreshInstalled: true, strict: true }); + expect(second.installed).toEqual([]); + expect(installer.run).toHaveBeenCalledTimes(1); + }); + + it("still refreshes an optional skill already installed in the managed store", async () => { + seedCore(store); + write(join(store, "reverse-any-video", "SKILL.md"), "# Stale workflow\n"); + + const result = await updateSkills({ cwd, refreshInstalled: true, strict: true }); + + expect(result.installed).toEqual(["reverse-any-video"]); + expect(readFileSync(join(store, "reverse-any-video", "SKILL.md"), "utf8")).toBe( + readFileSync(join(source, "reverse-any-video", "SKILL.md"), "utf8"), + ); + expect(existsSync(join(store, "slideshow"))).toBe(false); + }); + + it.each([false, true])( + "preserves another publisher's skill outside the target store (offline: %s)", + async (offline) => { + write(join(cursor, "hyperframes", "SKILL.md"), "# Another publisher\n"); + write( + join(home, ".agents", ".skill-lock.json"), + JSON.stringify({ + skills: { hyperframes: { source: "another/publisher" } }, + }), + ); + + if (offline) + vi.stubGlobal( + "fetch", + vi.fn(async () => { + throw new Error("offline"); + }), + ); + const result = await updateSkills({ + cwd, + requested: ["slideshow"], + refreshInstalled: true, + strict: true, + }); + + expect(result.targets).not.toContain("hyperframes"); + expect(readFileSync(join(cursor, "hyperframes", "SKILL.md"), "utf8")).toBe( + "# Another publisher\n", + ); + expect(existsSync(join(store, "hyperframes"))).toBe(false); + }, + ); + + it("does not accept Cursor's copies as proof that the destination install succeeded", async () => { + seedCore(cursor); + installer.run.mockImplementation((args) => install(args, ["hyperframes", "hyperframes-cli"])); + + await expect(updateSkills({ cwd, refreshInstalled: true, strict: true })).rejects.toThrow( + "Skill(s) still missing after install: hyperframes, hyperframes-cli", + ); + }); + + it("checks the write destination during the offline presence-only fallback too", async () => { + seedCore(cursor); + vi.stubGlobal( + "fetch", + vi.fn(async () => { + throw new Error("offline"); + }), + ); + + const result = await updateSkills({ cwd, requested: ["slideshow"], strict: true }); + + expect(result.presenceOnly).toBe(true); + expect(result.installed.sort()).toEqual(["slideshow", ...FALLBACK_CORE_SKILLS].sort()); + for (const name of result.targets) expect(existsSync(join(store, name, "SKILL.md"))).toBe(true); + }); + + it("uses CLAUDE_CONFIG_DIR even when the command runs from HOME", async () => { + store = join(home, "custom-claude", "skills"); + vi.stubEnv("CLAUDE_CONFIG_DIR", dirname(store)); + write( + join(home, ".agents", ".skill-lock.json"), + JSON.stringify({ + skills: { "reverse-any-video": { source: "another/publisher" } }, + }), + ); + seedCore(store); + write(join(store, "reverse-any-video", "SKILL.md"), "# Another publisher\n"); + + const result = await updateSkills({ cwd: home, refreshInstalled: true, strict: true }); + + expect(result.installed).toEqual([]); + expect(result.targets).not.toContain("reverse-any-video"); + expect(installer.run).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/cli/src/commands/skills.ts b/packages/cli/src/commands/skills.ts index 1e638e9516..849f8d05b9 100644 --- a/packages/cli/src/commands/skills.ts +++ b/packages/cli/src/commands/skills.ts @@ -10,6 +10,7 @@ import { withMeta } from "../utils/updateCheck.js"; import { checkSkills, FALLBACK_CORE_SKILLS, + foreignSkillNames, hyperframesSkillNames, isCoreSkill, presentSkills, @@ -346,7 +347,12 @@ export async function updateSkills( // that no longer exists, and verifyInstalled would strict-throw on a // "failure" that was never real. Resolving canonically means a retired // skill simply never appears as a target in the first place. - check = await checkSkills({ cwd: opts.cwd, canonical: true, cliVersion: VERSION }); + check = await checkSkills({ + cwd: opts.cwd, + canonical: true, + cliVersion: VERSION, + installTarget: true, + }); } catch (err) { // A *malformed* canonical manifest (the server was reached, but served a // bad shape) is otherwise indistinguishable from being offline — both fall @@ -408,7 +414,7 @@ export async function updateSkills( if (toInstall.length > 0) { await installSkills(result.installed, { cwd: opts.cwd, strict, ref: check.ref ?? "main" }); - verifyInstalled(result.installed, { strict, cwd: opts.cwd }); + verifyInstalled(result.targets, { strict, cwd: opts.cwd }); } // The install (or the fresh canonical check confirming everything current) // supersedes whatever the background nudge cached before it — drop the @@ -432,7 +438,7 @@ export async function updateSkills( * skills hiccup must never break scaffolding. */ function verifyInstalled(names: readonly string[], opts: { strict: boolean; cwd?: string }): void { - const present = new Set(presentSkills(names, { cwd: opts.cwd })); + const present = new Set(presentSkills(names, { cwd: opts.cwd, installTarget: true })); const absent = names.filter((name) => !present.has(name)); if (absent.length === 0) return; const message = `Skill(s) still missing after install: ${absent.join(", ")}`; @@ -471,8 +477,17 @@ async function updateSkillsOffline( ); } - const targets = [...new Set([...requested, ...FALLBACK_CORE_SKILLS])]; - const present = new Set(presentSkills(targets, { cwd: opts.cwd })); + const foreign = new Set(foreignSkillNames({ scope: "global" })); + const unknown = requested.filter((name) => foreign.has(name)); + if (unknown.length > 0) { + const message = `Skill(s) owned by another publisher: ${unknown.join(", ")}. Leaving them unchanged.`; + if (opts.strict) throw new Error(message); + clack.log.warn(c.warn(message)); + } + const targets = [...new Set([...requested, ...FALLBACK_CORE_SKILLS])].filter( + (name) => !foreign.has(name), + ); + const present = new Set(presentSkills(targets, { cwd: opts.cwd, installTarget: true })); const absent = targets.filter((name) => !present.has(name)); console.log( @@ -489,13 +504,13 @@ async function updateSkillsOffline( strict: opts.strict, ref: cliReleaseTag(VERSION) ?? "main", }); - verifyInstalled(absent, opts); + verifyInstalled(targets, opts); } return { targets, installed: absent, current: [...present], - unknown: [], + unknown, presenceOnly: true, }; } diff --git a/packages/cli/src/utils/skillsManifest.ts b/packages/cli/src/utils/skillsManifest.ts index 835a6eb660..c71c725ce8 100644 --- a/packages/cli/src/utils/skillsManifest.ts +++ b/packages/cli/src/utils/skillsManifest.ts @@ -392,6 +392,14 @@ function locateInstall( return null; } +function globalInstallRoot(home = homedir()): SkillRoot { + return { + dir: join(process.env.CLAUDE_CONFIG_DIR?.trim() || join(home, ".claude"), "skills"), + agent: "claude-code", + scope: "global", + }; +} + /** * Names from `skillNames` that are present (their SKILL.md exists) in the * located install. Local-only — no manifest fetch — so callers can verify the @@ -399,9 +407,11 @@ function locateInstall( */ export function presentSkills( skillNames: readonly string[], - opts: { dir?: string; cwd?: string; home?: string } = {}, + opts: { dir?: string; cwd?: string; home?: string; installTarget?: boolean } = {}, ): string[] { - const root = locateInstall([...skillNames], opts); + const root = opts.installTarget + ? globalInstallRoot(opts.home) + : locateInstall([...skillNames], opts); if (!root) return []; return skillNames.filter((name) => existsSync(join(root.dir, name, "SKILL.md"))); } @@ -549,6 +559,17 @@ export function hyperframesSkillNames(opts: { return skillsAttributedToSource(readSkillLock(lockPath), DEFAULT_REPO_SLUG); } +export function foreignSkillNames(opts: { + scope: "project" | "global"; + cwd?: string; + home?: string; +}): string[] { + const lock = readSkillLock(lockPathForScope(opts.scope, opts)); + return Object.entries(lock?.skills ?? {}) + .filter(([, entry]) => isFromOtherSource(entry, DEFAULT_REPO_SLUG)) + .map(([name]) => name); +} + // ── Resolving the "latest" manifest ────────────────────────────────────────── /** Walk up from `cwd` to find a repo checkout that ships the manifest. */ @@ -757,6 +778,8 @@ export async function checkSkills( canonical?: boolean; /** Read the remote manifest at this CLI version's release tag (see fetchRemoteManifest). */ cliVersion?: string; + /** Check the global store written by the installer, even before it exists. */ + installTarget?: boolean; } = {}, ): Promise { const { manifest: latest, ref } = await resolveLatestManifest(opts.source, opts.cwd, { @@ -764,14 +787,14 @@ export async function checkSkills( cliVersion: opts.cliVersion, }); const skillNames = Object.keys(latest.skills); - const root = locateInstall(skillNames, { dir: opts.dir, cwd: opts.cwd, home: opts.home }); + const root = opts.installTarget ? globalInstallRoot(opts.home) : locateInstall(skillNames, opts); // A directory sharing a name with one of ours can belong to another publisher. // The lock says so; such a skill is never compared, refreshed or overwritten. const lock = root ? readSkillLock(lockPathForScope(root.scope, opts)) : null; const foreign = root ? skillNames.filter( (name) => - existsSync(join(root.dir, name, "SKILL.md")) && + (opts.installTarget || existsSync(join(root.dir, name, "SKILL.md"))) && isFromOtherSource(lock?.skills?.[name], latest.source), ) : [];