diff --git a/.build/just/index.just b/.build/just/index.just index 1d73bbe..beda195 100644 --- a/.build/just/index.just +++ b/.build/just/index.just @@ -30,7 +30,7 @@ import "utilities.just" # pipeline-pr, pipeline-build, pipeline-tests - local runs of the Purview.Build pipeline import "purview-build.just" -# skills-* - the Purview.BuildSdk agent-skill targets +# skills-* - agent skills through the skills CLI, run by skills.mts (no .NET involved) import "skills.just" # Optional. pipeline-pack-validate, pipeline-local-release, pipeline-release - for a repository that diff --git a/.build/just/skills.just b/.build/just/skills.just index 0d33902..6dea181 100644 --- a/.build/just/skills.just +++ b/.build/just/skills.just @@ -1,18 +1,25 @@ -# The Purview.BuildSdk agent-skill targets. Each recipe names one target; the behaviour lives there. +# The agent-skill recipes: a thin wrapper over the standard skills CLI (`bun x skills@1` by default). # -# The targets are a thin wrapper over the standard skills CLI (`bun x skills` by default), run from the -# repository root. Every skill target runs once for the whole solution, however many projects it holds, -# so the recipes name the solution, not a hand-picked project. +# The work is done by skills.mts, beside this file, which needs no .NET at all - no solution to +# evaluate, no restore and no build - so a repository whose build is broken can still install the +# skills that might help fix it. It runs under Bun, then Deno, and falls back to Node with the +# generated skills.mjs. Set PURVIEW_SKILLS_RUNTIME to choose, for example `node`, `bun` or `deno run -A`. # # Every recipe here is run by a person, on purpose. Never make one a dependency of build, test or -# default, or call skills-add, -install, -update or -fix from a git hook: they change the repository, -# and the SDK refuses to run them inside a build (PRSKL0009). skills-check is read-only. +# default, or call skills-add, -install, -update or -fix from a git hook: they change the repository. +# skills-check is read-only. # -# The runner and agents are MSBuild properties (PurviewSkillsRunner, PurviewSkillsAgents), set once in -# Directory.Build.props. Pass a one-off through *args; `dotnet msbuild -p:` splits on `,` and `;`, so -# escape the separator: `just skills-update -p:PurviewSkillsAgents=claude-code%2Ccodex`. +# Settings live in the "Skills" section of .config/purview-build-sdk.json: +# +# { "Skills": { "Agents": ["claude-code", "codex"], "Runner": "bun" } } +# +# Pass a one-off through *args, for example `just skills-update --dry-run --agents claude-code,codex`, +# or set the matching PURVIEW_SKILLS_* environment variable. + +skills_script := source_directory() / "skills" -skills_project := solution_file +# Runs skills.mts (or skills.mjs) from the repository root with the given arguments. +_skills_run := 'purview_skills() { if [ -n "${PURVIEW_SKILLS_RUNTIME:-}" ]; then case "$PURVIEW_SKILLS_RUNTIME" in node*) $PURVIEW_SKILLS_RUNTIME "' + skills_script + '.mjs" "$@" ;; *) $PURVIEW_SKILLS_RUNTIME "' + skills_script + '.mts" "$@" ;; esac; elif command -v bun >/dev/null 2>&1; then bun "' + skills_script + '.mts" "$@"; elif command -v deno >/dev/null 2>&1; then deno run -A "' + skills_script + '.mts" "$@"; elif command -v node >/dev/null 2>&1; then node "' + skills_script + '.mjs" "$@"; else echo "error PRSKL0004: the skills recipes need Bun, Deno or Node.js on PATH." >&2; return 1; fi; }; purview_skills' # Install skills from another repository through the skills CLI (append '#' to pin it) # @@ -21,32 +28,32 @@ skills_project := solution_file [group('Agent Skills')] skills-add source *args: echo "==> Installing skills from {{ BLUE }}{{ source }}{{ NORMAL }}" - dotnet msbuild "{{ skills_project }}" -t:InstallPurviewSkills -p:PurviewSkillsSource={{ source }} -v:n {{ args }} + {{ _skills_run }} add {{ quote(source) }} --root "{{ justfile_directory() }}" {{ args }} # Restore every skill skills-lock.json records - how a fresh clone gets the repository's skills back [group('Agent Skills')] skills-install *args: - dotnet msbuild "{{ skills_project }}" -t:InstallPurviewSkills -v:n {{ args }} + {{ _skills_run }} install --root "{{ justfile_directory() }}" {{ args }} # Update the agent skills by re-adding every unique source in skills-lock.json # # Each source is re-added at its latest with every skill it has, which refreshes the installed skills -# and adds any a source has gained; `skills update` is never run. FixPurviewSkills then removes links -# from agent directories PurviewSkillsAgents does not select, and does nothing when it is unset. -# The -t: value is quoted because sh would otherwise end the command at the `;`. +# and adds any a source has gained; `skills update` is never run. skills-fix then removes links from +# agent directories Skills.Agents does not select, and does nothing when it is unset. # -# just skills-update -p:PurviewSkillsDryRun=true +# just skills-update --dry-run [doc('Update the agent skills by re-adding every unique source in skills-lock.json')] [group('Agent Skills')] skills-update *args: - dotnet msbuild "{{ skills_project }}" "-t:UpdatePurviewSkills;FixPurviewSkills" -v:n {{ args }} + {{ _skills_run }} update --root "{{ justfile_directory() }}" {{ args }} + {{ _skills_run }} fix --root "{{ justfile_directory() }}" {{ args }} -# Check that only the skill directories of the agents in PurviewSkillsAgents exist +# Check that only the skill directories of the agents in Skills.Agents exist [group('Agent Skills')] skills-check *args: - dotnet msbuild "{{ skills_project }}" -t:CheckPurviewSkills -v:n {{ args }} + {{ _skills_run }} check --root "{{ justfile_directory() }}" {{ args }} -# Remove the skills CLI's links from agent directories PurviewSkillsAgents does not select +# Remove the skills CLI's links from agent directories Skills.Agents does not select [group('Agent Skills')] skills-fix *args: - dotnet msbuild "{{ skills_project }}" -t:FixPurviewSkills -v:n {{ args }} + {{ _skills_run }} fix --root "{{ justfile_directory() }}" {{ args }} diff --git a/.build/just/skills.mjs b/.build/just/skills.mjs new file mode 100644 index 0000000..7c56ae8 --- /dev/null +++ b/.build/just/skills.mjs @@ -0,0 +1,686 @@ +// GENERATED from skills.mts by scripts/sync-skills-script.mjs in purview-dev/build-sdk - do not edit. +// It is skills.mts with the TypeScript removed, for a machine with Node but neither Bun nor Deno. + +// The Purview.BuildSdk agent-skill commands: a thin wrapper over the standard skills CLI +// (`bun x skills@1` by default), run by the skills-* recipes in skills.just. +// +// Nothing here needs .NET. There is no solution to evaluate, no package to restore and no project +// that has to build, so a repository whose build is broken can still install the skills that might +// help fix it. +// +// add skills add "" --skill "*" - append '#' to the source to pin it +// install [source] add , or restore skills-lock.json with skills experimental_install +// update re-add every unique skills-lock.json source at its latest, with every skill +// check fail when a skill directory exists for an agent that is not selected +// fix remove the skills CLI's links from those directories +// +// Settings, highest first: command-line options, PURVIEW_SKILLS_* environment variables, the +// "Skills" section of .config/purview-build-sdk.json, then the defaults below. Every command runs +// from the repository root, because skills-lock.json and the agent directories belong to the +// repository rather than to a project. +// +// skills.mts is the source. skills.mjs is generated from it by Node's own type stripper, for a +// machine with Node but neither Bun nor Deno: edit this file, then run `just skills-script-sync`. +// Keep to erasable TypeScript (no enums, namespaces or parameter properties) so both stay possible. + +import { spawnSync } from "node:child_process"; +import { existsSync, lstatSync, readdirSync, readFileSync, rmdirSync, statSync, unlinkSync } from "node:fs"; +import { delimiter, dirname, join, relative, resolve } from "node:path"; +import process from "node:process"; +import { parseArgs } from "node:util"; + +const configKeys = [ + "Agents", + "Runner", + "RunnerCandidates", + "Package", + "Command", + "LockFile", + "DryRun", + "AgentDirectories", +]; + +// Each package runner spells "run this npm package" its own way. Every form was checked against the +// real tool, because a wrong one is a command that simply does not run. A runner missing from this +// table still works: it falls through to ' ', the form most new runners adopt. +const launchers = { + skills: () => "skills", + npx: (spec) => `npx -y ${spec}`, + bunx: (spec) => `bunx ${spec}`, + bun: (spec) => `bun x ${spec}`, + pnpm: (spec) => `pnpm dlx ${spec}`, + yarn: (spec) => `yarn dlx ${spec}`, + deno: (spec) => `deno run -A npm:${spec}`, +}; + +// Where the skills CLI writes a project-scope install for each agent, from its own agent table +// (skills 1.7.6, docs/agents.md). Only check and fix read this, and only when agents are selected. +// The CLI adds agents independently of this script; add one through Skills.AgentDirectories in +// .config/purview-build-sdk.json rather than waiting for a release. +const defaultAgentDirectories = [ + { + path: ".agents/skills", + agents: [ + "amp", + "antigravity", + "antigravity-cli", + "cline", + "codex", + "cursor", + "deepagents", + "dexto", + "droid", + "firebender", + "fx", + "gemini-cli", + "github-copilot", + "kilo", + "kimi-code-cli", + "loaf", + "opencode", + "pi", + "promptscript", + "replit", + "sarvam-code", + "universal", + "warp", + "zed", + ], + }, + { path: ".adal/skills", agents: ["adal"] }, + { path: ".aider-desk/skills", agents: ["aider-desk"] }, + { path: ".augment/skills", agents: ["augment"] }, + { path: ".autohand/skills", agents: ["autohand-code"] }, + { path: ".bob/skills", agents: ["bob"] }, + { path: ".claude/skills", agents: ["claude-code"] }, + { path: ".codeartsdoer/skills", agents: ["codearts-agent"] }, + { path: ".codebuddy/skills", agents: ["codebuddy"] }, + { path: ".codemaker/skills", agents: ["codemaker"] }, + { path: ".codestudio/skills", agents: ["codestudio"] }, + { path: ".commandcode/skills", agents: ["command-code"] }, + { path: ".continue/skills", agents: ["continue"] }, + { path: ".cortex/skills", agents: ["cortex"] }, + { path: ".crush/skills", agents: ["crush"] }, + { path: ".devin/skills", agents: ["devin"] }, + { path: ".forge/skills", agents: ["forgecode"] }, + { path: ".goose/skills", agents: ["goose"] }, + { path: ".grok/skills", agents: ["grok"] }, + { path: ".hermes/skills", agents: ["hermes-agent"] }, + { path: ".iflow/skills", agents: ["iflow-cli"] }, + { path: ".inferencesh/skills", agents: ["inference-sh"] }, + { path: ".jazz/skills", agents: ["jazz"] }, + { path: ".junie/skills", agents: ["junie"] }, + { path: ".kimchi/skills", agents: ["kimchi"] }, + { path: ".kiro/skills", agents: ["kiro-cli"] }, + { path: ".kode/skills", agents: ["kode"] }, + { path: ".lingma/skills", agents: ["lingma"] }, + { path: ".mcpjam/skills", agents: ["mcpjam"] }, + { path: ".minimax/skills", agents: ["minimax-code"] }, + { path: ".moxby/skills", agents: ["moxby"] }, + { path: ".mux/skills", agents: ["mux"] }, + { path: ".neovate/skills", agents: ["neovate"] }, + { path: ".ona/skills", agents: ["ona"] }, + { path: ".openhands/skills", agents: ["openhands"] }, + { path: ".pochi/skills", agents: ["pochi"] }, + { path: ".posit/assistant/skills", agents: ["posit-assistant"] }, + { path: ".qoder/skills", agents: ["qoder", "qoder-cn"] }, + { path: ".qwen/skills", agents: ["qwen-code"] }, + { path: ".reasonix/skills", agents: ["reasonix"] }, + { path: ".roo/skills", agents: ["roo"] }, + { path: ".rovodev/skills", agents: ["rovodev"] }, + { path: ".tabnine/agent/skills", agents: ["tabnine-cli"] }, + { path: ".terramind/skills", agents: ["terramind"] }, + { path: ".tinycloud/skills", agents: ["tinycloud"] }, + { path: ".trae/skills", agents: ["trae", "trae-cn"] }, + { path: ".vibe/skills", agents: ["mistral-vibe"] }, + { path: ".windsurf/skills", agents: ["windsurf"] }, + { path: ".zcode/skills", agents: ["zcode"] }, + { path: ".zencoder/skills", agents: ["zencoder", "zenflow"] }, + { path: "agent/skills", agents: ["eve"] }, + { path: "data/skills", agents: ["astrbot"] }, + // openclaw installs into a root 'skills/', the folder a repository authors its own skills in. It is + // listed so selecting openclaw is not an unknown agent, but the authored folder is never touched. + { path: "skills", agents: ["openclaw"] }, +]; + +const usage = `Usage: skills.mts [options] + +Commands: + add Install every skill a source has (append '#' to pin it) + install [source] Install from a source, or restore skills-lock.json + update Re-add every skills-lock.json source at its latest + check Fail when a skill directory exists for an unselected agent + fix Remove the skills CLI's links from those directories + +Options: + --root Repository root (default: the nearest folder holding .git) + --config Settings file (default: .config/purview-build-sdk.json) + --agents Agents to install to, separated by ',', ';' or spaces + --runner Package runner: bun, npx, bunx, pnpm, yarn, deno or skills + --command Launch the skills CLI with this command instead + --package Package the launcher runs (default: skills@1) + --lock-file skills-lock.json location (default: the repository root) + --dry-run Print the skills CLI commands without running them +`; + +class SkillsError extends Error {} + +let failed = false; + +function report(code, message) { + console.error(`error ${code}: ${message}`); + failed = true; +} + +function warn(code, message) { + console.error(`warning ${code}: ${message}`); +} + +function info(message) { + console.log(message); +} + +function environment(name) { + const value = process.env[name]; + return value === undefined || value.trim() === "" ? undefined : value.trim(); +} + +function splitList(value) { + return value + .replace(/^[\s,;"']+|[\s,;"']+$/g, "") + .split(/[\s,;]+/) + .filter((entry) => entry.length > 0); +} + +function quote(value) { + if (value.includes('"')) throw new SkillsError(`'${value}' contains a double quote, which cannot be passed safely.`); + return `"${value}"`; +} + +function unique(values) { + const seen = new Set(); + return values.filter((value) => { + const key = value.toLowerCase(); + if (seen.has(key)) return false; + seen.add(key); + return true; + }); +} + +// The nearest ancestor holding '.git' - a directory in a clone, a file in a worktree or a submodule. +// The recipes always pass --root; this only matters when the script is run by hand. +function findRepositoryRoot(start) { + for (let directory = resolve(start); ; directory = dirname(directory)) { + if (existsSync(join(directory, ".git"))) return directory; + if (dirname(directory) === directory) return resolve(start); + } +} + +function readConfig(configPath) { + if (!existsSync(configPath)) return {}; + + let document; + try { + document = JSON.parse(readFileSync(configPath, "utf8")); + } catch (exception) { + throw new SkillsError(`PRSKL0018 '${configPath}' is not valid JSON: ${(exception).message}`); + } + + const section = (document)?.["Skills"]; + if (section === undefined) return {}; + if (section === null || typeof section !== "object" || Array.isArray(section)) + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills" must be an object.`); + + for (const key of Object.keys(section)) { + if (!configKeys.includes(key)) + warn("PRSKL0019", `'${configPath}': "Skills.${key}" is not a setting and is ignored. Known: ${configKeys.join(", ")}.`); + } + + return section; +} + +function configString(config, key, configPath) { + const value = config[key]; + if (value === undefined || value === null) return undefined; + if (typeof value !== "string") throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.${key}" must be a string.`); + return value.trim() === "" ? undefined : value.trim(); +} + +function configList(config, key, configPath) { + const value = config[key]; + if (value === undefined || value === null) return undefined; + if (typeof value === "string") return splitList(value); + if (Array.isArray(value) && value.every((entry) => typeof entry === "string")) + return value.flatMap((entry) => splitList(entry)); + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.${key}" must be a string or an array of strings.`); +} + +function configBoolean(config, key, configPath) { + const value = config[key]; + if (value === undefined || value === null) return undefined; + if (typeof value !== "boolean") throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.${key}" must be true or false.`); + return value; +} + +function configAgentDirectories(config, configPath) { + const value = config["AgentDirectories"]; + if (value === undefined || value === null) return []; + if (typeof value !== "object" || Array.isArray(value)) + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.AgentDirectories" must map a directory to its agents.`); + + return Object.entries(value).map(([path, agents]) => { + if (typeof agents === "string") return { path, agents: splitList(agents) }; + if (Array.isArray(agents) && agents.every((entry) => typeof entry === "string")) + return { path, agents: agents }; + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.AgentDirectories.${path}" must be a string or an array of strings.`); + }); +} + +function parseBoolean(value) { + if (value === undefined) return undefined; + return ["1", "true", "yes", "on"].includes(value.toLowerCase()); +} + +function resolveSettings(values) { + const option = (name) => { + const value = values[name]; + return typeof value === "string" && value.trim() !== "" ? value.trim() : undefined; + }; + + const root = resolve(option("root") ?? findRepositoryRoot(process.cwd())); + const configPath = resolve(root, option("config") ?? environment("PURVIEW_SKILLS_CONFIG") ?? ".config/purview-build-sdk.json"); + const config = readConfig(configPath); + + const agents = option("agents") ?? environment("PURVIEW_SKILLS_AGENTS"); + const candidates = environment("PURVIEW_SKILLS_RUNNER_CANDIDATES"); + const lockFile = option("lock-file") ?? environment("PURVIEW_SKILLS_LOCK_FILE") ?? configString(config, "LockFile", configPath); + + return { + root, + configPath, + agents: agents !== undefined ? splitList(agents) : (configList(config, "Agents", configPath) ?? []), + runner: option("runner") ?? environment("PURVIEW_SKILLS_RUNNER") ?? configString(config, "Runner", configPath) ?? "bun", + runnerCandidates: + candidates !== undefined + ? splitList(candidates) + : (configList(config, "RunnerCandidates", configPath) ?? ["bun", "npx", "bunx", "pnpm", "yarn", "deno"]), + packageSpec: + option("package") ?? environment("PURVIEW_SKILLS_PACKAGE") ?? configString(config, "Package", configPath) ?? "skills@1", + command: option("command") ?? environment("PURVIEW_SKILLS_COMMAND") ?? configString(config, "Command", configPath) ?? "", + lockFile: resolve(root, lockFile ?? "skills-lock.json"), + dryRun: + values["dry-run"] === true || + (parseBoolean(environment("PURVIEW_SKILLS_DRY_RUN")) ?? configBoolean(config, "DryRun", configPath) ?? false), + agentDirectories: [...defaultAgentDirectories, ...configAgentDirectories(config, configPath)], + }; +} + +function launcherFor(runner, spec) { + const launcher = launchers[runner]; + return launcher === undefined ? `${runner} ${spec}` : launcher(spec); +} + +// PATH is probed directly rather than by starting a version check: no process, nothing to download, +// nothing to hang. PATHEXT is honoured on Windows, where these commands are .cmd shims. +function findOnPath(names) { + const windows = process.platform === "win32"; + const extensions = windows ? ["", ...(environment("PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)] : [""]; + const directories = (process.env["PATH"] ?? "") + .split(delimiter) + .map((entry) => entry.trim().replace(/^"|"$/g, "")) + .filter((entry) => entry.length > 0); + + for (const name of names) { + for (const directory of directories) { + for (const extension of extensions) { + const candidate = join(directory, name + extension); + try { + if (statSync(candidate).isFile()) return { name, path: candidate }; + } catch { + // Not here; a malformed PATH entry must not stop the probe either. + } + } + } + } + + return undefined; +} + +// 'skills' already on PATH is tried first because it needs no download, then the configured runner, +// then the other candidates - so a machine with Node but no Bun still installs. +function resolveLauncher(settings) { + if (settings.command !== "") return settings.command; + + const found = findOnPath(unique(["skills", settings.runner, ...settings.runnerCandidates])); + if (found !== undefined) { + const launcher = launcherFor(found.name, settings.packageSpec); + info(`Using the skills CLI via '${launcher}' (${found.path}).`); + return launcher; + } + + // A dry run runs nothing, so it works on a machine with no runner at all. + if (settings.dryRun) return launcherFor(settings.runner, settings.packageSpec); + + throw new SkillsError( + `PRSKL0004 Cannot run the skills CLI: none of ${unique(["skills", settings.runner, ...settings.runnerCandidates]).join(", ")} was found on PATH. ` + + "Install Bun (which provides 'bun x') or Node.js (which provides npx), or any of pnpm, yarn or deno, " + + "or install the CLI globally with 'npm install -g skills'. Choose a runner with --runner or Skills.Runner; " + + "replace the launcher entirely with --command or Skills.Command.", + ); +} + +function agentArguments(settings) { + // The CLI does not split a comma-separated --agent, so each agent gets its own flag. + return settings.agents.map((agent) => ` --agent ${quote(agent)}`).join(""); +} + +function execute(settings, commandLine) { + info(settings.dryRun ? `Agent skills (dry run): ${commandLine}` : `Agent skills: ${commandLine}`); + if (settings.dryRun) return 0; + + const result = spawnSync(commandLine, { cwd: settings.root, shell: true, stdio: "inherit" }); + if (result.error !== undefined) { + console.error(result.error.message); + return 1; + } + + return result.status ?? 1; +} + +function addSource(settings, source) { + const launcher = resolveLauncher(settings); + // '-y' keeps 'add' non-interactive. '*' is every skill the source has, and a re-run is safe: the + // CLI reinstalls each skill it is given, replacing the installed copy. + const exitCode = execute(settings, `${launcher} add ${quote(source)} --skill "*"${agentArguments(settings)} -y`); + if (exitCode !== 0) report("PRSKL0008", `Agent skills: adding '${source}' failed with exit code ${exitCode}.`); +} + +function install(settings, source) { + if (source !== undefined) { + addSource(settings, source); + return; + } + + if (!existsSync(settings.lockFile)) + throw new SkillsError( + `PRSKL0007 Nothing to install: no source was given, and '${settings.lockFile}' does not exist to restore from. ` + + "Install from a source first, for example: just skills-add purview-dev/build-sdk", + ); + + const exitCode = execute(settings, `${resolveLauncher(settings)} experimental_install`); + if (exitCode !== 0) report("PRSKL0008", `Agent skills: restoring '${settings.lockFile}' failed with exit code ${exitCode}.`); +} + +function readLockSources(lockFile) { + let document; + try { + document = JSON.parse(readFileSync(lockFile, "utf8")); + } catch (exception) { + throw new SkillsError(`PRSKL0007 Cannot read '${lockFile}': ${(exception).message}`); + } + + const skills = (document)?.skills ?? {}; + const sources = Object.values(skills) + .map((entry) => (typeof entry?.source === "string" ? entry.source.trim() : "")) + .filter((source) => source.length > 0); + + return unique(sources).sort((left, right) => left.toLowerCase().localeCompare(right.toLowerCase())); +} + +// Update is 'add', never 'skills update'. 'skills add' reinstalls every skill it selects, so one +// re-add of each source, with every skill it has, both refreshes what is installed and brings in +// anything the source has gained. The lockfile's own skill names are deliberately not reused: naming +// them would leave out a skill added since. Every source is attempted even when one fails. +function update(settings) { + if (!existsSync(settings.lockFile)) + throw new SkillsError( + `PRSKL0007 Cannot update agent skills: '${settings.lockFile}' does not exist. ` + + "Update re-adds the sources the skills CLI recorded there; install skills first with: just skills-add ", + ); + + const sources = readLockSources(settings.lockFile); + if (sources.length === 0) { + info(`Agent skills: no sources recorded in ${settings.lockFile}.`); + return; + } + + const launcher = resolveLauncher(settings); + const failures = []; + for (const source of sources) { + const exitCode = execute(settings, `${launcher} add ${quote(source)} --skill "*"${agentArguments(settings)} -y`); + if (exitCode !== 0) { + report("PRSKL0008", `Agent skills: re-adding '${source}' failed with exit code ${exitCode}.`); + failures.push(source); + } + } + + if (settings.dryRun) info(`Agent skills: dry run, ${sources.length} source(s), nothing changed.`); + else if (failures.length === 0) info(`Agent skills: ${sources.length} source(s) refreshed.`); +} + +function pathExists(path) { + // lstat does not follow a link, so a dangling one still counts as present. + try { + return lstatSync(path, { throwIfNoEntry: false }) !== undefined; + } catch { + return false; + } +} + +// Removes a link and never its target: unlink on Unix, and on Windows the directory form for a +// directory symlink or junction. +function deleteLink(path) { + try { + unlinkSync(path); + } catch { + rmdirSync(path); + } +} + +// When agents are selected, the only agent skill directories allowed are theirs, plus '.agents/skills', +// the CLI's canonical store that every agent directory links into. With fix set, the CLI's links are +// removed - a link only, never its target - and folders left empty go too. A real file is not provably +// the CLI's, so it is kept and reported. +function enforceDirectories(settings, fix) { + if (settings.agents.length === 0) { + info( + "Agent skills: no agents are selected, so the skills CLI auto-detects agents and every agent skill directory is expected. " + + `Set Skills.Agents in ${relative(settings.root, settings.configPath).replace(/\\/g, "/")} (or pass --agents) to enforce a layout.`, + ); + return; + } + + // '*' is every agent, so every directory is allowed. + if (settings.agents.includes("*")) return; + + const windows = process.platform === "win32"; + const key = (path) => (windows ? path.toLowerCase() : path); + const selected = settings.agents.map((agent) => agent.toLowerCase()); + const root = resolve(settings.root); + const toRelative = (path) => relative(root, path).replace(/\\/g, "/"); + + const directories = settings.agentDirectories + .map((entry) => ({ path: entry.path.replace(/\\/g, "/").replace(/^\/+|\/+$/g, ""), agents: entry.agents })) + .filter((entry) => entry.path.length > 0); + + const known = new Set(directories.flatMap((entry) => entry.agents.map((agent) => agent.toLowerCase()))); + for (const agent of settings.agents.filter((agent) => !known.has(agent.toLowerCase()))) + warn( + "PRSKL0016", + `Agent skills: '${agent}' is selected but has no known skills directory, so none is allowed for it. ` + + `Add it to Skills.AgentDirectories in ${toRelative(settings.configPath)} if the skills CLI supports it.`, + ); + + const allowed = new Set([key(".agents/skills")]); + for (const entry of directories) { + if (entry.agents.some((agent) => selected.includes(agent.toLowerCase()))) allowed.add(key(entry.path)); + } + + const protectedPaths = new Set([key(resolve(root, "skills"))]); + + const grouped = new Map(); + for (const entry of directories.filter((candidate) => !allowed.has(key(candidate.path)))) { + const existing = grouped.get(key(entry.path)); + if (existing === undefined) grouped.set(key(entry.path), { path: entry.path, agents: [...entry.agents] }); + else existing.agents.push(...entry.agents); + } + + const removed = []; + let violations = 0; + const kept = []; + + const prune = (path) => { + const stats = lstatSync(path); + if (stats.isSymbolicLink()) { + deleteLink(path); + removed.push(toRelative(path)); + return; + } + + if (!stats.isDirectory()) { + kept.push(toRelative(path)); + return; + } + + for (const child of readdirSync(path).sort()) prune(join(path, child)); + + if (readdirSync(path).length === 0) { + rmdirSync(path); + removed.push(toRelative(path)); + } + }; + + const ordered = [...grouped.values()].sort((left, right) => + left.path < right.path ? -1 : left.path > right.path ? 1 : 0, + ); + + for (const directory of ordered) { + const full = resolve(root, directory.path); + if (protectedPaths.has(key(full)) || !pathExists(full)) continue; + + kept.length = 0; + + // A dry run changes nothing, so it names what fix would clean up and leaves the outcome open. + if (fix && settings.dryRun) { + info( + `Agent skills (dry run): would remove the skills CLI's links from '${directory.path}', ` + + `the skills directory for ${directory.agents.join(", ")}, which the selected agents do not include.`, + ); + continue; + } + + if (fix) { + prune(full); + + // A folder that only ever held the agent's skills is left empty; remove it too, but never + // climb to the repository root. + let parent = dirname(full); + while ( + !pathExists(full) && + parent.length > root.length && + existsSync(parent) && + readdirSync(parent).length === 0 + ) { + rmdirSync(parent); + removed.push(toRelative(parent)); + parent = dirname(parent); + } + + if (!pathExists(full)) continue; + } + + violations++; + const agents = directory.agents.join(", "); + if (fix) { + // The CLI copies rather than links for some agent selections, so a kept folder can hold every + // file of every skill: name enough to recognise, then count the rest. + const sample = kept.slice(0, 5).join(", ") + (kept.length > 5 ? ` and ${kept.length - 5} more` : ""); + report( + "PRSKL0015", + `Agent skills: '${directory.path}' is the skills directory for ${agents}, which the selected agents (${settings.agents.join(", ")}) do not include, ` + + `and still holds content the skills CLI did not create: ${sample}. Remove it by hand.`, + ); + } else { + report( + "PRSKL0015", + `Agent skills: '${directory.path}' is the skills directory for ${agents}, which the selected agents (${settings.agents.join(", ")}) do not include. ` + + "Remove it with: just skills-fix", + ); + } + } + + for (const path of removed) info(`Agent skills: removed ${path}`); + + if (fix && settings.dryRun) info("Agent skills: dry run, nothing removed."); + else if (violations === 0) + info( + fix + ? `Agent skills: ${removed.length} path(s) removed; only the directories for ${settings.agents.join(", ")} exist.` + : `Agent skills: only the directories for ${settings.agents.join(", ")} exist.`, + ); +} + +function main(argv) { + const { values, positionals } = parseArgs({ + args: argv, + allowPositionals: true, + options: { + root: { type: "string" }, + config: { type: "string" }, + agents: { type: "string" }, + runner: { type: "string" }, + command: { type: "string" }, + package: { type: "string" }, + "lock-file": { type: "string" }, + "dry-run": { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }, + }); + + const [command, ...rest] = positionals; + if (values.help === true || command === undefined || command === "help") { + info(usage); + return command === undefined && values.help !== true ? 1 : 0; + } + + const settings = resolveSettings(values); + + switch (command) { + case "add": + if (rest[0] === undefined) throw new SkillsError("PRSKL0007 'add' needs a source, for example: add purview-dev/build-sdk"); + addSource(settings, rest[0]); + break; + case "install": + install(settings, rest[0]); + break; + case "update": + update(settings); + break; + case "check": + enforceDirectories(settings, false); + break; + case "fix": + enforceDirectories(settings, true); + break; + default: + console.error(`Unknown command '${command}'.`); + info(usage); + return 1; + } + + return failed ? 1 : 0; +} + +try { + process.exitCode = main(process.argv.slice(2)); +} catch (exception) { + if (exception instanceof SkillsError) { + const match = /^(PRSKL\d{4}) ([\s\S]*)$/.exec(exception.message); + if (match === null) report("PRSKL0018", exception.message); + else report(match[1] ?? "", match[2] ?? ""); + } else { + console.error((exception).message); + } + + process.exitCode = 1; +} diff --git a/.build/just/skills.mts b/.build/just/skills.mts new file mode 100644 index 0000000..9e85a86 --- /dev/null +++ b/.build/just/skills.mts @@ -0,0 +1,700 @@ +// The Purview.BuildSdk agent-skill commands: a thin wrapper over the standard skills CLI +// (`bun x skills@1` by default), run by the skills-* recipes in skills.just. +// +// Nothing here needs .NET. There is no solution to evaluate, no package to restore and no project +// that has to build, so a repository whose build is broken can still install the skills that might +// help fix it. +// +// add skills add "" --skill "*" - append '#' to the source to pin it +// install [source] add , or restore skills-lock.json with skills experimental_install +// update re-add every unique skills-lock.json source at its latest, with every skill +// check fail when a skill directory exists for an agent that is not selected +// fix remove the skills CLI's links from those directories +// +// Settings, highest first: command-line options, PURVIEW_SKILLS_* environment variables, the +// "Skills" section of .config/purview-build-sdk.json, then the defaults below. Every command runs +// from the repository root, because skills-lock.json and the agent directories belong to the +// repository rather than to a project. +// +// skills.mts is the source. skills.mjs is generated from it by Node's own type stripper, for a +// machine with Node but neither Bun nor Deno: edit this file, then run `just skills-script-sync`. +// Keep to erasable TypeScript (no enums, namespaces or parameter properties) so both stay possible. + +import { spawnSync } from "node:child_process"; +import { existsSync, lstatSync, readdirSync, readFileSync, rmdirSync, statSync, unlinkSync } from "node:fs"; +import { delimiter, dirname, join, relative, resolve } from "node:path"; +import process from "node:process"; +import { parseArgs } from "node:util"; + +type AgentDirectory = { path: string; agents: string[] }; + +type Settings = { + root: string; + configPath: string; + agents: string[]; + runner: string; + runnerCandidates: string[]; + packageSpec: string; + command: string; + lockFile: string; + dryRun: boolean; + agentDirectories: AgentDirectory[]; +}; + +type ConfigSection = Record; + +const configKeys: string[] = [ + "Agents", + "Runner", + "RunnerCandidates", + "Package", + "Command", + "LockFile", + "DryRun", + "AgentDirectories", +]; + +// Each package runner spells "run this npm package" its own way. Every form was checked against the +// real tool, because a wrong one is a command that simply does not run. A runner missing from this +// table still works: it falls through to ' ', the form most new runners adopt. +const launchers: Record string> = { + skills: () => "skills", + npx: (spec: string) => `npx -y ${spec}`, + bunx: (spec: string) => `bunx ${spec}`, + bun: (spec: string) => `bun x ${spec}`, + pnpm: (spec: string) => `pnpm dlx ${spec}`, + yarn: (spec: string) => `yarn dlx ${spec}`, + deno: (spec: string) => `deno run -A npm:${spec}`, +}; + +// Where the skills CLI writes a project-scope install for each agent, from its own agent table +// (skills 1.7.6, docs/agents.md). Only check and fix read this, and only when agents are selected. +// The CLI adds agents independently of this script; add one through Skills.AgentDirectories in +// .config/purview-build-sdk.json rather than waiting for a release. +const defaultAgentDirectories: AgentDirectory[] = [ + { + path: ".agents/skills", + agents: [ + "amp", + "antigravity", + "antigravity-cli", + "cline", + "codex", + "cursor", + "deepagents", + "dexto", + "droid", + "firebender", + "fx", + "gemini-cli", + "github-copilot", + "kilo", + "kimi-code-cli", + "loaf", + "opencode", + "pi", + "promptscript", + "replit", + "sarvam-code", + "universal", + "warp", + "zed", + ], + }, + { path: ".adal/skills", agents: ["adal"] }, + { path: ".aider-desk/skills", agents: ["aider-desk"] }, + { path: ".augment/skills", agents: ["augment"] }, + { path: ".autohand/skills", agents: ["autohand-code"] }, + { path: ".bob/skills", agents: ["bob"] }, + { path: ".claude/skills", agents: ["claude-code"] }, + { path: ".codeartsdoer/skills", agents: ["codearts-agent"] }, + { path: ".codebuddy/skills", agents: ["codebuddy"] }, + { path: ".codemaker/skills", agents: ["codemaker"] }, + { path: ".codestudio/skills", agents: ["codestudio"] }, + { path: ".commandcode/skills", agents: ["command-code"] }, + { path: ".continue/skills", agents: ["continue"] }, + { path: ".cortex/skills", agents: ["cortex"] }, + { path: ".crush/skills", agents: ["crush"] }, + { path: ".devin/skills", agents: ["devin"] }, + { path: ".forge/skills", agents: ["forgecode"] }, + { path: ".goose/skills", agents: ["goose"] }, + { path: ".grok/skills", agents: ["grok"] }, + { path: ".hermes/skills", agents: ["hermes-agent"] }, + { path: ".iflow/skills", agents: ["iflow-cli"] }, + { path: ".inferencesh/skills", agents: ["inference-sh"] }, + { path: ".jazz/skills", agents: ["jazz"] }, + { path: ".junie/skills", agents: ["junie"] }, + { path: ".kimchi/skills", agents: ["kimchi"] }, + { path: ".kiro/skills", agents: ["kiro-cli"] }, + { path: ".kode/skills", agents: ["kode"] }, + { path: ".lingma/skills", agents: ["lingma"] }, + { path: ".mcpjam/skills", agents: ["mcpjam"] }, + { path: ".minimax/skills", agents: ["minimax-code"] }, + { path: ".moxby/skills", agents: ["moxby"] }, + { path: ".mux/skills", agents: ["mux"] }, + { path: ".neovate/skills", agents: ["neovate"] }, + { path: ".ona/skills", agents: ["ona"] }, + { path: ".openhands/skills", agents: ["openhands"] }, + { path: ".pochi/skills", agents: ["pochi"] }, + { path: ".posit/assistant/skills", agents: ["posit-assistant"] }, + { path: ".qoder/skills", agents: ["qoder", "qoder-cn"] }, + { path: ".qwen/skills", agents: ["qwen-code"] }, + { path: ".reasonix/skills", agents: ["reasonix"] }, + { path: ".roo/skills", agents: ["roo"] }, + { path: ".rovodev/skills", agents: ["rovodev"] }, + { path: ".tabnine/agent/skills", agents: ["tabnine-cli"] }, + { path: ".terramind/skills", agents: ["terramind"] }, + { path: ".tinycloud/skills", agents: ["tinycloud"] }, + { path: ".trae/skills", agents: ["trae", "trae-cn"] }, + { path: ".vibe/skills", agents: ["mistral-vibe"] }, + { path: ".windsurf/skills", agents: ["windsurf"] }, + { path: ".zcode/skills", agents: ["zcode"] }, + { path: ".zencoder/skills", agents: ["zencoder", "zenflow"] }, + { path: "agent/skills", agents: ["eve"] }, + { path: "data/skills", agents: ["astrbot"] }, + // openclaw installs into a root 'skills/', the folder a repository authors its own skills in. It is + // listed so selecting openclaw is not an unknown agent, but the authored folder is never touched. + { path: "skills", agents: ["openclaw"] }, +]; + +const usage: string = `Usage: skills.mts [options] + +Commands: + add Install every skill a source has (append '#' to pin it) + install [source] Install from a source, or restore skills-lock.json + update Re-add every skills-lock.json source at its latest + check Fail when a skill directory exists for an unselected agent + fix Remove the skills CLI's links from those directories + +Options: + --root Repository root (default: the nearest folder holding .git) + --config Settings file (default: .config/purview-build-sdk.json) + --agents Agents to install to, separated by ',', ';' or spaces + --runner Package runner: bun, npx, bunx, pnpm, yarn, deno or skills + --command Launch the skills CLI with this command instead + --package Package the launcher runs (default: skills@1) + --lock-file skills-lock.json location (default: the repository root) + --dry-run Print the skills CLI commands without running them +`; + +class SkillsError extends Error {} + +let failed = false; + +function report(code: string, message: string): void { + console.error(`error ${code}: ${message}`); + failed = true; +} + +function warn(code: string, message: string): void { + console.error(`warning ${code}: ${message}`); +} + +function info(message: string): void { + console.log(message); +} + +function environment(name: string): string | undefined { + const value = process.env[name]; + return value === undefined || value.trim() === "" ? undefined : value.trim(); +} + +function splitList(value: string): string[] { + return value + .replace(/^[\s,;"']+|[\s,;"']+$/g, "") + .split(/[\s,;]+/) + .filter((entry: string) => entry.length > 0); +} + +function quote(value: string): string { + if (value.includes('"')) throw new SkillsError(`'${value}' contains a double quote, which cannot be passed safely.`); + return `"${value}"`; +} + +function unique(values: string[]): string[] { + const seen: Set = new Set(); + return values.filter((value: string) => { + const key = value.toLowerCase(); + if (seen.has(key)) return false; + seen.add(key); + return true; + }); +} + +// The nearest ancestor holding '.git' - a directory in a clone, a file in a worktree or a submodule. +// The recipes always pass --root; this only matters when the script is run by hand. +function findRepositoryRoot(start: string): string { + for (let directory = resolve(start); ; directory = dirname(directory)) { + if (existsSync(join(directory, ".git"))) return directory; + if (dirname(directory) === directory) return resolve(start); + } +} + +function readConfig(configPath: string): ConfigSection { + if (!existsSync(configPath)) return {}; + + let document: unknown; + try { + document = JSON.parse(readFileSync(configPath, "utf8")); + } catch (exception) { + throw new SkillsError(`PRSKL0018 '${configPath}' is not valid JSON: ${(exception as Error).message}`); + } + + const section = (document as Record | null)?.["Skills"]; + if (section === undefined) return {}; + if (section === null || typeof section !== "object" || Array.isArray(section)) + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills" must be an object.`); + + for (const key of Object.keys(section)) { + if (!configKeys.includes(key)) + warn("PRSKL0019", `'${configPath}': "Skills.${key}" is not a setting and is ignored. Known: ${configKeys.join(", ")}.`); + } + + return section as ConfigSection; +} + +function configString(config: ConfigSection, key: string, configPath: string): string | undefined { + const value = config[key]; + if (value === undefined || value === null) return undefined; + if (typeof value !== "string") throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.${key}" must be a string.`); + return value.trim() === "" ? undefined : value.trim(); +} + +function configList(config: ConfigSection, key: string, configPath: string): string[] | undefined { + const value = config[key]; + if (value === undefined || value === null) return undefined; + if (typeof value === "string") return splitList(value); + if (Array.isArray(value) && value.every((entry: unknown) => typeof entry === "string")) + return value.flatMap((entry: string) => splitList(entry)); + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.${key}" must be a string or an array of strings.`); +} + +function configBoolean(config: ConfigSection, key: string, configPath: string): boolean | undefined { + const value = config[key]; + if (value === undefined || value === null) return undefined; + if (typeof value !== "boolean") throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.${key}" must be true or false.`); + return value; +} + +function configAgentDirectories(config: ConfigSection, configPath: string): AgentDirectory[] { + const value = config["AgentDirectories"]; + if (value === undefined || value === null) return []; + if (typeof value !== "object" || Array.isArray(value)) + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.AgentDirectories" must map a directory to its agents.`); + + return Object.entries(value as Record).map(([path, agents]: [string, unknown]) => { + if (typeof agents === "string") return { path, agents: splitList(agents) }; + if (Array.isArray(agents) && agents.every((entry: unknown) => typeof entry === "string")) + return { path, agents: agents as string[] }; + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.AgentDirectories.${path}" must be a string or an array of strings.`); + }); +} + +function parseBoolean(value: string | undefined): boolean | undefined { + if (value === undefined) return undefined; + return ["1", "true", "yes", "on"].includes(value.toLowerCase()); +} + +function resolveSettings(values: Record): Settings { + const option = (name: string): string | undefined => { + const value = values[name]; + return typeof value === "string" && value.trim() !== "" ? value.trim() : undefined; + }; + + const root = resolve(option("root") ?? findRepositoryRoot(process.cwd())); + const configPath = resolve(root, option("config") ?? environment("PURVIEW_SKILLS_CONFIG") ?? ".config/purview-build-sdk.json"); + const config = readConfig(configPath); + + const agents = option("agents") ?? environment("PURVIEW_SKILLS_AGENTS"); + const candidates = environment("PURVIEW_SKILLS_RUNNER_CANDIDATES"); + const lockFile = option("lock-file") ?? environment("PURVIEW_SKILLS_LOCK_FILE") ?? configString(config, "LockFile", configPath); + + return { + root, + configPath, + agents: agents !== undefined ? splitList(agents) : (configList(config, "Agents", configPath) ?? []), + runner: option("runner") ?? environment("PURVIEW_SKILLS_RUNNER") ?? configString(config, "Runner", configPath) ?? "bun", + runnerCandidates: + candidates !== undefined + ? splitList(candidates) + : (configList(config, "RunnerCandidates", configPath) ?? ["bun", "npx", "bunx", "pnpm", "yarn", "deno"]), + packageSpec: + option("package") ?? environment("PURVIEW_SKILLS_PACKAGE") ?? configString(config, "Package", configPath) ?? "skills@1", + command: option("command") ?? environment("PURVIEW_SKILLS_COMMAND") ?? configString(config, "Command", configPath) ?? "", + lockFile: resolve(root, lockFile ?? "skills-lock.json"), + dryRun: + values["dry-run"] === true || + (parseBoolean(environment("PURVIEW_SKILLS_DRY_RUN")) ?? configBoolean(config, "DryRun", configPath) ?? false), + agentDirectories: [...defaultAgentDirectories, ...configAgentDirectories(config, configPath)], + }; +} + +function launcherFor(runner: string, spec: string): string { + const launcher = launchers[runner]; + return launcher === undefined ? `${runner} ${spec}` : launcher(spec); +} + +// PATH is probed directly rather than by starting a version check: no process, nothing to download, +// nothing to hang. PATHEXT is honoured on Windows, where these commands are .cmd shims. +function findOnPath(names: string[]): { name: string; path: string } | undefined { + const windows = process.platform === "win32"; + const extensions = windows ? ["", ...(environment("PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)] : [""]; + const directories = (process.env["PATH"] ?? "") + .split(delimiter) + .map((entry: string) => entry.trim().replace(/^"|"$/g, "")) + .filter((entry: string) => entry.length > 0); + + for (const name of names) { + for (const directory of directories) { + for (const extension of extensions) { + const candidate = join(directory, name + extension); + try { + if (statSync(candidate).isFile()) return { name, path: candidate }; + } catch { + // Not here; a malformed PATH entry must not stop the probe either. + } + } + } + } + + return undefined; +} + +// 'skills' already on PATH is tried first because it needs no download, then the configured runner, +// then the other candidates - so a machine with Node but no Bun still installs. +function resolveLauncher(settings: Settings): string { + if (settings.command !== "") return settings.command; + + const found = findOnPath(unique(["skills", settings.runner, ...settings.runnerCandidates])); + if (found !== undefined) { + const launcher = launcherFor(found.name, settings.packageSpec); + info(`Using the skills CLI via '${launcher}' (${found.path}).`); + return launcher; + } + + // A dry run runs nothing, so it works on a machine with no runner at all. + if (settings.dryRun) return launcherFor(settings.runner, settings.packageSpec); + + throw new SkillsError( + `PRSKL0004 Cannot run the skills CLI: none of ${unique(["skills", settings.runner, ...settings.runnerCandidates]).join(", ")} was found on PATH. ` + + "Install Bun (which provides 'bun x') or Node.js (which provides npx), or any of pnpm, yarn or deno, " + + "or install the CLI globally with 'npm install -g skills'. Choose a runner with --runner or Skills.Runner; " + + "replace the launcher entirely with --command or Skills.Command.", + ); +} + +function agentArguments(settings: Settings): string { + // The CLI does not split a comma-separated --agent, so each agent gets its own flag. + return settings.agents.map((agent: string) => ` --agent ${quote(agent)}`).join(""); +} + +function execute(settings: Settings, commandLine: string): number { + info(settings.dryRun ? `Agent skills (dry run): ${commandLine}` : `Agent skills: ${commandLine}`); + if (settings.dryRun) return 0; + + const result = spawnSync(commandLine, { cwd: settings.root, shell: true, stdio: "inherit" }); + if (result.error !== undefined) { + console.error(result.error.message); + return 1; + } + + return result.status ?? 1; +} + +function addSource(settings: Settings, source: string): void { + const launcher = resolveLauncher(settings); + // '-y' keeps 'add' non-interactive. '*' is every skill the source has, and a re-run is safe: the + // CLI reinstalls each skill it is given, replacing the installed copy. + const exitCode = execute(settings, `${launcher} add ${quote(source)} --skill "*"${agentArguments(settings)} -y`); + if (exitCode !== 0) report("PRSKL0008", `Agent skills: adding '${source}' failed with exit code ${exitCode}.`); +} + +function install(settings: Settings, source: string | undefined): void { + if (source !== undefined) { + addSource(settings, source); + return; + } + + if (!existsSync(settings.lockFile)) + throw new SkillsError( + `PRSKL0007 Nothing to install: no source was given, and '${settings.lockFile}' does not exist to restore from. ` + + "Install from a source first, for example: just skills-add purview-dev/build-sdk", + ); + + const exitCode = execute(settings, `${resolveLauncher(settings)} experimental_install`); + if (exitCode !== 0) report("PRSKL0008", `Agent skills: restoring '${settings.lockFile}' failed with exit code ${exitCode}.`); +} + +function readLockSources(lockFile: string): string[] { + let document: unknown; + try { + document = JSON.parse(readFileSync(lockFile, "utf8")); + } catch (exception) { + throw new SkillsError(`PRSKL0007 Cannot read '${lockFile}': ${(exception as Error).message}`); + } + + const skills = (document as { skills?: Record } | null)?.skills ?? {}; + const sources = Object.values(skills) + .map((entry: { source?: unknown }) => (typeof entry?.source === "string" ? entry.source.trim() : "")) + .filter((source: string) => source.length > 0); + + return unique(sources).sort((left: string, right: string) => left.toLowerCase().localeCompare(right.toLowerCase())); +} + +// Update is 'add', never 'skills update'. 'skills add' reinstalls every skill it selects, so one +// re-add of each source, with every skill it has, both refreshes what is installed and brings in +// anything the source has gained. The lockfile's own skill names are deliberately not reused: naming +// them would leave out a skill added since. Every source is attempted even when one fails. +function update(settings: Settings): void { + if (!existsSync(settings.lockFile)) + throw new SkillsError( + `PRSKL0007 Cannot update agent skills: '${settings.lockFile}' does not exist. ` + + "Update re-adds the sources the skills CLI recorded there; install skills first with: just skills-add ", + ); + + const sources = readLockSources(settings.lockFile); + if (sources.length === 0) { + info(`Agent skills: no sources recorded in ${settings.lockFile}.`); + return; + } + + const launcher = resolveLauncher(settings); + const failures: string[] = []; + for (const source of sources) { + const exitCode = execute(settings, `${launcher} add ${quote(source)} --skill "*"${agentArguments(settings)} -y`); + if (exitCode !== 0) { + report("PRSKL0008", `Agent skills: re-adding '${source}' failed with exit code ${exitCode}.`); + failures.push(source); + } + } + + if (settings.dryRun) info(`Agent skills: dry run, ${sources.length} source(s), nothing changed.`); + else if (failures.length === 0) info(`Agent skills: ${sources.length} source(s) refreshed.`); +} + +function pathExists(path: string): boolean { + // lstat does not follow a link, so a dangling one still counts as present. + try { + return lstatSync(path, { throwIfNoEntry: false }) !== undefined; + } catch { + return false; + } +} + +// Removes a link and never its target: unlink on Unix, and on Windows the directory form for a +// directory symlink or junction. +function deleteLink(path: string): void { + try { + unlinkSync(path); + } catch { + rmdirSync(path); + } +} + +// When agents are selected, the only agent skill directories allowed are theirs, plus '.agents/skills', +// the CLI's canonical store that every agent directory links into. With fix set, the CLI's links are +// removed - a link only, never its target - and folders left empty go too. A real file is not provably +// the CLI's, so it is kept and reported. +function enforceDirectories(settings: Settings, fix: boolean): void { + if (settings.agents.length === 0) { + info( + "Agent skills: no agents are selected, so the skills CLI auto-detects agents and every agent skill directory is expected. " + + `Set Skills.Agents in ${relative(settings.root, settings.configPath).replace(/\\/g, "/")} (or pass --agents) to enforce a layout.`, + ); + return; + } + + // '*' is every agent, so every directory is allowed. + if (settings.agents.includes("*")) return; + + const windows = process.platform === "win32"; + const key = (path: string): string => (windows ? path.toLowerCase() : path); + const selected = settings.agents.map((agent: string) => agent.toLowerCase()); + const root = resolve(settings.root); + const toRelative = (path: string): string => relative(root, path).replace(/\\/g, "/"); + + const directories = settings.agentDirectories + .map((entry: AgentDirectory) => ({ path: entry.path.replace(/\\/g, "/").replace(/^\/+|\/+$/g, ""), agents: entry.agents })) + .filter((entry: AgentDirectory) => entry.path.length > 0); + + const known: Set = new Set(directories.flatMap((entry: AgentDirectory) => entry.agents.map((agent: string) => agent.toLowerCase()))); + for (const agent of settings.agents.filter((agent: string) => !known.has(agent.toLowerCase()))) + warn( + "PRSKL0016", + `Agent skills: '${agent}' is selected but has no known skills directory, so none is allowed for it. ` + + `Add it to Skills.AgentDirectories in ${toRelative(settings.configPath)} if the skills CLI supports it.`, + ); + + const allowed: Set = new Set([key(".agents/skills")]); + for (const entry of directories) { + if (entry.agents.some((agent: string) => selected.includes(agent.toLowerCase()))) allowed.add(key(entry.path)); + } + + const protectedPaths: Set = new Set([key(resolve(root, "skills"))]); + + const grouped: Map = new Map(); + for (const entry of directories.filter((candidate: AgentDirectory) => !allowed.has(key(candidate.path)))) { + const existing = grouped.get(key(entry.path)); + if (existing === undefined) grouped.set(key(entry.path), { path: entry.path, agents: [...entry.agents] }); + else existing.agents.push(...entry.agents); + } + + const removed: string[] = []; + let violations = 0; + const kept: string[] = []; + + const prune = (path: string): void => { + const stats = lstatSync(path); + if (stats.isSymbolicLink()) { + deleteLink(path); + removed.push(toRelative(path)); + return; + } + + if (!stats.isDirectory()) { + kept.push(toRelative(path)); + return; + } + + for (const child of readdirSync(path).sort()) prune(join(path, child)); + + if (readdirSync(path).length === 0) { + rmdirSync(path); + removed.push(toRelative(path)); + } + }; + + const ordered = [...grouped.values()].sort((left: AgentDirectory, right: AgentDirectory) => + left.path < right.path ? -1 : left.path > right.path ? 1 : 0, + ); + + for (const directory of ordered) { + const full = resolve(root, directory.path); + if (protectedPaths.has(key(full)) || !pathExists(full)) continue; + + kept.length = 0; + + // A dry run changes nothing, so it names what fix would clean up and leaves the outcome open. + if (fix && settings.dryRun) { + info( + `Agent skills (dry run): would remove the skills CLI's links from '${directory.path}', ` + + `the skills directory for ${directory.agents.join(", ")}, which the selected agents do not include.`, + ); + continue; + } + + if (fix) { + prune(full); + + // A folder that only ever held the agent's skills is left empty; remove it too, but never + // climb to the repository root. + let parent = dirname(full); + while ( + !pathExists(full) && + parent.length > root.length && + existsSync(parent) && + readdirSync(parent).length === 0 + ) { + rmdirSync(parent); + removed.push(toRelative(parent)); + parent = dirname(parent); + } + + if (!pathExists(full)) continue; + } + + violations++; + const agents = directory.agents.join(", "); + if (fix) { + // The CLI copies rather than links for some agent selections, so a kept folder can hold every + // file of every skill: name enough to recognise, then count the rest. + const sample = kept.slice(0, 5).join(", ") + (kept.length > 5 ? ` and ${kept.length - 5} more` : ""); + report( + "PRSKL0015", + `Agent skills: '${directory.path}' is the skills directory for ${agents}, which the selected agents (${settings.agents.join(", ")}) do not include, ` + + `and still holds content the skills CLI did not create: ${sample}. Remove it by hand.`, + ); + } else { + report( + "PRSKL0015", + `Agent skills: '${directory.path}' is the skills directory for ${agents}, which the selected agents (${settings.agents.join(", ")}) do not include. ` + + "Remove it with: just skills-fix", + ); + } + } + + for (const path of removed) info(`Agent skills: removed ${path}`); + + if (fix && settings.dryRun) info("Agent skills: dry run, nothing removed."); + else if (violations === 0) + info( + fix + ? `Agent skills: ${removed.length} path(s) removed; only the directories for ${settings.agents.join(", ")} exist.` + : `Agent skills: only the directories for ${settings.agents.join(", ")} exist.`, + ); +} + +function main(argv: string[]): number { + const { values, positionals } = parseArgs({ + args: argv, + allowPositionals: true, + options: { + root: { type: "string" }, + config: { type: "string" }, + agents: { type: "string" }, + runner: { type: "string" }, + command: { type: "string" }, + package: { type: "string" }, + "lock-file": { type: "string" }, + "dry-run": { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }, + }); + + const [command, ...rest] = positionals; + if (values.help === true || command === undefined || command === "help") { + info(usage); + return command === undefined && values.help !== true ? 1 : 0; + } + + const settings = resolveSettings(values as Record); + + switch (command) { + case "add": + if (rest[0] === undefined) throw new SkillsError("PRSKL0007 'add' needs a source, for example: add purview-dev/build-sdk"); + addSource(settings, rest[0]); + break; + case "install": + install(settings, rest[0]); + break; + case "update": + update(settings); + break; + case "check": + enforceDirectories(settings, false); + break; + case "fix": + enforceDirectories(settings, true); + break; + default: + console.error(`Unknown command '${command}'.`); + info(usage); + return 1; + } + + return failed ? 1 : 0; +} + +try { + process.exitCode = main(process.argv.slice(2)); +} catch (exception) { + if (exception instanceof SkillsError) { + const match = /^(PRSKL\d{4}) ([\s\S]*)$/.exec(exception.message); + if (match === null) report("PRSKL0018", exception.message); + else report(match[1] ?? "", match[2] ?? ""); + } else { + console.error((exception as Error).message); + } + + process.exitCode = 1; +} diff --git a/.editorconfig b/.editorconfig index a1e0051..b0390ec 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,4 +1,4 @@ -# Purview.BuildSdk 2.1.0 - managed file, do not edit +# Purview.BuildSdk 2.2.0 - managed file, do not edit # # This file is written by Purview.BuildSdk and is replaced whenever the SDK version changes. The version # on the first line is how the SDK recognises a file it owns: a .editorconfig without that marker is diff --git a/AGENTS.md b/AGENTS.md index 9d9672e..01bf262 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -78,9 +78,9 @@ The authored set, and what each one answers: | [`purview-buildsdk-project-detection`](skills/purview-buildsdk-project-detection/SKILL.md) | why did the SDK do that automatically, target framework included | | [`purview-buildsdk-testing`](skills/purview-buildsdk-testing/SKILL.md) | writing TUnit tests, and running them under MTP | | [`purview-buildsdk-skill-tests`](skills/purview-buildsdk-skill-tests/SKILL.md) | authoring a skill, and validating it with `Purview.Skills.Testing` | -| [`purview-buildsdk-skill-installation`](skills/purview-buildsdk-skill-installation/SKILL.md) | installing the skills a package ships, and the `PRSKL*` diagnostics | +| [`purview-buildsdk-skill-installation`](skills/purview-buildsdk-skill-installation/SKILL.md) | installing, updating and tidying skills with the `skills-*` recipes, `.config/purview-build-sdk.json`, and the `PRSKL*` diagnostics | | [`purview-buildsdk-repository-review`](skills/purview-buildsdk-repository-review/SKILL.md) | auditing a repository against the SDK's conventions | -| [`purview-buildsdk-justfile`](skills/purview-buildsdk-justfile/SKILL.md) | the root `Justfile` and the shared `.build/just/` modules: .NET, version and `bump`, pipeline, skill targets, utilities, docs site, and the exported environment | +| [`purview-buildsdk-justfile`](skills/purview-buildsdk-justfile/SKILL.md) | the root `Justfile` and the shared `.build/just/` modules: .NET, version and `bump`, pipeline, the skill recipes and `skills.mts`, utilities, docs site, and the exported environment | | [`purview-buildsdk-msbuild-properties`](skills/purview-buildsdk-msbuild-properties/SKILL.md) | adding, renaming, deprecating or removing an MSBuild property, its `.buildschema.json` sidecar, and `ValidatePurviewPropertySchema` (`PRPSC*`) | | [`purview-buildsdk-docs-sync`](./skills/purview-buildsdk-docs-sync/SKILL.md) | keeping the skills, agent instructions, READMEs and `docs/wiki/` true to the code, and the wiki hierarchical | @@ -118,46 +118,47 @@ Tests live in `src/tests/BuildSdk.IntegrationTests/RepositoryFileSyncTests.cs` ( Installing skills into the agent-specific directories is a separate, **explicit** step — it must never be a side effect of a restore, a build, a design-time build or a test run. -The skill targets are a **thin wrapper over the standard skills CLI** (`bun x skills` by default), with nothing bespoke: no package-to-skill mapping, no metadata in packages, no competing lockfile. A repository publishes skills in its root `skills/`; the CLI installs them and records each in `skills-lock.json`. +It is **not MSBuild**. The `skills-*` recipes in the `purview-buildsdk-justfile` skill's `skills.just` run `skills.mts` beside it, a thin wrapper over the standard skills CLI (`bun x skills` by default), with nothing bespoke: no package-to-skill mapping, no metadata in packages, no competing lockfile. A repository publishes skills in its root `skills/`; the CLI installs them and records each in `skills-lock.json`. ```bash -dotnet msbuild -t:InstallPurviewSkills -p:PurviewSkillsSource=owner/repo # skills add "owner/repo" --skill "*" -dotnet msbuild -t:InstallPurviewSkills # skills experimental_install -dotnet msbuild -t:UpdatePurviewSkills # skills add "" --skill "*", once per lockfile source -dotnet msbuild -t:CheckPurviewSkills # only the PurviewSkillsAgents directories exist -dotnet msbuild -t:FixPurviewSkills # remove the CLI's links from any other agent directory +just skills-add owner/repo # skills add "owner/repo" --skill "*" +just skills-install # skills experimental_install +just skills-update # skills add "" --skill "*", once per lockfile source; then fix +just skills-check # only the selected agents' directories exist +just skills-fix # remove the CLI's links from any other agent directory ``` -The caller owns the ref: append `#` to a source to pin it. With no source and no lockfile, install is `PRSKL0007`. This used to be package-driven — `ResolvePurviewSkillSources` read a `.agents/skills/` folder inside each restored package plus its nuspec commit, and `ListPurviewSkills`/`RecommendPurviewSkills`/`VerifyPurviewSkills` reported missing or drifted skills (`PRSKL0001`/`0002`/`0010`–`0014`/`0017`). All of that was removed: it was bespoke metadata that no package built by this SDK carried, so it never found anything. +The MSBuild targets that used to do this — `InstallPurviewSkills`, `UpdatePurviewSkills`, `CheckPurviewSkills`, `FixPurviewSkills`, with the solution-leader election, `DetectPurviewSkillsCli`, `ReadPurviewSkillsLockSources`, `EnforcePurviewSkillDirectories`, the `PurviewSkillsRunnerLauncher`/`PurviewSkillsAgentDirectory` items and the `PurviewSkillsAgents`/`Runner`/`RunnerCandidates`/`Package`/`Command`/`Source`/`LockFile`/`DryRun` properties — were **removed**, not wrapped. Each run evaluated every project in the solution (about 5 s here, against 0.4 s for the script), and failed outright whenever one project did not evaluate — exactly when a repository may need new skills to fix its build. `PRSKL0003` and `PRSKL0009` went with them. Do not reintroduce an MSBuild skill target. -The CLI owns the agent-specific destinations and their discovery conventions — which differ per agent and change independently of this SDK — and owns `skills-lock.json`, which is why installation is delegated rather than reimplemented. +### Three files, one source -`PurviewSkillsAgents` is **empty by default**, which passes no `--agent` at all, so the CLI auto-detects agents. Set, it becomes one `--agent` per name (`_ResolvePurviewSkillsAgents` splits on `,`, `;` and spaces) — the CLI's `--agent` does not split a comma-separated value, so the old `--agent "claude-code,codex"` form named one agent that does not exist. `dotnet msbuild -p:` itself splits on `,` and `;`, so a command line needs `%2C` or a quoted value; tests use `%2C`. A restore (`experimental_install`) is passed no agent flag. -### Package runners and the repository root +`skills.mts` is the source. `skills.mjs` is **generated** from it by `scripts/sync-skills-script.mjs`, which uses Node's own `module.stripTypeScriptTypes` (Node 22.13+) and then removes the characters it blanked, so the output is the source minus its types with every comment kept. Edit `skills/purview-buildsdk-justfile/assets/just/skills.mts`, then `just skills-script-sync` regenerates `skills.mjs` and copies both into `.build/just/`. `SkillsScriptTests.GeneratedJavaScript_MatchesTheTypeScriptSource` fails while they differ (and skips on a Node without the stripper); `JustModuleParityTests` fails while `.build/just/` differs from the skill. Keep `skills.mts` to erasable TypeScript — no `enum`, `namespace` or parameter properties — and keep explicit generics off calls (`const m: Map = new Map()`), which the generator's clean-up assumes. + +The recipes pick the runtime in a small `sh` function: Bun with `skills.mts`, then Deno with `skills.mts`, then Node with `skills.mjs`; `PURVIEW_SKILLS_RUNTIME` overrides. `just`'s `which()` is deliberately not used — it needs an unstable setting. -Two invariants govern how the CLI is launched, and both are load-bearing. +### Settings -**Any package runner, defaulting to bun.** The CLI is published to npm and each runner spells "run this npm package" differently. `PurviewSkillsRunner` (default `bun`, i.e. `bun x skills@1`) selects one; the mapping lives in the `PurviewSkillsRunnerLauncher` item group in `Sdk/Sdk.targets`, which carries one version-pinned `Exec` launcher per runner. A runner with no entry falls through to ` $(PurviewSkillsPackage)`, so an unknown runner still works. Each invocation form was verified against the real tool — `npx -y`, `bunx`, `bun x`, `pnpm dlx`, `yarn dlx` (Yarn 2+ only), `deno run -A npm:` — because a wrong form is a command that simply does not run. +`.config/purview-build-sdk.json`, section `Skills`: `Agents`, `Runner`, `RunnerCandidates`, `Package`, `Command`, `LockFile`, `DryRun`, `AgentDirectories`. Highest first: a command-line option (`--agents`, `--runner`, `--package`, `--command`, `--lock-file`, `--dry-run`), a `PURVIEW_SKILLS_*` environment variable, the file, the default. Invalid JSON or a wrong type is `PRSKL0018`; an unknown key is `PRSKL0019` (warning). The PascalCase keys match `.config/purview-build.json`. -`DetectPurviewSkillsCli` (inline task) probes `PATH` for `skills` first, then `$(PurviewSkillsRunner)`, then `$(PurviewSkillsRunnerCandidates)`, honouring `PATHEXT` on Windows where these are `.cmd` shims. `PATH` is read directly rather than by spawning a version check: deterministic, no process, cannot hang on a cold download. The runner actually found wins over the configured preference. Nothing found is `PRSKL0004`; `PurviewSkillsCommand` overrides the launcher entirely and skips detection. +`Agents` is **empty by default**, which passes no `--agent` at all, so the CLI auto-detects agents. Set, it becomes one `--agent` per name — the CLI's `--agent` does not split a comma-separated value. A restore (`experimental_install`) is passed no agent flag. -**Always the repository root.** `skills-lock.json` and the agent directories belong to the repository, not to a project, so `ResolvePurviewSkillsRepositoryRoot` resolves one root and every skill target runs from it: `PurviewSkillsInstallRoot` → a user-set `PurviewSkillsRepoRoot` → the marker walk → `PurviewSkillsRepoRoot`/`RepoRoot` as guessed → CI workspace variables → SourceLink's git `SourceRoot`. There is deliberately **no project-directory fallback** — that would scatter a lockfile and an agent directory through the tree, one per project. An unresolved root is `PRSKL0003` (naming `PurviewSkillsInstallRoot`). +### Package runners and the repository root -The marker walk is `FindPurviewRepositoryRoot` (inline task), driven by `PurviewRepositoryRootMarkers` — `.git/;.github/;.gitattributes;LICENSE.md;AGENTS.md;.agents/;CLAUDE.md;.claude/;package.json`. Three things about it are load-bearing and easy to break: +**Any package runner, defaulting to bun.** The `launchers` table in `skills.mts` carries one version-pinned launcher per runner (`bun x`, `npx -y`, `bunx`, `pnpm dlx`, `yarn dlx` (Yarn 2+), `deno run -A npm:`), each verified against the real tool. A runner with no entry falls through to ` `. `PATH` is probed directly for `skills`, then `Runner`, then `RunnerCandidates`, honouring `PATHEXT` on Windows — no version-check process, nothing to hang on. The runner actually found wins. Nothing found is `PRSKL0004`; `Command` overrides the launcher and skips detection. A dry run with no runner prints the configured runner's launcher. Every command is printed (`Agent skills: `) before it runs, which is what the tests assert on. -- **It cannot be an MSBuild intrinsic.** `GetDirectoryNameOfFileAbove` matches *files only* and returns nothing for `.git/`, `.github/`, `.agents/` or `.claude/` — four of the nine markers. Verified, not assumed. -- **Two passes.** The first marker in the list is definitive and is searched all the way up (`.git/` *is* the repository root, so a monorepo sub-package does not win). Every other marker uses nearest-ancestor-wins, with list order breaking ties inside one directory. Searching them all to the top would let a stray `.claude/` in a developer's home directory outrank the real root. -- **The home directory and everything above it are never candidates.** Without that bound, a project outside any repository resolves to `~` and installs into it. A repository below the home directory is unaffected. +**Always the repository root.** The recipes pass `--root` as the directory holding the root `Justfile`; run by hand, the script uses the nearest ancestor holding `.git`, else the current directory. Every CLI command runs with that as its working directory. -The marker walk outranks the evaluation-time `PurviewSkillsRepoRoot` guess (which only knows `RepoRoot` and an `AGENTS.md` walk-up), because an `AGENTS.md` can legitimately sit in a subdirectory. `_PurviewSkillsRepoRootWasSpecified` is captured in `Sdk.props` before defaulting so a value the *user* set still wins. +### Update, check and fix -A dry run (`PurviewSkillsDryRun=true`) with no runner on `PATH` prints the configured runner's launcher rather than failing. +`update` re-adds each unique lockfile source once, at its latest with `--skill "*"`, and **that is the whole update — `skills update` is never run**. `skills add` reinstalls every skill it selects (verified in the CLI source, skills 1.7.6: `installSkillForAgent` cleans each skill's folder and copies it again), so one re-add both refreshes the installed skills and adds any the source has gained. The lockfile's recorded names are deliberately not reused, which would leave out anything new. Every source is attempted and each failure named (`PRSKL0008`); `--dry-run` prints and runs nothing. -Note that a target's `Condition` is evaluated *before* its `DependsOnTargets` run, so a property a dependency computes is still empty there. That is why the unresolved-root check (`PRSKL0003`) and the `PRSKL0009` guard are `Error`s inside dependency targets rather than `Condition`s on the public targets. +`check`/`fix` do nothing unless agents are selected. Then the only agent skill directories allowed are those agents', per the `defaultAgentDirectories` table in `skills.mts` (copied from the CLI's agent table — extend it, or let a repository add to it through `AgentDirectories`), plus `.agents/skills`, the canonical store. The authored `skills/` folder is protected even though openclaw installs there. Fix deletes links only (never their targets) and folders left empty; a real file is kept and reported as `PRSKL0015`. The CLI writes copies, not links, for some agent selections, so those are kept too. + +Tests live in `src/tests/BuildSdk.IntegrationTests/SkillsScriptTests.cs`. Each behaviour test runs once per runtime (Node with `skills.mjs`, Bun and Deno with `skills.mts`) and skips a runtime that is not on `PATH`. `--command echo` stands in for the CLI: never let a test reach `bun x` or `npx`, which download from the network. An empty `PATH` stands in for a machine with no runner. ### Validating skills -`ValidatePurviewSkills` runs `BeforeTargets="Pack"` and checks that every authored skill is well formed, so a malformed skill fails in the repository that owns it rather than reaching the CLI, which would silently skip it. It validates the folder under the root `ResolvePurviewSkillsRepositoryRoot` resolved — the same one every skill target uses — rather than the evaluation-time `PurviewSkillsSourceFolder`, because that guess only knows `RepoRoot` and an `AGENTS.md` walk-up: on a CI runner `RepoRoot` comes from `GITHUB_WORKSPACE`, so reading it there validated a different repository's skills and passed silently. It checks: +`ValidatePurviewSkills` runs `BeforeTargets="Pack"` and checks that every authored skill is well formed, so a malformed skill fails in the repository that owns it rather than reaching the CLI, which would silently skip it. It validates the folder under the root `ResolvePurviewSkillsRepositoryRoot` resolved — the same one `SkillRepositoryRoot` resolves in the tests — rather than the evaluation-time `PurviewSkillsSourceFolder`, because that guess only knows `RepoRoot` and an `AGENTS.md` walk-up: on a CI runner `RepoRoot` comes from `GITHUB_WORKSPACE`, so reading it there validated a different repository's skills and passed silently. It checks: - every folder under the skills root has a `SKILL.md`, - that file opens with YAML frontmatter carrying `name` and `description` (a `>-` block scalar counts), @@ -229,52 +230,6 @@ Two rules are worth knowing the reasoning for. A repository with **no** `skills/ Tests live in `src/tests/SkillsTesting.UnitTests/`, with the repository-level ones in `src/tests/BuildSdk.IntegrationTests/RepositorySkillTests.cs`, `SkillRepositoryRootParityTests.cs` and `RepositorySkillsSelfTests.cs`. -### Nothing about skills runs during a build - -There used to be a `RecommendPurviewSkillsOnBuild` hook on `AfterTargets="Build"`. It was removed after -measurement — on a 39-project solution it read and regex-scanned every project's `project.assets.json` -on every build to print advice — and the recommendation targets went later with the package-to-skill -mapping. What remains is the explicit targets in "Explicit skill installation" above. - -### Once per solution: the leader - -Pointed at a solution, MSBuild runs a custom target in **every** project, so each skill target used -to re-run the CLI once per project. Every public skill target is now a thin wrapper: -`_ResolvePurviewSkillsProjects` reads the solution's project list from -`CurrentSolutionConfigurationContents` (the same value in every project, for `.sln` and `.slnx`; -outside a solution it is the project itself), asks each project whether it imports the SDK through -`_GetPurviewSkillsProjectInfo`, and elects as leader the first, by sorted path, that answered. The -wrapper then calls `_Core` on the leader through the `MSBuild` task. MSBuild runs one -project's target once per set of global properties and returns the cached result to every later -caller, so the work runs once — no lock and no stamp file. - -Three things are load-bearing: - -- **The leader is a consumer project, not a `.proj` shipped in the package.** The skill settings live - in the consumer's `Directory.Build.props`, which a project in the NuGet cache would never import. -- **Every wrapper passes identical global properties** (`_PurviewSkillsLeaderRemoveProperties` strips - `TargetFramework`/`RuntimeIdentifier`). Anything that varies per caller would give each caller its - own cache entry and quietly bring back the fan-out. -- **The query's reply has its own item type** (`_PurviewSkillsProjectInfoReply`). Asking the calling - project runs the query in the caller's own instance, so reusing the caller's item put the caller - first in its own list, and every project elected itself. - -Tests live in `src/tests/BuildSdk.IntegrationTests/PurviewSkillSolutionTests.cs`, which writes its -own `.slnx` because the harness's lists projects as `` entries. - -### Installing, updating, checking and fixing - -**Install, update and fix run only when named — never automatically.** Two layers, both tested in `PurviewSkillTargetIsolationTests`: no SDK target hooks or depends on them (a structural scan of every `.props`/`.targets` under `Sdk/`, including `*DependsOn` properties), and `_GuardExplicitPurviewSkillsTarget` — first in each one's `DependsOnTargets` — fails with `PRSKL0009` when `BuildingProject`, `DesignTimeBuild` or `MSBuildIsRestoring` is true, which catches a consumer's own `AfterTargets="Build"` hook. A git hook or a recipe dependency that runs a target on its own is not a build and is not caught. Do not add a `BeforeTargets`/`AfterTargets` to any of them, and do not weaken the guard. `PurviewSkillTargetIsolationTests.OrdinaryBuild_DoesNotInstallSkills` pins that an ordinary restore-and-build writes no lockfile and creates no agent directory. - -`InstallPurviewSkills` runs `skills add "" --skill "*"` for `PurviewSkillsSource`, or `skills experimental_install` without one (`PRSKL0007` when there is no lockfile either). - -`UpdatePurviewSkills` (`ReadPurviewSkillsLockSources` inline task) re-adds each unique lockfile source once, at its latest with `--skill "*"`, and **that is the whole update — `skills update` is never run**. `skills add` reinstalls every skill it selects (verified in the CLI source, skills 1.7.6: `installSkillForAgent` cleans each skill's folder and copies it again, skipping only when source and destination are the same folder), so one re-add both refreshes the installed skills and adds any the source has gained; `skills update` only re-fetches entries the lockfile already has. The lockfile's recorded names are deliberately not reused, which would leave out anything new. The re-adds use target batching (`_UpdatePurviewSkillsSource`) so each failure is attributed to its source (`PRSKL0008`, `ErrorAndContinue` so all are named); `-p:PurviewSkillsDryRun=true` prints and runs nothing. `PurviewSkillsUpdateMode` and `PRSKL0006` went with the `skills update` step. - -`CheckPurviewSkills`/`FixPurviewSkills` (`EnforcePurviewSkillDirectories`) do nothing unless `PurviewSkillsAgents` names agents. Then the only agent skill directories allowed are those agents', per the `PurviewSkillsAgentDirectory` item group (copied from the CLI's agent table — extend it, don't hard-code), plus `.agents/skills`, the canonical store every agent directory links into. The authored `skills/` folder is protected even though openclaw installs there. Fix deletes links only (never their targets — `RemoveDirectory` on Windows, `unlink` on Unix) and folders left empty; a real file is kept and reported as `PRSKL0015`, because it cannot be told from hand-written content. Note the CLI writes copies, not links, for some agent selections, so those are kept too. - -Tests live in `src/tests/BuildSdk.IntegrationTests/PurviewSkillInstallCommandTests.cs` (install commands, runner mapping and repository-root resolution) and `PurviewSkillUpdateTests.cs` (update, check and fix), with the lockfile writer in `SkillLockFileFixtures.cs`. - -Two harness facts to know when adding tests here. `BuildingProject` is only `true` when the `Build` target actually runs, so a test that names a skill target but needs to look like a build must pass `-p:BuildingProject=true` itself — `PurviewSkillTargetIsolationTests` does exactly that to prove the `PRSKL0009` guard fires. And the throwaway solution is not a git repository and has no `AGENTS.md`, so the repository root does not resolve on its own: write an `AGENTS.md` beside the solution, or pass `-p:PurviewSkillsInstallRoot`. Never assert runner behaviour by letting a test actually invoke `npx`/`pnpm dlx` — that downloads from the network and is not a unit of this SDK; `PurviewSkillsCommand=echo` stands in for the CLI. ## Repository map - `src/src/SkillsTesting/` — packable agent-skill rule engine (`Purview.Skills.Testing`) @@ -326,8 +281,9 @@ Prefer `just` tasks: - `just pack` - `just skills-validate` — the pack-time check over the authored skills - `just skills-add ` — install a skill from another repository into `.agents/skills/` -- `just skills-update` — `UpdatePurviewSkills` then `FixPurviewSkills` -- `just skills-check` / `just skills-fix` — enforce the `PurviewSkillsAgents` layout +- `just skills-update` — re-add every `skills-lock.json` source, then `skills-fix` +- `just skills-check` / `just skills-fix` — enforce the `Skills.Agents` layout from `.config/purview-build-sdk.json` +- `just skills-script-sync` / `just skills-script-check` — regenerate or check `skills.mjs` from `skills.mts` - `just skills-install` — restore `skills-lock.json` (`skills experimental_install`) - `just version` — the version in `package.json` - `just bump major|minor|patch` — bump it, resetting the parts after the one bumped, then `version-sync` @@ -343,7 +299,7 @@ Prefer `just` tasks: The root `Justfile` imports one barrel, `.build/just/index.just`, and holds only what is specific to this repository: `solution_file`, `version-sync`, `properties-check`, `test-linux`, `skills-validate`, -and the `_after-bump` hook that runs `version-sync`. Everything else comes from the modules in +`skills-script-sync`/`skills-script-check`, and the `_after-bump` hook that runs `version-sync`. Everything else comes from the modules in `.build/just/`. **Those modules are the published `purview-buildsdk-justfile` skill's `assets/just/`, copied verbatim.** diff --git a/CHANGELOG.md b/CHANGELOG.md index 5632892..c66fe5d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,41 @@ is used only while the version is a pre-release (`-alpha`, `-beta`, `-rc`). This file was reconstructed from the conventional-commit history at 1.0.7, so entries before that release summarise what the commits recorded rather than what was written at the time. +## [2.2.0] - 2026-11-17 + +### Changed (breaking) + +- **Installing agent skills no longer goes through MSBuild.** The `skills-*` recipes in the + `purview-buildsdk-justfile` skill now run `skills.mts`, a script shipped beside `skills.just`, instead + of `dotnet msbuild -t:...`. It needs no solution, no restore and no build: `just + skills-check` takes 0.4 s here instead of 5 s, and the recipes work in a repository whose build is + broken — when new or updated skills may be what fixes it. It runs under Bun or Deno, and under Node + through `skills.mjs`, generated from `skills.mts` with the types removed. +- **`InstallPurviewSkills`, `UpdatePurviewSkills`, `CheckPurviewSkills` and `FixPurviewSkills` are + removed**, with the solution-leader election behind them and the `PurviewSkillsAgents`, + `PurviewSkillsRunner`, `PurviewSkillsRunnerCandidates`, `PurviewSkillsPackage`, + `PurviewSkillsCommand`, `PurviewSkillsSource`, `PurviewSkillsLockFile` and `PurviewSkillsDryRun` + properties and the `PurviewSkillsAgentDirectory` items. Their settings move to the `Skills` section of + `.config/purview-build-sdk.json` (`Agents`, `Runner`, `RunnerCandidates`, `Package`, `Command`, + `LockFile`, `DryRun`, `AgentDirectories`), each overridable by a recipe option or a + `PURVIEW_SKILLS_*` environment variable. **To migrate**, copy `skills.just`, `skills.mts` and + `skills.mjs` from the skill's `assets/just/` into `.build/just/`, and move any of those properties out + of `Directory.Build.props`. `PRSKL0003` and `PRSKL0009` are retired with the targets. + +### Added + +- `PRSKL0018` (an invalid `.config/purview-build-sdk.json`) and `PRSKL0019` (an unknown key in its + `Skills` section, a warning). +- `just skills-script-sync` and `just skills-script-check` in this repository: regenerate or check + `skills.mjs` against `skills.mts`. `SkillsScriptTests` runs every script behaviour under Node, Bun and + Deno, whichever are present, and fails when `skills.mjs` is stale. + +### Unchanged + +- `ValidatePurviewSkills`, the pack-time check on authored skills (`PRSKL0005`), and the + `PurviewSkillsSourceFolder`, `PurviewSkillsInstallRoot`, `PurviewSkillsRepoRoot` and + `PurviewRepositoryRootMarkers` properties that decide which folder it checks. + ## [2.1.0] - 2026-11-13 ### Added @@ -686,6 +721,7 @@ dotnet msbuild -t:VerifyPurviewSkills - `.editorconfig` values missing test projects. - Source-generator resolution on pack. +[2.2.0]: https://github.com/purview-dev/build-sdk/compare/v2.1.0...v2.2.0 [2.1.0]: https://github.com/purview-dev/build-sdk/compare/v2.0.1...v2.1.0 [2.0.1]: https://github.com/purview-dev/build-sdk/compare/v2.0.0...v2.0.1 [2.0.0]: https://github.com/purview-dev/build-sdk/compare/v1.3.2...v2.0.0 diff --git a/Justfile b/Justfile index 5e29459..30073af 100644 --- a/Justfile +++ b/Justfile @@ -71,3 +71,17 @@ properties-check *args: skills-validate *args: echo "==> Validating authored skills in {{ BLUE }}skills/{{ NORMAL }}" dotnet msbuild "{{ skills_validate_project }}" -t:ValidatePurviewSkills -v:n {{ args }} + +# Regenerate skills.mjs from skills.mts and copy both into .build/just/ +# +# skills.mts in the purview-buildsdk-justfile skill is the source; skills.mjs is generated from it for +# a machine with Node but neither Bun nor Deno. Needs Node 22.13 or later for its type stripper. +[doc('Regenerate skills.mjs from skills.mts and copy both into .build/just/')] +[group('Agent Skills')] +skills-script-sync: + node scripts/sync-skills-script.mjs + +# Check skills.mjs is up to date with skills.mts, writing nothing +[group('Agent Skills')] +skills-script-check: + node scripts/sync-skills-script.mjs --check diff --git a/README.md b/README.md index 2b4fcee..7e9bf99 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ A reusable MSBuild SDK NuGet package that delivers standardised .NET project def "runner": "Microsoft.Testing.Platform" }, "msbuild-sdks": { - "Purview.BuildSdk": "2.1.0" + "Purview.BuildSdk": "2.2.0" } } ``` @@ -238,7 +238,7 @@ to a low-importance message) and only a copy that still fails after every retry The bootstrapped `.editorconfig` opens with a version marker: ```editorconfig -# Purview.BuildSdk 2.1.0 - managed file, do not edit +# Purview.BuildSdk 2.2.0 - managed file, do not edit ``` That line is how the SDK recognises a file **it** wrote. When the SDK version changes, a file carrying @@ -315,30 +315,27 @@ which is worth roughly 0.7s per build. Skills are published in the standard [Agent Skills](https://skills.sh/) format, in a repository's root `skills/` folder, and installed with the standard `skills` CLI (`bun x skills add owner/repo`). -The SDK adds nothing bespoke: its targets are a thin wrapper that runs that CLI from the repository -root, once per solution, and keeps the agent directories tidy. Nothing about skills runs during a -restore or a build. +The SDK adds nothing bespoke: the `purview-buildsdk-justfile` skill's `skills-*` recipes are a thin +wrapper that runs that CLI from the repository root and keeps the agent directories tidy. They run a +small script (`skills.mts` under Bun or Deno, `skills.mjs` under Node), not MSBuild, so they need no +solution, restore or build — they take well under a second and still work when the build is broken. +Nothing about skills runs during a restore or a build. ```bash -bun x skills add purview-dev/build-sdk # install, the ordinary way -dotnet msbuild -t:InstallPurviewSkills -p:PurviewSkillsSource=owner/repo # the same, through the SDK -dotnet msbuild -t:InstallPurviewSkills # restore skills-lock.json -dotnet msbuild -t:UpdatePurviewSkills # re-add every skills-lock.json source at its latest -dotnet msbuild -t:CheckPurviewSkills # only the PurviewSkillsAgents directories exist -dotnet msbuild -t:FixPurviewSkills # remove the CLI's links from any other agent directory +bun x skills add purview-dev/build-sdk # install, the ordinary way +just skills-add owner/repo # the same, with the repository's runner and agents +just skills-install # restore skills-lock.json +just skills-update # re-add every skills-lock.json source at its latest +just skills-check # only the selected agents' directories exist +just skills-fix # remove the CLI's links from any other agent directory ``` -These run only when named: install, update and fix fail with `PRSKL0009` if anything pulls them into -a build, a restore or a design-time build. Append `#` to a source to pin it. `PurviewSkillsAgents` -is empty by default, so the CLI auto-detects agents; set it (for example `universal`) to choose, and -`CheckPurviewSkills`/`FixPurviewSkills` then enforce that only those agents' skill directories exist. - -The CLI is launched through a package runner. `PurviewSkillsRunner` defaults to `bun` (`bun x -skills`) and also accepts `npx`, `bunx`, `pnpm`, `yarn`, `deno` or `skills`; anything else -falls through to ` skills@1`. Because `skills-lock.json` and the agent directories belong to -the repository rather than to a project, every skill target runs **from the repository root, -always**, and reports `PRSKL0003` rather than falling back to a project folder when that root cannot -be resolved. See [Agent Skills](docs/wiki/tooling/Agent-Skills.md). +Append `#` to a source to pin it. Settings live in the `Skills` section of +`.config/purview-build-sdk.json`. `Agents` is empty by default, so the CLI auto-detects agents; set it +(for example `["universal"]`) to choose, and `skills-check`/`skills-fix` then enforce that only those +agents' skill directories exist. `Runner` defaults to `bun` (`bun x skills`) and also accepts `npx`, +`bunx`, `pnpm`, `yarn`, `deno` or `skills`; anything else falls through to ` skills@1`. See +[Agent Skills](docs/wiki/tooling/Agent-Skills.md). --- ## Configuration reference @@ -476,20 +473,16 @@ Non-packable projects (including web applications) default `WarnOnPackingNonPack ### Agent skills +These configure `ValidatePurviewSkills`, the pack-time check on authored skills. Installing and +updating skills is configured in `.config/purview-build-sdk.json` instead; see +[Agent Skills](docs/wiki/tooling/Agent-Skills.md). + | Property | Default | Description | | -- | -- | -- | -| `PurviewSkillsLockFile` | `/skills-lock.json` | Overrides where the skills CLI's lockfile is read from. | | `PurviewSkillsSourceFolder` | `/skills` | Repository folder holding authored skills. | -| `PurviewSkillsAgents` | *(empty, so the skills CLI auto-detects agents)* | Comma-separated agents the skill targets install to, and that recommended commands name. When set, `CheckPurviewSkills`/`FixPurviewSkills` allow only those agents' skill directories. | -| `PurviewSkillsDryRun` | *(unset, which is treated as false)* | When `true`, `InstallPurviewSkills` and `UpdatePurviewSkills` print the CLI commands without running them. | -| `PurviewSkillsRunner` | `bun` | Package runner used to launch the skills CLI (`bun`, `npx`, `bunx`, `pnpm`, `yarn`, `deno`, `skills`, or any other). | -| `PurviewSkillsRunnerCandidates` | `bun;npx;bunx;pnpm;yarn;deno` | Runners probed on `PATH` after `PurviewSkillsRunner`. | -| `PurviewSkillsPackage` | `skills@1` | Package spec the executed launcher pins to. | -| `PurviewSkillsInstallRoot` | *(resolved)* | Overrides the repository root every skill target runs from. | +| `PurviewSkillsInstallRoot` | *(resolved)* | Overrides the repository root whose `skills/` folder `ValidatePurviewSkills` checks. | | `PurviewRepositoryRootMarkers` | `.git/;.github/;.gitattributes;LICENSE.md;AGENTS.md;.agents/;CLAUDE.md;.claude/;package.json` | Ordered markers identifying a repository root. The first is definitive and searched to the top; the rest resolve nearest-first. | -| `PurviewSkillsCommand` | *(detected)* | Overrides the launcher entirely and skips runner detection. | -| `PurviewSkillsSource` | *(none)* | The source `InstallPurviewSkills` adds (`owner/repo`, optionally `#ref`); without it, install restores `skills-lock.json`. | -| `PurviewSkillsRepoRoot` | *(RepoRoot, else the nearest folder with an AGENTS.md)* | Evaluation-time guess at the repository root for the skill targets; a value you set outranks the marker walk. Set it before the `Sdk.props` import. | +| `PurviewSkillsRepoRoot` | *(RepoRoot, else the nearest folder with an AGENTS.md)* | Evaluation-time guess at the repository root for skill validation; a value you set outranks the marker walk. Set it before the `Sdk.props` import. | When a project is packable, the SDK treats any content under `Sdk/` as a pack target with these rules: @@ -625,16 +618,8 @@ Read the exported property rather than re-deriving SDK behaviour — it is the S | `ExcludePurviewTelemetry` | Opt-out for `Purview.Telemetry.SourceGenerator`. | | `ExcludeMSTelemetryExtension` | Opt-out for `Microsoft.Extensions.Telemetry.Abstractions`. | | `PurviewSkillsSourceFolder` | Repository folder holding authored agent skills (default `/skills`). | -| `PurviewSkillsAgents` | Comma-separated agents the skill targets install to (default empty: the CLI auto-detects). | -| `PurviewSkillsDryRun` | When `true`, `InstallPurviewSkills` and `UpdatePurviewSkills` print commands without running them. | -| `PurviewSkillsCommand` | Overrides the launcher entirely and skips runner detection. | -| `PurviewSkillsSource` | The source `InstallPurviewSkills` adds (`owner/repo`, optionally `#ref`); without it, install restores `skills-lock.json`. | -| `PurviewSkillsLockFile` | Where the skills CLI's `skills-lock.json` is read from (default `/skills-lock.json`). | -| `PurviewSkillsInstallRoot` | Overrides the repository root every skill target runs from. | +| `PurviewSkillsInstallRoot` | Overrides the repository root whose `skills/` folder `ValidatePurviewSkills` checks. | | `PurviewRepositoryRootMarkers` | Ordered markers identifying a repository root (default `.git/;.github/;.gitattributes;LICENSE.md;AGENTS.md;.agents/;CLAUDE.md;.claude/;package.json`). | -| `PurviewSkillsRunner` | Package runner used to launch the skills CLI (default `bun`; also `npx`, `bunx`, `pnpm`, `yarn`, `deno`, `skills`). | -| `PurviewSkillsRunnerCandidates` | Runners probed on `PATH` after `PurviewSkillsRunner` (default `bun;npx;bunx;pnpm;yarn;deno`). | -| `PurviewSkillsPackage` | Package spec the executed launcher pins to (default `skills@1`). | | `PurviewRepoBootstrapMode` | Controls repo file bootstrapping: `IfMissing` (default), `Always`, `WarnOnDrift` or `Never`. | | `PurviewRepoBootstrapCopyRetries` | Number of write attempts before a bootstrap failure is reported (default `3`). | | `PurviewRepoBootstrapCopyRetryDelayMilliseconds` | Base delay between bootstrap write attempts (default `500`). | diff --git a/docs/wiki/Configuration-Reference.md b/docs/wiki/Configuration-Reference.md index b807eb8..8f58cc7 100644 --- a/docs/wiki/Configuration-Reference.md +++ b/docs/wiki/Configuration-Reference.md @@ -327,22 +327,16 @@ Override one by setting it before the `Sdk.props` import. See [Project Type Dete ## Agent skills -See [Agent Skills](tooling/Agent-Skills.md) for the targets these configure. +These configure `ValidatePurviewSkills`, the pack-time check on authored skills. Installing, updating, +checking and fixing skills is not MSBuild's: the `skills-*` recipes read the `Skills` section of +`.config/purview-build-sdk.json` instead — see [Agent Skills](tooling/Agent-Skills.md). | Property | Default | Description | | -- | -- | -- | -| `PurviewSkillsLockFile` | `/skills-lock.json` | Overrides where the skills CLI's lockfile is read from. | | `PurviewSkillsSourceFolder` | `/skills` | Repository folder holding authored skills. | -| `PurviewSkillsAgents` | *(empty, so the skills CLI auto-detects agents)* | Comma-separated agents the skill targets install to, and that recommended commands name. When set, `CheckPurviewSkills`/`FixPurviewSkills` allow only those agents' skill directories. | -| `PurviewSkillsDryRun` | *(unset, which is treated as false)* | When `true`, `InstallPurviewSkills` and `UpdatePurviewSkills` print the CLI commands without running them. | -| `PurviewSkillsRunner` | `bun` | Package runner used to launch the skills CLI (`bun`, `npx`, `bunx`, `pnpm`, `yarn`, `deno`, `skills`, or any other). | -| `PurviewSkillsRunnerCandidates` | `bun;npx;bunx;pnpm;yarn;deno` | Runners probed on `PATH` after `PurviewSkillsRunner`. | -| `PurviewSkillsPackage` | `skills@1` | Package spec the executed launcher pins to. | -| `PurviewSkillsInstallRoot` | *(resolved)* | Overrides the repository root every skill target runs from. | +| `PurviewSkillsInstallRoot` | *(resolved)* | Overrides the repository root whose `skills/` folder `ValidatePurviewSkills` checks. | | `PurviewRepositoryRootMarkers` | `.git/;.github/;.gitattributes;LICENSE.md;AGENTS.md;.agents/;CLAUDE.md;.claude/;package.json` | Ordered markers identifying a repository root. The first is definitive and searched to the top; the rest resolve nearest-first. | -| `PurviewSkillsCommand` | *(detected)* | Overrides the launcher entirely and skips runner detection. | -| `PurviewSkillsSource` | *(none)* | The source `InstallPurviewSkills` adds (`owner/repo`, optionally `#ref`); without it, install restores `skills-lock.json`. | -| `PurviewSkillsRepoRoot` | *(RepoRoot, else the nearest folder with an AGENTS.md)* | Evaluation-time guess at the repository root for the skill targets; a value you set outranks the marker walk. Set it before the `Sdk.props` import. | +| `PurviewSkillsRepoRoot` | *(RepoRoot, else the nearest folder with an AGENTS.md)* | Evaluation-time guess at the repository root for skill validation; a value you set outranks the marker walk. Set it before the `Sdk.props` import. | ## Property schema validation @@ -389,16 +383,8 @@ property that is not in this list. | `ExcludePurviewTelemetry` | Opt-out for `Purview.Telemetry.SourceGenerator`. | | `ExcludeMSTelemetryExtension` | Opt-out for `Microsoft.Extensions.Telemetry.Abstractions`. | | `PurviewSkillsSourceFolder` | Repository folder holding authored agent skills (default `/skills`). | -| `PurviewSkillsAgents` | Comma-separated agents the skill targets install to (default empty: the CLI auto-detects). | -| `PurviewSkillsDryRun` | When `true`, `InstallPurviewSkills` and `UpdatePurviewSkills` print commands without running them. | -| `PurviewSkillsCommand` | Overrides the launcher entirely and skips runner detection. | -| `PurviewSkillsSource` | The source `InstallPurviewSkills` adds (`owner/repo`, optionally `#ref`); without it, install restores `skills-lock.json`. | -| `PurviewSkillsLockFile` | Where the skills CLI's `skills-lock.json` is read from (default `/skills-lock.json`). | -| `PurviewSkillsInstallRoot` | Overrides the repository root every skill target runs from. | +| `PurviewSkillsInstallRoot` | Overrides the repository root whose `skills/` folder `ValidatePurviewSkills` checks. | | `PurviewRepositoryRootMarkers` | Ordered markers identifying a repository root (default `.git/;.github/;.gitattributes;LICENSE.md;AGENTS.md;.agents/;CLAUDE.md;.claude/;package.json`). | -| `PurviewSkillsRunner` | Package runner used to launch the skills CLI (default `bun`; also `npx`, `bunx`, `pnpm`, `yarn`, `deno`, `skills`). | -| `PurviewSkillsRunnerCandidates` | Runners probed on `PATH` after `PurviewSkillsRunner` (default `bun;npx;bunx;pnpm;yarn;deno`). | -| `PurviewSkillsPackage` | Package spec the executed launcher pins to (default `skills@1`). | | `PurviewRepoBootstrapMode` | Controls repo file bootstrapping: `IfMissing` (default), `Always`, `WarnOnDrift` or `Never`. | | `PurviewRepoBootstrapCopyRetries` | Number of write attempts before a bootstrap failure is reported (default `3`). | | `PurviewRepoBootstrapCopyRetryDelayMilliseconds` | Base delay between bootstrap write attempts (default `500`). | diff --git a/docs/wiki/Getting-Started.md b/docs/wiki/Getting-Started.md index 09f4dac..397240c 100644 --- a/docs/wiki/Getting-Started.md +++ b/docs/wiki/Getting-Started.md @@ -15,7 +15,7 @@ pinned SDK version — bump it deliberately, because a released version can chan "runner": "Microsoft.Testing.Platform" }, "msbuild-sdks": { - "Purview.BuildSdk": "2.1.0" + "Purview.BuildSdk": "2.2.0" } } ``` diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md index 4ea9372..1c51c95 100644 --- a/docs/wiki/Home.md +++ b/docs/wiki/Home.md @@ -120,9 +120,10 @@ sidebar to all of that. (`PDS0001`, `PDS0005`, `PDS0006`, `PDS0007`), plus IDE code fixes for naming and extensions-namespace conventions. - **Agent skills** — a thin wrapper over the standard skills CLI (`bun x skills`): install a repository's - root `skills/` (`-t:InstallPurviewSkills -p:PurviewSkillsSource=owner/repo`), restore `skills-lock.json`, - update every recorded source, and keep the agent directories tidy. Each is an explicit step that runs - once per solution from the repository root — never during an ordinary build. The SDK itself writes nothing into an agent directory: the build-time + root `skills/` (`just skills-add owner/repo`), restore `skills-lock.json`, update every recorded + source, and keep the agent directories tidy. Each is an explicit step that runs from the repository + root, with no solution, restore or build involved — never during an ordinary build. The SDK itself + writes nothing into an agent directory: the build-time `.agents/**` mirror was removed outright, because the CLI owns those paths and two writers on one set of paths meant the mirror silently overwriting a pinned install. diff --git a/docs/wiki/development/Performance.md b/docs/wiki/development/Performance.md index cdfa15d..8bc1e9d 100644 --- a/docs/wiki/development/Performance.md +++ b/docs/wiki/development/Performance.md @@ -186,8 +186,9 @@ The intermediate 6.4 s / 1-compile case is worth keeping: it was Two findings were measured, judged, and left alone. Both are recorded so they are not re-litigated: - **`ResolvePurviewSkillSources` regex-scanned the whole assets file.** It was taken off the build path - then, and later removed altogether with the package-to-skill mapping it served: the skill targets now - only run the skills CLI, and read no restore graph at all. + then, and later removed altogether with the package-to-skill mapping it served. The skill targets + themselves went later still: the `skills-*` recipes run a script instead, with no MSBuild evaluation + at all (`just skills-check` took 0.4 s against 5 s on this repository's warm 8-project solution). - **`ImportProjectReferencedBuildTransitiveAssets` is not worth changing either**, and this is worth recording because it looked like the obvious next target. Its target-level timing (≈2 s across 38 projects) is inflated by nesting, and on a transitional build it appeared to cost 19 s. Toggling it diff --git a/docs/wiki/tooling/Agent-Skills.md b/docs/wiki/tooling/Agent-Skills.md index 71dfebb..d23a1d1 100644 --- a/docs/wiki/tooling/Agent-Skills.md +++ b/docs/wiki/tooling/Agent-Skills.md @@ -3,13 +3,11 @@ [Agent Skills](https://skills.sh/) are folders of `SKILL.md` guidance that coding agents load on demand. A repository publishes them in its root `skills/` folder, and the standard [`skills` CLI](https://skills.sh/) installs them — `bun x skills add owner/repo` — and records each -install in `skills-lock.json`. `Purview.BuildSdk` adds nothing bespoke to that: its skill targets are -a thin wrapper that runs the CLI from the repository root, once per solution, and keeps the agent -directories tidy. +install in `skills-lock.json`. `Purview.BuildSdk` adds nothing bespoke to that: its `skills-*` recipes +are a thin wrapper that runs the CLI from the repository root and keeps the agent directories tidy. -> Nothing on this page runs as a side effect of a restore, a build, a design-time build or a test run. -> Each target runs only when it is named, and the ones that change the repository refuse to run inside -> a build (`PRSKL0009`). +> Nothing on this page runs as a side effect of a restore, a build, a design-time build or a test run, +> and installing skills does not involve .NET at all. Each recipe runs only when a person runs it. ## Publication @@ -42,89 +40,104 @@ Failures are reported as `PRSKL0005`. The fuller rule set — names, description bundled links, body size — is `Purview.Skills.Testing`, run as tests (see the `purview-buildsdk-skill-tests` skill). Prose quality is deliberately not checked. -## The targets +## The recipes ```bash -dotnet msbuild -t:InstallPurviewSkills -p:PurviewSkillsSource=owner/repo[#ref] -dotnet msbuild -t:InstallPurviewSkills -dotnet msbuild -t:UpdatePurviewSkills -dotnet msbuild -t:CheckPurviewSkills -dotnet msbuild -t:FixPurviewSkills +just skills-add owner/repo[#ref] +just skills-install +just skills-update +just skills-check +just skills-fix ``` -| Target | Runs | Changes the repository | +| Recipe | Runs | Changes the repository | | -- | -- | -- | -| `InstallPurviewSkills` with `PurviewSkillsSource` | `skills add "" --skill "*"` — every skill in that repository's root `skills/`; append `#` to pin | yes | -| `InstallPurviewSkills` | `skills experimental_install` — restore exactly what `skills-lock.json` records | yes | -| `UpdatePurviewSkills` | `skills add "" --skill "*"` once per unique lockfile source, at its latest | yes | -| `CheckPurviewSkills` | nothing; fails (`PRSKL0015`) for an agent directory `PurviewSkillsAgents` does not name | no | -| `FixPurviewSkills` | nothing; removes the CLI's links from those directories | yes | - -`-p:PurviewSkillsDryRun=true` makes install and update print every command and run none. With no -`PurviewSkillsSource` and no `skills-lock.json` there is nothing to install or update, which is -`PRSKL0007`. +| `skills-add ` | `skills add "" --skill "*"` — every skill in that repository's root `skills/`; append `#` to pin | yes | +| `skills-install` | `skills experimental_install` — restore exactly what `skills-lock.json` records | yes | +| `skills-update` | `skills add "" --skill "*"` once per unique lockfile source, at its latest; then `skills-fix` | yes | +| `skills-check` | nothing; fails (`PRSKL0015`) for an agent directory the selected agents do not include | no | +| `skills-fix` | nothing; removes the CLI's links from those directories | yes | + +They come from the [`purview-buildsdk-justfile` skill](../../../skills/purview-buildsdk-justfile/SKILL.md): +`skills.just` holds the recipes and `skills.mts` does the work. The script needs no solution, no +restore and no build, so it runs in well under a second and still works when the build is broken — +which is when new or updated skills may be what fixes it. It runs under Bun, then Deno, and falls back +to Node with `skills.mjs`, which is generated from `skills.mts` with the types removed. +`PURVIEW_SKILLS_RUNTIME` picks one explicitly. + +`--dry-run` makes install and update print every command and run none, and makes fix name what it +would remove and remove nothing (`just skills-update --dry-run` passes it to both). With no source and no `skills-lock.json` there is nothing to install +or update, which is `PRSKL0007`. **Update is `skills add`, never `skills update`.** `skills add` reinstalls every skill it selects (the CLI cleans each skill's folder and copies it again), so one re-add both refreshes the installed skills and adds any the source has gained; `skills update` only re-fetches what the lockfile already lists. Every source is attempted even when one fails, and each failure is named as `PRSKL0008`. -**Name the solution.** Pointed at a solution, MSBuild runs a target in every project, so each project -hands the work to one elected leader — the first solution project, by path, that imports the SDK — and -MSBuild's result cache runs the leader's target once. A single project works too. For `just` recipes, -see the [`purview-buildsdk-justfile` skill](../../../skills/purview-buildsdk-justfile/SKILL.md), whose -`skills.just` module carries them. - -**Never during a build.** No skill target has `BeforeTargets`/`AfterTargets`, nothing in the SDK -depends on one, and install, update and fix fail with `PRSKL0009` when `BuildingProject`, -`DesignTimeBuild` or `MSBuildIsRestoring` is true — which catches a consumer's own -`AfterTargets="Build"` hook. A git hook or a `just` recipe dependency that runs a target on its own is -not a build, so it is not caught: do not wire one up. +**Never from a build or a hook.** Do not make a skills recipe a dependency of `build`, `test` or +`default`, and do not run `skills-add`, `-install`, `-update` or `-fix` from a git hook: they change +the repository. `skills-check` is read-only. -## Choosing agents +## Settings -`PurviewSkillsAgents` is **empty by default**: no `--agent` is passed and the CLI auto-detects the -agents installed on the machine. Set it to choose. Each agent becomes its own `--agent` flag, because -the CLI does not split a comma-separated value. A restore (`experimental_install`) is passed no agent -flag. +Settings live in the `Skills` section of `.config/purview-build-sdk.json` at the repository root: -```xml - - universal - +```json +{ + "Skills": { + "Agents": ["universal"], + "Runner": "bun" + } +} ``` -On a command line, `dotnet msbuild -p:` itself splits on `,` and `;`, so escape the separator -(`-p:PurviewSkillsAgents=claude-code%2Ccodex`) or quote the whole value -(`-p:PurviewSkillsAgents=\"claude-code codex\"`); spaces separate agents too. +| Setting | Default | Description | +| -- | -- | -- | +| `Agents` | *(empty — the CLI auto-detects)* | Agents to install to; when set, the only agent skill directories `skills-check` allows. | +| `Runner` | `bun` | Package runner used to launch the CLI. | +| `RunnerCandidates` | `bun npx bunx pnpm yarn deno` | Probed in order after `Runner`. | +| `Package` | `skills@1` | Package spec the launcher pins to. | +| `Command` | *(detected)* | Overrides the launcher entirely and skips runner detection. | +| `LockFile` | `skills-lock.json` | Where the CLI's lockfile is read from, relative to the repository root. | +| `DryRun` | `false` | Print the install and update commands without running them, and make fix remove nothing. | +| `AgentDirectories` | *(the CLI's agent table)* | Extra agent skill directories, each mapped to its agents. | + +Each has a command-line option (`--agents`, `--runner`, `--package`, `--command`, `--lock-file`, +`--dry-run`) and a `PURVIEW_SKILLS_*` environment variable (`PURVIEW_SKILLS_AGENTS`, and so on). +Highest first: the option, the environment variable, the file, the default. A list may be a JSON array +or one string separated by `,`, `;` or spaces. A setting with the wrong type, or a file that is not +JSON, is `PRSKL0018`; a key that is not a setting is `PRSKL0019`, a warning, because it is usually a +misspelling. + +## Choosing agents + +`Agents` is **empty by default**: no `--agent` is passed and the CLI auto-detects the agents installed +on the machine. Set it to choose. Each agent becomes its own `--agent` flag, because the CLI does not +split a comma-separated value. A restore (`experimental_install`) is passed no agent flag. -Once agents are named, `CheckPurviewSkills` enforces them: any agent skill directory at the repository -root that belongs to an agent not named fails as `PRSKL0015`. Two directories are always allowed — +Once agents are named, `skills-check` enforces them: any agent skill directory at the repository root +that belongs to an agent not named fails as `PRSKL0015`. Two directories are always allowed — `.agents/skills`, the CLI's canonical store that every agent directory links into, and the authored -`skills/` folder, even though openclaw installs into a root `skills/`. With `PurviewSkillsAgents` -empty, every agent directory is a legitimate destination and both targets report that there is -nothing to enforce. - -`FixPurviewSkills` removes what is provably the CLI's: links (symlinks, and junctions on Windows) — -the link only, never its target — and then any folder left empty. A real file is kept and reported, -because it cannot be told from hand-written content; for some agent selections the CLI writes copies -rather than links, and those are kept too. - -The agent-to-directory map is the `PurviewSkillsAgentDirectory` item group, taken from the CLI's agent -table. The CLI adds agents independently of this SDK, so an agent the map does not know is `PRSKL0016` -(a warning), fixed by adding an item: - -```xml - - - +`skills/` folder, even though openclaw installs into a root `skills/`. With `Agents` empty, every agent +directory is a legitimate destination and both recipes report that there is nothing to enforce. + +`skills-fix` removes what is provably the CLI's: links (symlinks, and junctions on Windows) — the link +only, never its target — and then any folder left empty. A real file is kept and reported, because it +cannot be told from hand-written content; for some agent selections the CLI writes copies rather than +links, and those are kept too. + +The agent-to-directory map is taken from the CLI's agent table. The CLI adds agents independently of +this SDK, so an agent the map does not know is `PRSKL0016` (a warning), fixed by adding it: + +```json +{ "Skills": { "AgentDirectories": { ".new-agent/skills": ["new-agent"] } } } ``` ## The lockfile -`skills-lock.json` is the CLI's own record of what is installed and where it came from. The SDK reads -it for `UpdatePurviewSkills` and introduces no competing lockfile and no competing metadata. Commit it: -a fresh clone then restores the same set with `-t:InstallPurviewSkills`. Everything the CLI writes into +`skills-lock.json` is the CLI's own record of what is installed and where it came from. The recipes +read it for `skills-update` and introduce no competing lockfile and no competing metadata. Commit it: +a fresh clone then restores the same set with `just skills-install`. Everything the CLI writes into the agent directories is reproducible from it, so ignore those: | Path | Written by | Tracked | @@ -153,7 +166,7 @@ A repository that authors skills it also uses can install from its own working t `skills//SKILL.md` reaches its agents without a push: ```bash -dotnet msbuild -t:InstallPurviewSkills -p:PurviewSkillsSource=. +just skills-add . ``` The CLI records that portably — `"source": "."`, `"sourceType": "local"`. `Purview.BuildSdk` itself does @@ -163,9 +176,9 @@ their authored path. ## Package runners The CLI is published to npm, and every package runner spells "run this npm package" its own way. -`PurviewSkillsRunner` picks one; it defaults to **`bun`** (`bun x skills`). +`Runner` picks one; it defaults to **`bun`** (`bun x skills`). -| `PurviewSkillsRunner` | Executed | +| `Runner` | Executed | | -- | -- | | `bun` *(default)* | `bun x skills@1` | | `npx` | `npx -y skills@1` | @@ -175,29 +188,35 @@ The CLI is published to npm, and every package runner spells "run this npm packa | `deno` | `deno run -A npm:skills@1` | | `skills` | `skills` | -A runner this SDK has never heard of still works: it falls through to ` skills@1`. `yarn dlx` -needs Yarn 2+. The launcher pins the CLI to a major so a breaking release cannot change what a target -does; `PurviewSkillsPackage` (default `skills@1`) overrides the pin. +A runner this script has never heard of still works: it falls through to ` skills@1`. +`yarn dlx` needs Yarn 2+. The launcher pins the CLI to a major so a breaking release cannot change +what a recipe does; `Package` (default `skills@1`) overrides the pin. ### Detecting the CLI -A target probes `PATH` rather than assuming the configured runner is present, honouring `PATHEXT` on -Windows where these are `.cmd` shims, in this order: +The script probes `PATH` rather than assuming the configured runner is present, honouring `PATHEXT` +on Windows where these are `.cmd` shims, in this order: 1. `skills` — used as-is if it is already on `PATH`. No download, works offline. -2. `$(PurviewSkillsRunner)` — the configured preference. -3. `$(PurviewSkillsRunnerCandidates)` — `bun;npx;bunx;pnpm;yarn;deno` by default. +2. `Runner` — the configured preference. +3. `RunnerCandidates` — `bun npx bunx pnpm yarn deno` by default. The runner actually found wins over the configured preference, because it is the one that can really run. `PATH` is read directly rather than by spawning a version check: deterministic, no process, and -it cannot hang on a cold download. Nothing found is `PRSKL0004`, naming the fix; `PurviewSkillsCommand` -overrides the launcher entirely and skips detection. A dry run with nothing on `PATH` prints the -configured runner's command instead of failing. +it cannot hang on a cold download. Nothing found is `PRSKL0004`, naming the fix; `Command` overrides +the launcher entirely and skips detection. A dry run with nothing on `PATH` prints the configured +runner's command instead of failing. ## Always from the repository root `skills-lock.json` and the agent directories belong to the repository, not to a project, so every -skill target runs the CLI **from the repository root, always**. The root is resolved by this chain: +command runs the CLI **from the repository root**. The recipes pass it as `--root`: the directory +holding the root `Justfile`. Run by hand, the script uses the nearest folder holding `.git`, else the +current one. + +### Where validation looks + +`ValidatePurviewSkills` is MSBuild, so it resolves the root itself, through this chain: 1. `PurviewSkillsInstallRoot` — an explicit override 2. `PurviewSkillsRepoRoot` — when the *user* set it @@ -206,9 +225,8 @@ skill target runs the CLI **from the repository root, always**. The root is reso 5. `GITHUB_WORKSPACE`, `BUILD_SOURCESDIRECTORY` or `CI_PROJECT_DIR` 6. the git source root SourceLink reports -There is deliberately **no fall back to the project directory**: that would scatter a lockfile and an -agent directory through the tree, one per project. If the root cannot be resolved, the target reports -`PRSKL0003` and names `PurviewSkillsInstallRoot` rather than guessing. +There is deliberately **no fall back to the project directory**: a project's own folder is not where a +repository's skills live. ### The marker walk @@ -241,39 +259,33 @@ the same reason the home directory and everything above it are **never** candida | `/repo/.git/` + `/repo/sub/package.json` | `/repo` — the definitive marker wins from a distance | | `/repo/.github/` + `/repo/sub/package.json` | `/repo/sub` — nearest wins once `.git/` is absent | | `/repo/LICENSE.md` + `/repo/package.json` | `/repo`, reported as `LICENSE.md` (higher in the list) | -| no marker below the home directory | unresolved — `PRSKL0003`, never `~` | +| no marker below the home directory | unresolved, never `~` | ## Configuration | Property | Default | Description | | -- | -- | -- | -| `PurviewSkillsSource` | *(none)* | The source `InstallPurviewSkills` adds (`owner/repo`, optionally `#ref`); without it, install restores the lockfile. | -| `PurviewSkillsLockFile` | `/skills-lock.json` | Overrides where the CLI's lockfile is read from. | -| `PurviewSkillsAgents` | *(empty — the CLI auto-detects)* | Agents to install to; when set, the only agent skill directories `CheckPurviewSkills` allows. | -| `PurviewSkillsDryRun` | *(unset, which is treated as false)* | Print the install and update commands without running them. | -| `PurviewSkillsRunner` | `bun` | Package runner used to launch the CLI. | -| `PurviewSkillsRunnerCandidates` | `bun;npx;bunx;pnpm;yarn;deno` | Probed in order after `PurviewSkillsRunner`. | -| `PurviewSkillsPackage` | `skills@1` | Package spec the launcher pins to. | -| `PurviewSkillsCommand` | *(detected)* | Overrides the launcher entirely and skips runner detection. | -| `PurviewSkillsInstallRoot` | *(resolved)* | Overrides the repository root every skill target runs from. | +| `PurviewSkillsInstallRoot` | *(resolved)* | Overrides the repository root whose `skills/` folder `ValidatePurviewSkills` checks. | | `PurviewRepositoryRootMarkers` | `.git/;.github/;.gitattributes;LICENSE.md;AGENTS.md;.agents/;CLAUDE.md;.claude/;package.json` | Ordered markers that identify a repository root; the first is definitive. | ## Diagnostics | Code | Meaning | | -- | -- | -| `PRSKL0003` | The repository root could not be resolved, so there is nowhere correct to install | | `PRSKL0004` | No package runner was found on `PATH` | | `PRSKL0005` | An authored skill is malformed | -| `PRSKL0007` | Nothing to install or update: no `PurviewSkillsSource`, and no `skills-lock.json` | -| `PRSKL0008` | Re-adding a lockfile source failed | -| `PRSKL0009` | Install, update or fix was pulled into a build, a restore or a design-time build | -| `PRSKL0015` | An agent skill directory exists for an agent `PurviewSkillsAgents` does not name | -| `PRSKL0016` | `PurviewSkillsAgents` names an agent with no known skills directory | - -Retired: `PRSKL0001`, `PRSKL0002`, `PRSKL0010`–`PRSKL0014` and `PRSKL0017`, with the package-to-skill -mapping and the `ListPurviewSkills`, `RecommendPurviewSkills` and `VerifyPurviewSkills` targets they -belonged to; and `PRSKL0006`, with `PurviewSkillsUpdateMode`. +| `PRSKL0007` | Nothing to install or update: no source, and no `skills-lock.json` | +| `PRSKL0008` | Adding or re-adding a source failed | +| `PRSKL0015` | An agent skill directory exists for an agent `Agents` does not name | +| `PRSKL0016` | `Agents` names an agent with no known skills directory | +| `PRSKL0018` | `.config/purview-build-sdk.json` is not valid JSON, or a setting has the wrong type | +| `PRSKL0019` | The `Skills` section has a key that is not a setting | + +Retired: `PRSKL0003` and `PRSKL0009`, with the `InstallPurviewSkills`, `UpdatePurviewSkills`, +`CheckPurviewSkills` and `FixPurviewSkills` targets and their `PurviewSkills*` properties, which the +recipes replaced; `PRSKL0001`, `PRSKL0002`, `PRSKL0010`–`PRSKL0014` and `PRSKL0017`, with the +package-to-skill mapping and the `ListPurviewSkills`, `RecommendPurviewSkills` and `VerifyPurviewSkills` +targets they belonged to; and `PRSKL0006`, with `PurviewSkillsUpdateMode`. ## Supported CLI commands @@ -281,8 +293,8 @@ The skills CLI v1 commands, and the role each plays here: | Command | Purpose | Role here | | -- | -- | -- | -| `bun x skills add ` | Install skills | What `InstallPurviewSkills` and `UpdatePurviewSkills` run; accepts `owner/repo#` | -| `bun x skills experimental_install` | Restore from `skills-lock.json` | What `InstallPurviewSkills` runs without a source; experimental in the CLI | +| `bun x skills add ` | Install skills | What `skills-add` and `skills-update` run; accepts `owner/repo#` | +| `bun x skills experimental_install` | Restore from `skills-lock.json` | What `skills-install` runs; experimental in the CLI | | `bun x skills list` | List installed skills | Diagnostics, run directly | | `bun x skills find [query]` | Search for skills | Discovery, run directly | | `bun x skills update` | Update to latest | Not used — an update is a re-add, which also picks up new skills | diff --git a/docs/wiki/tooling/Justfile.md b/docs/wiki/tooling/Justfile.md index e095934..8fd009f 100644 --- a/docs/wiki/tooling/Justfile.md +++ b/docs/wiki/tooling/Justfile.md @@ -18,6 +18,8 @@ Justfile settings, one import, the repository's variables and utilities.just lint-check, lint-fix, vs, scrub purview-build.just pipeline-pr, pipeline-build, pipeline-tests skills.just skills-add, -install, -update, -check, -fix + skills.mts what the skills recipes run under Bun or Deno; no .NET involved + skills.mjs skills.mts with the types removed, for Node - generated, never edited purview-build-nuget.just optional: pipeline-pack-validate, pipeline-local-release, pipeline-release docs.just optional: docs, docs-install, docs-check (a pm-docs-site project site) ``` @@ -31,16 +33,21 @@ on by copying its file into `.build/just/` and off by deleting it; the barrel ne | Variable | Default | Used by | | -- | -- | -- | -| `solution_file` | `.` | every .NET, utility and skill recipe | +| `solution_file` | `.` | every .NET and utility recipe | | `build_configuration` | `Debug` | `build`, `clean`, `test`, `pack` | | `artifacts_folder` | `./artifacts` | `pack`, `scrub` | | `test_filter` | `/*/*/*/*/` | `test` with no argument | | `version_file` | `package.json` | `version`, `bump` | | `csharpier` | `dotnet csharpier` | `lint-check`, `lint-fix` | | `pipeline_tool` | `dotnet purview-build` | the `pipeline-*` recipes | -| `skills_project` | `solution_file` | the `skills-*` recipes | | `docs_site` | `src/docs-site` | the `docs*` recipes | +## Agent skills + +The `skills-*` recipes run `skills.mts` rather than MSBuild, so they need no solution, restore or +build and work while the build is broken. Their settings live in `.config/purview-build-sdk.json`; see +[Agent Skills](Agent-Skills.md). + ## Version `just version` prints the version in `package.json`, read by `just` itself. `just bump major`, @@ -64,7 +71,8 @@ bootstraps, not from the environment. ## This repository -The root `Justfile` here keeps `version-sync`, `version-sync-check`, `properties-check`, `test-linux` -and `skills-validate`, and overrides `_after-bump`. `JustModuleParityTests` fails if `.build/just/` +The root `Justfile` here keeps `version-sync`, `version-sync-check`, `properties-check`, `test-linux`, +`skills-validate`, and `skills-script-sync`/`skills-script-check` — which regenerate and check +`skills.mjs` from `skills.mts` — and overrides `_after-bump`. `JustModuleParityTests` fails if `.build/just/` differs from the skill's assets, holds a file the skill does not ship, or if the root `Justfile` imports anything but the barrel or redefines a module's recipe. diff --git a/package.json b/package.json index 230d914..16f91f7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "build-sdk", - "version": "2.1.0", + "version": "2.2.0", "homepage": "https://purview.dev/projects/build-sdk/", "bugs": { "url": "https://github.com/purview-dev/build-sdk/issues" diff --git a/scripts/sync-skills-script.mjs b/scripts/sync-skills-script.mjs new file mode 100644 index 0000000..291851e --- /dev/null +++ b/scripts/sync-skills-script.mjs @@ -0,0 +1,113 @@ +// Generates skills.mjs from skills.mts, the agent-skill script the purview-buildsdk-justfile skill +// ships, and copies both into this repository's .build/just/. +// +// skills.mts is the source; skills.mjs is the fallback for a machine with Node but neither Bun nor +// Deno. Node's own type stripper does the work, so the output is exactly the source minus its types, +// with every comment kept. The stripper replaces each erased character with a space to keep +// positions, which reads badly, so the characters it erased are removed instead, along with a space +// left dangling before ',', ')' or ';' and any line erasing emptied. +// +// just skills-script-sync regenerate skills.mjs and copy both into .build/just/ +// node scripts/sync-skills-script.mjs --check +// exit 1 when skills.mjs is stale, writing nothing +// +// Plain JavaScript on purpose: it needs module.stripTypeScriptTypes (Node 22.13+), and exits 3 when +// that is missing so a caller can tell "cannot check here" from "stale". + +import { copyFileSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import * as nodeModule from "node:module"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const assets = join(root, "skills", "purview-buildsdk-justfile", "assets", "just"); +const modules = join(root, ".build", "just"); +const source = join(assets, "skills.mts"); +const output = join(assets, "skills.mjs"); +const checkOnly = process.argv.includes("--check"); + +if (typeof nodeModule.stripTypeScriptTypes !== "function") { + console.error(`module.stripTypeScriptTypes is not available in Node ${process.version}; Node 22.13 or later is needed.`); + process.exit(3); +} + +const header = [ + "// GENERATED from skills.mts by scripts/sync-skills-script.mjs in purview-dev/build-sdk - do not edit.", + "// It is skills.mts with the TypeScript removed, for a machine with Node but neither Bun nor Deno.", + "", +]; + +export function generate(typescript) { + const text = typescript.replace(/\r\n/g, "\n"); + const stripped = nodeModule.stripTypeScriptTypes(text, { mode: "strip" }); + if (stripped.length !== text.length) throw new Error("The type stripper changed the text length; positions cannot be compared."); + + const lines = []; + let start = 0; + for (const sourceLine of text.split("\n")) { + const strippedLine = stripped.slice(start, start + sourceLine.length); + start += sourceLine.length + 1; + + // A character is erased when the stripper blanked it. A space is erased too when it sits inside an + // erased run - the one in ': string' - so 'name: string = x' becomes 'name = x', not 'name = x'. + const erased = [...sourceLine].map((character, index) => strippedLine[index] === " " && character !== " "); + const nearest = (index, step) => { + for (let at = index + step; at >= 0 && at < sourceLine.length; at += step) { + if (sourceLine[at] !== " ") return at; + } + return -1; + }; + for (let index = 0; index < sourceLine.length; index++) { + if (sourceLine[index] !== " ") continue; + const before = nearest(index, -1); + const after = nearest(index, 1); + if (before >= 0 && after >= 0 && erased[before] && erased[after]) erased[index] = true; + } + + let line = ""; + let erasedBefore = false; + for (let index = 0; index < sourceLine.length; index++) { + if (erased[index]) { + erasedBefore = true; + continue; + } + + // A space the erasure left in front of punctuation: 'value as Type)' becomes 'value)'. + if (erasedBefore && /[,);\]]/.test(strippedLine[index])) line = line.replace(/ +$/, ""); + if (strippedLine[index] !== " ") erasedBefore = false; + line += strippedLine[index]; + } + + line = line.replace(/\s+$/, ""); + // A line that held only types - a type alias, an interface member - goes entirely. + if (line.length === 0 && sourceLine.trim().length > 0) continue; + lines.push(line); + } + + // Erased declarations can leave blank lines next to each other; keep one. + const collapsed = lines.filter((line, index) => !(line === "" && lines[index - 1] === "")); + return [...header, ...collapsed].join("\n").replace(/\n*$/, "\n"); +} + +const expected = generate(readFileSync(source, "utf8")); +const current = (() => { + try { + return readFileSync(output, "utf8").replace(/\r\n/g, "\n"); + } catch { + return ""; + } +})(); + +if (checkOnly) { + if (current !== expected) { + console.error("skills.mjs is out of date with skills.mts. Run: just skills-script-sync"); + process.exit(1); + } + + console.log("skills.mjs matches skills.mts."); + process.exit(0); +} + +if (current !== expected) writeFileSync(output, expected); +for (const name of ["skills.mts", "skills.mjs"]) copyFileSync(join(assets, name), join(modules, name)); +console.log("skills.mjs regenerated; skills.mts and skills.mjs copied to .build/just/."); diff --git a/skills/purview-buildsdk-adoption/SKILL.md b/skills/purview-buildsdk-adoption/SKILL.md index 07be90a..ad73114 100644 --- a/skills/purview-buildsdk-adoption/SKILL.md +++ b/skills/purview-buildsdk-adoption/SKILL.md @@ -125,14 +125,15 @@ silently gets no runner, no coverage, no `InternalsVisibleTo` and no category. ## 5. Agent skills are a separate, explicit step -Nothing the SDK does during a restore or a build touches agent skills. Installing, updating and -cleaning them up are separate targets a person runs by name — `InstallPurviewSkills`, -`UpdatePurviewSkills`, `CheckPurviewSkills`, `FixPurviewSkills` — and the ones that change the -repository refuse to run inside a build (`PRSKL0009`). Do not hook them into one. The skills CLI does -the installing, through `bun x` by default; with `PurviewSkillsAgents` unset it auto-detects agents. - -If the repository uses `just`, add recipes for them — see `purview-buildsdk-justfile`. For what each -target does and the `PRSKL*` diagnostics, see `purview-buildsdk-skill-installation`. +Nothing the SDK does during a restore or a build touches agent skills, and installing them does not +involve MSBuild at all. Installing, updating and cleaning them up are `just` recipes a person runs — +`skills-add`, `skills-install`, `skills-update`, `skills-check`, `skills-fix` — from the +`purview-buildsdk-justfile` skill, which run its `skills.mts` script with no solution, restore or +build. Do not hook them into a build or a git hook. The skills CLI does the installing, through +`bun x` by default; with no `Agents` set in `.config/purview-build-sdk.json` it auto-detects agents. + +For what each recipe does, its settings and the `PRSKL*` diagnostics, see +`purview-buildsdk-skill-installation`. ## 6. Target frameworks diff --git a/skills/purview-buildsdk-configuration/SKILL.md b/skills/purview-buildsdk-configuration/SKILL.md index 767a81a..8b4a05a 100644 --- a/skills/purview-buildsdk-configuration/SKILL.md +++ b/skills/purview-buildsdk-configuration/SKILL.md @@ -169,17 +169,18 @@ the repository; that is gone, along with `EnableAgentFolderInPackage`, `AgentPac and the `PurviewAgentFolder*` properties. Skills have exactly one installer, the skills CLI — see `purview-buildsdk-skill-installation`. -The skill targets read their settings when they run, so these can go in `Directory.Build.props` or -on the command line, and a repository-wide choice belongs in `Directory.Build.props`: +Installing skills is not configured in MSBuild. The `skills-*` recipes read the `Skills` section of +`.config/purview-build-sdk.json`, so a repository-wide choice goes there: -| Property | Default | Controls | +| Setting | Default | Controls | | -- | -- | -- | -| `PurviewSkillsRunner` | `bun` (`bun x skills`) | Which package runner launches the skills CLI | -| `PurviewSkillsAgents` | empty — the CLI auto-detects | Agents to install to; when set, the only agent directories `CheckPurviewSkills` allows | -| `PurviewSkillsDryRun` | `false` | Install and update print commands instead of running them | +| `Runner` | `bun` (`bun x skills`) | Which package runner launches the skills CLI | +| `Agents` | empty — the CLI auto-detects | Agents to install to; when set, the only agent directories `skills-check` allows | +| `DryRun` | `false` | Install and update print commands instead of running them; fix removes nothing | -On a command line, `dotnet msbuild -p:` splits values on `,` and `;` — write -`-p:PurviewSkillsAgents=claude-code%2Ccodex`. For `just` recipes, see `purview-buildsdk-justfile`. +A one-off goes after the recipe: `just skills-update --dry-run --agents claude-code,codex`. The +`PurviewSkillsAgents`, `PurviewSkillsRunner`, `PurviewSkillsDryRun` and other install properties were +removed with the MSBuild skill targets; `purview-buildsdk-skill-installation` maps each to its setting. ## SourceLink diff --git a/skills/purview-buildsdk-configuration/references/properties.md b/skills/purview-buildsdk-configuration/references/properties.md index 8efd3db..ff7a85e 100644 --- a/skills/purview-buildsdk-configuration/references/properties.md +++ b/skills/purview-buildsdk-configuration/references/properties.md @@ -168,10 +168,14 @@ nothing else was left for the mirror to deliver. ## Skills -Covered in full by `purview-buildsdk-skill-installation`: `PurviewSkillsRunner`, -`PurviewSkillsRunnerCandidates`, `PurviewSkillsCommand`, `PurviewSkillsPackage`, -`PurviewSkillsAgents`, `PurviewSkillsSource`, `PurviewSkillsInstallRoot`, `PurviewSkillsRepoRoot`, -`PurviewSkillsDryRun`, and the `PurviewSkillsAgentDirectory` item group. +Only the pack-time validation of authored skills is MSBuild: `PurviewSkillsSourceFolder`, +`PurviewSkillsInstallRoot`, `PurviewSkillsRepoRoot` and `PurviewRepositoryRootMarkers` decide which +`skills/` folder `ValidatePurviewSkills` checks. Installing and updating skills is configured in the +`Skills` section of `.config/purview-build-sdk.json`, covered in full by +`purview-buildsdk-skill-installation`. `PurviewSkillsRunner`, `PurviewSkillsRunnerCandidates`, +`PurviewSkillsCommand`, `PurviewSkillsPackage`, `PurviewSkillsAgents`, `PurviewSkillsSource`, +`PurviewSkillsLockFile`, `PurviewSkillsDryRun` and the `PurviewSkillsAgentDirectory` items were +removed with the MSBuild skill targets. ## Compiler-visible properties @@ -212,8 +216,6 @@ table in the [Configuration Reference](https://github.com/purview-dev/build-sdk/ - `PurviewRepoBootstrapMode`, `PurviewRepoBootstrapCopyRetries`, `PurviewRepoBootstrapCopyRetryDelayMilliseconds`, `PurviewRepoBootstrapCopyFailureAsError` - `PurviewSuppressCopyRetryWarnings` -- `PurviewSkillsSourceFolder`, - `PurviewSkillsAgents`, `PurviewSkillsInstallRoot`, `PurviewRepositoryRootMarkers`, - `PurviewSkillsRunner`, `PurviewSkillsDryRun` +- `PurviewSkillsSourceFolder`, `PurviewSkillsInstallRoot`, `PurviewRepositoryRootMarkers` - `PurviewBuildSdkVersionForGlobalJson`, `CurrentYear`, `AutoGeneratedAssemblyInfoFile`, `AutoGeneratedAssemblyIdentifierFile` diff --git a/skills/purview-buildsdk-docs-sync/references/truth-audit.md b/skills/purview-buildsdk-docs-sync/references/truth-audit.md index 3da13b7..2cee686 100644 --- a/skills/purview-buildsdk-docs-sync/references/truth-audit.md +++ b/skills/purview-buildsdk-docs-sync/references/truth-audit.md @@ -12,7 +12,7 @@ that describes it. | A diagnostic id, its severity and its meaning | the `DiagnosticDescriptor` (analyzers) or the `Code="..."` on an MSBuild `Error`/`Warning`/`Message` (targets) | `git grep -n 'PRSKL0012'`. The severity is the descriptor's default or the task's `Importance`, not the docs table | | A target exists and what it runs | the ``, its `DependsOnTargets`, `BeforeTargets`/`AfterTargets` | read the target; "never runs during a build" means it has no hook *and* nothing hooks it | | A `just` recipe and what it does | the `Justfile` and every file it imports | `just --list` for names, `just --dry-run ` for the exact command — never read a recipe name off another document | -| A command line works | running it | run it, or `--dry-run`/`-p:...DryRun=true` when it changes things; do not quote output you did not see | +| A command line works | running it | run it, or with `--dry-run` (or the tool's own dry-run switch) when it changes things; do not quote output you did not see | | A file or folder path | the file system | `git ls-files `, which also proves it is tracked rather than generated | | A package id, and what it contains | the `.csproj` (`PackageId`, `IsPackable`) and the packed `.nupkg` | `dotnet pack`, then list the archive; pack validation config (for example `.config/purview-build.json` `RequiredContent`) lists the expected files | | A target framework or framework set | the `.props` defining the sets, and the project's evaluated value | `dotnet msbuild -getProperty:TargetFrameworks` | diff --git a/skills/purview-buildsdk-justfile/SKILL.md b/skills/purview-buildsdk-justfile/SKILL.md index 0ac76c2..ecb2dc9 100644 --- a/skills/purview-buildsdk-justfile/SKILL.md +++ b/skills/purview-buildsdk-justfile/SKILL.md @@ -1,6 +1,6 @@ --- name: purview-buildsdk-justfile -description: Set up or update the Justfile of a repository that uses Purview.BuildSdk - a root Justfile that imports one barrel, .build/just/index.just, over shared modules for .NET (restore, build, test, pack, ensure-tools), version display and `just bump major|minor|patch`, local Purview.Build pipeline runs (pipeline-pr, pipeline-local-release), the agent-skill targets (skills-add, skills-install, skills-update, skills-check, skills-fix), lint-check/lint-fix, vs, scrub, an optional pm-docs-site Docs group, and exported telemetry opt-outs and .NET CLI speed-ups. Use when adding a Justfile, splitting or de-duplicating one, adding a just recipe, bumping the version from just, replacing hand-written skill scripts (update-agent-skills.ts, package.json skills:* scripts) with the SDK targets, or when a recipe runs the wrong project, runner or agents. +description: Set up or update the Justfile of a repository that uses Purview.BuildSdk - a root Justfile that imports one barrel, .build/just/index.just, over shared modules for .NET (restore, build, test, pack, ensure-tools), version display and `just bump major|minor|patch`, local Purview.Build pipeline runs (pipeline-pr, pipeline-local-release), the agent-skill recipes (skills-add, skills-install, skills-update, skills-check, skills-fix) and the skills.mts script that runs them without MSBuild, lint-check/lint-fix, vs, scrub, an optional pm-docs-site Docs group, and exported telemetry opt-outs and .NET CLI speed-ups. Use when adding a Justfile, splitting or de-duplicating one, adding a just recipe, bumping the version from just, replacing hand-written skill scripts (update-agent-skills.ts, package.json skills:* scripts) or the old dotnet msbuild skill recipes, or when a recipe runs the wrong project, runner or agents. license: MIT metadata: package: Purview.BuildSdk @@ -10,7 +10,7 @@ metadata: # The Justfile A repository's recipes are mostly the same everywhere: restore, build, test, pack, lint, the -pipeline, the skill targets. Written into each `Justfile` by hand they drift, and every repository +pipeline, the agent skills. Written into each `Justfile` by hand they drift, and every repository fixes the same quoting bug separately. So the shared recipes are **modules**, copied verbatim from this skill's [`assets/just/`](assets/just/index.just) into the repository, and the root `Justfile` holds only what is specific to that repository. @@ -26,6 +26,8 @@ Justfile settings, one import, the repository's variables and o utilities.just lint-check, lint-fix, vs, scrub purview-build.just pipeline-pr, pipeline-build, pipeline-tests skills.just skills-add, -install, -update, -check, -fix + skills.mts what the skills recipes run (Bun or Deno); no .NET involved + skills.mjs skills.mts with the types removed, for Node - generated, never edited purview-build-nuget.just optional: pipeline-pack-validate, pipeline-local-release, pipeline-release docs.just optional: docs, docs-install, docs-check ``` @@ -77,7 +79,6 @@ Override only what differs from the default. `solution_file` is the one nearly e | `current_version` | `version.just` | from `version_file` | shown by `build`, `pack`, `version` | | `csharpier` | `utilities.just` | `dotnet csharpier` | | | `pipeline_tool` | `purview-build.just` | `dotnet purview-build` | | -| `skills_project` | `skills.just` | `solution_file` | always the solution — see [the skill recipes](references/skills-recipes.md) | | `docs_site` | `docs.just` | `src/docs-site` | pm-docs-site's `SITE_ROOT` | To find `solution_file`: an existing `Justfile` variable or the path its `build`/`test` recipes use; @@ -157,6 +158,8 @@ anything runs. It needs Bun. | `ensure-pipeline-tool`, `restore-tools` | `ensure-tools` | | `current_version` (recipe) | `version` | | `import "Justfile.skills.just"` | `skills.just`, through the barrel — delete the old file | + | `dotnet msbuild ... -t:InstallPurviewSkills` (and Update, Check, Fix) | `skills.just` with `skills.mts`/`skills.mjs`; move `PurviewSkills*` properties to `.config/purview-build-sdk.json` | + | a `skills_project` variable | nothing — delete it | | a hand-written `Docs` group | `docs.just` | 7. **Do not add `set shell` or `set windows-shell`.** The modules are written for just's default `sh` @@ -168,6 +171,10 @@ Change it here, in the skill's `assets/just/`, then copy the file into each repo that edits its copy drifts from every other, and the next copy overwrites the edit. If one repository needs different behaviour, override the recipe or variable in its root `Justfile`. +`skills.mjs` is the exception to editing in place anywhere: it is generated from `skills.mts`. In the +Purview.BuildSdk repository, edit `skills.mts` and run `just skills-script-sync`, which regenerates +`skills.mjs` with Node's own type stripper and copies both into `.build/just/`. + Recipe comments: just shows a recipe's **last** comment line in `just --list`. A recipe with a multi-line comment carries `[doc('...')]` with its one-line summary. @@ -178,7 +185,7 @@ git check-ignore -v .build/just/index.just # no output: tracked just --list # every group, one-line descriptions just --dry-run build # the solution path is the right one just bump patch --dry-run # prints the next version, writes nothing -just skills-update -p:PurviewSkillsDryRun=true +just skills-update --dry-run # the skills CLI commands, nothing run ``` For the skill recipes in detail, replacing hand-written skill scripts, and the runner and agent diff --git a/skills/purview-buildsdk-justfile/assets/just/index.just b/skills/purview-buildsdk-justfile/assets/just/index.just index 1d73bbe..beda195 100644 --- a/skills/purview-buildsdk-justfile/assets/just/index.just +++ b/skills/purview-buildsdk-justfile/assets/just/index.just @@ -30,7 +30,7 @@ import "utilities.just" # pipeline-pr, pipeline-build, pipeline-tests - local runs of the Purview.Build pipeline import "purview-build.just" -# skills-* - the Purview.BuildSdk agent-skill targets +# skills-* - agent skills through the skills CLI, run by skills.mts (no .NET involved) import "skills.just" # Optional. pipeline-pack-validate, pipeline-local-release, pipeline-release - for a repository that diff --git a/skills/purview-buildsdk-justfile/assets/just/skills.just b/skills/purview-buildsdk-justfile/assets/just/skills.just index 0d33902..6dea181 100644 --- a/skills/purview-buildsdk-justfile/assets/just/skills.just +++ b/skills/purview-buildsdk-justfile/assets/just/skills.just @@ -1,18 +1,25 @@ -# The Purview.BuildSdk agent-skill targets. Each recipe names one target; the behaviour lives there. +# The agent-skill recipes: a thin wrapper over the standard skills CLI (`bun x skills@1` by default). # -# The targets are a thin wrapper over the standard skills CLI (`bun x skills` by default), run from the -# repository root. Every skill target runs once for the whole solution, however many projects it holds, -# so the recipes name the solution, not a hand-picked project. +# The work is done by skills.mts, beside this file, which needs no .NET at all - no solution to +# evaluate, no restore and no build - so a repository whose build is broken can still install the +# skills that might help fix it. It runs under Bun, then Deno, and falls back to Node with the +# generated skills.mjs. Set PURVIEW_SKILLS_RUNTIME to choose, for example `node`, `bun` or `deno run -A`. # # Every recipe here is run by a person, on purpose. Never make one a dependency of build, test or -# default, or call skills-add, -install, -update or -fix from a git hook: they change the repository, -# and the SDK refuses to run them inside a build (PRSKL0009). skills-check is read-only. +# default, or call skills-add, -install, -update or -fix from a git hook: they change the repository. +# skills-check is read-only. # -# The runner and agents are MSBuild properties (PurviewSkillsRunner, PurviewSkillsAgents), set once in -# Directory.Build.props. Pass a one-off through *args; `dotnet msbuild -p:` splits on `,` and `;`, so -# escape the separator: `just skills-update -p:PurviewSkillsAgents=claude-code%2Ccodex`. +# Settings live in the "Skills" section of .config/purview-build-sdk.json: +# +# { "Skills": { "Agents": ["claude-code", "codex"], "Runner": "bun" } } +# +# Pass a one-off through *args, for example `just skills-update --dry-run --agents claude-code,codex`, +# or set the matching PURVIEW_SKILLS_* environment variable. + +skills_script := source_directory() / "skills" -skills_project := solution_file +# Runs skills.mts (or skills.mjs) from the repository root with the given arguments. +_skills_run := 'purview_skills() { if [ -n "${PURVIEW_SKILLS_RUNTIME:-}" ]; then case "$PURVIEW_SKILLS_RUNTIME" in node*) $PURVIEW_SKILLS_RUNTIME "' + skills_script + '.mjs" "$@" ;; *) $PURVIEW_SKILLS_RUNTIME "' + skills_script + '.mts" "$@" ;; esac; elif command -v bun >/dev/null 2>&1; then bun "' + skills_script + '.mts" "$@"; elif command -v deno >/dev/null 2>&1; then deno run -A "' + skills_script + '.mts" "$@"; elif command -v node >/dev/null 2>&1; then node "' + skills_script + '.mjs" "$@"; else echo "error PRSKL0004: the skills recipes need Bun, Deno or Node.js on PATH." >&2; return 1; fi; }; purview_skills' # Install skills from another repository through the skills CLI (append '#' to pin it) # @@ -21,32 +28,32 @@ skills_project := solution_file [group('Agent Skills')] skills-add source *args: echo "==> Installing skills from {{ BLUE }}{{ source }}{{ NORMAL }}" - dotnet msbuild "{{ skills_project }}" -t:InstallPurviewSkills -p:PurviewSkillsSource={{ source }} -v:n {{ args }} + {{ _skills_run }} add {{ quote(source) }} --root "{{ justfile_directory() }}" {{ args }} # Restore every skill skills-lock.json records - how a fresh clone gets the repository's skills back [group('Agent Skills')] skills-install *args: - dotnet msbuild "{{ skills_project }}" -t:InstallPurviewSkills -v:n {{ args }} + {{ _skills_run }} install --root "{{ justfile_directory() }}" {{ args }} # Update the agent skills by re-adding every unique source in skills-lock.json # # Each source is re-added at its latest with every skill it has, which refreshes the installed skills -# and adds any a source has gained; `skills update` is never run. FixPurviewSkills then removes links -# from agent directories PurviewSkillsAgents does not select, and does nothing when it is unset. -# The -t: value is quoted because sh would otherwise end the command at the `;`. +# and adds any a source has gained; `skills update` is never run. skills-fix then removes links from +# agent directories Skills.Agents does not select, and does nothing when it is unset. # -# just skills-update -p:PurviewSkillsDryRun=true +# just skills-update --dry-run [doc('Update the agent skills by re-adding every unique source in skills-lock.json')] [group('Agent Skills')] skills-update *args: - dotnet msbuild "{{ skills_project }}" "-t:UpdatePurviewSkills;FixPurviewSkills" -v:n {{ args }} + {{ _skills_run }} update --root "{{ justfile_directory() }}" {{ args }} + {{ _skills_run }} fix --root "{{ justfile_directory() }}" {{ args }} -# Check that only the skill directories of the agents in PurviewSkillsAgents exist +# Check that only the skill directories of the agents in Skills.Agents exist [group('Agent Skills')] skills-check *args: - dotnet msbuild "{{ skills_project }}" -t:CheckPurviewSkills -v:n {{ args }} + {{ _skills_run }} check --root "{{ justfile_directory() }}" {{ args }} -# Remove the skills CLI's links from agent directories PurviewSkillsAgents does not select +# Remove the skills CLI's links from agent directories Skills.Agents does not select [group('Agent Skills')] skills-fix *args: - dotnet msbuild "{{ skills_project }}" -t:FixPurviewSkills -v:n {{ args }} + {{ _skills_run }} fix --root "{{ justfile_directory() }}" {{ args }} diff --git a/skills/purview-buildsdk-justfile/assets/just/skills.mjs b/skills/purview-buildsdk-justfile/assets/just/skills.mjs new file mode 100644 index 0000000..7c56ae8 --- /dev/null +++ b/skills/purview-buildsdk-justfile/assets/just/skills.mjs @@ -0,0 +1,686 @@ +// GENERATED from skills.mts by scripts/sync-skills-script.mjs in purview-dev/build-sdk - do not edit. +// It is skills.mts with the TypeScript removed, for a machine with Node but neither Bun nor Deno. + +// The Purview.BuildSdk agent-skill commands: a thin wrapper over the standard skills CLI +// (`bun x skills@1` by default), run by the skills-* recipes in skills.just. +// +// Nothing here needs .NET. There is no solution to evaluate, no package to restore and no project +// that has to build, so a repository whose build is broken can still install the skills that might +// help fix it. +// +// add skills add "" --skill "*" - append '#' to the source to pin it +// install [source] add , or restore skills-lock.json with skills experimental_install +// update re-add every unique skills-lock.json source at its latest, with every skill +// check fail when a skill directory exists for an agent that is not selected +// fix remove the skills CLI's links from those directories +// +// Settings, highest first: command-line options, PURVIEW_SKILLS_* environment variables, the +// "Skills" section of .config/purview-build-sdk.json, then the defaults below. Every command runs +// from the repository root, because skills-lock.json and the agent directories belong to the +// repository rather than to a project. +// +// skills.mts is the source. skills.mjs is generated from it by Node's own type stripper, for a +// machine with Node but neither Bun nor Deno: edit this file, then run `just skills-script-sync`. +// Keep to erasable TypeScript (no enums, namespaces or parameter properties) so both stay possible. + +import { spawnSync } from "node:child_process"; +import { existsSync, lstatSync, readdirSync, readFileSync, rmdirSync, statSync, unlinkSync } from "node:fs"; +import { delimiter, dirname, join, relative, resolve } from "node:path"; +import process from "node:process"; +import { parseArgs } from "node:util"; + +const configKeys = [ + "Agents", + "Runner", + "RunnerCandidates", + "Package", + "Command", + "LockFile", + "DryRun", + "AgentDirectories", +]; + +// Each package runner spells "run this npm package" its own way. Every form was checked against the +// real tool, because a wrong one is a command that simply does not run. A runner missing from this +// table still works: it falls through to ' ', the form most new runners adopt. +const launchers = { + skills: () => "skills", + npx: (spec) => `npx -y ${spec}`, + bunx: (spec) => `bunx ${spec}`, + bun: (spec) => `bun x ${spec}`, + pnpm: (spec) => `pnpm dlx ${spec}`, + yarn: (spec) => `yarn dlx ${spec}`, + deno: (spec) => `deno run -A npm:${spec}`, +}; + +// Where the skills CLI writes a project-scope install for each agent, from its own agent table +// (skills 1.7.6, docs/agents.md). Only check and fix read this, and only when agents are selected. +// The CLI adds agents independently of this script; add one through Skills.AgentDirectories in +// .config/purview-build-sdk.json rather than waiting for a release. +const defaultAgentDirectories = [ + { + path: ".agents/skills", + agents: [ + "amp", + "antigravity", + "antigravity-cli", + "cline", + "codex", + "cursor", + "deepagents", + "dexto", + "droid", + "firebender", + "fx", + "gemini-cli", + "github-copilot", + "kilo", + "kimi-code-cli", + "loaf", + "opencode", + "pi", + "promptscript", + "replit", + "sarvam-code", + "universal", + "warp", + "zed", + ], + }, + { path: ".adal/skills", agents: ["adal"] }, + { path: ".aider-desk/skills", agents: ["aider-desk"] }, + { path: ".augment/skills", agents: ["augment"] }, + { path: ".autohand/skills", agents: ["autohand-code"] }, + { path: ".bob/skills", agents: ["bob"] }, + { path: ".claude/skills", agents: ["claude-code"] }, + { path: ".codeartsdoer/skills", agents: ["codearts-agent"] }, + { path: ".codebuddy/skills", agents: ["codebuddy"] }, + { path: ".codemaker/skills", agents: ["codemaker"] }, + { path: ".codestudio/skills", agents: ["codestudio"] }, + { path: ".commandcode/skills", agents: ["command-code"] }, + { path: ".continue/skills", agents: ["continue"] }, + { path: ".cortex/skills", agents: ["cortex"] }, + { path: ".crush/skills", agents: ["crush"] }, + { path: ".devin/skills", agents: ["devin"] }, + { path: ".forge/skills", agents: ["forgecode"] }, + { path: ".goose/skills", agents: ["goose"] }, + { path: ".grok/skills", agents: ["grok"] }, + { path: ".hermes/skills", agents: ["hermes-agent"] }, + { path: ".iflow/skills", agents: ["iflow-cli"] }, + { path: ".inferencesh/skills", agents: ["inference-sh"] }, + { path: ".jazz/skills", agents: ["jazz"] }, + { path: ".junie/skills", agents: ["junie"] }, + { path: ".kimchi/skills", agents: ["kimchi"] }, + { path: ".kiro/skills", agents: ["kiro-cli"] }, + { path: ".kode/skills", agents: ["kode"] }, + { path: ".lingma/skills", agents: ["lingma"] }, + { path: ".mcpjam/skills", agents: ["mcpjam"] }, + { path: ".minimax/skills", agents: ["minimax-code"] }, + { path: ".moxby/skills", agents: ["moxby"] }, + { path: ".mux/skills", agents: ["mux"] }, + { path: ".neovate/skills", agents: ["neovate"] }, + { path: ".ona/skills", agents: ["ona"] }, + { path: ".openhands/skills", agents: ["openhands"] }, + { path: ".pochi/skills", agents: ["pochi"] }, + { path: ".posit/assistant/skills", agents: ["posit-assistant"] }, + { path: ".qoder/skills", agents: ["qoder", "qoder-cn"] }, + { path: ".qwen/skills", agents: ["qwen-code"] }, + { path: ".reasonix/skills", agents: ["reasonix"] }, + { path: ".roo/skills", agents: ["roo"] }, + { path: ".rovodev/skills", agents: ["rovodev"] }, + { path: ".tabnine/agent/skills", agents: ["tabnine-cli"] }, + { path: ".terramind/skills", agents: ["terramind"] }, + { path: ".tinycloud/skills", agents: ["tinycloud"] }, + { path: ".trae/skills", agents: ["trae", "trae-cn"] }, + { path: ".vibe/skills", agents: ["mistral-vibe"] }, + { path: ".windsurf/skills", agents: ["windsurf"] }, + { path: ".zcode/skills", agents: ["zcode"] }, + { path: ".zencoder/skills", agents: ["zencoder", "zenflow"] }, + { path: "agent/skills", agents: ["eve"] }, + { path: "data/skills", agents: ["astrbot"] }, + // openclaw installs into a root 'skills/', the folder a repository authors its own skills in. It is + // listed so selecting openclaw is not an unknown agent, but the authored folder is never touched. + { path: "skills", agents: ["openclaw"] }, +]; + +const usage = `Usage: skills.mts [options] + +Commands: + add Install every skill a source has (append '#' to pin it) + install [source] Install from a source, or restore skills-lock.json + update Re-add every skills-lock.json source at its latest + check Fail when a skill directory exists for an unselected agent + fix Remove the skills CLI's links from those directories + +Options: + --root Repository root (default: the nearest folder holding .git) + --config Settings file (default: .config/purview-build-sdk.json) + --agents Agents to install to, separated by ',', ';' or spaces + --runner Package runner: bun, npx, bunx, pnpm, yarn, deno or skills + --command Launch the skills CLI with this command instead + --package Package the launcher runs (default: skills@1) + --lock-file skills-lock.json location (default: the repository root) + --dry-run Print the skills CLI commands without running them +`; + +class SkillsError extends Error {} + +let failed = false; + +function report(code, message) { + console.error(`error ${code}: ${message}`); + failed = true; +} + +function warn(code, message) { + console.error(`warning ${code}: ${message}`); +} + +function info(message) { + console.log(message); +} + +function environment(name) { + const value = process.env[name]; + return value === undefined || value.trim() === "" ? undefined : value.trim(); +} + +function splitList(value) { + return value + .replace(/^[\s,;"']+|[\s,;"']+$/g, "") + .split(/[\s,;]+/) + .filter((entry) => entry.length > 0); +} + +function quote(value) { + if (value.includes('"')) throw new SkillsError(`'${value}' contains a double quote, which cannot be passed safely.`); + return `"${value}"`; +} + +function unique(values) { + const seen = new Set(); + return values.filter((value) => { + const key = value.toLowerCase(); + if (seen.has(key)) return false; + seen.add(key); + return true; + }); +} + +// The nearest ancestor holding '.git' - a directory in a clone, a file in a worktree or a submodule. +// The recipes always pass --root; this only matters when the script is run by hand. +function findRepositoryRoot(start) { + for (let directory = resolve(start); ; directory = dirname(directory)) { + if (existsSync(join(directory, ".git"))) return directory; + if (dirname(directory) === directory) return resolve(start); + } +} + +function readConfig(configPath) { + if (!existsSync(configPath)) return {}; + + let document; + try { + document = JSON.parse(readFileSync(configPath, "utf8")); + } catch (exception) { + throw new SkillsError(`PRSKL0018 '${configPath}' is not valid JSON: ${(exception).message}`); + } + + const section = (document)?.["Skills"]; + if (section === undefined) return {}; + if (section === null || typeof section !== "object" || Array.isArray(section)) + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills" must be an object.`); + + for (const key of Object.keys(section)) { + if (!configKeys.includes(key)) + warn("PRSKL0019", `'${configPath}': "Skills.${key}" is not a setting and is ignored. Known: ${configKeys.join(", ")}.`); + } + + return section; +} + +function configString(config, key, configPath) { + const value = config[key]; + if (value === undefined || value === null) return undefined; + if (typeof value !== "string") throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.${key}" must be a string.`); + return value.trim() === "" ? undefined : value.trim(); +} + +function configList(config, key, configPath) { + const value = config[key]; + if (value === undefined || value === null) return undefined; + if (typeof value === "string") return splitList(value); + if (Array.isArray(value) && value.every((entry) => typeof entry === "string")) + return value.flatMap((entry) => splitList(entry)); + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.${key}" must be a string or an array of strings.`); +} + +function configBoolean(config, key, configPath) { + const value = config[key]; + if (value === undefined || value === null) return undefined; + if (typeof value !== "boolean") throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.${key}" must be true or false.`); + return value; +} + +function configAgentDirectories(config, configPath) { + const value = config["AgentDirectories"]; + if (value === undefined || value === null) return []; + if (typeof value !== "object" || Array.isArray(value)) + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.AgentDirectories" must map a directory to its agents.`); + + return Object.entries(value).map(([path, agents]) => { + if (typeof agents === "string") return { path, agents: splitList(agents) }; + if (Array.isArray(agents) && agents.every((entry) => typeof entry === "string")) + return { path, agents: agents }; + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.AgentDirectories.${path}" must be a string or an array of strings.`); + }); +} + +function parseBoolean(value) { + if (value === undefined) return undefined; + return ["1", "true", "yes", "on"].includes(value.toLowerCase()); +} + +function resolveSettings(values) { + const option = (name) => { + const value = values[name]; + return typeof value === "string" && value.trim() !== "" ? value.trim() : undefined; + }; + + const root = resolve(option("root") ?? findRepositoryRoot(process.cwd())); + const configPath = resolve(root, option("config") ?? environment("PURVIEW_SKILLS_CONFIG") ?? ".config/purview-build-sdk.json"); + const config = readConfig(configPath); + + const agents = option("agents") ?? environment("PURVIEW_SKILLS_AGENTS"); + const candidates = environment("PURVIEW_SKILLS_RUNNER_CANDIDATES"); + const lockFile = option("lock-file") ?? environment("PURVIEW_SKILLS_LOCK_FILE") ?? configString(config, "LockFile", configPath); + + return { + root, + configPath, + agents: agents !== undefined ? splitList(agents) : (configList(config, "Agents", configPath) ?? []), + runner: option("runner") ?? environment("PURVIEW_SKILLS_RUNNER") ?? configString(config, "Runner", configPath) ?? "bun", + runnerCandidates: + candidates !== undefined + ? splitList(candidates) + : (configList(config, "RunnerCandidates", configPath) ?? ["bun", "npx", "bunx", "pnpm", "yarn", "deno"]), + packageSpec: + option("package") ?? environment("PURVIEW_SKILLS_PACKAGE") ?? configString(config, "Package", configPath) ?? "skills@1", + command: option("command") ?? environment("PURVIEW_SKILLS_COMMAND") ?? configString(config, "Command", configPath) ?? "", + lockFile: resolve(root, lockFile ?? "skills-lock.json"), + dryRun: + values["dry-run"] === true || + (parseBoolean(environment("PURVIEW_SKILLS_DRY_RUN")) ?? configBoolean(config, "DryRun", configPath) ?? false), + agentDirectories: [...defaultAgentDirectories, ...configAgentDirectories(config, configPath)], + }; +} + +function launcherFor(runner, spec) { + const launcher = launchers[runner]; + return launcher === undefined ? `${runner} ${spec}` : launcher(spec); +} + +// PATH is probed directly rather than by starting a version check: no process, nothing to download, +// nothing to hang. PATHEXT is honoured on Windows, where these commands are .cmd shims. +function findOnPath(names) { + const windows = process.platform === "win32"; + const extensions = windows ? ["", ...(environment("PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)] : [""]; + const directories = (process.env["PATH"] ?? "") + .split(delimiter) + .map((entry) => entry.trim().replace(/^"|"$/g, "")) + .filter((entry) => entry.length > 0); + + for (const name of names) { + for (const directory of directories) { + for (const extension of extensions) { + const candidate = join(directory, name + extension); + try { + if (statSync(candidate).isFile()) return { name, path: candidate }; + } catch { + // Not here; a malformed PATH entry must not stop the probe either. + } + } + } + } + + return undefined; +} + +// 'skills' already on PATH is tried first because it needs no download, then the configured runner, +// then the other candidates - so a machine with Node but no Bun still installs. +function resolveLauncher(settings) { + if (settings.command !== "") return settings.command; + + const found = findOnPath(unique(["skills", settings.runner, ...settings.runnerCandidates])); + if (found !== undefined) { + const launcher = launcherFor(found.name, settings.packageSpec); + info(`Using the skills CLI via '${launcher}' (${found.path}).`); + return launcher; + } + + // A dry run runs nothing, so it works on a machine with no runner at all. + if (settings.dryRun) return launcherFor(settings.runner, settings.packageSpec); + + throw new SkillsError( + `PRSKL0004 Cannot run the skills CLI: none of ${unique(["skills", settings.runner, ...settings.runnerCandidates]).join(", ")} was found on PATH. ` + + "Install Bun (which provides 'bun x') or Node.js (which provides npx), or any of pnpm, yarn or deno, " + + "or install the CLI globally with 'npm install -g skills'. Choose a runner with --runner or Skills.Runner; " + + "replace the launcher entirely with --command or Skills.Command.", + ); +} + +function agentArguments(settings) { + // The CLI does not split a comma-separated --agent, so each agent gets its own flag. + return settings.agents.map((agent) => ` --agent ${quote(agent)}`).join(""); +} + +function execute(settings, commandLine) { + info(settings.dryRun ? `Agent skills (dry run): ${commandLine}` : `Agent skills: ${commandLine}`); + if (settings.dryRun) return 0; + + const result = spawnSync(commandLine, { cwd: settings.root, shell: true, stdio: "inherit" }); + if (result.error !== undefined) { + console.error(result.error.message); + return 1; + } + + return result.status ?? 1; +} + +function addSource(settings, source) { + const launcher = resolveLauncher(settings); + // '-y' keeps 'add' non-interactive. '*' is every skill the source has, and a re-run is safe: the + // CLI reinstalls each skill it is given, replacing the installed copy. + const exitCode = execute(settings, `${launcher} add ${quote(source)} --skill "*"${agentArguments(settings)} -y`); + if (exitCode !== 0) report("PRSKL0008", `Agent skills: adding '${source}' failed with exit code ${exitCode}.`); +} + +function install(settings, source) { + if (source !== undefined) { + addSource(settings, source); + return; + } + + if (!existsSync(settings.lockFile)) + throw new SkillsError( + `PRSKL0007 Nothing to install: no source was given, and '${settings.lockFile}' does not exist to restore from. ` + + "Install from a source first, for example: just skills-add purview-dev/build-sdk", + ); + + const exitCode = execute(settings, `${resolveLauncher(settings)} experimental_install`); + if (exitCode !== 0) report("PRSKL0008", `Agent skills: restoring '${settings.lockFile}' failed with exit code ${exitCode}.`); +} + +function readLockSources(lockFile) { + let document; + try { + document = JSON.parse(readFileSync(lockFile, "utf8")); + } catch (exception) { + throw new SkillsError(`PRSKL0007 Cannot read '${lockFile}': ${(exception).message}`); + } + + const skills = (document)?.skills ?? {}; + const sources = Object.values(skills) + .map((entry) => (typeof entry?.source === "string" ? entry.source.trim() : "")) + .filter((source) => source.length > 0); + + return unique(sources).sort((left, right) => left.toLowerCase().localeCompare(right.toLowerCase())); +} + +// Update is 'add', never 'skills update'. 'skills add' reinstalls every skill it selects, so one +// re-add of each source, with every skill it has, both refreshes what is installed and brings in +// anything the source has gained. The lockfile's own skill names are deliberately not reused: naming +// them would leave out a skill added since. Every source is attempted even when one fails. +function update(settings) { + if (!existsSync(settings.lockFile)) + throw new SkillsError( + `PRSKL0007 Cannot update agent skills: '${settings.lockFile}' does not exist. ` + + "Update re-adds the sources the skills CLI recorded there; install skills first with: just skills-add ", + ); + + const sources = readLockSources(settings.lockFile); + if (sources.length === 0) { + info(`Agent skills: no sources recorded in ${settings.lockFile}.`); + return; + } + + const launcher = resolveLauncher(settings); + const failures = []; + for (const source of sources) { + const exitCode = execute(settings, `${launcher} add ${quote(source)} --skill "*"${agentArguments(settings)} -y`); + if (exitCode !== 0) { + report("PRSKL0008", `Agent skills: re-adding '${source}' failed with exit code ${exitCode}.`); + failures.push(source); + } + } + + if (settings.dryRun) info(`Agent skills: dry run, ${sources.length} source(s), nothing changed.`); + else if (failures.length === 0) info(`Agent skills: ${sources.length} source(s) refreshed.`); +} + +function pathExists(path) { + // lstat does not follow a link, so a dangling one still counts as present. + try { + return lstatSync(path, { throwIfNoEntry: false }) !== undefined; + } catch { + return false; + } +} + +// Removes a link and never its target: unlink on Unix, and on Windows the directory form for a +// directory symlink or junction. +function deleteLink(path) { + try { + unlinkSync(path); + } catch { + rmdirSync(path); + } +} + +// When agents are selected, the only agent skill directories allowed are theirs, plus '.agents/skills', +// the CLI's canonical store that every agent directory links into. With fix set, the CLI's links are +// removed - a link only, never its target - and folders left empty go too. A real file is not provably +// the CLI's, so it is kept and reported. +function enforceDirectories(settings, fix) { + if (settings.agents.length === 0) { + info( + "Agent skills: no agents are selected, so the skills CLI auto-detects agents and every agent skill directory is expected. " + + `Set Skills.Agents in ${relative(settings.root, settings.configPath).replace(/\\/g, "/")} (or pass --agents) to enforce a layout.`, + ); + return; + } + + // '*' is every agent, so every directory is allowed. + if (settings.agents.includes("*")) return; + + const windows = process.platform === "win32"; + const key = (path) => (windows ? path.toLowerCase() : path); + const selected = settings.agents.map((agent) => agent.toLowerCase()); + const root = resolve(settings.root); + const toRelative = (path) => relative(root, path).replace(/\\/g, "/"); + + const directories = settings.agentDirectories + .map((entry) => ({ path: entry.path.replace(/\\/g, "/").replace(/^\/+|\/+$/g, ""), agents: entry.agents })) + .filter((entry) => entry.path.length > 0); + + const known = new Set(directories.flatMap((entry) => entry.agents.map((agent) => agent.toLowerCase()))); + for (const agent of settings.agents.filter((agent) => !known.has(agent.toLowerCase()))) + warn( + "PRSKL0016", + `Agent skills: '${agent}' is selected but has no known skills directory, so none is allowed for it. ` + + `Add it to Skills.AgentDirectories in ${toRelative(settings.configPath)} if the skills CLI supports it.`, + ); + + const allowed = new Set([key(".agents/skills")]); + for (const entry of directories) { + if (entry.agents.some((agent) => selected.includes(agent.toLowerCase()))) allowed.add(key(entry.path)); + } + + const protectedPaths = new Set([key(resolve(root, "skills"))]); + + const grouped = new Map(); + for (const entry of directories.filter((candidate) => !allowed.has(key(candidate.path)))) { + const existing = grouped.get(key(entry.path)); + if (existing === undefined) grouped.set(key(entry.path), { path: entry.path, agents: [...entry.agents] }); + else existing.agents.push(...entry.agents); + } + + const removed = []; + let violations = 0; + const kept = []; + + const prune = (path) => { + const stats = lstatSync(path); + if (stats.isSymbolicLink()) { + deleteLink(path); + removed.push(toRelative(path)); + return; + } + + if (!stats.isDirectory()) { + kept.push(toRelative(path)); + return; + } + + for (const child of readdirSync(path).sort()) prune(join(path, child)); + + if (readdirSync(path).length === 0) { + rmdirSync(path); + removed.push(toRelative(path)); + } + }; + + const ordered = [...grouped.values()].sort((left, right) => + left.path < right.path ? -1 : left.path > right.path ? 1 : 0, + ); + + for (const directory of ordered) { + const full = resolve(root, directory.path); + if (protectedPaths.has(key(full)) || !pathExists(full)) continue; + + kept.length = 0; + + // A dry run changes nothing, so it names what fix would clean up and leaves the outcome open. + if (fix && settings.dryRun) { + info( + `Agent skills (dry run): would remove the skills CLI's links from '${directory.path}', ` + + `the skills directory for ${directory.agents.join(", ")}, which the selected agents do not include.`, + ); + continue; + } + + if (fix) { + prune(full); + + // A folder that only ever held the agent's skills is left empty; remove it too, but never + // climb to the repository root. + let parent = dirname(full); + while ( + !pathExists(full) && + parent.length > root.length && + existsSync(parent) && + readdirSync(parent).length === 0 + ) { + rmdirSync(parent); + removed.push(toRelative(parent)); + parent = dirname(parent); + } + + if (!pathExists(full)) continue; + } + + violations++; + const agents = directory.agents.join(", "); + if (fix) { + // The CLI copies rather than links for some agent selections, so a kept folder can hold every + // file of every skill: name enough to recognise, then count the rest. + const sample = kept.slice(0, 5).join(", ") + (kept.length > 5 ? ` and ${kept.length - 5} more` : ""); + report( + "PRSKL0015", + `Agent skills: '${directory.path}' is the skills directory for ${agents}, which the selected agents (${settings.agents.join(", ")}) do not include, ` + + `and still holds content the skills CLI did not create: ${sample}. Remove it by hand.`, + ); + } else { + report( + "PRSKL0015", + `Agent skills: '${directory.path}' is the skills directory for ${agents}, which the selected agents (${settings.agents.join(", ")}) do not include. ` + + "Remove it with: just skills-fix", + ); + } + } + + for (const path of removed) info(`Agent skills: removed ${path}`); + + if (fix && settings.dryRun) info("Agent skills: dry run, nothing removed."); + else if (violations === 0) + info( + fix + ? `Agent skills: ${removed.length} path(s) removed; only the directories for ${settings.agents.join(", ")} exist.` + : `Agent skills: only the directories for ${settings.agents.join(", ")} exist.`, + ); +} + +function main(argv) { + const { values, positionals } = parseArgs({ + args: argv, + allowPositionals: true, + options: { + root: { type: "string" }, + config: { type: "string" }, + agents: { type: "string" }, + runner: { type: "string" }, + command: { type: "string" }, + package: { type: "string" }, + "lock-file": { type: "string" }, + "dry-run": { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }, + }); + + const [command, ...rest] = positionals; + if (values.help === true || command === undefined || command === "help") { + info(usage); + return command === undefined && values.help !== true ? 1 : 0; + } + + const settings = resolveSettings(values); + + switch (command) { + case "add": + if (rest[0] === undefined) throw new SkillsError("PRSKL0007 'add' needs a source, for example: add purview-dev/build-sdk"); + addSource(settings, rest[0]); + break; + case "install": + install(settings, rest[0]); + break; + case "update": + update(settings); + break; + case "check": + enforceDirectories(settings, false); + break; + case "fix": + enforceDirectories(settings, true); + break; + default: + console.error(`Unknown command '${command}'.`); + info(usage); + return 1; + } + + return failed ? 1 : 0; +} + +try { + process.exitCode = main(process.argv.slice(2)); +} catch (exception) { + if (exception instanceof SkillsError) { + const match = /^(PRSKL\d{4}) ([\s\S]*)$/.exec(exception.message); + if (match === null) report("PRSKL0018", exception.message); + else report(match[1] ?? "", match[2] ?? ""); + } else { + console.error((exception).message); + } + + process.exitCode = 1; +} diff --git a/skills/purview-buildsdk-justfile/assets/just/skills.mts b/skills/purview-buildsdk-justfile/assets/just/skills.mts new file mode 100644 index 0000000..9e85a86 --- /dev/null +++ b/skills/purview-buildsdk-justfile/assets/just/skills.mts @@ -0,0 +1,700 @@ +// The Purview.BuildSdk agent-skill commands: a thin wrapper over the standard skills CLI +// (`bun x skills@1` by default), run by the skills-* recipes in skills.just. +// +// Nothing here needs .NET. There is no solution to evaluate, no package to restore and no project +// that has to build, so a repository whose build is broken can still install the skills that might +// help fix it. +// +// add skills add "" --skill "*" - append '#' to the source to pin it +// install [source] add , or restore skills-lock.json with skills experimental_install +// update re-add every unique skills-lock.json source at its latest, with every skill +// check fail when a skill directory exists for an agent that is not selected +// fix remove the skills CLI's links from those directories +// +// Settings, highest first: command-line options, PURVIEW_SKILLS_* environment variables, the +// "Skills" section of .config/purview-build-sdk.json, then the defaults below. Every command runs +// from the repository root, because skills-lock.json and the agent directories belong to the +// repository rather than to a project. +// +// skills.mts is the source. skills.mjs is generated from it by Node's own type stripper, for a +// machine with Node but neither Bun nor Deno: edit this file, then run `just skills-script-sync`. +// Keep to erasable TypeScript (no enums, namespaces or parameter properties) so both stay possible. + +import { spawnSync } from "node:child_process"; +import { existsSync, lstatSync, readdirSync, readFileSync, rmdirSync, statSync, unlinkSync } from "node:fs"; +import { delimiter, dirname, join, relative, resolve } from "node:path"; +import process from "node:process"; +import { parseArgs } from "node:util"; + +type AgentDirectory = { path: string; agents: string[] }; + +type Settings = { + root: string; + configPath: string; + agents: string[]; + runner: string; + runnerCandidates: string[]; + packageSpec: string; + command: string; + lockFile: string; + dryRun: boolean; + agentDirectories: AgentDirectory[]; +}; + +type ConfigSection = Record; + +const configKeys: string[] = [ + "Agents", + "Runner", + "RunnerCandidates", + "Package", + "Command", + "LockFile", + "DryRun", + "AgentDirectories", +]; + +// Each package runner spells "run this npm package" its own way. Every form was checked against the +// real tool, because a wrong one is a command that simply does not run. A runner missing from this +// table still works: it falls through to ' ', the form most new runners adopt. +const launchers: Record string> = { + skills: () => "skills", + npx: (spec: string) => `npx -y ${spec}`, + bunx: (spec: string) => `bunx ${spec}`, + bun: (spec: string) => `bun x ${spec}`, + pnpm: (spec: string) => `pnpm dlx ${spec}`, + yarn: (spec: string) => `yarn dlx ${spec}`, + deno: (spec: string) => `deno run -A npm:${spec}`, +}; + +// Where the skills CLI writes a project-scope install for each agent, from its own agent table +// (skills 1.7.6, docs/agents.md). Only check and fix read this, and only when agents are selected. +// The CLI adds agents independently of this script; add one through Skills.AgentDirectories in +// .config/purview-build-sdk.json rather than waiting for a release. +const defaultAgentDirectories: AgentDirectory[] = [ + { + path: ".agents/skills", + agents: [ + "amp", + "antigravity", + "antigravity-cli", + "cline", + "codex", + "cursor", + "deepagents", + "dexto", + "droid", + "firebender", + "fx", + "gemini-cli", + "github-copilot", + "kilo", + "kimi-code-cli", + "loaf", + "opencode", + "pi", + "promptscript", + "replit", + "sarvam-code", + "universal", + "warp", + "zed", + ], + }, + { path: ".adal/skills", agents: ["adal"] }, + { path: ".aider-desk/skills", agents: ["aider-desk"] }, + { path: ".augment/skills", agents: ["augment"] }, + { path: ".autohand/skills", agents: ["autohand-code"] }, + { path: ".bob/skills", agents: ["bob"] }, + { path: ".claude/skills", agents: ["claude-code"] }, + { path: ".codeartsdoer/skills", agents: ["codearts-agent"] }, + { path: ".codebuddy/skills", agents: ["codebuddy"] }, + { path: ".codemaker/skills", agents: ["codemaker"] }, + { path: ".codestudio/skills", agents: ["codestudio"] }, + { path: ".commandcode/skills", agents: ["command-code"] }, + { path: ".continue/skills", agents: ["continue"] }, + { path: ".cortex/skills", agents: ["cortex"] }, + { path: ".crush/skills", agents: ["crush"] }, + { path: ".devin/skills", agents: ["devin"] }, + { path: ".forge/skills", agents: ["forgecode"] }, + { path: ".goose/skills", agents: ["goose"] }, + { path: ".grok/skills", agents: ["grok"] }, + { path: ".hermes/skills", agents: ["hermes-agent"] }, + { path: ".iflow/skills", agents: ["iflow-cli"] }, + { path: ".inferencesh/skills", agents: ["inference-sh"] }, + { path: ".jazz/skills", agents: ["jazz"] }, + { path: ".junie/skills", agents: ["junie"] }, + { path: ".kimchi/skills", agents: ["kimchi"] }, + { path: ".kiro/skills", agents: ["kiro-cli"] }, + { path: ".kode/skills", agents: ["kode"] }, + { path: ".lingma/skills", agents: ["lingma"] }, + { path: ".mcpjam/skills", agents: ["mcpjam"] }, + { path: ".minimax/skills", agents: ["minimax-code"] }, + { path: ".moxby/skills", agents: ["moxby"] }, + { path: ".mux/skills", agents: ["mux"] }, + { path: ".neovate/skills", agents: ["neovate"] }, + { path: ".ona/skills", agents: ["ona"] }, + { path: ".openhands/skills", agents: ["openhands"] }, + { path: ".pochi/skills", agents: ["pochi"] }, + { path: ".posit/assistant/skills", agents: ["posit-assistant"] }, + { path: ".qoder/skills", agents: ["qoder", "qoder-cn"] }, + { path: ".qwen/skills", agents: ["qwen-code"] }, + { path: ".reasonix/skills", agents: ["reasonix"] }, + { path: ".roo/skills", agents: ["roo"] }, + { path: ".rovodev/skills", agents: ["rovodev"] }, + { path: ".tabnine/agent/skills", agents: ["tabnine-cli"] }, + { path: ".terramind/skills", agents: ["terramind"] }, + { path: ".tinycloud/skills", agents: ["tinycloud"] }, + { path: ".trae/skills", agents: ["trae", "trae-cn"] }, + { path: ".vibe/skills", agents: ["mistral-vibe"] }, + { path: ".windsurf/skills", agents: ["windsurf"] }, + { path: ".zcode/skills", agents: ["zcode"] }, + { path: ".zencoder/skills", agents: ["zencoder", "zenflow"] }, + { path: "agent/skills", agents: ["eve"] }, + { path: "data/skills", agents: ["astrbot"] }, + // openclaw installs into a root 'skills/', the folder a repository authors its own skills in. It is + // listed so selecting openclaw is not an unknown agent, but the authored folder is never touched. + { path: "skills", agents: ["openclaw"] }, +]; + +const usage: string = `Usage: skills.mts [options] + +Commands: + add Install every skill a source has (append '#' to pin it) + install [source] Install from a source, or restore skills-lock.json + update Re-add every skills-lock.json source at its latest + check Fail when a skill directory exists for an unselected agent + fix Remove the skills CLI's links from those directories + +Options: + --root Repository root (default: the nearest folder holding .git) + --config Settings file (default: .config/purview-build-sdk.json) + --agents Agents to install to, separated by ',', ';' or spaces + --runner Package runner: bun, npx, bunx, pnpm, yarn, deno or skills + --command Launch the skills CLI with this command instead + --package Package the launcher runs (default: skills@1) + --lock-file skills-lock.json location (default: the repository root) + --dry-run Print the skills CLI commands without running them +`; + +class SkillsError extends Error {} + +let failed = false; + +function report(code: string, message: string): void { + console.error(`error ${code}: ${message}`); + failed = true; +} + +function warn(code: string, message: string): void { + console.error(`warning ${code}: ${message}`); +} + +function info(message: string): void { + console.log(message); +} + +function environment(name: string): string | undefined { + const value = process.env[name]; + return value === undefined || value.trim() === "" ? undefined : value.trim(); +} + +function splitList(value: string): string[] { + return value + .replace(/^[\s,;"']+|[\s,;"']+$/g, "") + .split(/[\s,;]+/) + .filter((entry: string) => entry.length > 0); +} + +function quote(value: string): string { + if (value.includes('"')) throw new SkillsError(`'${value}' contains a double quote, which cannot be passed safely.`); + return `"${value}"`; +} + +function unique(values: string[]): string[] { + const seen: Set = new Set(); + return values.filter((value: string) => { + const key = value.toLowerCase(); + if (seen.has(key)) return false; + seen.add(key); + return true; + }); +} + +// The nearest ancestor holding '.git' - a directory in a clone, a file in a worktree or a submodule. +// The recipes always pass --root; this only matters when the script is run by hand. +function findRepositoryRoot(start: string): string { + for (let directory = resolve(start); ; directory = dirname(directory)) { + if (existsSync(join(directory, ".git"))) return directory; + if (dirname(directory) === directory) return resolve(start); + } +} + +function readConfig(configPath: string): ConfigSection { + if (!existsSync(configPath)) return {}; + + let document: unknown; + try { + document = JSON.parse(readFileSync(configPath, "utf8")); + } catch (exception) { + throw new SkillsError(`PRSKL0018 '${configPath}' is not valid JSON: ${(exception as Error).message}`); + } + + const section = (document as Record | null)?.["Skills"]; + if (section === undefined) return {}; + if (section === null || typeof section !== "object" || Array.isArray(section)) + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills" must be an object.`); + + for (const key of Object.keys(section)) { + if (!configKeys.includes(key)) + warn("PRSKL0019", `'${configPath}': "Skills.${key}" is not a setting and is ignored. Known: ${configKeys.join(", ")}.`); + } + + return section as ConfigSection; +} + +function configString(config: ConfigSection, key: string, configPath: string): string | undefined { + const value = config[key]; + if (value === undefined || value === null) return undefined; + if (typeof value !== "string") throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.${key}" must be a string.`); + return value.trim() === "" ? undefined : value.trim(); +} + +function configList(config: ConfigSection, key: string, configPath: string): string[] | undefined { + const value = config[key]; + if (value === undefined || value === null) return undefined; + if (typeof value === "string") return splitList(value); + if (Array.isArray(value) && value.every((entry: unknown) => typeof entry === "string")) + return value.flatMap((entry: string) => splitList(entry)); + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.${key}" must be a string or an array of strings.`); +} + +function configBoolean(config: ConfigSection, key: string, configPath: string): boolean | undefined { + const value = config[key]; + if (value === undefined || value === null) return undefined; + if (typeof value !== "boolean") throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.${key}" must be true or false.`); + return value; +} + +function configAgentDirectories(config: ConfigSection, configPath: string): AgentDirectory[] { + const value = config["AgentDirectories"]; + if (value === undefined || value === null) return []; + if (typeof value !== "object" || Array.isArray(value)) + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.AgentDirectories" must map a directory to its agents.`); + + return Object.entries(value as Record).map(([path, agents]: [string, unknown]) => { + if (typeof agents === "string") return { path, agents: splitList(agents) }; + if (Array.isArray(agents) && agents.every((entry: unknown) => typeof entry === "string")) + return { path, agents: agents as string[] }; + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.AgentDirectories.${path}" must be a string or an array of strings.`); + }); +} + +function parseBoolean(value: string | undefined): boolean | undefined { + if (value === undefined) return undefined; + return ["1", "true", "yes", "on"].includes(value.toLowerCase()); +} + +function resolveSettings(values: Record): Settings { + const option = (name: string): string | undefined => { + const value = values[name]; + return typeof value === "string" && value.trim() !== "" ? value.trim() : undefined; + }; + + const root = resolve(option("root") ?? findRepositoryRoot(process.cwd())); + const configPath = resolve(root, option("config") ?? environment("PURVIEW_SKILLS_CONFIG") ?? ".config/purview-build-sdk.json"); + const config = readConfig(configPath); + + const agents = option("agents") ?? environment("PURVIEW_SKILLS_AGENTS"); + const candidates = environment("PURVIEW_SKILLS_RUNNER_CANDIDATES"); + const lockFile = option("lock-file") ?? environment("PURVIEW_SKILLS_LOCK_FILE") ?? configString(config, "LockFile", configPath); + + return { + root, + configPath, + agents: agents !== undefined ? splitList(agents) : (configList(config, "Agents", configPath) ?? []), + runner: option("runner") ?? environment("PURVIEW_SKILLS_RUNNER") ?? configString(config, "Runner", configPath) ?? "bun", + runnerCandidates: + candidates !== undefined + ? splitList(candidates) + : (configList(config, "RunnerCandidates", configPath) ?? ["bun", "npx", "bunx", "pnpm", "yarn", "deno"]), + packageSpec: + option("package") ?? environment("PURVIEW_SKILLS_PACKAGE") ?? configString(config, "Package", configPath) ?? "skills@1", + command: option("command") ?? environment("PURVIEW_SKILLS_COMMAND") ?? configString(config, "Command", configPath) ?? "", + lockFile: resolve(root, lockFile ?? "skills-lock.json"), + dryRun: + values["dry-run"] === true || + (parseBoolean(environment("PURVIEW_SKILLS_DRY_RUN")) ?? configBoolean(config, "DryRun", configPath) ?? false), + agentDirectories: [...defaultAgentDirectories, ...configAgentDirectories(config, configPath)], + }; +} + +function launcherFor(runner: string, spec: string): string { + const launcher = launchers[runner]; + return launcher === undefined ? `${runner} ${spec}` : launcher(spec); +} + +// PATH is probed directly rather than by starting a version check: no process, nothing to download, +// nothing to hang. PATHEXT is honoured on Windows, where these commands are .cmd shims. +function findOnPath(names: string[]): { name: string; path: string } | undefined { + const windows = process.platform === "win32"; + const extensions = windows ? ["", ...(environment("PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)] : [""]; + const directories = (process.env["PATH"] ?? "") + .split(delimiter) + .map((entry: string) => entry.trim().replace(/^"|"$/g, "")) + .filter((entry: string) => entry.length > 0); + + for (const name of names) { + for (const directory of directories) { + for (const extension of extensions) { + const candidate = join(directory, name + extension); + try { + if (statSync(candidate).isFile()) return { name, path: candidate }; + } catch { + // Not here; a malformed PATH entry must not stop the probe either. + } + } + } + } + + return undefined; +} + +// 'skills' already on PATH is tried first because it needs no download, then the configured runner, +// then the other candidates - so a machine with Node but no Bun still installs. +function resolveLauncher(settings: Settings): string { + if (settings.command !== "") return settings.command; + + const found = findOnPath(unique(["skills", settings.runner, ...settings.runnerCandidates])); + if (found !== undefined) { + const launcher = launcherFor(found.name, settings.packageSpec); + info(`Using the skills CLI via '${launcher}' (${found.path}).`); + return launcher; + } + + // A dry run runs nothing, so it works on a machine with no runner at all. + if (settings.dryRun) return launcherFor(settings.runner, settings.packageSpec); + + throw new SkillsError( + `PRSKL0004 Cannot run the skills CLI: none of ${unique(["skills", settings.runner, ...settings.runnerCandidates]).join(", ")} was found on PATH. ` + + "Install Bun (which provides 'bun x') or Node.js (which provides npx), or any of pnpm, yarn or deno, " + + "or install the CLI globally with 'npm install -g skills'. Choose a runner with --runner or Skills.Runner; " + + "replace the launcher entirely with --command or Skills.Command.", + ); +} + +function agentArguments(settings: Settings): string { + // The CLI does not split a comma-separated --agent, so each agent gets its own flag. + return settings.agents.map((agent: string) => ` --agent ${quote(agent)}`).join(""); +} + +function execute(settings: Settings, commandLine: string): number { + info(settings.dryRun ? `Agent skills (dry run): ${commandLine}` : `Agent skills: ${commandLine}`); + if (settings.dryRun) return 0; + + const result = spawnSync(commandLine, { cwd: settings.root, shell: true, stdio: "inherit" }); + if (result.error !== undefined) { + console.error(result.error.message); + return 1; + } + + return result.status ?? 1; +} + +function addSource(settings: Settings, source: string): void { + const launcher = resolveLauncher(settings); + // '-y' keeps 'add' non-interactive. '*' is every skill the source has, and a re-run is safe: the + // CLI reinstalls each skill it is given, replacing the installed copy. + const exitCode = execute(settings, `${launcher} add ${quote(source)} --skill "*"${agentArguments(settings)} -y`); + if (exitCode !== 0) report("PRSKL0008", `Agent skills: adding '${source}' failed with exit code ${exitCode}.`); +} + +function install(settings: Settings, source: string | undefined): void { + if (source !== undefined) { + addSource(settings, source); + return; + } + + if (!existsSync(settings.lockFile)) + throw new SkillsError( + `PRSKL0007 Nothing to install: no source was given, and '${settings.lockFile}' does not exist to restore from. ` + + "Install from a source first, for example: just skills-add purview-dev/build-sdk", + ); + + const exitCode = execute(settings, `${resolveLauncher(settings)} experimental_install`); + if (exitCode !== 0) report("PRSKL0008", `Agent skills: restoring '${settings.lockFile}' failed with exit code ${exitCode}.`); +} + +function readLockSources(lockFile: string): string[] { + let document: unknown; + try { + document = JSON.parse(readFileSync(lockFile, "utf8")); + } catch (exception) { + throw new SkillsError(`PRSKL0007 Cannot read '${lockFile}': ${(exception as Error).message}`); + } + + const skills = (document as { skills?: Record } | null)?.skills ?? {}; + const sources = Object.values(skills) + .map((entry: { source?: unknown }) => (typeof entry?.source === "string" ? entry.source.trim() : "")) + .filter((source: string) => source.length > 0); + + return unique(sources).sort((left: string, right: string) => left.toLowerCase().localeCompare(right.toLowerCase())); +} + +// Update is 'add', never 'skills update'. 'skills add' reinstalls every skill it selects, so one +// re-add of each source, with every skill it has, both refreshes what is installed and brings in +// anything the source has gained. The lockfile's own skill names are deliberately not reused: naming +// them would leave out a skill added since. Every source is attempted even when one fails. +function update(settings: Settings): void { + if (!existsSync(settings.lockFile)) + throw new SkillsError( + `PRSKL0007 Cannot update agent skills: '${settings.lockFile}' does not exist. ` + + "Update re-adds the sources the skills CLI recorded there; install skills first with: just skills-add ", + ); + + const sources = readLockSources(settings.lockFile); + if (sources.length === 0) { + info(`Agent skills: no sources recorded in ${settings.lockFile}.`); + return; + } + + const launcher = resolveLauncher(settings); + const failures: string[] = []; + for (const source of sources) { + const exitCode = execute(settings, `${launcher} add ${quote(source)} --skill "*"${agentArguments(settings)} -y`); + if (exitCode !== 0) { + report("PRSKL0008", `Agent skills: re-adding '${source}' failed with exit code ${exitCode}.`); + failures.push(source); + } + } + + if (settings.dryRun) info(`Agent skills: dry run, ${sources.length} source(s), nothing changed.`); + else if (failures.length === 0) info(`Agent skills: ${sources.length} source(s) refreshed.`); +} + +function pathExists(path: string): boolean { + // lstat does not follow a link, so a dangling one still counts as present. + try { + return lstatSync(path, { throwIfNoEntry: false }) !== undefined; + } catch { + return false; + } +} + +// Removes a link and never its target: unlink on Unix, and on Windows the directory form for a +// directory symlink or junction. +function deleteLink(path: string): void { + try { + unlinkSync(path); + } catch { + rmdirSync(path); + } +} + +// When agents are selected, the only agent skill directories allowed are theirs, plus '.agents/skills', +// the CLI's canonical store that every agent directory links into. With fix set, the CLI's links are +// removed - a link only, never its target - and folders left empty go too. A real file is not provably +// the CLI's, so it is kept and reported. +function enforceDirectories(settings: Settings, fix: boolean): void { + if (settings.agents.length === 0) { + info( + "Agent skills: no agents are selected, so the skills CLI auto-detects agents and every agent skill directory is expected. " + + `Set Skills.Agents in ${relative(settings.root, settings.configPath).replace(/\\/g, "/")} (or pass --agents) to enforce a layout.`, + ); + return; + } + + // '*' is every agent, so every directory is allowed. + if (settings.agents.includes("*")) return; + + const windows = process.platform === "win32"; + const key = (path: string): string => (windows ? path.toLowerCase() : path); + const selected = settings.agents.map((agent: string) => agent.toLowerCase()); + const root = resolve(settings.root); + const toRelative = (path: string): string => relative(root, path).replace(/\\/g, "/"); + + const directories = settings.agentDirectories + .map((entry: AgentDirectory) => ({ path: entry.path.replace(/\\/g, "/").replace(/^\/+|\/+$/g, ""), agents: entry.agents })) + .filter((entry: AgentDirectory) => entry.path.length > 0); + + const known: Set = new Set(directories.flatMap((entry: AgentDirectory) => entry.agents.map((agent: string) => agent.toLowerCase()))); + for (const agent of settings.agents.filter((agent: string) => !known.has(agent.toLowerCase()))) + warn( + "PRSKL0016", + `Agent skills: '${agent}' is selected but has no known skills directory, so none is allowed for it. ` + + `Add it to Skills.AgentDirectories in ${toRelative(settings.configPath)} if the skills CLI supports it.`, + ); + + const allowed: Set = new Set([key(".agents/skills")]); + for (const entry of directories) { + if (entry.agents.some((agent: string) => selected.includes(agent.toLowerCase()))) allowed.add(key(entry.path)); + } + + const protectedPaths: Set = new Set([key(resolve(root, "skills"))]); + + const grouped: Map = new Map(); + for (const entry of directories.filter((candidate: AgentDirectory) => !allowed.has(key(candidate.path)))) { + const existing = grouped.get(key(entry.path)); + if (existing === undefined) grouped.set(key(entry.path), { path: entry.path, agents: [...entry.agents] }); + else existing.agents.push(...entry.agents); + } + + const removed: string[] = []; + let violations = 0; + const kept: string[] = []; + + const prune = (path: string): void => { + const stats = lstatSync(path); + if (stats.isSymbolicLink()) { + deleteLink(path); + removed.push(toRelative(path)); + return; + } + + if (!stats.isDirectory()) { + kept.push(toRelative(path)); + return; + } + + for (const child of readdirSync(path).sort()) prune(join(path, child)); + + if (readdirSync(path).length === 0) { + rmdirSync(path); + removed.push(toRelative(path)); + } + }; + + const ordered = [...grouped.values()].sort((left: AgentDirectory, right: AgentDirectory) => + left.path < right.path ? -1 : left.path > right.path ? 1 : 0, + ); + + for (const directory of ordered) { + const full = resolve(root, directory.path); + if (protectedPaths.has(key(full)) || !pathExists(full)) continue; + + kept.length = 0; + + // A dry run changes nothing, so it names what fix would clean up and leaves the outcome open. + if (fix && settings.dryRun) { + info( + `Agent skills (dry run): would remove the skills CLI's links from '${directory.path}', ` + + `the skills directory for ${directory.agents.join(", ")}, which the selected agents do not include.`, + ); + continue; + } + + if (fix) { + prune(full); + + // A folder that only ever held the agent's skills is left empty; remove it too, but never + // climb to the repository root. + let parent = dirname(full); + while ( + !pathExists(full) && + parent.length > root.length && + existsSync(parent) && + readdirSync(parent).length === 0 + ) { + rmdirSync(parent); + removed.push(toRelative(parent)); + parent = dirname(parent); + } + + if (!pathExists(full)) continue; + } + + violations++; + const agents = directory.agents.join(", "); + if (fix) { + // The CLI copies rather than links for some agent selections, so a kept folder can hold every + // file of every skill: name enough to recognise, then count the rest. + const sample = kept.slice(0, 5).join(", ") + (kept.length > 5 ? ` and ${kept.length - 5} more` : ""); + report( + "PRSKL0015", + `Agent skills: '${directory.path}' is the skills directory for ${agents}, which the selected agents (${settings.agents.join(", ")}) do not include, ` + + `and still holds content the skills CLI did not create: ${sample}. Remove it by hand.`, + ); + } else { + report( + "PRSKL0015", + `Agent skills: '${directory.path}' is the skills directory for ${agents}, which the selected agents (${settings.agents.join(", ")}) do not include. ` + + "Remove it with: just skills-fix", + ); + } + } + + for (const path of removed) info(`Agent skills: removed ${path}`); + + if (fix && settings.dryRun) info("Agent skills: dry run, nothing removed."); + else if (violations === 0) + info( + fix + ? `Agent skills: ${removed.length} path(s) removed; only the directories for ${settings.agents.join(", ")} exist.` + : `Agent skills: only the directories for ${settings.agents.join(", ")} exist.`, + ); +} + +function main(argv: string[]): number { + const { values, positionals } = parseArgs({ + args: argv, + allowPositionals: true, + options: { + root: { type: "string" }, + config: { type: "string" }, + agents: { type: "string" }, + runner: { type: "string" }, + command: { type: "string" }, + package: { type: "string" }, + "lock-file": { type: "string" }, + "dry-run": { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }, + }); + + const [command, ...rest] = positionals; + if (values.help === true || command === undefined || command === "help") { + info(usage); + return command === undefined && values.help !== true ? 1 : 0; + } + + const settings = resolveSettings(values as Record); + + switch (command) { + case "add": + if (rest[0] === undefined) throw new SkillsError("PRSKL0007 'add' needs a source, for example: add purview-dev/build-sdk"); + addSource(settings, rest[0]); + break; + case "install": + install(settings, rest[0]); + break; + case "update": + update(settings); + break; + case "check": + enforceDirectories(settings, false); + break; + case "fix": + enforceDirectories(settings, true); + break; + default: + console.error(`Unknown command '${command}'.`); + info(usage); + return 1; + } + + return failed ? 1 : 0; +} + +try { + process.exitCode = main(process.argv.slice(2)); +} catch (exception) { + if (exception instanceof SkillsError) { + const match = /^(PRSKL\d{4}) ([\s\S]*)$/.exec(exception.message); + if (match === null) report("PRSKL0018", exception.message); + else report(match[1] ?? "", match[2] ?? ""); + } else { + console.error((exception as Error).message); + } + + process.exitCode = 1; +} diff --git a/skills/purview-buildsdk-justfile/references/skills-recipes.md b/skills/purview-buildsdk-justfile/references/skills-recipes.md index 5c850f5..5d5d87e 100644 --- a/skills/purview-buildsdk-justfile/references/skills-recipes.md +++ b/skills/purview-buildsdk-justfile/references/skills-recipes.md @@ -1,35 +1,54 @@ # The agent-skill recipes -`skills.just` gives each SDK skill target a recipe. The targets are a thin wrapper over the standard -skills CLI (`bun x skills` by default), which finds a repository's skills in its root `skills/` -folder and records what it installed in `skills-lock.json`. Their behaviour is covered by -`purview-buildsdk-skill-installation`; this page is about the recipes that run them. +`skills.just` gives each skill command a recipe, and `skills.mts` beside it does the work: a thin +wrapper over the standard skills CLI (`bun x skills` by default), which finds a repository's skills in +its root `skills/` folder and records what it installed in `skills-lock.json`. Their behaviour is +covered by `purview-buildsdk-skill-installation`; this page is about the recipes and the files. + +## Three files, copied together + +| File | What it is | +| -- | -- | +| `skills.just` | the recipes | +| `skills.mts` | the script, in TypeScript; Bun and Deno run it directly | +| `skills.mjs` | the same script with the types removed, for a machine with Node but neither Bun nor Deno | + +`skills.mjs` is **generated** from `skills.mts` and must not be edited by hand. Copy all three, or the +recipes fail on the machine whose runtime needs the missing one. + +None of them involves .NET. There is no solution to evaluate, no restore and no build, so the recipes +take well under a second and work in a repository whose build is broken. ## The rule that matters most -**Every skill recipe is run by a person, on purpose.** `InstallPurviewSkills`, `UpdatePurviewSkills` -and `FixPurviewSkills` change the repository, and the SDK refuses to run them inside a build, a -restore or a design-time build (`PRSKL0009`). Keep the `Justfile` consistent with that: +**Every skill recipe is run by a person, on purpose.** `skills-add`, `-install`, `-update` and `-fix` +change the repository. Keep the `Justfile` consistent with that: - never make a skills recipe a dependency of `build`, `test`, `default` or any other recipe; - never call `skills-add`, `skills-install`, `skills-update` or `skills-fix` from a git hook - (`lefthook.yml`, `.husky/`) or from a CI job that commits — `PRSKL0009` cannot see those, because they - run the target on its own; + (`lefthook.yml`, `.husky/`) or from a CI job that commits; - `skills-check` is read-only and safe anywhere. ## The recipes -| Recipe | Target | Runs | Changes the repository | +| Recipe | Command | Runs | Changes the repository | | -- | -- | -- | -- | -| `skills-add ` | `InstallPurviewSkills` with `PurviewSkillsSource` | `skills add --skill "*"` | yes | -| `skills-install` | `InstallPurviewSkills` | `skills experimental_install` — restore `skills-lock.json` | yes | -| `skills-update` | `UpdatePurviewSkills;FixPurviewSkills` | `skills add --skill "*"` once per lockfile source | yes | -| `skills-check` | `CheckPurviewSkills` | nothing | no | -| `skills-fix` | `FixPurviewSkills` | nothing; removes links itself | yes | +| `skills-add ` | `add` | `skills add --skill "*"` | yes | +| `skills-install` | `install` | `skills experimental_install` — restore `skills-lock.json` | yes | +| `skills-update` | `update`, then `fix` | `skills add --skill "*"` once per lockfile source | yes | +| `skills-check` | `check` | nothing | no | +| `skills-fix` | `fix` | nothing; removes links itself | yes | + +Each passes `--root` with the directory holding the root `Justfile`, and `*args` last, so a caller can +add options: `just skills-update --dry-run --agents claude-code,codex`. + +The runtime is the first of Bun (`skills.mts`), Deno (`skills.mts`) and Node (`skills.mjs`) on `PATH`. +`PURVIEW_SKILLS_RUNTIME` overrides it — `node`, `bun`, or `deno run -A`. `just`'s own `which()` is not +used, because it needs an unstable setting; the choice is a small `sh` function instead. A repository that *authors* skills usually adds `skills-validate` to its root `Justfile`. It runs -`ValidatePurviewSkills` against the one project that packs, because that target runs once per -project it is invoked on: +`ValidatePurviewSkills` — the pack-time check, which is still MSBuild — against the one project that +packs, because that target runs once per project it is invoked on: ```just [group('Agent Skills')] @@ -37,64 +56,64 @@ skills-validate *args: dotnet msbuild "src/src/Acme/Acme.csproj" -t:ValidatePurviewSkills -v:n {{ args }} ``` -## Why the recipes name the solution +## Settings belong in `.config/purview-build-sdk.json`, not in the recipe -`skills_project` defaults to `solution_file`. Every skill target runs once for the whole solution, -however many projects it holds: each project hands the work to the same elected leader, and MSBuild -runs it once. A single project works too. An old `Justfile.skills.just` pointed at a hand-picked -"small" project gets the same treatment: delete it, and let `skills.just` name the solution. +Set repository-wide choices once, not as flags repeated in each recipe, so running the script by hand +behaves the same as the recipe: -## Details that break a recipe if missed +```json +{ + "Skills": { + "Runner": "bun", + "Agents": ["universal"] + } +} +``` -- **Quote a multi-target `-t:`.** `"-t:UpdatePurviewSkills;FixPurviewSkills"` — unquoted, `sh` ends the - command at the `;` and runs `FixPurviewSkills` as a separate, failing command. The same holds under - PowerShell. -- **Keep `*args` last** so a caller can pass properties: `just skills-update -p:PurviewSkillsDryRun=true`. -- `FixPurviewSkills` after `UpdatePurviewSkills` does nothing unless `PurviewSkillsAgents` is set, so - it is safe in the recipe either way. -- `skills-install` with no lockfile fails with `PRSKL0007`: add a source first with `skills-add`. +`Agents` is optional; setting it makes `skills-check`/`skills-fix` enforce that only those agents' +skill directories exist. One-off overrides go after the recipe name or in a `PURVIEW_SKILLS_*` +environment variable. The full table is in `purview-buildsdk-skill-installation`. -## Runner and agents belong in MSBuild, not in the recipe +| Option | Effect | +| -- | -- | +| `--dry-run` | Print every CLI command; run none | +| `--runner npx` | Launch the CLI through another runner (`bunx`, `pnpm`, `yarn`, `deno`) | +| `--agents a,b` | Install to, and enforce, these agents | -Set repository-wide choices once in `Directory.Build.props`, not as flags repeated in each recipe, so -a plain `dotnet msbuild -t:...` behaves the same as the recipe: +## Details that break a recipe if missed -```xml - - - bun - - universal - -``` +- **Keep `*args` last** so a caller can pass options. +- `fix` after `update` does nothing unless agents are selected, so it is safe in the recipe either way. +- `skills-install` with no lockfile fails with `PRSKL0007`: add a source first with `skills-add`. +- `skills.mts` must stay erasable TypeScript — no `enum`, `namespace` or parameter properties — or + Node's type stripper cannot produce `skills.mjs` from it. -One-off overrides go on the command line. `dotnet msbuild -p:` splits values on `,` and `;`, so escape -the separator: `just skills-update -p:PurviewSkillsAgents=claude-code%2Ccodex`. +## Moving from the MSBuild targets -| Property | Effect | -| -- | -- | -| `PurviewSkillsDryRun=true` | Print every CLI command; run none | -| `PurviewSkillsRunner=npx` | Launch the CLI through another runner (`bunx`, `pnpm`, `yarn`, `deno`) | -| `PurviewSkillsSource=owner/repo#ref` | What `skills-add` sets: the source to install from | +The recipes used to run `dotnet msbuild -t:InstallPurviewSkills` and friends, which +evaluated every project in the solution each time and failed whenever one did not evaluate. Those +targets and their `PurviewSkills*` properties are gone. Copy the three files above, and move any +`PurviewSkills*` property from `Directory.Build.props` into `.config/purview-build-sdk.json` — the +mapping is in `purview-buildsdk-skill-installation`. Delete a `skills_project` override from the root +`Justfile`; nothing reads it. ## Replacing hand-written skill scripts | Hand-written | Replace with | | -- | -- | -| `scripts/update-agent-skills.ts`, `"skills:update"` | `skills-update` (`UpdatePurviewSkills`) | +| `scripts/update-agent-skills.ts`, `"skills:update"` | `skills-update` | | `--update` / `--no-update` | Nothing: the re-add refreshes installed skills and adds new ones, so there is no separate `skills update` step to switch | -| `--dry-run` | `-p:PurviewSkillsDryRun=true` | -| `scripts/ensure-universal-skills.ts check`, `"skills:check"` | `skills-check` with `PurviewSkillsAgents=universal` | +| `--dry-run` | `--dry-run` | +| `scripts/ensure-universal-skills.ts check`, `"skills:check"` | `skills-check` with `Agents` set to `universal` | | `scripts/ensure-universal-skills.ts fix`, `"skills:fix"` | `skills-fix` | -| a hard-coded `-a universal` | `PurviewSkillsAgents` — or leave it empty to auto-detect | +| a hard-coded `-a universal` | `Agents` — or leave it empty to auto-detect | Update is `skills add`, not `skills update`, so it also installs skills a source has **gained**: each source is re-added with `--skill "*"`. Mention that when migrating. -Before deleting the scripts, run `just skills-update -p:PurviewSkillsDryRun=true` and compare the -printed commands with what the old script ran. Then delete the scripts and their `package.json` -entries — but keep `package.json` itself, which Purview.BuildSdk reads the version from. +Before deleting the scripts, run `just skills-update --dry-run` and compare the printed commands with +what the old script ran. Then delete the scripts and their `package.json` entries — but keep +`package.json` itself, which Purview.BuildSdk reads the version from. -An existing `skills-recommend`, `skills-verify` or `skills-list` recipe has no target behind it any +An existing `skills-recommend`, `skills-verify` or `skills-list` recipe has nothing behind it any more: delete it, and its callers. diff --git a/skills/purview-buildsdk-repository-review/SKILL.md b/skills/purview-buildsdk-repository-review/SKILL.md index 15f90c0..8feb4e8 100644 --- a/skills/purview-buildsdk-repository-review/SKILL.md +++ b/skills/purview-buildsdk-repository-review/SKILL.md @@ -100,19 +100,23 @@ go stale: Only relevant when the repository has a `skills-lock.json` or an agent skills directory: -- **Anything that runs `InstallPurviewSkills`, `UpdatePurviewSkills` or `FixPurviewSkills` - implicitly** — an `AfterTargets`/`BeforeTargets` hook, a `*DependsOn` property, a git hook, a - `just` recipe dependency — is structural debt: skill changes should only happen when somebody asks. - The SDK fails the build-time cases with `PRSKL0009` (inside a build, a restore or a design-time - build); a git hook or a recipe dependency that runs the target on its own is **not** caught, so - look for those by reading the hook configuration and the `Justfile`. +- **Anything that runs `skills-add`, `skills-install`, `skills-update` or `skills-fix` + implicitly** — a git hook, a `just` recipe dependency, a CI job that commits — is structural debt: + skill changes should only happen when somebody asks. Look for those by reading the hook + configuration and the `Justfile`. +- **Old MSBuild skill recipes** — `dotnet msbuild ... -t:InstallPurviewSkills` (or Update, Check, + Fix), or `PurviewSkills*` install properties in `Directory.Build.props` — are a structural finding: + those targets were removed, so the recipes fail. Replace them with the `purview-buildsdk-justfile` + skill's `skills.just`, `skills.mts` and `skills.mjs`, and move the properties into + `.config/purview-build-sdk.json`. - **Hand-written skill scripts** (`update-agent-skills.ts`, `ensure-universal-skills.ts`, - `package.json` `skills:*` entries) are an incremental opportunity: the SDK targets wrap the same - standard CLI, from the repository root, once per solution. See `purview-buildsdk-justfile`. + `package.json` `skills:*` entries) are an incremental opportunity: the `skills-*` recipes wrap the + same standard CLI, from the repository root. See `purview-buildsdk-justfile`. - **A fresh clone**: a committed `skills-lock.json` with no agent skills directory beside it means the - skills were never restored — `-t:InstallPurviewSkills` (`skills experimental_install`) restores them. -- **Layout**: if `PurviewSkillsAgents` is set, run `-t:CheckPurviewSkills` and quote any `PRSKL0015`. - If it is not set, every agent directory is legitimate — that is acceptable variance, not a finding. + skills were never restored — `just skills-install` (`skills experimental_install`) restores them. +- **Layout**: if `Skills.Agents` is set in `.config/purview-build-sdk.json`, run `just skills-check` + and quote any `PRSKL0015`. If it is not set, every agent directory is legitimate — that is + acceptable variance, not a finding. ## 7. Explain consequences, not just mismatches diff --git a/skills/purview-buildsdk-skill-installation/SKILL.md b/skills/purview-buildsdk-skill-installation/SKILL.md index 545eb9f..eda17bc 100644 --- a/skills/purview-buildsdk-skill-installation/SKILL.md +++ b/skills/purview-buildsdk-skill-installation/SKILL.md @@ -1,6 +1,6 @@ --- name: purview-buildsdk-skill-installation -description: Install, update, check and tidy agent skills in a repository that uses Purview.BuildSdk, through the standard skills CLI (bun x skills). Use for the InstallPurviewSkills, UpdatePurviewSkills, CheckPurviewSkills and FixPurviewSkills MSBuild targets, for installing skills from a repository's root skills/ folder (owner/repo#ref), for restoring skills-lock.json in a fresh clone, for choosing agents with PurviewSkillsAgents, for any PRSKL diagnostic, for choosing a package runner (bun x, npx, pnpm dlx, bunx, yarn dlx, deno), or when an agent cannot see a skill that should be installed. +description: Install, update, check and tidy agent skills in a repository that uses Purview.BuildSdk, through the standard skills CLI (bun x skills). Use for the just skills-add, skills-install, skills-update, skills-check and skills-fix recipes and the skills.mts script behind them, for .config/purview-build-sdk.json and its Skills section, for installing skills from a repository's root skills/ folder (owner/repo#ref), for restoring skills-lock.json in a fresh clone, for choosing agents, for any PRSKL diagnostic, for choosing a package runner (bun x, npx, pnpm dlx, bunx, yarn dlx, deno), for the removed InstallPurviewSkills/UpdatePurviewSkills MSBuild targets, or when an agent cannot see a skill that should be installed. license: MIT metadata: package: Purview.BuildSdk @@ -9,114 +9,144 @@ metadata: # Installing agent skills -For *authoring* skills, use `purview-buildsdk-skill-tests`; for `just` recipes that run these -targets, `purview-buildsdk-justfile`. +For *authoring* skills, use `purview-buildsdk-skill-tests`; for the `just` modules themselves, +`purview-buildsdk-justfile`. ## The one thing to understand first -**The SDK is a thin wrapper over the standard skills CLI, and adds nothing bespoke.** A repository -publishes skills in its root `skills/` folder; the skills CLI installs them with -`bun x skills add owner/repo` and records each install in `skills-lock.json`. The SDK's targets only -run that CLI — from the repository root, once per solution, never during a build — and keep the -agent directories tidy. There is no package-to-skill mapping: a NuGet package carries .NET artifacts, -and skills come from git. +**Skill installation is a thin wrapper over the standard skills CLI, and it does not involve .NET.** A +repository publishes skills in its root `skills/` folder; the skills CLI installs them with +`bun x skills add owner/repo` and records each install in `skills-lock.json`. The `skills-*` recipes +run that CLI from the repository root and keep the agent directories tidy. There is no package-to-skill +mapping: a NuGet package carries .NET artifacts, and skills come from git. + +The recipes run `skills.mts`, a script the `purview-buildsdk-justfile` skill ships beside +`skills.just` in `.build/just/`. It needs no solution, no restore and no build, so it takes well under a +second and works in a repository whose build is broken — exactly when new or updated skills may be +what fixes it. It runs under Bun, then Deno, and falls back to Node with the generated `skills.mjs`. + +```bash +just skills-add purview-dev/build-sdk # add every skill a source has (append '#' to pin it) +just skills-install # restore skills-lock.json (a fresh clone) +just skills-update # re-add every lockfile source at its latest, then fix +just skills-check # only the selected agents' directories exist +just skills-fix # remove the CLI's links from any other agent directory +``` + +They run **only when a person runs them**. Do not make one a dependency of `build`, `test` or +`default`, and do not call `skills-add`, `-install`, `-update` or `-fix` from a git hook: they change +the repository. `skills-check` is read-only. The SDK writes nothing into an agent directory itself. The CLI is the single writer, because its universal install location is `.agents/skills/` and a second writer on the same paths would overwrite a pinned install. +Without `just`, run the script directly from the repository root: + ```bash -dotnet msbuild -t:InstallPurviewSkills -p:PurviewSkillsSource=purview-dev/build-sdk # add a source -dotnet msbuild -t:InstallPurviewSkills # restore skills-lock.json (a fresh clone) -dotnet msbuild -t:UpdatePurviewSkills # re-add every lockfile source at its latest -dotnet msbuild -t:CheckPurviewSkills # only the PurviewSkillsAgents directories exist -dotnet msbuild -t:FixPurviewSkills # remove the CLI's links from any other agent directory +bun .build/just/skills.mts update --dry-run +node .build/just/skills.mjs check --agents claude-code ``` -They run **only when named**. None has `BeforeTargets` or `AfterTargets`, nothing in the SDK depends -on them, and `InstallPurviewSkills`, `UpdatePurviewSkills` and `FixPurviewSkills` refuse to run when -something pulls them into a build, a restore or a design-time build (`PRSKL0009`). A git hook or a -`just` recipe dependency that runs one on its own is not caught by that — do not wire them up that way. +## Settings -Name **the solution**. Skills belong to the repository, so each target runs once however many projects -the solution holds: every project hands the work to the same elected leader, and MSBuild runs it once. -A single project works too. +Settings live in the `Skills` section of `.config/purview-build-sdk.json` at the repository root: + +```json +{ + "Skills": { + "Agents": ["claude-code", "codex"], + "Runner": "bun" + } +} +``` + +| Setting | Option | Environment | Default | +| -- | -- | -- | -- | +| `Agents` | `--agents` | `PURVIEW_SKILLS_AGENTS` | empty: the CLI auto-detects | +| `Runner` | `--runner` | `PURVIEW_SKILLS_RUNNER` | `bun` | +| `RunnerCandidates` | — | `PURVIEW_SKILLS_RUNNER_CANDIDATES` | `bun npx bunx pnpm yarn deno` | +| `Package` | `--package` | `PURVIEW_SKILLS_PACKAGE` | `skills@1` | +| `Command` | `--command` | `PURVIEW_SKILLS_COMMAND` | empty: detected from `PATH` | +| `LockFile` | `--lock-file` | `PURVIEW_SKILLS_LOCK_FILE` | `skills-lock.json` at the root | +| `DryRun` | `--dry-run` | `PURVIEW_SKILLS_DRY_RUN` | `false` | +| `AgentDirectories` | — | — | the CLI's agent table, extended by this | + +Highest first: a command-line option, then the environment variable, then the file, then the default. +A list may be an array or one string separated by `,`, `;` or spaces. `--config` or +`PURVIEW_SKILLS_CONFIG` names a different file. Pass an option through a recipe's arguments: +`just skills-update --dry-run --agents claude-code,codex`. + +`PURVIEW_SKILLS_RUNTIME` chooses the runtime the recipes start the script with — `node`, `bun` or +`deno run -A` — instead of the first of Bun, Deno and Node on `PATH`. ## Installing -| Command | Runs | +| Recipe | Runs | | -- | -- | -| `-t:InstallPurviewSkills -p:PurviewSkillsSource=owner/repo` | `skills add "owner/repo" --skill "*"` — every skill in that repository's root `skills/` | -| `-t:InstallPurviewSkills -p:PurviewSkillsSource=owner/repo#` | the same, pinned to a commit, tag or branch | -| `-t:InstallPurviewSkills` | `skills experimental_install` — restore exactly what `skills-lock.json` records | +| `just skills-add owner/repo` | `skills add "owner/repo" --skill "*"` — every skill in that repository's root `skills/` | +| `just skills-add owner/repo#` | the same, pinned to a commit, tag or branch | +| `just skills-install` | `skills experimental_install` — restore exactly what `skills-lock.json` records | The caller owns the ref: append `#` to pin it. With no source and no `skills-lock.json` there is nothing to install, which is `PRSKL0007`. `bun x skills add` works just as well run directly; the -target exists so a repository uses one runner, one root and one agent selection everywhere. +recipes exist so a repository uses one runner, one root and one agent selection everywhere. ## Updating ```bash -dotnet msbuild -t:UpdatePurviewSkills -p:PurviewSkillsDryRun=true # see the commands first -dotnet msbuild -t:UpdatePurviewSkills +just skills-update --dry-run # see the commands first; the fix step removes nothing either +just skills-update ``` -`UpdatePurviewSkills` re-adds every unique source recorded in `skills-lock.json` with +`update` re-adds every unique source recorded in `skills-lock.json` with `skills add "" --skill "*"`, at its latest. That is the whole update: `skills add` reinstalls every skill it selects, so one re-add both refreshes the installed skills and adds any the source has gained, whereas `skills update` would only re-fetch what the lockfile already lists, and is never run. Every source is attempted even when one fails, and each failure is named (`PRSKL0008`). No lockfile is -`PRSKL0007`. +`PRSKL0007`. The recipe then runs `fix`. ## Choosing agents -`PurviewSkillsAgents` is **empty by default**, which passes no `--agent` and lets the CLI auto-detect -the agents on the machine. Set it to choose — in `Directory.Build.props` -(`universal`), or on a command line with the separator -escaped, because `dotnet msbuild -p:` itself splits on `,` and `;`: - -```bash -dotnet msbuild -t:UpdatePurviewSkills -p:PurviewSkillsAgents=claude-code%2Ccodex -``` +`Agents` is **empty by default**, which passes no `--agent` and lets the CLI auto-detect the agents on +the machine. Set it to choose. Each agent becomes its own `--agent` flag; the CLI does not split a +comma-separated value. A restore (`experimental_install`) is passed no agent flag. -Each agent becomes its own `--agent` flag; the CLI does not split a comma-separated value. A restore -(`experimental_install`) is passed no agent flag. +When `Agents` is set, `check` fails (`PRSKL0015`) for any agent skill directory at the repository root +that belongs to an agent it does not name. `.agents/skills` is always allowed — it is the CLI's +canonical store — and the authored `skills/` folder is never touched. `fix` removes links (symlinks, +junctions) from those directories, never their targets, and then any folder left empty; a real file is +kept and reported, because it is not provably the CLI's. The agent-to-directory map is taken from the +CLI's own agent table; an agent it does not know is `PRSKL0016`, fixed by adding it: -When `PurviewSkillsAgents` is set, `CheckPurviewSkills` fails (`PRSKL0015`) for any agent skill -directory at the repository root that belongs to an agent it does not name. `.agents/skills` is always -allowed — it is the CLI's canonical store — and the authored `skills/` folder is never touched. -`FixPurviewSkills` removes links (symlinks, junctions) from those directories, never their targets, -and then any folder left empty; a real file is kept and reported, because it is not provably the -CLI's. The agent-to-directory map is the `PurviewSkillsAgentDirectory` item group, taken from the -CLI's own agent table; an agent it does not know is `PRSKL0016`, fixed by adding an item: - -```xml - +```json +{ "Skills": { "AgentDirectories": { ".new-agent/skills": ["new-agent"] } } } ``` -With `PurviewSkillsAgents` empty, both targets say so and do nothing: every agent directory is then a -legitimate destination. +With `Agents` empty, both commands say so and do nothing: every agent directory is then a legitimate +destination. ## Diagnostics | Code | Meaning | Fix | | -- | -- | -- | -| `PRSKL0003` | No repository root resolved | Pass `-p:PurviewSkillsInstallRoot=`, or add an `AGENTS.md` at the root | -| `PRSKL0004` | No skills CLI and no package runner found | Install Bun or Node, or set `PurviewSkillsCommand` | +| `PRSKL0004` | No skills CLI and no package runner found | Install Bun or Node, or set `Command` | | `PRSKL0005` | An authored skill is malformed | See `purview-buildsdk-skill-tests` | -| `PRSKL0007` | Nothing to install or update: no `PurviewSkillsSource`, and no `skills-lock.json` | Install from a source first | -| `PRSKL0008` | Re-adding a lockfile source failed | Read the CLI output above it | -| `PRSKL0009` | Install, update or fix was pulled into a build, a restore or a design-time build | Remove the hook; run the target on its own | -| `PRSKL0015` | An agent skill directory exists for an agent `PurviewSkillsAgents` does not name | `-t:FixPurviewSkills`, then remove anything it kept by hand | -| `PRSKL0016` | `PurviewSkillsAgents` names an agent with no known skills directory | Warning. Add a `PurviewSkillsAgentDirectory` item | +| `PRSKL0007` | Nothing to install or update: no source, and no `skills-lock.json` | Install from a source first | +| `PRSKL0008` | Adding or re-adding a source failed | Read the CLI output above it | +| `PRSKL0015` | An agent skill directory exists for an agent `Agents` does not name | `just skills-fix`, then remove anything it kept by hand | +| `PRSKL0016` | `Agents` names an agent with no known skills directory | Warning. Add it to `AgentDirectories` | +| `PRSKL0018` | `.config/purview-build-sdk.json` is not valid JSON, or a setting has the wrong type | Fix the file | +| `PRSKL0019` | The `Skills` section has a key that is not a setting | Warning. Usually a misspelling | -`PRSKL0001`, `PRSKL0002`, `PRSKL0006`, `PRSKL0010`–`PRSKL0014` and `PRSKL0017` are retired: they -belonged to the package-to-skill mapping and recommendation targets, which are gone. +`PRSKL0003` and `PRSKL0009` went with the MSBuild skill targets. `PRSKL0001`, `PRSKL0002`, +`PRSKL0006`, `PRSKL0010`–`PRSKL0014` and `PRSKL0017` belonged to the earlier package-to-skill mapping. +All are retired. ## Package runners -The CLI is published to npm, and every runner spells "run this npm package" differently. -`PurviewSkillsRunner` selects one, defaulting to `bun` (`bun x skills`). +The CLI is published to npm, and every runner spells "run this npm package" differently. `Runner` +selects one, defaulting to `bun` (`bun x skills`). | Runner | Invocation | | -- | -- | @@ -128,37 +158,50 @@ The CLI is published to npm, and every runner spells "run this npm package" diff | `deno` | `deno run -A npm:skills@1` | | `skills` | `skills` — already on `PATH`, no download | -An unknown runner falls through to ` $(PurviewSkillsPackage)`, so it still works. The launcher -pins the CLI to a major (`PurviewSkillsPackage`, default `skills@1`). +An unknown runner falls through to ` `, so it still works. The launcher pins the CLI +to a major (`Package`, default `skills@1`). -`DetectPurviewSkillsCli` probes `PATH` for `skills` first, then `$(PurviewSkillsRunner)`, then -`$(PurviewSkillsRunnerCandidates)`, honouring `PATHEXT` on Windows where these are `.cmd` shims. -`PATH` is read directly rather than by spawning a version check: deterministic, no process, and it -cannot hang on a cold download. **The runner actually found wins over the configured preference.** -`PurviewSkillsCommand` overrides the launcher entirely and skips detection. A dry run with no runner -on `PATH` prints the configured runner's command rather than failing. +The script probes `PATH` for `skills` first, then `Runner`, then `RunnerCandidates`, honouring +`PATHEXT` on Windows where these are `.cmd` shims. `PATH` is read directly rather than by spawning a +version check: deterministic, no process, and it cannot hang on a cold download. **The runner actually +found wins over the configured preference.** `Command` overrides the launcher entirely and skips +detection. A dry run with no runner on `PATH` prints the configured runner's command rather than +failing. ## Always the repository root `skills-lock.json` and the agent directories belong to the repository, not to a project, so every -skill target runs from one resolved root: +command runs from the repository root. The recipes pass it as `--root` (the directory holding the root +`Justfile`); run by hand, the script uses the nearest folder holding `.git`, else the current one. + +`ValidatePurviewSkills`, the pack-time check on authored skills, is still MSBuild and resolves the +root its own way; see [references/repository-root.md](references/repository-root.md). -1. `PurviewSkillsInstallRoot` — an explicit override -2. `PurviewSkillsRepoRoot` — only when the **user** set it -3. the `PurviewRepositoryRootMarkers` walk -4. `PurviewSkillsRepoRoot` / `RepoRoot` as the SDK guessed them -5. CI workspace variables -6. SourceLink's git `SourceRoot` +## Moving from the MSBuild targets -There is deliberately **no project-directory fallback**. That would scatter a lockfile and an agent -directory through the tree, one per project. An unresolved root is `PRSKL0003`. +`InstallPurviewSkills`, `UpdatePurviewSkills`, `CheckPurviewSkills` and `FixPurviewSkills` were +removed, with the `PurviewSkillsAgents`, `PurviewSkillsDryRun`, `PurviewSkillsCommand`, +`PurviewSkillsSource`, `PurviewSkillsLockFile`, `PurviewSkillsRunner`, `PurviewSkillsRunnerCandidates` +and `PurviewSkillsPackage` properties and the `PurviewSkillsAgentDirectory` items. They evaluated every +project in the solution on each run, so they were slow and failed outright whenever a project did not +evaluate. Copy `skills.just`, `skills.mts` and `skills.mjs` from the `purview-buildsdk-justfile` skill +into `.build/just/`, and move any of those properties into `.config/purview-build-sdk.json`: -The marker walk is described in [references/repository-root.md](references/repository-root.md); its -two-pass behaviour and its home-directory bound are both load-bearing. +| Removed property | Setting | +| -- | -- | +| `PurviewSkillsAgents` | `Agents` | +| `PurviewSkillsRunner` | `Runner` | +| `PurviewSkillsRunnerCandidates` | `RunnerCandidates` | +| `PurviewSkillsPackage` | `Package` | +| `PurviewSkillsCommand` | `Command` | +| `PurviewSkillsLockFile` | `LockFile` | +| `PurviewSkillsDryRun` | `--dry-run` | +| `PurviewSkillsSource` | the `skills-add` argument | +| `PurviewSkillsAgentDirectory` items | `AgentDirectories` | ## Why the CLI rather than a reimplementation The CLI owns the agent-specific destinations and their discovery conventions, which differ per agent and change independently of this SDK. It also owns `skills-lock.json`, which is what lets a fresh -clone restore the same set with `-t:InstallPurviewSkills` (`skills experimental_install`). There is +clone restore the same set with `just skills-install` (`skills experimental_install`). There is deliberately no competing lockfile and no competing metadata. diff --git a/skills/purview-buildsdk-skill-installation/references/repository-root.md b/skills/purview-buildsdk-skill-installation/references/repository-root.md index 64cd1c4..ae31fe8 100644 --- a/skills/purview-buildsdk-skill-installation/references/repository-root.md +++ b/skills/purview-buildsdk-skill-installation/references/repository-root.md @@ -1,5 +1,17 @@ # The repository-root marker walk +`ValidatePurviewSkills`, the pack-time check on a repository's authored `skills/`, finds the +repository root with `ResolvePurviewSkillsRepositoryRoot`: + +1. `PurviewSkillsInstallRoot` — an explicit override +2. `PurviewSkillsRepoRoot` — only when the **user** set it +3. the `PurviewRepositoryRootMarkers` walk +4. `PurviewSkillsRepoRoot` / `RepoRoot` as the SDK guessed them +5. CI workspace variables +6. SourceLink's git `SourceRoot` + +The `skills-*` recipes do not use any of this: they pass the directory holding the root `Justfile`. + `FindPurviewRepositoryRoot` is an inline MSBuild task driven by `PurviewRepositoryRootMarkers`: ```text @@ -28,14 +40,14 @@ a repository root. ### The home directory is never a candidate The home directory and everything above it are excluded. Without that bound, a project outside any -repository resolves to `~` and installs into it — and a `.claude/` or a `.github/` very commonly -sits there. A repository *below* the home directory is unaffected, because it is below it. +repository resolves to `~` — and a `.claude/` or a `.github/` very commonly sits there. A repository +*below* the home directory is unaffected, because it is below it. ## Why the marker walk outranks the evaluation-time guess `PurviewSkillsRepoRoot` is computed during evaluation from `RepoRoot` and an `AGENTS.md` walk-up. -An `AGENTS.md` can legitimately sit in a subdirectory, and resolving to it would put a lockfile and -an agent directory somewhere that is not the repository. +An `AGENTS.md` can legitimately sit in a subdirectory, and resolving to it would validate a folder +that is not the repository's `skills/`. `_PurviewSkillsRepoRootWasSpecified` is captured in `Sdk.props` *before* defaulting, so a value the **user** set still outranks the walk while a value the SDK guessed does not. @@ -43,16 +55,13 @@ an agent directory somewhere that is not the repository. ## A target's Condition is evaluated before its DependsOnTargets A property a dependency computes is still empty in the depending target's `Condition`. That is why -the unresolved-root check (`PRSKL0003`) is an `Error` inside a dependency target rather than a -`Condition` on the public target, and why the explicit-only guard (`PRSKL0009`) is a dependency target with -its own `Error` rather than a `Condition` on `InstallPurviewSkills`, `UpdatePurviewSkills` or -`FixPurviewSkills`. +`ValidatePurviewSkills` tests that the folder exists on its task rather than in its own `Condition`. ## The managed port `Purview.Skills.Testing` ships `SkillRepositoryRoot`, a managed port of the same walk with the same -default markers, so a test that validates a repository's skills resolves the same root the build -installs them into. In the Purview.BuildSdk repository the two are kept in step twice over: +default markers, so a test that validates a repository's skills resolves the same root the pack-time +check validates. In the Purview.BuildSdk repository the two are kept in step twice over: `SkillRepositoryRootParityTests` runs the real MSBuild target and the managed port over the same folders and compares the root and the matched marker, and `SkillRepositoryRootTests` pins the default marker list itself — both are defaults nobody sets, so nothing else would notice them drifting apart. diff --git a/src/src/BuildSdk/Sdk/Props/Defaults.props b/src/src/BuildSdk/Sdk/Props/Defaults.props index 82126de..951abc6 100644 --- a/src/src/BuildSdk/Sdk/Props/Defaults.props +++ b/src/src/BuildSdk/Sdk/Props/Defaults.props @@ -76,28 +76,9 @@ check the two agree before Pack (PRPSC, Targets/PropertySchema.targets). --> false - - - - - bun - - bun;npx;bunx;pnpm;yarn;deno - - - - skills@1 + diff --git a/src/src/BuildSdk/Sdk/Sdk.props.buildschema.json b/src/src/BuildSdk/Sdk/Sdk.props.buildschema.json index 124a5be..11b9142 100644 --- a/src/src/BuildSdk/Sdk/Sdk.props.buildschema.json +++ b/src/src/BuildSdk/Sdk/Sdk.props.buildschema.json @@ -362,53 +362,14 @@ "type": { "$ref": "#/types/purview-shared-testing-output-type" }, "defaultValue": "Library" }, - "PurviewSkillsAgents": { - "description": "Agents the skill targets install to, separated by commas, semicolons or spaces. When set, CheckPurviewSkills and FixPurviewSkills allow only those agents' skill directories. On a dotnet msbuild command line write a comma as %2C. No default: empty, so the skills CLI auto-detects agents.", - "type": "string", - "isList": true, - "listSeparators": ";," - }, - "PurviewSkillsCommand": { - "description": "Replaces the skills CLI launcher entirely, skipping runner detection. No default: detected from PATH (skills, then PurviewSkillsRunner, then PurviewSkillsRunnerCandidates).", - "type": "string" - }, - "PurviewSkillsDryRun": { - "description": "Makes InstallPurviewSkills and UpdatePurviewSkills print the skills CLI commands without running them. No default: unset, which is treated as false.", - "type": "bool" - }, "PurviewSkillsInstallRoot": { - "description": "Overrides the repository root every skill target runs from. No default: resolved from PurviewRepositoryRootMarkers, CI workspace variables and SourceLink.", + "description": "Overrides the repository root whose skills/ folder ValidatePurviewSkills checks. No default: resolved from PurviewRepositoryRootMarkers, CI workspace variables and SourceLink.", "type": "folder" }, - "PurviewSkillsLockFile": { - "description": "Where the skills CLI's lockfile is read from. No default: skills-lock.json at the resolved repository root.", - "type": "file" - }, - "PurviewSkillsPackage": { - "description": "Package spec the executed skills CLI launcher pins to.", - "type": "string", - "defaultValue": "skills@1" - }, "PurviewSkillsRepoRoot": { - "description": "Evaluation-time guess at the repository root for the skill targets; a value you set outranks the marker walk. Set it before the `Sdk.props` import. No default: RepoRoot, else the nearest folder with an AGENTS.md.", + "description": "Evaluation-time guess at the repository root for skill validation; a value you set outranks the marker walk. Set it before the `Sdk.props` import. No default: RepoRoot, else the nearest folder with an AGENTS.md.", "type": "folder" }, - "PurviewSkillsRunner": { - "description": "Package runner used to launch the skills CLI. A runner without a known launcher runs as ' skills@1'.", - "type": { "$ref": "#/types/purview-skills-runner" }, - "defaultValue": "bun" - }, - "PurviewSkillsRunnerCandidates": { - "description": "Runners probed on PATH, in order, after PurviewSkillsRunner.", - "type": "string", - "isList": true, - "listSeparators": ";", - "defaultValue": "bun;npx;bunx;pnpm;yarn;deno" - }, - "PurviewSkillsSource": { - "description": "The git source InstallPurviewSkills adds through the skills CLI (owner/repo, optionally #ref). No default: unset, which makes InstallPurviewSkills restore skills-lock.json instead.", - "type": "string" - }, "PurviewSkillsSourceFolder": { "description": "Repository folder holding authored skills. No default: skills/ under PurviewSkillsRepoRoot.", "type": "folder" @@ -576,19 +537,6 @@ "Exe": "An executable test host." } }, - "purview-skills-runner": { - "description": "A package runner that can launch the skills CLI.", - "allowUnknownValues": true, - "values": { - "bun": "bun x skills", - "npx": "npx -y skills", - "bunx": "bunx skills", - "pnpm": "pnpm dlx skills", - "yarn": "yarn dlx skills (Yarn 2 or later)", - "deno": "deno run -A npm:skills", - "skills": "A globally installed skills CLI." - } - }, "purview-sourcelink-package": { "description": "A SourceLink provider package.", "allowUnknownValues": true, diff --git a/src/src/BuildSdk/Sdk/Sdk.targets b/src/src/BuildSdk/Sdk/Sdk.targets index 0d64f78..d414f4f 100644 --- a/src/src/BuildSdk/Sdk/Sdk.targets +++ b/src/src/BuildSdk/Sdk/Sdk.targets @@ -371,365 +371,6 @@ >true - - - - - - - - - - - - - - - - - - (); - - foreach (Match element in Regex.Matches(SolutionConfiguration ?? string.Empty, "]*>")) - { - // A project the solution configuration does not build is not part of this run. - if (Regex.IsMatch(element.Value, "\\bBuildProjectInSolution\\s*=\\s*\"False\"", RegexOptions.IgnoreCase)) - continue; - - var path = Regex.Match(element.Value, "\\bAbsolutePath\\s*=\\s*\"(?[^\"]+)\""); - if (!path.Success) - continue; - - var fullPath = Path.GetFullPath(WebUtility.HtmlDecode(path.Groups["path"].Value)); - if (File.Exists(fullPath)) - projects.Add(fullPath); - } - - if (projects.Count == 0) - projects.Add(Path.GetFullPath(ProjectPath)); - - Projects = projects - .Distinct(StringComparer.OrdinalIgnoreCase) - .OrderBy(project => project, StringComparer.OrdinalIgnoreCase) - .Select(project => (ITaskItem)new TaskItem(project)) - .ToArray(); - ]]> - - - - - - - - - - - - - - - - - - - - - (); - LockFileFound = File.Exists(LockFilePath); - - var lockText = string.Empty; - if (LockFileFound) - { - try { lockText = File.ReadAllText(LockFilePath); } - catch (IOException) { LockFileFound = false; } - catch (UnauthorizedAccessException) { LockFileFound = false; } - } - - if (LockFileFound) - { - // Walk to the brace that closes the 'skills' object, then one regex per flat entry. - var namesBySource = new Dictionary>(StringComparer.OrdinalIgnoreCase); - var skillsKey = lockText.IndexOf("\"skills\"", StringComparison.Ordinal); - var open = skillsKey < 0 ? -1 : lockText.IndexOf('{', skillsKey); - if (open >= 0) - { - var depth = 0; - var inString = false; - var escaped = false; - var close = -1; - for (var index = open; index < lockText.Length; index++) - { - var character = lockText[index]; - if (escaped) { escaped = false; continue; } - if (character == '\\' && inString) { escaped = true; continue; } - if (character == '"') { inString = !inString; continue; } - if (inString) continue; - if (character == '{') depth++; - else if (character == '}') - { - depth--; - if (depth == 0) { close = index; break; } - } - } - - if (close > open) - { - var body = lockText.Substring(open, close - open + 1); - var entryPattern = new Regex("\"(?[^\"]+)\"\\s*:\\s*\\{(?[^{}]*)\\}", RegexOptions.Singleline); - var sourcePattern = new Regex("\"source\"\\s*:\\s*\"(?[^\"]*)\""); - - foreach (Match entry in entryPattern.Matches(body)) - { - var sourceMatch = sourcePattern.Match(entry.Groups["entry"].Value); - var source = sourceMatch.Success ? sourceMatch.Groups["value"].Value.Trim() : string.Empty; - if (source.Length == 0) - continue; - - List names; - if (!namesBySource.TryGetValue(source, out names)) - namesBySource[source] = names = new List(); - names.Add(entry.Groups["name"].Value); - } - } - } - - foreach (var pair in namesBySource.OrderBy(pair => pair.Key, StringComparer.OrdinalIgnoreCase)) - { - // Every skill the source has now, not just the ones recorded: re-adding is - // how an update picks up a skill the source has gained since. - var created = new TaskItem(pair.Key); - created.SetMetadata("Skills", "*"); - created.SetMetadata("Origin", "skills-lock.json"); - updates.Add(created); - } - } - - UpdateSources = updates.ToArray(); - ]]> - - - - - - - - - - - - - - - - - - - - - - - - - (); - var removed = new List(); - var unknown = new List(); - var windows = Path.DirectorySeparatorChar == '\\'; - var pathComparer = windows ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; - - var selected = (Agents ?? string.Empty) - .Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries) - .Select(agent => agent.Trim()) - .Where(agent => agent.Length > 0) - .ToList(); - - // '*' is every agent, so every directory is allowed. - if (selected.Count > 0 && !selected.Contains("*")) - { - var root = Path.GetFullPath(RepositoryRoot).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); - var toRelative = new Func(full => - full.Substring(root.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).Replace('\\', '/')); - - var directories = (AgentDirectories ?? new ITaskItem[0]) - .Select(item => new - { - Relative = item.ItemSpec.Replace('\\', '/').Trim('/'), - Agents = (item.GetMetadata("Agents") ?? string.Empty) - .Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries) - .Select(agent => agent.Trim()) - .ToArray(), - }) - .Where(directory => directory.Relative.Length > 0) - .ToList(); - - var known = new HashSet(directories.SelectMany(directory => directory.Agents), StringComparer.OrdinalIgnoreCase); - foreach (var agent in selected.Where(agent => !known.Contains(agent))) - unknown.Add(new TaskItem(agent)); - - var allowed = new HashSet(pathComparer) { ".agents/skills" }; - foreach (var directory in directories) - { - if (directory.Agents.Any(agent => selected.Contains(agent, StringComparer.OrdinalIgnoreCase))) - allowed.Add(directory.Relative); - } - - var protectedPaths = new HashSet( - (ProtectedDirectories ?? new ITaskItem[0]) - .Where(item => !string.IsNullOrWhiteSpace(item.ItemSpec)) - .Select(item => Path.GetFullPath(item.ItemSpec).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)), - pathComparer - ); - - // GetAttributes does not follow a link, so a dangling one still counts as present. - var exists = new Func(path => - { - try { File.GetAttributes(path); return true; } - catch (IOException) { return false; } - catch (UnauthorizedAccessException) { return false; } - }); - - var deleteLink = new Action((path, attributes) => - { - // On Windows a directory link or junction is removed by RemoveDirectory, which - // removes the link and never its target. On Unix, unlink does the same for any - // symlink, whatever it points at. - if (windows && (attributes & FileAttributes.Directory) != 0) - Directory.Delete(path, false); - else - File.Delete(path); - }); - - var kept = new List(); - Action prune = null; - prune = path => - { - var attributes = File.GetAttributes(path); - if ((attributes & FileAttributes.ReparsePoint) != 0) - { - deleteLink(path, attributes); - removed.Add(new TaskItem(toRelative(path))); - return; - } - - if ((attributes & FileAttributes.Directory) == 0) - { - kept.Add(toRelative(path)); - return; - } - - foreach (var child in Directory.GetFileSystemEntries(path).OrderBy(child => child, StringComparer.Ordinal)) - prune(child); - - if (Directory.GetFileSystemEntries(path).Length == 0) - { - Directory.Delete(path, false); - removed.Add(new TaskItem(toRelative(path))); - } - }; - - foreach (var directory in directories - .Where(directory => !allowed.Contains(directory.Relative)) - .GroupBy(directory => directory.Relative, pathComparer) - .OrderBy(group => group.Key, StringComparer.Ordinal)) - { - var full = Path.GetFullPath(Path.Combine(root, directory.Key.Replace('/', Path.DirectorySeparatorChar))); - if (protectedPaths.Contains(full) || !exists(full)) - continue; - - kept.Clear(); - if (Fix) - { - prune(full); - - // A folder that only ever held the agent's skills is left empty; remove it too, - // but never climb to the repository root. - var parent = Path.GetDirectoryName(full); - while (!exists(full) && parent != null && parent.Length > root.Length - && Directory.Exists(parent) && Directory.GetFileSystemEntries(parent).Length == 0) - { - Directory.Delete(parent, false); - removed.Add(new TaskItem(toRelative(parent))); - parent = Path.GetDirectoryName(parent); - } - - if (!exists(full)) - continue; - } - - var violation = new TaskItem(directory.Key); - violation.SetMetadata("Agents", string.Join(", ", directory.SelectMany(entry => entry.Agents))); - // The CLI copies rather than links for some agent selections, so a kept folder can - // hold every file of every skill; name enough to recognise, then count the rest. - violation.SetMetadata( - "Kept", - string.Join(", ", kept.Take(5)) + (kept.Count > 5 ? " and " + (kept.Count - 5) + " more" : string.Empty) - ); - violations.Add(violation); - } - } - - Violations = violations.ToArray(); - Removed = removed.ToArray(); - UnknownAgents = unknown.ToArray(); - ]]> - - - - - - - - - - - - - - - - - - { string.Empty }; - if (isWindows) - { - // An empty PATHEXT is not a realistic machine, but defaulting keeps the probe - // working rather than silently finding nothing. - var pathExt = Environment.GetEnvironmentVariable("PATHEXT"); - if (string.IsNullOrEmpty(pathExt)) - pathExt = ".COM;.EXE;.BAT;.CMD"; - - foreach (var ext in pathExt.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) - extensions.Add(ext.Trim()); - } - - var pathDirectories = (Environment.GetEnvironmentVariable("PATH") ?? string.Empty) - .Split(new[] { Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries); - - foreach (var commandName in CommandNames.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) - { - var trimmedCommand = commandName.Trim(); - if (trimmedCommand.Length == 0) - continue; - - foreach (var pathDirectory in pathDirectories) - { - // A malformed PATH entry is common and must not abort the probe. - string directory; - try - { - directory = pathDirectory.Trim().Trim('"'); - if (directory.Length == 0) - continue; - } - catch - { - continue; - } - - foreach (var extension in extensions) - { - string candidate; - try - { - candidate = Path.Combine(directory, trimmedCommand + extension); - } - catch - { - continue; - } - - if (!File.Exists(candidate)) - continue; - - FoundCommand = trimmedCommand; - FoundPath = candidate; - break; - } - - if (FoundCommand.Length > 0) - break; - } - - if (FoundCommand.Length > 0) - break; - } - ]]> - - - - <_PurviewSkillsSourceRoot Include="@(SourceRoot -> WithMetadataValue('SourceControl', 'git'))" /> @@ -1975,619 +1509,6 @@ - - - - skills - - - npx -y $(PurviewSkillsPackage) - - - bunx $(PurviewSkillsPackage) - - - bun x $(PurviewSkillsPackage) - - - pnpm dlx $(PurviewSkillsPackage) - - - yarn dlx $(PurviewSkillsPackage) - - - deno run -A npm:$(PurviewSkillsPackage) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <_PurviewSkillsProjectInfoReply Include="$(MSBuildProjectFullPath)" /> - - - - - - - - - - - - - - - - <_PurviewSkillsAnsweringProjects>@(_PurviewSkillsProjectInfo) - <_PurviewSkillsLeaderProject>$([System.Text.RegularExpressions.Regex]::Match('$(_PurviewSkillsAnsweringProjects)', '^[^;]+').Value) - <_PurviewSkillsLeaderProject Condition="'$(_PurviewSkillsLeaderProject)' == ''" - >$(MSBuildProjectFullPath) - - - - - - <_PurviewSkillsLeaderRemoveProperties>TargetFramework;RuntimeIdentifier - - - - - - <_PurviewSkillsAgentList>$([System.Text.RegularExpressions.Regex]::Replace('$(PurviewSkillsAgents)', '^[\s,;"'']+|[\s,;"'']+$', '')) - <_PurviewSkillsAgentList>$([System.Text.RegularExpressions.Regex]::Replace('$(_PurviewSkillsAgentList)', '[\s,;]+', ';')) - <_PurviewSkillsAgentArguments> - <_PurviewSkillsAgentArguments Condition="'$(_PurviewSkillsAgentList)' != ''" - > --agent "$(_PurviewSkillsAgentList.Replace(';', '" --agent "'))" - - - - - - - - - - - - - @(PurviewSkillsRunnerLauncher->WithMetadataValue('Identity', '$(_PurviewSkillsCliCommand)')->'%(Exec)') - $(_PurviewSkillsCliCommand) $(PurviewSkillsPackage) - - - - - - - @(PurviewSkillsRunnerLauncher->WithMetadataValue('Identity', '$(PurviewSkillsRunner)')->'%(Exec)') - $(PurviewSkillsRunner) $(PurviewSkillsPackage) - - - - - - - - - - - - - - - - $([MSBuild]::NormalizePath('$(_PurviewSkillsRepositoryRoot)', 'skills-lock.json')) - <_PurviewSkillsCommandRequired>true - - - - - - - - - - - - <_PurviewSkillsInstallCommand Condition="'$(PurviewSkillsSource)' != ''" - >$(PurviewSkillsCommand) add "$(PurviewSkillsSource)" --skill "*"$(_PurviewSkillsAgentArguments) -y - <_PurviewSkillsInstallCommand Condition="'$(PurviewSkillsSource)' == ''" - >$(PurviewSkillsCommand) experimental_install - - - - - - - - - - $([MSBuild]::NormalizePath('$(_PurviewSkillsRepositoryRoot)', 'skills-lock.json')) - - - - - - - - <_PurviewSkillsCommandRequired Condition="'@(_PurviewSkillsUpdateSource)' != ''" - >true - - - - - - - <_PurviewSkillsUpdateCommand>$(PurviewSkillsCommand) add "%(_PurviewSkillsUpdateSource.Identity)" --skill "$([System.String]::Copy('%(_PurviewSkillsUpdateSource.Skills)').Replace(';', '" --skill "'))"$(_PurviewSkillsAgentArguments) -y - <_PurviewSkillsUpdateExitCode>0 - - - - - - - <_PurviewSkillsUpdateFailure - Include="%(_PurviewSkillsUpdateSource.Identity)" - Condition="'$(_PurviewSkillsUpdateExitCode)' != '0'" - > - $(_PurviewSkillsUpdateExitCode) - - - - - - - - - - - - - - - - - - - - - - <_PurviewSkillsProtectedDirectory Include="$([MSBuild]::NormalizeDirectory('$(_PurviewSkillsRepositoryRoot)', 'skills'))" /> - <_PurviewSkillsProtectedDirectory - Include="$(PurviewSkillsSourceFolder)" - Condition="'$(PurviewSkillsSourceFolder)' != ''" - /> - - - - - - - - - - - - - - - - - - - - - <_PurviewSkillsFixDirectories>true - - - - - - - - - - - - - FindPurviewRepositoryRoot inline MSBuild task, and the /// two are kept in step deliberately: skills belong to the repository rather than to a project, so a /// test that validates them has to agree with the build about which directory that is. A test that -/// resolved a different root from InstallPurviewSkills would validate one set of skills while -/// the build installed another. +/// resolved a different root from ValidatePurviewSkills would pass one set of skills while the +/// pack-time check failed another. /// /// /// Three properties of the walk are load-bearing and easy to lose in a rewrite: diff --git a/src/tests/BuildSdk.IntegrationTests/PurviewSkillInstallCommandTests.cs b/src/tests/BuildSdk.IntegrationTests/PurviewSkillInstallCommandTests.cs deleted file mode 100644 index 36a72c8..0000000 --- a/src/tests/BuildSdk.IntegrationTests/PurviewSkillInstallCommandTests.cs +++ /dev/null @@ -1,464 +0,0 @@ -using System.Text.Json; -using Purview.BuildSdk.Harness; -using Purview.BuildSdk.Infra; - -namespace Purview.BuildSdk; - -/// -/// Verifies the command InstallPurviewSkills hands to the skills CLI, and the repository root it -/// runs from. The target is a thin wrapper: skills add <source> for an explicit -/// PurviewSkillsSource, or skills experimental_install to restore skills-lock.json. -/// -/// -/// echo stands in for the CLI so a test asserts on the command without needing Node, a network, -/// or a real install. Exec runs through the platform shell, and echo is a builtin of both cmd and sh, -/// so this is identical on Windows, Linux and macOS. The throwaway solution is not a git repository and -/// has no AGENTS.md, so the repository root is named explicitly where a test needs one. -/// -sealed class PurviewSkillInstallCommandTests -{ - [Test] - public async Task InstallPurviewSkills_FromASource_AddsEverySkillItHas(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillInstaller", cancellationToken: cancellationToken); - - var (exitCode, stdOut, stdErr) = await harness.RunMSBuildAsync( - "-t:InstallPurviewSkills -v:n " - + $"-p:PurviewSkillsInstallRoot=\"{harness.SolutionDirectory}\" " - + "-p:PurviewSkillsSource=purview-dev/engineering-playbook#abc123 " - + "-p:PurviewSkillsCommand=echo -p:PurviewSkillsAgents=claude-code", - cancellationToken - ); - - await Assert.That(exitCode).IsZero().Because(TestHelpers.GenerateError(stdOut, stdErr)); - // The caller's source and ref verbatim, every skill it has, then the agent selection. - await Assert - .That(stdOut) - .Contains("add \"purview-dev/engineering-playbook#abc123\" --skill \"*\" --agent \"claude-code\" -y"); - } - - [Test] - public async Task InstallPurviewSkills_WithoutAgents_LetsTheCliAutoDetect(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillInstaller", cancellationToken: cancellationToken); - - var (exitCode, stdOut, stdErr) = await harness.RunMSBuildAsync( - "-t:InstallPurviewSkills -v:n " - + $"-p:PurviewSkillsInstallRoot=\"{harness.SolutionDirectory}\" " - + "-p:PurviewSkillsSource=purview-dev/build-sdk -p:PurviewSkillsCommand=echo", - cancellationToken - ); - - await Assert.That(exitCode).IsZero().Because(TestHelpers.GenerateError(stdOut, stdErr)); - await Assert.That(stdOut).Contains("--skill \"*\" -y"); - await Assert.That(stdOut).DoesNotContain("--agent"); - } - - [Test] - public async Task InstallPurviewSkills_WithoutASource_RestoresTheLockFile(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillRestorer", cancellationToken: cancellationToken); - await File.WriteAllTextAsync( - Path.Combine(harness.SolutionDirectory, "skills-lock.json"), - /*lang=json,strict*/"""{"version": 1, "skills": {}}""", - cancellationToken - ); - - var (exitCode, stdOut, stdErr) = await harness.RunMSBuildAsync( - "-t:InstallPurviewSkills -v:n " - + $"-p:PurviewSkillsInstallRoot=\"{harness.SolutionDirectory}\" -p:PurviewSkillsCommand=echo", - cancellationToken - ); - - // A fresh clone gets its skills back the standard way: the CLI restores what the lockfile records. - await Assert.That(exitCode).IsZero().Because(TestHelpers.GenerateError(stdOut, stdErr)); - await Assert.That(stdOut).Contains("experimental_install"); - await Assert.That(stdOut).DoesNotContain(" add "); - } - - [Test] - public async Task InstallPurviewSkills_WithoutASourceOrALockFile_SaysWhatToDo(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillNothing", cancellationToken: cancellationToken); - - var (exitCode, stdOut, stdErr) = await harness.RunMSBuildAsync( - "-t:InstallPurviewSkills -v:n " - + $"-p:PurviewSkillsInstallRoot=\"{harness.SolutionDirectory}\" -p:PurviewSkillsCommand=echo", - cancellationToken - ); - - await Assert.That(exitCode).IsNotEqualTo(0); - var output = stdOut + stdErr; - await Assert.That(output).Contains("PRSKL0007"); - await Assert.That(output).Contains("PurviewSkillsSource"); - } - - /// - /// The CLI is published to npm and every package runner spells "run this npm package" its own - /// way, so the runner a repository standardises on has to map to the right launcher. A wrong - /// mapping is not a formatting detail: it is a command that does not run. - /// - [Test] - [Arguments("npx", "npx -y skills@1")] - [Arguments("bunx", "bunx skills@1")] - [Arguments("bun", "bun x skills@1")] - [Arguments("pnpm", "pnpm dlx skills@1")] - [Arguments("yarn", "yarn dlx skills@1")] - [Arguments("deno", "deno run -A npm:skills@1")] - [Arguments("skills", "skills")] - // A runner this SDK has never heard of still resolves, rather than being silently dropped. - [Arguments("future-runner", "future-runner skills@1")] - public async Task SkillsRunner_DrivesTheExecutedCommand( - string runner, - string expectedLauncher, - CancellationToken cancellationToken - ) - { - // An empty PATH means no runner is found, so the dry run falls back to the configured one. - using var harness = await ProjectHarness.CreateAsync( - "SkillRunner", - extraEnv: new Dictionary { ["PATH"] = string.Empty }, - cancellationToken: cancellationToken - ); - - var (exitCode, stdOut, stdErr) = await harness.RunMSBuildAsync( - "-t:InstallPurviewSkills -v:n " - + $"-p:PurviewSkillsInstallRoot=\"{harness.SolutionDirectory}\" " - + $"-p:PurviewSkillsSource=purview-dev/build-sdk -p:PurviewSkillsDryRun=true -p:PurviewSkillsRunner={runner}", - cancellationToken - ); - - await Assert.That(exitCode).IsZero().Because(TestHelpers.GenerateError(stdOut, stdErr)); - await Assert.That(stdOut).Contains($"Agent skills (dry run): {expectedLauncher} add \"purview-dev/build-sdk\""); - } - - [Test] - public async Task SkillsRunner_DefaultsToBun(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillRunner", cancellationToken: cancellationToken); - - var (exitCode, stdOut, stdErr) = await harness.RunMSBuildAsync( - "-getProperty:PurviewSkillsRunner", - cancellationToken - ); - - await Assert.That(exitCode).IsZero().Because(TestHelpers.GenerateError(stdOut, stdErr)); - await Assert.That(stdOut.Trim()).IsEqualTo("bun"); - } - - /// - /// The executed launcher pins the CLI to a major, so a breaking release cannot change what - /// InstallPurviewSkills does. Each runner's exact invocation was verified against the real - /// tool; getting one wrong produces a command that simply does not run, so they are asserted - /// literally rather than derived. - /// - [Test] - public async Task SkillsRunnerLaunchers_PinTheCliToAMajor(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillRunner", cancellationToken: cancellationToken); - - var (exitCode, stdOut, stdErr) = await harness.RunMSBuildAsync( - "-getItem:PurviewSkillsRunnerLauncher", - cancellationToken - ); - - await Assert.That(exitCode).IsZero().Because(TestHelpers.GenerateError(stdOut, stdErr)); - - var jsonStart = stdOut.IndexOf('{', StringComparison.Ordinal); - await Assert.That(jsonStart).IsGreaterThanOrEqualTo(0); - - using var document = JsonDocument.Parse(stdOut[jsonStart..]); - var launchers = document - .RootElement.GetProperty("Items") - .GetProperty("PurviewSkillsRunnerLauncher") - .EnumerateArray() - .ToDictionary( - entry => entry.GetProperty("Identity").GetString()!, - entry => entry.GetProperty("Exec").GetString()! - ); - - await Assert.That(launchers["npx"]).IsEqualTo("npx -y skills@1"); - await Assert.That(launchers["bunx"]).IsEqualTo("bunx skills@1"); - await Assert.That(launchers["bun"]).IsEqualTo("bun x skills@1"); - await Assert.That(launchers["pnpm"]).IsEqualTo("pnpm dlx skills@1"); - await Assert.That(launchers["yarn"]).IsEqualTo("yarn dlx skills@1"); - await Assert.That(launchers["deno"]).IsEqualTo("deno run -A npm:skills@1"); - // Already on PATH: used as-is, no download, works offline. - await Assert.That(launchers["skills"]).IsEqualTo("skills"); - } - - [Test] - public async Task InstallPurviewSkills_WithoutACliOnPath_ReportsHowToInstallOne(CancellationToken cancellationToken) - { - // An empty PATH is the cleanest way to stand in for a machine with no Node tooling, and it - // does not depend on whether this machine happens to have npx installed. - using var harness = await ProjectHarness.CreateAsync( - "SkillNoCli", - extraEnv: new Dictionary { ["PATH"] = string.Empty }, - cancellationToken: cancellationToken - ); - - var (exitCode, stdOut, stdErr) = await harness.RunMSBuildAsync( - "-t:InstallPurviewSkills -v:n " - + $"-p:PurviewSkillsInstallRoot=\"{harness.SolutionDirectory}\" -p:PurviewSkillsSource=purview-dev/build-sdk", - cancellationToken - ); - - // It fails, but with a diagnostic that names the fix rather than a raw shell error. - await Assert.That(exitCode).IsNotEqualTo(0); - var output = stdOut + stdErr; - await Assert.That(output).Contains("PRSKL0004"); - await Assert.That(output).Contains("npm install -g skills"); - } - - /// - /// Resolves the repository root every skill target runs from, by asking - /// MSBuild for the property the shared resolution target computes. - /// - static async Task ResolveRepositoryRootAsync( - ProjectHarness harness, - string extraArguments, - CancellationToken cancellationToken - ) - { - var (exitCode, stdOut, stdErr) = await harness.RunMSBuildAsync( - "-t:ResolvePurviewSkillsRepositoryRoot -getProperty:_PurviewSkillsRepositoryRoot " + extraArguments, - cancellationToken - ); - - await Assert.That(exitCode).IsZero().Because(TestHelpers.GenerateError(stdOut, stdErr)); - return stdOut.Trim(); - } - - /// - /// Every marker in the default list, on its own, identifies a repository root. Four of them are - /// directories, which MSBuild's own GetDirectoryNameOfFileAbove cannot find at all - it - /// matches files only - so each one is pinned here rather than assumed to work. - /// - [Test] - [Arguments(".git", true)] - [Arguments(".github", true)] - [Arguments(".agents", true)] - [Arguments(".claude", true)] - [Arguments(".gitattributes", false)] - [Arguments("LICENSE.md", false)] - [Arguments("AGENTS.md", false)] - [Arguments("CLAUDE.md", false)] - [Arguments("package.json", false)] - public async Task RepositoryRoot_IsFoundFromAnyDefaultMarker( - string marker, - bool isDirectory, - CancellationToken cancellationToken - ) - { - using var harness = await ProjectHarness.CreateAsync("SkillRepoRoot", cancellationToken: cancellationToken); - - var markerPath = Path.Combine(harness.SolutionDirectory, marker); - if (isDirectory) - Directory.CreateDirectory(markerPath); - else - await File.WriteAllTextAsync(markerPath, "marker\n", cancellationToken); - - var resolved = await ResolveRepositoryRootAsync(harness, string.Empty, cancellationToken); - - await Assert - .That(Path.GetFullPath(resolved)) - .IsEqualTo(Path.GetFullPath(harness.SolutionDirectory)) - .Because($"'{marker}' should identify the repository root"); - } - - [Test] - public async Task RepositoryRoot_MatchesAFileNamedDotGit(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillRepoRoot", cancellationToken: cancellationToken); - - // '.git' is a directory in a clone but a *file* in a worktree or a submodule, and both - // identify a repository root. A directory marker therefore matches either. - await File.WriteAllTextAsync( - Path.Combine(harness.SolutionDirectory, ".git"), - "gitdir: ../../.git/worktrees/x\n", - cancellationToken - ); - - var resolved = await ResolveRepositoryRootAsync(harness, string.Empty, cancellationToken); - - await Assert.That(Path.GetFullPath(resolved)).IsEqualTo(Path.GetFullPath(harness.SolutionDirectory)); - } - - [Test] - public async Task RepositoryRoot_LetsTheDefinitiveMarkerBeatANearerOne(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillRepoRoot", cancellationToken: cancellationToken); - - // '.git/' sits at the solution, a 'package.json' sits nearer in the project folder. '.git/' - // is the repository root by definition, so a package inside a monorepo must not win. - Directory.CreateDirectory(Path.Combine(harness.SolutionDirectory, ".git")); - await File.WriteAllTextAsync( - Path.Combine(harness.ProjectDirectory, "package.json"), - /*lang=json,strict*/"{ \"name\": \"nested\" }\n", - cancellationToken - ); - - var resolved = await ResolveRepositoryRootAsync(harness, string.Empty, cancellationToken); - - await Assert.That(Path.GetFullPath(resolved)).IsEqualTo(Path.GetFullPath(harness.SolutionDirectory)); - await Assert.That(Path.GetFullPath(resolved)).IsNotEqualTo(Path.GetFullPath(harness.ProjectDirectory)); - } - - [Test] - public async Task RepositoryRoot_PrefersANearerMarkerOverADistantNonDefinitiveOne( - CancellationToken cancellationToken - ) - { - using var harness = await ProjectHarness.CreateAsync("SkillRepoRoot", cancellationToken: cancellationToken); - - // '.github/' outranks 'package.json' in the list, but only '.git/' is allowed to win from a - // distance. Were that not so, a stray '.claude/' or '.github/' in a developer's home - // directory would outrank the real repository root and scatter a lockfile outside it. - Directory.CreateDirectory(Path.Combine(harness.SolutionDirectory, ".github")); - await File.WriteAllTextAsync( - Path.Combine(harness.ProjectDirectory, "package.json"), - /*lang=json,strict*/"{ \"name\": \"nested\" }\n", - cancellationToken - ); - - var resolved = await ResolveRepositoryRootAsync(harness, string.Empty, cancellationToken); - - await Assert - .That(Path.GetFullPath(resolved)) - .IsEqualTo(Path.GetFullPath(harness.ProjectDirectory)) - .Because("the nearest marker wins once the definitive one is absent"); - } - - [Test] - public async Task RepositoryRoot_BreaksTiesWithinADirectoryByListOrder(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillRepoRoot", cancellationToken: cancellationToken); - - // Both markers sit in the same directory, so the list order decides which one is reported. - await File.WriteAllTextAsync(Path.Combine(harness.SolutionDirectory, "LICENSE.md"), "MIT\n", cancellationToken); - await File.WriteAllTextAsync( - Path.Combine(harness.SolutionDirectory, "package.json"), - /*lang=json,strict*/"{ \"name\": \"root\" }\n", - cancellationToken - ); - - var (exitCode, stdOut, stdErr) = await harness.RunMSBuildAsync( - "-t:ResolvePurviewSkillsRepositoryRoot -getProperty:_PurviewSkillsRepositoryRootMarker", - cancellationToken - ); - - await Assert.That(exitCode).IsZero().Because(TestHelpers.GenerateError(stdOut, stdErr)); - await Assert.That(stdOut.Trim()).IsEqualTo("LICENSE.md"); - } - - [Test] - public async Task RepositoryRoot_FallsThroughWhenTheLeadingMarkersAreAbsent(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillRepoRoot", cancellationToken: cancellationToken); - - // Nothing above '.claude/' exists, so the walk has to keep going down the list rather than - // stopping at the first marker it cannot find. - Directory.CreateDirectory(Path.Combine(harness.SolutionDirectory, ".claude")); - - var resolved = await ResolveRepositoryRootAsync(harness, string.Empty, cancellationToken); - - await Assert.That(Path.GetFullPath(resolved)).IsEqualTo(Path.GetFullPath(harness.SolutionDirectory)); - } - - [Test] - public async Task RepositoryRootMarkers_CanBeReplaced(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillRepoRoot", cancellationToken: cancellationToken); - - await File.WriteAllTextAsync( - Path.Combine(harness.SolutionDirectory, "my-repo-marker"), - "marker\n", - cancellationToken - ); - - var resolved = await ResolveRepositoryRootAsync( - harness, - "-p:PurviewRepositoryRootMarkers=my-repo-marker", - cancellationToken - ); - - await Assert.That(Path.GetFullPath(resolved)).IsEqualTo(Path.GetFullPath(harness.SolutionDirectory)); - } - - [Test] - public async Task RepositoryRoot_IsFoundFromAnAgentsMarkerAboveTheProject(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillRepoRoot", cancellationToken: cancellationToken); - - // The marker sits beside the solution, a level above the project, which is exactly the shape - // the walk-up exists for: skills belong to the repository, not to whichever project built. - await File.WriteAllTextAsync( - Path.Combine(harness.SolutionDirectory, "AGENTS.md"), - "# Test repository\n", - cancellationToken - ); - - var resolved = await ResolveRepositoryRootAsync(harness, string.Empty, cancellationToken); - - await Assert.That(resolved).IsNotEmpty(); - await Assert.That(Path.GetFullPath(resolved)).IsEqualTo(Path.GetFullPath(harness.SolutionDirectory)); - // Never the project folder - that is the scattering this prevents. - await Assert.That(Path.GetFullPath(resolved)).IsNotEqualTo(Path.GetFullPath(harness.ProjectDirectory)); - } - - [Test] - public async Task RepositoryRoot_PrefersAnExplicitInstallRoot(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillRepoRoot", cancellationToken: cancellationToken); - - await File.WriteAllTextAsync( - Path.Combine(harness.SolutionDirectory, "AGENTS.md"), - "# Test repository\n", - cancellationToken - ); - - var elsewhere = Path.Combine(harness.SolutionDirectory, "elsewhere"); - Directory.CreateDirectory(elsewhere); - - var resolved = await ResolveRepositoryRootAsync( - harness, - $"-p:PurviewSkillsInstallRoot=\"{elsewhere}\"", - cancellationToken - ); - - await Assert.That(Path.GetFullPath(resolved)).IsEqualTo(Path.GetFullPath(elsewhere)); - } - - [Test] - public async Task InstallPurviewSkills_WithoutAResolvableRepositoryRoot_RefusesToGuess( - CancellationToken cancellationToken - ) - { - // No marker anywhere between the project and the home directory, not a git repository, and no - // CI workspace variables: nothing says where the repository is. The project folder is - // deliberately not an acceptable answer, and neither is the home directory - a '.claude/' or - // '.github/' commonly sits there, and resolving to it would install outside any repository. - using var harness = await ProjectHarness.CreateAsync( - "SkillNoRoot", - extraEnv: new Dictionary - { - ["GITHUB_WORKSPACE"] = string.Empty, - ["BUILD_SOURCESDIRECTORY"] = string.Empty, - ["CI_PROJECT_DIR"] = string.Empty, - }, - cancellationToken: cancellationToken - ); - - var (exitCode, stdOut, stdErr) = await harness.RunMSBuildAsync( - "-t:InstallPurviewSkills -v:n -p:PurviewSkillsSource=purview-dev/build-sdk -p:PurviewSkillsCommand=echo", - cancellationToken - ); - - await Assert.That(exitCode).IsNotEqualTo(0); - var output = stdOut + stdErr; - await Assert.That(output).Contains("PRSKL0003"); - // The diagnostic names the way out rather than silently installing somewhere wrong. - await Assert.That(output).Contains("PurviewSkillsInstallRoot"); - } -} diff --git a/src/tests/BuildSdk.IntegrationTests/PurviewSkillSolutionTests.cs b/src/tests/BuildSdk.IntegrationTests/PurviewSkillSolutionTests.cs deleted file mode 100644 index d91a69a..0000000 --- a/src/tests/BuildSdk.IntegrationTests/PurviewSkillSolutionTests.cs +++ /dev/null @@ -1,110 +0,0 @@ -using System.Text.RegularExpressions; -using Purview.BuildSdk.Harness; - -namespace Purview.BuildSdk; - -/// -/// Skills belong to the repository, so a skill target pointed at a solution must do its work once -/// for the whole solution rather than once per project. MSBuild runs a custom target in every project -/// of a solution, so each project hands the work to one elected leader, and MSBuild's result cache runs -/// the leader's target once however many projects asked. -/// -sealed partial class PurviewSkillSolutionTests -{ - const string SolutionFileName = "Skills.slnx"; - - // The dry run prints the command it would have run, once per run of the install target. - [GeneratedRegex("Agent skills \\(dry run\\):")] - private static partial Regex DryRunInstallLine(); - - // MSBuild logs this line when a target actually runs, not when a cached result is handed back. - [GeneratedRegex("is building \"[^\"]+\" \\([^)]+\\) on node \\d+ \\(_CheckPurviewSkillsCore")] - private static partial Regex CheckCoreRun(); - - /// - /// Three SDK projects in one solution. The harness's own solution lists projects as files, so this - /// writes one that lists them as projects. - /// - static async Task CreateSolutionAsync(CancellationToken cancellationToken) - { - var first = await ProjectHarness.CreateAsync("Alpha", cancellationToken: cancellationToken); - - var projects = new List { first }; - foreach (var name in new[] { "Bravo", "Charlie" }) - { - projects.Add( - await ProjectHarness - .For(name) - .WithNamespacePrefix("Test") - .WithSolutionDirectory(first.SolutionDirectory) - .BuildAsync(cancellationToken) - ); - } - - await File.WriteAllTextAsync( - Path.Combine(first.SolutionDirectory, SolutionFileName), - $""" - - {string.Concat( - projects.Select(project => - $"\t\n" - ) - )} - """, - cancellationToken - ); - - // The repository root resolves from a marker, as it would in a real repository. - await File.WriteAllTextAsync(Path.Combine(first.SolutionDirectory, "AGENTS.md"), "# Test", cancellationToken); - - return [.. projects]; - } - - static async Task<(int Code, string Output)> RunOnSolutionAsync( - ProjectHarness harness, - string arguments, - CancellationToken cancellationToken - ) - { - var (code, stdOut, stdErr) = await harness.RunProcessAsync( - "dotnet", - $"msbuild \"{Path.Combine(harness.SolutionDirectory, SolutionFileName)}\" -nologo -v:n {arguments}", - harness.SolutionDirectory, - cancellationToken - ); - - return (code, stdOut + stdErr); - } - - [Test] - [Arguments("-m:1")] - [Arguments("-m")] - public async Task ASkillTargetOnASolution_RunsOnce(string parallelism, CancellationToken cancellationToken) - { - var projects = await CreateSolutionAsync(cancellationToken); - using var owner = projects[0]; - - var (code, output) = await RunOnSolutionAsync( - owner, - $"{parallelism} -t:InstallPurviewSkills -p:PurviewSkillsDryRun=true " - + "-p:PurviewSkillsSource=purview-dev/engineering-playbook -p:PurviewSkillsRunner=npx", - cancellationToken - ); - - await Assert.That(code).IsZero().Because(output); - await Assert.That(DryRunInstallLine().Count(output)).IsEqualTo(1).Because(output); - } - - [Test] - public async Task ASolution_ElectsTheSameLeaderFromEveryProject(CancellationToken cancellationToken) - { - var projects = await CreateSolutionAsync(cancellationToken); - using var owner = projects[0]; - - var (code, output) = await RunOnSolutionAsync(owner, "-t:CheckPurviewSkills", cancellationToken); - - await Assert.That(code).IsZero().Because(output); - // Each project runs the public target, but only the leader runs the work behind it. - await Assert.That(CheckCoreRun().Count(output)).IsEqualTo(1).Because(output); - } -} diff --git a/src/tests/BuildSdk.IntegrationTests/PurviewSkillTargetIsolationTests.cs b/src/tests/BuildSdk.IntegrationTests/PurviewSkillTargetIsolationTests.cs deleted file mode 100644 index a6e148b..0000000 --- a/src/tests/BuildSdk.IntegrationTests/PurviewSkillTargetIsolationTests.cs +++ /dev/null @@ -1,185 +0,0 @@ -using System.Xml.Linq; -using Purview.BuildSdk.Harness; -using Purview.BuildSdk.Infra; - -namespace Purview.BuildSdk; - -/// -/// InstallPurviewSkills, UpdatePurviewSkills and FixPurviewSkills change the -/// repository - they run the skills CLI or delete files - so they must only ever run because a person -/// named them. Two layers keep it that way, and each is tested: nothing in the SDK hooks or depends on -/// them, and a guard refuses to run when something else has pulled one into a build, a restore or a -/// design-time build. -/// -sealed class PurviewSkillTargetIsolationTests -{ - static readonly string[] ExplicitTargets = - [ - "InstallPurviewSkills", - "UpdatePurviewSkills", - "FixPurviewSkills", - "CheckPurviewSkills", - // The leader-side halves the public targets hand their work to; reaching one directly is - // reaching the work. - "_InstallPurviewSkillsCore", - "_UpdatePurviewSkillsCore", - "_FixPurviewSkillsCore", - "_CheckPurviewSkillsCore", - ]; - - static IEnumerable SdkProjectFiles() => - Directory - .EnumerateFiles(SdkPaths.SdkDirectory, "*.*", SearchOption.AllDirectories) - .Where(path => - path.EndsWith(".props", StringComparison.OrdinalIgnoreCase) - || path.EndsWith(".targets", StringComparison.OrdinalIgnoreCase) - ); - - static string[] SplitTargetList(string? value) => - (value ?? string.Empty).Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - - [Test] - public async Task ExplicitTargets_AreNeverHookedOrDependedOn() - { - var problems = new List(); - - foreach (var file in SdkProjectFiles()) - { - var document = XDocument.Load(file); - var name = Path.GetFileName(file); - - foreach (var target in document.Descendants().Where(element => element.Name.LocalName == "Target")) - { - var targetName = (string?)target.Attribute("Name") ?? string.Empty; - - if (ExplicitTargets.Contains(targetName, StringComparer.OrdinalIgnoreCase)) - { - foreach (var hook in new[] { "BeforeTargets", "AfterTargets" }) - { - if (target.Attribute(hook) is not null) - problems.Add($"{name}: {targetName} has {hook}, so it would run without being named"); - } - - continue; - } - - foreach (var attribute in new[] { "BeforeTargets", "AfterTargets", "DependsOnTargets" }) - { - foreach (var referenced in SplitTargetList((string?)target.Attribute(attribute))) - { - if (ExplicitTargets.Contains(referenced, StringComparer.OrdinalIgnoreCase)) - problems.Add($"{name}: {targetName} references {referenced} in {attribute}"); - } - } - } - - // $(BuildDependsOn), $(CoreBuildDependsOn) and friends are the other way to splice a - // target into an ordinary build. - foreach ( - var property in document - .Descendants() - .Where(element => element.Name.LocalName.EndsWith("DependsOn", StringComparison.Ordinal)) - ) - { - foreach (var referenced in SplitTargetList(property.Value)) - { - if (ExplicitTargets.Contains(referenced, StringComparer.OrdinalIgnoreCase)) - problems.Add($"{name}: {property.Name.LocalName} includes {referenced}"); - } - } - } - - await Assert.That(problems).IsEmpty().Because(string.Join(Environment.NewLine, problems)); - } - - [Test] - [Arguments("UpdatePurviewSkills", "BuildingProject")] - [Arguments("InstallPurviewSkills", "BuildingProject")] - [Arguments("FixPurviewSkills", "BuildingProject")] - [Arguments("UpdatePurviewSkills", "DesignTimeBuild")] - [Arguments("InstallPurviewSkills", "DesignTimeBuild")] - [Arguments("InstallPurviewSkills", "MSBuildIsRestoring")] - public async Task ExplicitTargets_RefuseToRunInsideABuild( - string target, - string context, - CancellationToken cancellationToken - ) - { - using var harness = await ProjectHarness.CreateAsync("SkillGuard", cancellationToken: cancellationToken); - SkillLockFileFixtures.WriteLockFile( - Path.Combine(harness.SolutionDirectory, "skills-lock.json"), - ("web-design", "vercel-labs/agent-skills", null) - ); - - // 'echo' would succeed, so reaching the CLI at all would show up as a pass. - var (code, stdOut, stdErr) = await harness.RunMSBuildAsync( - $"-v:n -t:{target} -p:{context}=true " - + $"-p:PurviewSkillsInstallRoot=\"{harness.SolutionDirectory}\" " - + "-p:PurviewSkillsSource=vercel-labs/agent-skills -p:PurviewSkillsAgents=universal " - + "-p:PurviewSkillsCommand=purview-guard-reached-the-cli", - cancellationToken - ); - - var output = stdOut + stdErr; - await Assert.That(code).IsNotEqualTo(0); - await Assert.That(output).Contains("PRSKL0009"); - await Assert.That(output).DoesNotContain("purview-guard-reached-the-cli add"); - } - - [Test] - public async Task AConsumerHook_CannotRunUpdateDuringABuild(CancellationToken cancellationToken) - { - // The shape somebody might reasonably try: chaining update onto every build. - // The default telemetry packages would need Central Package Management versions the throwaway - // solution does not declare, and are not part of this scenario. - using var harness = await ProjectHarness.CreateAsync( - "SkillHook", - extraProps: """ - true - true - """, - cancellationToken: cancellationToken - ); - await File.WriteAllTextAsync( - Path.Combine(harness.SolutionDirectory, "Directory.Build.targets"), - $""" - - - - - """, - cancellationToken - ); - - var (success, output, errors) = await harness.BuildAsync(restore: true, cancellationToken: cancellationToken); - - await Assert.That(success).IsFalse(); - await Assert.That(output + errors).Contains("PRSKL0009"); - } - - [Test] - public async Task OrdinaryBuild_DoesNotInstallSkills(CancellationToken cancellationToken) - { - // The telemetry packages the SDK adds by default are not part of this scenario and would - // need Central Package Management versions the throwaway solution does not declare. - using var harness = await ProjectHarness.CreateAsync( - "SkillConsumer", - extraProps: """ - true - true - """, - cancellationToken: cancellationToken - ); - - // A restore is part of the scenario: the point is that a *complete*, ordinary - // restore-and-build cycle still installs nothing. - var (success, output, errors) = await harness.BuildAsync(restore: true, cancellationToken: cancellationToken); - - await Assert.That(success).IsTrue().Because(TestHelpers.GenerateError(output, errors)); - // Installation is explicit: a build must not write the skills CLI's lockfile, and must not - // create an agent directory the CLI owns. - await Assert.That(File.Exists(Path.Combine(harness.SolutionDirectory, "skills-lock.json"))).IsFalse(); - await Assert.That(Directory.Exists(Path.Combine(harness.SolutionDirectory, ".claude", "skills"))).IsFalse(); - await Assert.That(Directory.Exists(Path.Combine(harness.ProjectDirectory, ".claude", "skills"))).IsFalse(); - } -} diff --git a/src/tests/BuildSdk.IntegrationTests/PurviewSkillUpdateTests.cs b/src/tests/BuildSdk.IntegrationTests/PurviewSkillUpdateTests.cs deleted file mode 100644 index 11f807e..0000000 --- a/src/tests/BuildSdk.IntegrationTests/PurviewSkillUpdateTests.cs +++ /dev/null @@ -1,275 +0,0 @@ -using Purview.BuildSdk.Harness; - -namespace Purview.BuildSdk; - -/// -/// Verifies UpdatePurviewSkills, CheckPurviewSkills and FixPurviewSkills. The -/// skills CLI is stood in for by echo, so the assertions are about the commands handed to it - -/// never letting a test reach bun x or npx, which would download from the network. -/// -sealed class PurviewSkillUpdateTests -{ - const string PurviewSource = "purview-dev/build-sdk"; - const string OtherSource = "vercel-labs/agent-skills"; - const string OldCommit = "aaaaaaaabbbbbbbbccccccccddddddddeeeeeeee"; - - static string LockFilePath(ProjectHarness harness) => Path.Combine(harness.SolutionDirectory, "skills-lock.json"); - - /// One skill pinned at an old ref, plus two skills from a second repository. - static void GivenInstalledSkills(ProjectHarness harness) => - SkillLockFileFixtures.WriteLockFile( - LockFilePath(harness), - ("purview-buildsdk-testing", PurviewSource, OldCommit), - ("web-design", OtherSource, null), - ("frontend-design", OtherSource, null) - ); - - static async Task<(int Code, string Output)> RunAsync( - ProjectHarness harness, - string target, - string extraArguments = "", - CancellationToken cancellationToken = default - ) - { - var (code, stdOut, stdErr) = await harness.RunMSBuildAsync( - $"-v:n \"-t:{target}\" -p:PurviewSkillsInstallRoot=\"{harness.SolutionDirectory}\" {extraArguments}", - cancellationToken - ); - - return (code, stdOut + stdErr); - } - - [Test] - public async Task Update_ReAddsEachSource_AtItsLatest_WithEverySkill(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillUpdate", cancellationToken: cancellationToken); - GivenInstalledSkills(harness); - - var (code, output) = await RunAsync( - harness, - "UpdatePurviewSkills", - "-p:PurviewSkillsCommand=echo", - cancellationToken - ); - - await Assert.That(code).IsZero().Because(output); - // Each unique source once, unpinned, with every skill it has - so a skill the repository has - // gained since the last install comes in too, and the old ref is not kept. - await Assert.That(output).Contains($"add \"{PurviewSource}\" --skill \"*\""); - await Assert.That(output).Contains($"add \"{OtherSource}\" --skill \"*\""); - await Assert.That(output).DoesNotContain("--skill \"web-design\""); - await Assert.That(output).DoesNotContain(OldCommit); - // No agents named: the CLI auto-detects, so no agent flag is passed. - await Assert.That(output).DoesNotContain("--agent"); - // The re-adds are the whole update: 'skills add' refreshes installed skills and adds new ones, - // so 'skills update' is never run. - await Assert.That(output).Contains("2 source(s) refreshed."); - await Assert.That(output).DoesNotContain("echo update"); - } - - [Test] - public async Task Update_NamedAgents_BecomeOneFlagEach(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillUpdate", cancellationToken: cancellationToken); - GivenInstalledSkills(harness); - - var (code, output) = await RunAsync( - harness, - "UpdatePurviewSkills", - "-p:PurviewSkillsCommand=echo -p:PurviewSkillsAgents=claude-code%2Ccodex", - cancellationToken - ); - - await Assert.That(code).IsZero().Because(output); - // 'dotnet msbuild -p:' splits on a bare comma, so the separator is escaped; the CLI does not - // split a comma-separated agent list either, so each agent gets its own flag. - await Assert.That(output).Contains("--agent \"claude-code\" --agent \"codex\" -y"); - await Assert.That(output).DoesNotContain("claude-code,codex\""); - } - - [Test] - public async Task Update_DryRun_RunsNothing(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillUpdate", cancellationToken: cancellationToken); - GivenInstalledSkills(harness); - - // A command that cannot run proves nothing was executed. - var (code, output) = await RunAsync( - harness, - "UpdatePurviewSkills", - "-p:PurviewSkillsCommand=purview-no-such-command -p:PurviewSkillsDryRun=true", - cancellationToken - ); - - await Assert.That(code).IsZero().Because(output); - await Assert.That(output).Contains($"purview-no-such-command add \"{OtherSource}\""); - await Assert.That(output).Contains("dry run, 2 source(s), nothing changed"); - } - - [Test] - public async Task Update_EveryFailedSource_IsNamed(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillUpdate", cancellationToken: cancellationToken); - GivenInstalledSkills(harness); - - // 'dotnet ' exits non-zero on every platform without touching the network. - var (code, output) = await RunAsync( - harness, - "UpdatePurviewSkills", - "\"-p:PurviewSkillsCommand=dotnet purview-no-such-command\"", - cancellationToken - ); - - await Assert.That(code).IsNotEqualTo(0); - await Assert.That(output).Contains("PRSKL0008"); - await Assert.That(output).Contains($"re-adding '{OtherSource}' failed"); - await Assert.That(output).Contains($"re-adding '{PurviewSource}' failed"); - await Assert.That(output).DoesNotContain("source(s) refreshed."); - } - - [Test] - public async Task Update_WithoutALockFile_ReportsHowToInstall(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillUpdate", cancellationToken: cancellationToken); - - var (code, output) = await RunAsync( - harness, - "UpdatePurviewSkills", - "-p:PurviewSkillsCommand=echo", - cancellationToken - ); - - await Assert.That(code).IsNotEqualTo(0); - await Assert.That(output).Contains("PRSKL0007"); - await Assert.That(output).Contains("InstallPurviewSkills"); - } - - [Test] - public async Task Check_WithoutAgents_EnforcesNothing(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillLayout", cancellationToken: cancellationToken); - Directory.CreateDirectory(Path.Combine(harness.SolutionDirectory, ".claude", "skills", "purview-alpha")); - - var (code, output) = await RunAsync(harness, "CheckPurviewSkills", cancellationToken: cancellationToken); - - // The CLI auto-detects agents, so an agent directory is expected, not a violation. - await Assert.That(code).IsZero().Because(output); - await Assert.That(output).Contains("PurviewSkillsAgents is not set"); - await Assert.That(output).DoesNotContain("PRSKL0015"); - } - - [Test] - public async Task Check_WithAgents_ReportsOnlyUnselectedAgentDirectories(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillLayout", cancellationToken: cancellationToken); - var root = harness.SolutionDirectory; - Directory.CreateDirectory(Path.Combine(root, ".agents", "skills", "purview-alpha")); - Directory.CreateDirectory(Path.Combine(root, ".claude", "skills", "purview-alpha")); - Directory.CreateDirectory(Path.Combine(root, ".windsurf", "skills", "purview-alpha")); - // The authored folder, which openclaw would also install into, is never a violation. - Directory.CreateDirectory(Path.Combine(root, "skills", "my-skill")); - - var (code, output) = await RunAsync( - harness, - "CheckPurviewSkills", - "-p:PurviewSkillsAgents=claude-code", - cancellationToken - ); - - await Assert.That(code).IsNotEqualTo(0); - await Assert.That(output).Contains("PRSKL0015"); - await Assert.That(output).Contains("'.windsurf/skills'"); - // '.agents/skills' is the canonical store, and claude-code was selected. - await Assert.That(output).DoesNotContain("'.agents/skills'"); - await Assert.That(output).DoesNotContain("'.claude/skills'"); - await Assert.That(output).DoesNotContain("'skills'"); - } - - [Test] - public async Task Check_UnknownAgent_IsAWarning(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillLayout", cancellationToken: cancellationToken); - - var (code, output) = await RunAsync( - harness, - "CheckPurviewSkills", - "-p:PurviewSkillsAgents=universal%2Cpurview-imaginary", - cancellationToken - ); - - await Assert.That(code).IsZero().Because(output); - await Assert.That(output).Contains("PRSKL0016"); - await Assert.That(output).Contains("purview-imaginary"); - } - - [Test] - public async Task Fix_RemovesEmptyAgentDirectories_AndKeepsRealContent(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillLayout", cancellationToken: cancellationToken); - var root = harness.SolutionDirectory; - // Emptied of links already: nothing real left, so the folder - and its now-empty parent - go. - Directory.CreateDirectory(Path.Combine(root, ".windsurf", "skills", "purview-alpha")); - // Real content beside the skills folder is not the CLI's, and neither is a real file inside it. - Directory.CreateDirectory(Path.Combine(root, ".claude", "skills", "hand-written")); - await File.WriteAllTextAsync(Path.Combine(root, ".claude", "settings.json"), "{}", cancellationToken); - await File.WriteAllTextAsync( - Path.Combine(root, ".claude", "skills", "hand-written", "SKILL.md"), - "---\nname: hand-written\n---\n", - cancellationToken - ); - - var (code, output) = await RunAsync( - harness, - "FixPurviewSkills", - "-p:PurviewSkillsAgents=universal", - cancellationToken - ); - - await Assert.That(Directory.Exists(Path.Combine(root, ".windsurf"))).IsFalse().Because(output); - await Assert.That(File.Exists(Path.Combine(root, ".claude", "settings.json"))).IsTrue(); - await Assert.That(File.Exists(Path.Combine(root, ".claude", "skills", "hand-written", "SKILL.md"))).IsTrue(); - // What could not be removed fails the target and names what was kept. - await Assert.That(code).IsNotEqualTo(0); - await Assert.That(output).Contains("PRSKL0015"); - await Assert.That(output).Contains(".claude/skills/hand-written/SKILL.md"); - } - - [Test] - public async Task Fix_RemovesLinks_NeverTheirTargets(CancellationToken cancellationToken) - { - using var harness = await ProjectHarness.CreateAsync("SkillLayout", cancellationToken: cancellationToken); - var root = harness.SolutionDirectory; - var canonical = Path.Combine(root, ".agents", "skills", "purview-alpha"); - Directory.CreateDirectory(canonical); - await File.WriteAllTextAsync( - Path.Combine(canonical, "SKILL.md"), - "---\nname: purview-alpha\n---\n", - cancellationToken - ); - Directory.CreateDirectory(Path.Combine(root, ".claude", "skills")); - - var link = Path.Combine(root, ".claude", "skills", "purview-alpha"); - try - { - Directory.CreateSymbolicLink(link, canonical); - } - catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) - { - // Windows only allows symlinks with Developer Mode or elevation; CI on Linux always runs this. - Skip.Test($"Symbolic links cannot be created here: {exception.Message}"); - } - - var (code, output) = await RunAsync( - harness, - "FixPurviewSkills", - "-p:PurviewSkillsAgents=universal", - cancellationToken - ); - - await Assert.That(code).IsZero().Because(output); - await Assert.That(Directory.Exists(Path.Combine(root, ".claude", "skills"))).IsFalse(); - // The canonical copy the link pointed at is untouched. - await Assert.That(File.Exists(Path.Combine(canonical, "SKILL.md"))).IsTrue(); - await Assert.That(output).Contains("removed .claude/skills/purview-alpha"); - } -} diff --git a/src/tests/BuildSdk.IntegrationTests/PurviewSkillsRepositoryRootTests.cs b/src/tests/BuildSdk.IntegrationTests/PurviewSkillsRepositoryRootTests.cs new file mode 100644 index 0000000..a164cae --- /dev/null +++ b/src/tests/BuildSdk.IntegrationTests/PurviewSkillsRepositoryRootTests.cs @@ -0,0 +1,234 @@ +using Purview.BuildSdk.Harness; +using Purview.BuildSdk.Infra; + +namespace Purview.BuildSdk; + +/// +/// Verifies ResolvePurviewSkillsRepositoryRoot, the repository root whose skills/ folder +/// ValidatePurviewSkills checks at pack time. +/// +/// +/// The throwaway solution is not a git repository and has no AGENTS.md, so each test places the +/// marker it is about. +/// +sealed class PurviewSkillsRepositoryRootTests +{ + /// + /// Resolves the repository root skill validation uses, by asking + /// MSBuild for the property the shared resolution target computes. + /// + static async Task ResolveRepositoryRootAsync( + ProjectHarness harness, + string extraArguments, + CancellationToken cancellationToken + ) + { + var (exitCode, stdOut, stdErr) = await harness.RunMSBuildAsync( + "-t:ResolvePurviewSkillsRepositoryRoot -getProperty:_PurviewSkillsRepositoryRoot " + extraArguments, + cancellationToken + ); + + await Assert.That(exitCode).IsZero().Because(TestHelpers.GenerateError(stdOut, stdErr)); + return stdOut.Trim(); + } + + /// + /// Every marker in the default list, on its own, identifies a repository root. Four of them are + /// directories, which MSBuild's own GetDirectoryNameOfFileAbove cannot find at all - it + /// matches files only - so each one is pinned here rather than assumed to work. + /// + [Test] + [Arguments(".git", true)] + [Arguments(".github", true)] + [Arguments(".agents", true)] + [Arguments(".claude", true)] + [Arguments(".gitattributes", false)] + [Arguments("LICENSE.md", false)] + [Arguments("AGENTS.md", false)] + [Arguments("CLAUDE.md", false)] + [Arguments("package.json", false)] + public async Task RepositoryRoot_IsFoundFromAnyDefaultMarker( + string marker, + bool isDirectory, + CancellationToken cancellationToken + ) + { + using var harness = await ProjectHarness.CreateAsync("SkillRepoRoot", cancellationToken: cancellationToken); + + var markerPath = Path.Combine(harness.SolutionDirectory, marker); + if (isDirectory) + Directory.CreateDirectory(markerPath); + else + await File.WriteAllTextAsync(markerPath, "marker\n", cancellationToken); + + var resolved = await ResolveRepositoryRootAsync(harness, string.Empty, cancellationToken); + + await Assert + .That(Path.GetFullPath(resolved)) + .IsEqualTo(Path.GetFullPath(harness.SolutionDirectory)) + .Because($"'{marker}' should identify the repository root"); + } + + [Test] + public async Task RepositoryRoot_MatchesAFileNamedDotGit(CancellationToken cancellationToken) + { + using var harness = await ProjectHarness.CreateAsync("SkillRepoRoot", cancellationToken: cancellationToken); + + // '.git' is a directory in a clone but a *file* in a worktree or a submodule, and both + // identify a repository root. A directory marker therefore matches either. + await File.WriteAllTextAsync( + Path.Combine(harness.SolutionDirectory, ".git"), + "gitdir: ../../.git/worktrees/x\n", + cancellationToken + ); + + var resolved = await ResolveRepositoryRootAsync(harness, string.Empty, cancellationToken); + + await Assert.That(Path.GetFullPath(resolved)).IsEqualTo(Path.GetFullPath(harness.SolutionDirectory)); + } + + [Test] + public async Task RepositoryRoot_LetsTheDefinitiveMarkerBeatANearerOne(CancellationToken cancellationToken) + { + using var harness = await ProjectHarness.CreateAsync("SkillRepoRoot", cancellationToken: cancellationToken); + + // '.git/' sits at the solution, a 'package.json' sits nearer in the project folder. '.git/' + // is the repository root by definition, so a package inside a monorepo must not win. + Directory.CreateDirectory(Path.Combine(harness.SolutionDirectory, ".git")); + await File.WriteAllTextAsync( + Path.Combine(harness.ProjectDirectory, "package.json"), + /*lang=json,strict*/"{ \"name\": \"nested\" }\n", + cancellationToken + ); + + var resolved = await ResolveRepositoryRootAsync(harness, string.Empty, cancellationToken); + + await Assert.That(Path.GetFullPath(resolved)).IsEqualTo(Path.GetFullPath(harness.SolutionDirectory)); + await Assert.That(Path.GetFullPath(resolved)).IsNotEqualTo(Path.GetFullPath(harness.ProjectDirectory)); + } + + [Test] + public async Task RepositoryRoot_PrefersANearerMarkerOverADistantNonDefinitiveOne( + CancellationToken cancellationToken + ) + { + using var harness = await ProjectHarness.CreateAsync("SkillRepoRoot", cancellationToken: cancellationToken); + + // '.github/' outranks 'package.json' in the list, but only '.git/' is allowed to win from a + // distance. Were that not so, a stray '.claude/' or '.github/' in a developer's home + // directory would outrank the real repository root and scatter a lockfile outside it. + Directory.CreateDirectory(Path.Combine(harness.SolutionDirectory, ".github")); + await File.WriteAllTextAsync( + Path.Combine(harness.ProjectDirectory, "package.json"), + /*lang=json,strict*/"{ \"name\": \"nested\" }\n", + cancellationToken + ); + + var resolved = await ResolveRepositoryRootAsync(harness, string.Empty, cancellationToken); + + await Assert + .That(Path.GetFullPath(resolved)) + .IsEqualTo(Path.GetFullPath(harness.ProjectDirectory)) + .Because("the nearest marker wins once the definitive one is absent"); + } + + [Test] + public async Task RepositoryRoot_BreaksTiesWithinADirectoryByListOrder(CancellationToken cancellationToken) + { + using var harness = await ProjectHarness.CreateAsync("SkillRepoRoot", cancellationToken: cancellationToken); + + // Both markers sit in the same directory, so the list order decides which one is reported. + await File.WriteAllTextAsync(Path.Combine(harness.SolutionDirectory, "LICENSE.md"), "MIT\n", cancellationToken); + await File.WriteAllTextAsync( + Path.Combine(harness.SolutionDirectory, "package.json"), + /*lang=json,strict*/"{ \"name\": \"root\" }\n", + cancellationToken + ); + + var (exitCode, stdOut, stdErr) = await harness.RunMSBuildAsync( + "-t:ResolvePurviewSkillsRepositoryRoot -getProperty:_PurviewSkillsRepositoryRootMarker", + cancellationToken + ); + + await Assert.That(exitCode).IsZero().Because(TestHelpers.GenerateError(stdOut, stdErr)); + await Assert.That(stdOut.Trim()).IsEqualTo("LICENSE.md"); + } + + [Test] + public async Task RepositoryRoot_FallsThroughWhenTheLeadingMarkersAreAbsent(CancellationToken cancellationToken) + { + using var harness = await ProjectHarness.CreateAsync("SkillRepoRoot", cancellationToken: cancellationToken); + + // Nothing above '.claude/' exists, so the walk has to keep going down the list rather than + // stopping at the first marker it cannot find. + Directory.CreateDirectory(Path.Combine(harness.SolutionDirectory, ".claude")); + + var resolved = await ResolveRepositoryRootAsync(harness, string.Empty, cancellationToken); + + await Assert.That(Path.GetFullPath(resolved)).IsEqualTo(Path.GetFullPath(harness.SolutionDirectory)); + } + + [Test] + public async Task RepositoryRootMarkers_CanBeReplaced(CancellationToken cancellationToken) + { + using var harness = await ProjectHarness.CreateAsync("SkillRepoRoot", cancellationToken: cancellationToken); + + await File.WriteAllTextAsync( + Path.Combine(harness.SolutionDirectory, "my-repo-marker"), + "marker\n", + cancellationToken + ); + + var resolved = await ResolveRepositoryRootAsync( + harness, + "-p:PurviewRepositoryRootMarkers=my-repo-marker", + cancellationToken + ); + + await Assert.That(Path.GetFullPath(resolved)).IsEqualTo(Path.GetFullPath(harness.SolutionDirectory)); + } + + [Test] + public async Task RepositoryRoot_IsFoundFromAnAgentsMarkerAboveTheProject(CancellationToken cancellationToken) + { + using var harness = await ProjectHarness.CreateAsync("SkillRepoRoot", cancellationToken: cancellationToken); + + // The marker sits beside the solution, a level above the project, which is exactly the shape + // the walk-up exists for: skills belong to the repository, not to whichever project built. + await File.WriteAllTextAsync( + Path.Combine(harness.SolutionDirectory, "AGENTS.md"), + "# Test repository\n", + cancellationToken + ); + + var resolved = await ResolveRepositoryRootAsync(harness, string.Empty, cancellationToken); + + await Assert.That(resolved).IsNotEmpty(); + await Assert.That(Path.GetFullPath(resolved)).IsEqualTo(Path.GetFullPath(harness.SolutionDirectory)); + // Never the project folder - that is the scattering this prevents. + await Assert.That(Path.GetFullPath(resolved)).IsNotEqualTo(Path.GetFullPath(harness.ProjectDirectory)); + } + + [Test] + public async Task RepositoryRoot_PrefersAnExplicitInstallRoot(CancellationToken cancellationToken) + { + using var harness = await ProjectHarness.CreateAsync("SkillRepoRoot", cancellationToken: cancellationToken); + + await File.WriteAllTextAsync( + Path.Combine(harness.SolutionDirectory, "AGENTS.md"), + "# Test repository\n", + cancellationToken + ); + + var elsewhere = Path.Combine(harness.SolutionDirectory, "elsewhere"); + Directory.CreateDirectory(elsewhere); + + var resolved = await ResolveRepositoryRootAsync( + harness, + $"-p:PurviewSkillsInstallRoot=\"{elsewhere}\"", + cancellationToken + ); + + await Assert.That(Path.GetFullPath(resolved)).IsEqualTo(Path.GetFullPath(elsewhere)); + } +} diff --git a/src/tests/BuildSdk.IntegrationTests/RepositorySkillTests.cs b/src/tests/BuildSdk.IntegrationTests/RepositorySkillTests.cs index 171ffa0..ac2066b 100644 --- a/src/tests/BuildSdk.IntegrationTests/RepositorySkillTests.cs +++ b/src/tests/BuildSdk.IntegrationTests/RepositorySkillTests.cs @@ -14,7 +14,7 @@ namespace Purview.BuildSdk; /// /// There is no RepositoryRoot override, deliberately: the default is /// 's marker walk, so an ordinary test run exercises the same -/// resolution InstallPurviewSkills uses. If the walk regressed, this class would validate +/// resolution ValidatePurviewSkills uses. If the walk regressed, this class would validate /// the wrong folder - or none - and SkillsFolder_ResolvesToThisRepository is what catches it. /// /// diff --git a/src/tests/BuildSdk.IntegrationTests/SkillLockFileFixtures.cs b/src/tests/BuildSdk.IntegrationTests/SkillLockFileFixtures.cs index c048099..546aaac 100644 --- a/src/tests/BuildSdk.IntegrationTests/SkillLockFileFixtures.cs +++ b/src/tests/BuildSdk.IntegrationTests/SkillLockFileFixtures.cs @@ -1,8 +1,8 @@ namespace Purview.BuildSdk; /// -/// Writes the skills CLI's own skills-lock.json directly, so the skill target tests stay offline -/// and need no Node tooling. +/// Writes the skills CLI's own skills-lock.json directly, so the skills script tests stay offline +/// and never run the CLI. /// static class SkillLockFileFixtures { diff --git a/src/tests/BuildSdk.IntegrationTests/SkillRepositoryRootParityTests.cs b/src/tests/BuildSdk.IntegrationTests/SkillRepositoryRootParityTests.cs index ee413ce..b77436a 100644 --- a/src/tests/BuildSdk.IntegrationTests/SkillRepositoryRootParityTests.cs +++ b/src/tests/BuildSdk.IntegrationTests/SkillRepositoryRootParityTests.cs @@ -24,7 +24,7 @@ namespace Purview.BuildSdk; /// public class SkillRepositoryRootParityTests { - /// Asks MSBuild for the root the skill targets would run from. + /// Asks MSBuild for the root ValidatePurviewSkills would validate. /// The throwaway project. /// The cancellation token. /// The resolved root. diff --git a/src/tests/BuildSdk.IntegrationTests/SkillsScriptTests.cs b/src/tests/BuildSdk.IntegrationTests/SkillsScriptTests.cs new file mode 100644 index 0000000..fffc2ba --- /dev/null +++ b/src/tests/BuildSdk.IntegrationTests/SkillsScriptTests.cs @@ -0,0 +1,663 @@ +using System.ComponentModel; +using Purview.BuildSdk.Infra; + +namespace Purview.BuildSdk; + +/// +/// Verifies skills.mts and its generated skills.mjs, the script the +/// purview-buildsdk-justfile skill's skills-* recipes run to install, update, check and +/// fix agent skills without MSBuild. +/// +/// +/// +/// Every behaviour test runs once per runtime the recipes can choose: Node with the generated +/// skills.mjs, and Bun and Deno with the skills.mts source. A runtime that is not on +/// PATH is skipped, not failed; CI always has Node. +/// +/// +/// echo stands in for the skills CLI, and the script prints every command before it runs it, so a +/// test asserts on the command without a network, a download or a real install. Never let a test reach +/// bun x or npx. +/// +/// +sealed class SkillsScriptTests +{ + const string PurviewSource = "purview-dev/build-sdk"; + const string OtherSource = "vercel-labs/agent-skills"; + const string OldCommit = "aaaaaaaabbbbbbbbccccccccddddddddeeeeeeee"; + + public static IEnumerable Runtimes() => ["node", "bun", "deno"]; + + static string RepositoryRoot + { + get + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + while (directory is not null) + { + if (File.Exists(Path.Combine(directory.FullName, "AGENTS.md"))) + return directory.FullName; + + directory = directory.Parent; + } + + throw new InvalidOperationException($"No AGENTS.md was found above '{AppContext.BaseDirectory}'."); + } + } + + static string ScriptFolder => Path.Combine(RepositoryRoot, "skills", "purview-buildsdk-justfile", "assets", "just"); + + /// A throwaway repository root under the temporary folder, deleted afterwards. + sealed class TempRoot : IDisposable + { + public string Path { get; } = + System.IO.Path.Combine(System.IO.Path.GetTempPath(), "purview-skills-" + Guid.NewGuid().ToString("N")); + + public TempRoot() => Directory.CreateDirectory(Path); + + public string Combine(params string[] parts) => System.IO.Path.Combine([Path, .. parts]); + + public void Dispose() + { + try + { + Directory.Delete(Path, recursive: true); + } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + } + } + + static async Task<(int Code, string Output)> RunAsync( + string runtime, + TempRoot root, + string arguments, + IReadOnlyDictionary? environment = null, + CancellationToken cancellationToken = default + ) + { + var (fileName, script) = runtime switch + { + "node" => ("node", $"\"{Path.Combine(ScriptFolder, "skills.mjs")}\""), + "bun" => ("bun", $"\"{Path.Combine(ScriptFolder, "skills.mts")}\""), + "deno" => ("deno", $"run -A \"{Path.Combine(ScriptFolder, "skills.mts")}\""), + _ => throw new ArgumentOutOfRangeException(nameof(runtime), runtime, null), + }; + + try + { + var (code, stdOut, stdErr) = await ProcessRunner.RunWithEnvironmentAsync( + fileName, + $"{script} {arguments} --root \"{root.Path}\"", + root.Path, + environment, + cancellationToken + ); + + return (code, stdOut + stdErr); + } + catch (Win32Exception exception) + { + Skip.Test($"{fileName} is not on PATH: {exception.Message}"); + return default; + } + } + + /// One skill pinned at an old ref, plus two skills from a second repository. + static void GivenInstalledSkills(TempRoot root) => + SkillLockFileFixtures.WriteLockFile( + root.Combine("skills-lock.json"), + ("purview-buildsdk-testing", PurviewSource, OldCommit), + ("web-design", OtherSource, null), + ("frontend-design", OtherSource, null) + ); + + static void GivenConfig(TempRoot root, string json) + { + Directory.CreateDirectory(root.Combine(".config")); + File.WriteAllText(root.Combine(".config", "purview-build-sdk.json"), json); + } + + // An empty PATH stands in for a machine with no package runner, whatever this one has installed. + static readonly Dictionary NoRunners = new() { ["PATH"] = string.Empty }; + + [Test] + [MethodDataSource(nameof(Runtimes))] + public async Task Add_PassesTheSourceVerbatim_WithEverySkill_AndOneFlagPerAgent( + string runtime, + CancellationToken cancellationToken + ) + { + using var root = new TempRoot(); + + var (code, output) = await RunAsync( + runtime, + root, + "add purview-dev/engineering-playbook#abc123 --command echo --agents claude-code,codex", + cancellationToken: cancellationToken + ); + + await Assert.That(code).IsZero().Because(output); + // The CLI does not split a comma-separated --agent, so each agent is its own flag. + await Assert + .That(output) + .Contains( + "Agent skills: echo add \"purview-dev/engineering-playbook#abc123\" --skill \"*\" --agent \"claude-code\" --agent \"codex\" -y" + ); + } + + [Test] + [MethodDataSource(nameof(Runtimes))] + public async Task Install_WithoutAgents_LetsTheCliAutoDetect(string runtime, CancellationToken cancellationToken) + { + using var root = new TempRoot(); + + var (code, output) = await RunAsync( + runtime, + root, + $"install {PurviewSource} --command echo", + cancellationToken: cancellationToken + ); + + await Assert.That(code).IsZero().Because(output); + await Assert.That(output).Contains("--skill \"*\" -y"); + await Assert.That(output).DoesNotContain("--agent"); + } + + [Test] + [MethodDataSource(nameof(Runtimes))] + public async Task Install_WithoutASource_RestoresTheLockFile(string runtime, CancellationToken cancellationToken) + { + using var root = new TempRoot(); + GivenInstalledSkills(root); + + var (code, output) = await RunAsync( + runtime, + root, + "install --command echo", + cancellationToken: cancellationToken + ); + + await Assert.That(code).IsZero().Because(output); + await Assert.That(output).Contains("Agent skills: echo experimental_install"); + await Assert.That(output).DoesNotContain(" add "); + } + + [Test] + [MethodDataSource(nameof(Runtimes))] + public async Task Install_WithoutASourceOrALockFile_SaysWhatToDo( + string runtime, + CancellationToken cancellationToken + ) + { + using var root = new TempRoot(); + + var (code, output) = await RunAsync( + runtime, + root, + "install --command echo", + cancellationToken: cancellationToken + ); + + await Assert.That(code).IsNotEqualTo(0); + await Assert.That(output).Contains("PRSKL0007"); + await Assert.That(output).Contains("just skills-add"); + } + + /// + /// Every package runner spells "run this npm package" its own way, so each must map to the launcher + /// verified against the real tool. A wrong mapping is a command that does not run. + /// + [Test] + [Arguments("npx", "npx -y skills@1")] + [Arguments("bunx", "bunx skills@1")] + [Arguments("bun", "bun x skills@1")] + [Arguments("pnpm", "pnpm dlx skills@1")] + [Arguments("yarn", "yarn dlx skills@1")] + [Arguments("deno", "deno run -A npm:skills@1")] + [Arguments("skills", "skills")] + // A runner this script has never heard of still resolves, rather than being dropped. + [Arguments("future-runner", "future-runner skills@1")] + public async Task Runner_DrivesTheLauncher( + string runner, + string expectedLauncher, + CancellationToken cancellationToken + ) + { + using var root = new TempRoot(); + + var (code, output) = await RunAsync( + "node", + root, + $"add {PurviewSource} --dry-run --runner {runner}", + NoRunners, + cancellationToken + ); + + await Assert.That(code).IsZero().Because(output); + await Assert.That(output).Contains($"Agent skills (dry run): {expectedLauncher} add \"{PurviewSource}\""); + } + + [Test] + [MethodDataSource(nameof(Runtimes))] + public async Task Runner_DefaultsToBun_AndThePackageToTheFirstMajor( + string runtime, + CancellationToken cancellationToken + ) + { + using var root = new TempRoot(); + + var (code, output) = await RunAsync( + runtime, + root, + $"add {PurviewSource} --dry-run", + NoRunners, + cancellationToken + ); + + await Assert.That(code).IsZero().Because(output); + await Assert.That(output).Contains($"Agent skills (dry run): bun x skills@1 add \"{PurviewSource}\""); + } + + [Test] + [MethodDataSource(nameof(Runtimes))] + public async Task WithoutARunnerOnPath_ReportsHowToInstallOne(string runtime, CancellationToken cancellationToken) + { + using var root = new TempRoot(); + + var (code, output) = await RunAsync(runtime, root, $"add {PurviewSource}", NoRunners, cancellationToken); + + // It fails, but with a diagnostic that names the fix rather than a raw shell error. + await Assert.That(code).IsNotEqualTo(0); + await Assert.That(output).Contains("PRSKL0004"); + await Assert.That(output).Contains("npm install -g skills"); + } + + [Test] + [MethodDataSource(nameof(Runtimes))] + public async Task Update_ReAddsEachSource_AtItsLatest_WithEverySkill( + string runtime, + CancellationToken cancellationToken + ) + { + using var root = new TempRoot(); + GivenInstalledSkills(root); + + var (code, output) = await RunAsync( + runtime, + root, + "update --command echo", + cancellationToken: cancellationToken + ); + + await Assert.That(code).IsZero().Because(output); + // Each unique source once, unpinned, with every skill it has - so a skill the source has gained + // comes in too, and the old ref is not kept. + await Assert.That(output).Contains($"echo add \"{PurviewSource}\" --skill \"*\" -y"); + await Assert.That(output).Contains($"echo add \"{OtherSource}\" --skill \"*\" -y"); + await Assert.That(output).DoesNotContain("--skill \"web-design\""); + await Assert.That(output).DoesNotContain(OldCommit); + await Assert.That(output).Contains("2 source(s) refreshed."); + // The re-adds are the whole update; 'skills update' is never run. + await Assert.That(output).DoesNotContain("echo update"); + } + + [Test] + [MethodDataSource(nameof(Runtimes))] + public async Task Update_DryRun_RunsNothing(string runtime, CancellationToken cancellationToken) + { + using var root = new TempRoot(); + GivenInstalledSkills(root); + + // A command that cannot run proves nothing was executed. + var (code, output) = await RunAsync( + runtime, + root, + "update --command purview-no-such-command --dry-run", + cancellationToken: cancellationToken + ); + + await Assert.That(code).IsZero().Because(output); + await Assert.That(output).Contains($"purview-no-such-command add \"{OtherSource}\""); + await Assert.That(output).Contains("dry run, 2 source(s), nothing changed"); + } + + [Test] + [MethodDataSource(nameof(Runtimes))] + public async Task Update_EveryFailedSource_IsNamed(string runtime, CancellationToken cancellationToken) + { + using var root = new TempRoot(); + GivenInstalledSkills(root); + + // 'dotnet ' exits non-zero on every platform without touching the network. + var (code, output) = await RunAsync( + runtime, + root, + "update --command \"dotnet purview-no-such-command\"", + cancellationToken: cancellationToken + ); + + await Assert.That(code).IsNotEqualTo(0); + await Assert.That(output).Contains("PRSKL0008"); + await Assert.That(output).Contains($"re-adding '{OtherSource}' failed"); + await Assert.That(output).Contains($"re-adding '{PurviewSource}' failed"); + await Assert.That(output).DoesNotContain("source(s) refreshed."); + } + + [Test] + [MethodDataSource(nameof(Runtimes))] + public async Task Update_WithoutALockFile_ReportsHowToInstall(string runtime, CancellationToken cancellationToken) + { + using var root = new TempRoot(); + + var (code, output) = await RunAsync( + runtime, + root, + "update --command echo", + cancellationToken: cancellationToken + ); + + await Assert.That(code).IsNotEqualTo(0); + await Assert.That(output).Contains("PRSKL0007"); + await Assert.That(output).Contains("just skills-add"); + } + + [Test] + [MethodDataSource(nameof(Runtimes))] + public async Task Check_WithoutAgents_EnforcesNothing(string runtime, CancellationToken cancellationToken) + { + using var root = new TempRoot(); + Directory.CreateDirectory(root.Combine(".claude", "skills", "purview-alpha")); + + var (code, output) = await RunAsync(runtime, root, "check", cancellationToken: cancellationToken); + + // The CLI auto-detects agents, so an agent directory is expected, not a violation. + await Assert.That(code).IsZero().Because(output); + await Assert.That(output).Contains("no agents are selected"); + await Assert.That(output).DoesNotContain("PRSKL0015"); + } + + [Test] + [MethodDataSource(nameof(Runtimes))] + public async Task Check_WithAgents_ReportsOnlyUnselectedAgentDirectories( + string runtime, + CancellationToken cancellationToken + ) + { + using var root = new TempRoot(); + Directory.CreateDirectory(root.Combine(".agents", "skills", "purview-alpha")); + Directory.CreateDirectory(root.Combine(".claude", "skills", "purview-alpha")); + Directory.CreateDirectory(root.Combine(".windsurf", "skills", "purview-alpha")); + // The authored folder, which openclaw would also install into, is never a violation. + Directory.CreateDirectory(root.Combine("skills", "my-skill")); + + var (code, output) = await RunAsync( + runtime, + root, + "check --agents claude-code", + cancellationToken: cancellationToken + ); + + await Assert.That(code).IsNotEqualTo(0); + await Assert.That(output).Contains("PRSKL0015"); + await Assert.That(output).Contains("'.windsurf/skills'"); + // '.agents/skills' is the canonical store, and claude-code was selected. + await Assert.That(output).DoesNotContain("'.agents/skills'"); + await Assert.That(output).DoesNotContain("'.claude/skills'"); + await Assert.That(output).DoesNotContain("'skills'"); + // Check is read-only. + await Assert.That(Directory.Exists(root.Combine(".windsurf", "skills"))).IsTrue(); + } + + [Test] + [MethodDataSource(nameof(Runtimes))] + public async Task Check_UnknownAgent_IsAWarning(string runtime, CancellationToken cancellationToken) + { + using var root = new TempRoot(); + + var (code, output) = await RunAsync( + runtime, + root, + "check --agents universal,purview-imaginary", + cancellationToken: cancellationToken + ); + + await Assert.That(code).IsZero().Because(output); + await Assert.That(output).Contains("PRSKL0016"); + await Assert.That(output).Contains("purview-imaginary"); + } + + [Test] + [MethodDataSource(nameof(Runtimes))] + public async Task Fix_RemovesEmptyAgentDirectories_AndKeepsRealContent( + string runtime, + CancellationToken cancellationToken + ) + { + using var root = new TempRoot(); + // Emptied of links already: nothing real left, so the folder - and its now-empty parent - go. + Directory.CreateDirectory(root.Combine(".windsurf", "skills", "purview-alpha")); + // Real content beside the skills folder is not the CLI's, and neither is a real file inside it. + Directory.CreateDirectory(root.Combine(".claude", "skills", "hand-written")); + await File.WriteAllTextAsync(root.Combine(".claude", "settings.json"), "{}", cancellationToken); + await File.WriteAllTextAsync( + root.Combine(".claude", "skills", "hand-written", "SKILL.md"), + "---\nname: hand-written\n---\n", + cancellationToken + ); + + var (code, output) = await RunAsync( + runtime, + root, + "fix --agents universal", + cancellationToken: cancellationToken + ); + + await Assert.That(Directory.Exists(root.Combine(".windsurf"))).IsFalse().Because(output); + await Assert.That(File.Exists(root.Combine(".claude", "settings.json"))).IsTrue(); + await Assert.That(File.Exists(root.Combine(".claude", "skills", "hand-written", "SKILL.md"))).IsTrue(); + // What could not be removed fails the command and names what was kept. + await Assert.That(code).IsNotEqualTo(0); + await Assert.That(output).Contains("PRSKL0015"); + await Assert.That(output).Contains(".claude/skills/hand-written/SKILL.md"); + } + + /// + /// just skills-update --dry-run hands --dry-run to fix as well, so a dry-run fix must + /// only say what it would remove. + /// + [Test] + [MethodDataSource(nameof(Runtimes))] + public async Task Fix_DryRun_RemovesNothing(string runtime, CancellationToken cancellationToken) + { + using var root = new TempRoot(); + Directory.CreateDirectory(root.Combine(".windsurf", "skills", "purview-alpha")); + + var (code, output) = await RunAsync( + runtime, + root, + "fix --agents universal --dry-run", + cancellationToken: cancellationToken + ); + + await Assert.That(code).IsZero().Because(output); + await Assert.That(Directory.Exists(root.Combine(".windsurf", "skills", "purview-alpha"))).IsTrue(); + await Assert.That(output).Contains("would remove the skills CLI's links from '.windsurf/skills'"); + await Assert.That(output).Contains("dry run, nothing removed"); + } + + [Test] + [MethodDataSource(nameof(Runtimes))] + public async Task Fix_RemovesLinks_NeverTheirTargets(string runtime, CancellationToken cancellationToken) + { + using var root = new TempRoot(); + var canonical = root.Combine(".agents", "skills", "purview-alpha"); + Directory.CreateDirectory(canonical); + await File.WriteAllTextAsync( + Path.Combine(canonical, "SKILL.md"), + "---\nname: purview-alpha\n---\n", + cancellationToken + ); + Directory.CreateDirectory(root.Combine(".claude", "skills")); + + try + { + Directory.CreateSymbolicLink(root.Combine(".claude", "skills", "purview-alpha"), canonical); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // Windows only allows symlinks with Developer Mode or elevation; CI on Linux always runs this. + Skip.Test($"Symbolic links cannot be created here: {exception.Message}"); + } + + var (code, output) = await RunAsync( + runtime, + root, + "fix --agents universal", + cancellationToken: cancellationToken + ); + + await Assert.That(code).IsZero().Because(output); + await Assert.That(Directory.Exists(root.Combine(".claude", "skills"))).IsFalse(); + // The canonical copy the link pointed at is untouched. + await Assert.That(File.Exists(Path.Combine(canonical, "SKILL.md"))).IsTrue(); + await Assert.That(output).Contains("removed .claude/skills/purview-alpha"); + } + + [Test] + [MethodDataSource(nameof(Runtimes))] + public async Task Config_SuppliesTheSettings(string runtime, CancellationToken cancellationToken) + { + using var root = new TempRoot(); + GivenConfig( + root, + /*lang=json,strict*/"""{ "Skills": { "Agents": ["claude-code", "codex"], "Command": "echo" } }""" + ); + + var (code, output) = await RunAsync( + runtime, + root, + $"add {PurviewSource}", + cancellationToken: cancellationToken + ); + + await Assert.That(code).IsZero().Because(output); + await Assert + .That(output) + .Contains($"echo add \"{PurviewSource}\" --skill \"*\" --agent \"claude-code\" --agent \"codex\" -y"); + } + + [Test] + [MethodDataSource(nameof(Runtimes))] + public async Task Options_OutrankTheEnvironment_WhichOutranksTheConfig( + string runtime, + CancellationToken cancellationToken + ) + { + using var root = new TempRoot(); + GivenConfig( + root, /*lang=json,strict*/ + """{ "Skills": { "Agents": "from-config", "Command": "echo" } }""" + ); + var environment = new Dictionary { ["PURVIEW_SKILLS_AGENTS"] = "from-environment" }; + + var (_, fromEnvironment) = await RunAsync( + runtime, + root, + $"add {PurviewSource}", + environment, + cancellationToken + ); + var (_, fromOption) = await RunAsync( + runtime, + root, + $"add {PurviewSource} --agents from-option", + environment, + cancellationToken + ); + + await Assert.That(fromEnvironment).Contains("--agent \"from-environment\""); + await Assert.That(fromEnvironment).DoesNotContain("from-config"); + await Assert.That(fromOption).Contains("--agent \"from-option\""); + await Assert.That(fromOption).DoesNotContain("from-environment\""); + } + + [Test] + [MethodDataSource(nameof(Runtimes))] + public async Task Config_AgentDirectories_ExtendTheKnownTable(string runtime, CancellationToken cancellationToken) + { + using var root = new TempRoot(); + GivenConfig( + root, + /*lang=json,strict*/"""{ "Skills": { "Agents": "new-agent", "AgentDirectories": { ".new-agent/skills": ["new-agent"] } } }""" + ); + Directory.CreateDirectory(root.Combine(".new-agent", "skills", "purview-alpha")); + + var (code, output) = await RunAsync(runtime, root, "check", cancellationToken: cancellationToken); + + await Assert.That(code).IsZero().Because(output); + await Assert.That(output).DoesNotContain("PRSKL0016"); + await Assert.That(output).DoesNotContain("PRSKL0015"); + } + + [Test] + [MethodDataSource(nameof(Runtimes))] + public async Task Config_InvalidJson_IsAnError(string runtime, CancellationToken cancellationToken) + { + using var root = new TempRoot(); + GivenConfig(root, "{ \"Skills\": "); + + var (code, output) = await RunAsync(runtime, root, "check", cancellationToken: cancellationToken); + + await Assert.That(code).IsNotEqualTo(0); + await Assert.That(output).Contains("PRSKL0018"); + } + + [Test] + [MethodDataSource(nameof(Runtimes))] + public async Task Config_UnknownSetting_IsAWarning(string runtime, CancellationToken cancellationToken) + { + using var root = new TempRoot(); + GivenConfig( + root, /*lang=json,strict*/ + """{ "Skills": { "Agent": "claude-code" } }""" + ); + + var (code, output) = await RunAsync(runtime, root, "check", cancellationToken: cancellationToken); + + // A misspelt key would otherwise be silently ignored. + await Assert.That(code).IsZero().Because(output); + await Assert.That(output).Contains("PRSKL0019"); + await Assert.That(output).Contains("Skills.Agent"); + } + + /// + /// skills.mjs is generated from skills.mts. A hand edit to either, or an edit to skills.mts that was + /// not regenerated, would leave Node running different code from Bun and Deno. + /// + [Test] + public async Task GeneratedJavaScript_MatchesTheTypeScriptSource(CancellationToken cancellationToken) + { + (int Code, string StdOut, string StdErr) result; + try + { + result = await ProcessRunner.RunAsync( + "node", + $"\"{Path.Combine(RepositoryRoot, "scripts", "sync-skills-script.mjs")}\" --check", + RepositoryRoot, + cancellationToken + ); + } + catch (Win32Exception exception) + { + Skip.Test($"node is not on PATH: {exception.Message}"); + return; + } + + // Exit 3: this Node has no type stripper (before 22.13), so it cannot tell. + if (result.Code == 3) + Skip.Test(result.StdErr.Trim()); + + await Assert.That(result.Code).IsZero().Because(result.StdOut + result.StdErr); + } +} diff --git a/templates/global.json b/templates/global.json index e93611f..09220e8 100644 --- a/templates/global.json +++ b/templates/global.json @@ -3,6 +3,6 @@ "runner": "Microsoft.Testing.Platform" }, "msbuild-sdks": { - "Purview.BuildSdk": "2.1.0" + "Purview.BuildSdk": "2.2.0" } }