diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 80683e6..27535f9 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "opencode-power-pack", - "version": "0.3.0", + "version": "0.4.0", "description": "Fifty-five Claude Code workflows packaged for Codex, OpenCode, and Pi.", "author": { "name": "Wayner Barrios", diff --git a/README.md b/README.md index 32b6d0a..3b73430 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,7 @@

Install · + Select Skills · Codex Quick Install · Pi Quick Install · Skills · @@ -51,6 +52,45 @@ Pi discovers the fifty-five skills declared by the package. Use `pi list` to ver pi install git:github.com/waybarrios/opencode-power-pack -l ``` +## Selective Install With npm + +Install only the workflows you want into the shared `.agents/skills` location recognized by Codex, OpenCode, and Pi: + +```bash +# Inspect every profile and skill +npx opencode-power-pack list + +# Install the balanced recommended profile for your user +npx opencode-power-pack install --profile recommended + +# Install individual skills +npx opencode-power-pack install code-review security-review + +# Install a profile only for the current repository +npx opencode-power-pack install --profile review --project + +# Preview a selection without writing anything +npx opencode-power-pack install --profile security --dry-run + +# Update previously copied skills from the latest package +npx opencode-power-pack@latest install --profile review --force +``` + +| Profile | Intended use | +|---|---| +| `recommended` | Balanced software development without the specialized security and ML catalogs | +| `review` | Comprehensive and focused code review plus quality and differential review | +| `feature-dev` | End-to-end feature workflow with its explorer, architect, and reviewer dependencies | +| `frontend` | Frontend implementation and anti-generic design critique | +| `security` | Security review, threat modeling, static analysis, validation, and reporting | +| `huggingface` | Model discovery, local inference, training, evaluation, Spaces, and AWS deployment | +| `authoring` | Skill and MCP authoring plus technical-paper summarization | +| `project-memory` | Audit and maintain durable project guidance | + +Profiles automatically include required companion skills and can be combined with individual skill names. The default destination is `~/.agents/skills`; `--project` finds the current Git root and installs into its `.agents/skills` directory. Existing directories are skipped unless `--force` is provided, and replacements are staged with rollback plus per-skill locking. Every copied skill retains its provenance, third-party notices, and license texts. Use `--dry-run` to preview or `--all` to install the complete catalog. + +The npm installer and the full Codex/OpenCode plugin are alternative activation paths. If the full plugin is already active, selectively copying the same skills does not reduce that plugin's loaded catalog. + ## Why This Exists Codex, OpenCode, and Pi read `SKILL.md` workflows, but many valuable Claude Code workflows originated as Claude-specific commands and agents. Copying those artifacts directly does not preserve their orchestration, permissions, or subagent behavior. @@ -121,11 +161,22 @@ It complements [obra/superpowers](https://github.com/obra/superpowers), which pr `code-explorer`, `code-architect`, and `code-reviewer` are standalone skills and specialist roles used by `feature-dev`. OpenCode registers named least-privilege agents; Codex can carry out the same assignments with native subagents and can use matching custom agents when the user configures them. +### Which Code Review Skill? + +| Situation | Use | Why | +|---|---|---| +| PR, branch, commit range, or complete pending diff | `code-review` (Comprehensive Code Review) | Freezes the scope, runs multiple review lenses, cross-checks candidates, and can post validated findings to GitHub when requested | +| One file, function, or small local change | `code-reviewer` (Focused Code Review) | Uses a lighter two-pass review with full-file and caller context | +| `feature-dev` quality phase | `code-reviewer` (Focused Code Review) | Acts as the focused specialist role dispatched by the feature workflow | + +They are complementary rather than duplicate workflows. Codex shows the distinct user-facing titles above, while the stable skill IDs continue to work across Codex, OpenCode, and Pi. Start with `code-review` for merge decisions and `code-reviewer` for focused iteration. + ## Installation ### Prerequisites - Git +- Node.js 20 or newer, including npm/npx, for [selective installation](#selective-install-with-npm) - One supported host: - OpenCode 1.18.7 or newer: - A current Codex CLI or Codex desktop environment with plugin support: @@ -143,6 +194,8 @@ codex plugin list --marketplace opencode-power-pack Start a new Codex session after installation so the fifty-five bundled skills are loaded. Use `/plugins` to inspect the installed plugin or `$` to select one of its skills explicitly. Codex plugin packaging follows the [official plugin structure](https://developers.openai.com/plugins/build/plugins). +For a smaller personal or repository-specific set, use the [selective npm installer](#selective-install-with-npm) instead of the full plugin. + ### OpenCode From GitHub ```bash @@ -174,6 +227,8 @@ pi install git:github.com/waybarrios/opencode-power-pack Pi installs the Git package and loads the `skills/` directory declared in `package.json`. Use `-l` to save it to project settings instead of user settings. See the [Pi package documentation](https://pi.dev/docs/latest/packages) for source, update, filtering, and trust behavior. +Pi can also narrow an installed package through `pi config`. The npm installer is useful when you want the same selected set to be discovered by Pi, Codex, and OpenCode from `.agents/skills`. + ### Verify OpenCode ```bash diff --git a/bin/opencode-power-pack.mjs b/bin/opencode-power-pack.mjs new file mode 100755 index 0000000..5246df0 --- /dev/null +++ b/bin/opencode-power-pack.mjs @@ -0,0 +1,379 @@ +#!/usr/bin/env node + +import { randomUUID } from "node:crypto"; +import { realpathSync } from "node:fs"; +import { + cp, + lstat, + mkdir, + mkdtemp, + readFile, + readdir, + rename, + rm, +} from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const USAGE = `OpenCode Power Pack selective skill installer + +Usage: + npx opencode-power-pack list + npx opencode-power-pack install [options] + npx opencode-power-pack install --profile [options] + npx opencode-power-pack install --all [options] + +Options: + --profile Install a curated profile. Repeatable. + --all Install every bundled skill. + --project Install into ./.agents/skills for this repository. + --global Install into ~/.agents/skills. This is the default. + --force Replace an existing skill directory with rollback on failure. + --dry-run Show what would change without writing files. + -h, --help Show this help. + +The .agents/skills location is shared by Codex, OpenCode, and Pi.`; + +async function pathExists(target) { + try { + await lstat(target); + return true; + } catch (error) { + if (error?.code === "ENOENT") return false; + throw error; + } +} + +export async function resolveProjectRoot(start) { + let current = path.resolve(start); + while (true) { + if (await pathExists(path.join(current, ".git"))) return current; + const parent = path.dirname(current); + if (parent === current) { + throw new Error("--project requires running inside a Git repository."); + } + current = parent; + } +} + +export async function loadCatalog(packageRoot = PACKAGE_ROOT) { + const source = await readFile(path.join(packageRoot, "skillsets.json"), "utf8"); + return JSON.parse(source); +} + +export async function discoverSkills(packageRoot = PACKAGE_ROOT) { + const skillsRoot = path.join(packageRoot, "skills"); + const entries = await readdir(skillsRoot, { withFileTypes: true }); + const skills = []; + + for (const entry of entries) { + if (!entry.isDirectory()) continue; + const skillFile = path.join(skillsRoot, entry.name, "SKILL.md"); + if (!(await pathExists(skillFile))) continue; + const source = await readFile(skillFile, "utf8"); + const description = source + .match(/^---\r?\n([\s\S]*?)\r?\n---/)?.[1] + .split(/\r?\n/) + .find((line) => line.startsWith("description:")) + ?.slice("description:".length) + .trim() + .replace(/^(["'])(.*)\1$/, "$2"); + skills.push({ name: entry.name, description: description || "" }); + } + + return skills.sort((left, right) => left.name.localeCompare(right.name)); +} + +export function resolveSelection({ skillNames = [], profileNames = [], all = false }, catalog, availableNames) { + const available = new Set(availableNames); + const selected = new Set(all ? availableNames : skillNames); + + for (const profileName of profileNames) { + const profile = catalog.profiles[profileName]; + if (!profile) { + throw new Error(`Unknown profile: ${profileName}`); + } + for (const skillName of profile.skills) selected.add(skillName); + } + + if (selected.size === 0) { + throw new Error("Choose at least one skill, profile, or --all."); + } + + const pending = [...selected]; + while (pending.length > 0) { + const skillName = pending.pop(); + if (!available.has(skillName)) { + throw new Error(`Unknown skill: ${skillName}`); + } + for (const dependency of catalog.dependencies[skillName] || []) { + if (!selected.has(dependency)) { + selected.add(dependency); + pending.push(dependency); + } + } + } + + return [...selected].sort((left, right) => left.localeCompare(right)); +} + +async function replaceDirectoryWithRollback(source, destination, force, packageRoot) { + const parent = path.dirname(destination); + const name = path.basename(destination); + const lock = `${destination}.opp-lock`; + try { + await mkdir(lock); + } catch (error) { + if (error?.code === "EEXIST") { + throw new Error( + `Another installation is updating ${name}. If no installer is running, remove ${lock}.`, + ); + } + throw error; + } + + let stagingRoot; + let staged; + let backup; + let operationError; + const warnings = []; + + try { + stagingRoot = await mkdtemp(path.join(parent, `.opp-${name}-`)); + staged = path.join(stagingRoot, name); + await cp(source, staged, { recursive: true, errorOnExist: true, force: false }); + await cp(path.join(packageRoot, "UPSTREAMS.json"), path.join(staged, "UPSTREAMS.json")); + await cp( + path.join(packageRoot, "THIRD_PARTY_NOTICES.md"), + path.join(staged, "THIRD_PARTY_NOTICES.md"), + ); + await cp(path.join(packageRoot, "LICENSES"), path.join(staged, "LICENSES"), { recursive: true }); + if (force && await pathExists(destination)) { + backup = path.join(parent, `.opp-backup-${name}-${randomUUID()}`); + await rename(destination, backup); + } + + try { + await rename(staged, destination); + } catch (error) { + if (backup && !(await pathExists(destination))) { + try { + await rename(backup, destination); + backup = undefined; + } catch (rollbackError) { + throw new AggregateError( + [error, rollbackError], + [ + `Could not promote ${name} or restore its backup at ${backup}.`, + `Promotion failed: ${error.message}`, + `Rollback failed: ${rollbackError.message}`, + ].join(" "), + ); + } + } + throw error; + } + + if (backup) { + try { + await rm(backup, { recursive: true, force: true }); + } catch (error) { + warnings.push(`Installed ${name}, but could not remove backup ${backup}: ${error.message}`); + } + } + } catch (error) { + operationError = error; + } + + if (stagingRoot) { + try { + await rm(stagingRoot, { recursive: true, force: true }); + } catch (error) { + if (operationError) { + operationError = new AggregateError( + [operationError, error], + `Installation and staging cleanup both failed for ${name}.`, + ); + } else { + warnings.push(`Installed ${name}, but could not remove staging directory ${stagingRoot}: ${error.message}`); + } + } + } + + try { + await rm(lock, { recursive: true, force: true }); + } catch (error) { + if (operationError) { + operationError = new AggregateError( + [operationError, error], + `Installation and lock cleanup both failed for ${name}. Lock: ${lock}`, + ); + } else { + warnings.push(`Installed ${name}, but could not remove lock ${lock}: ${error.message}`); + } + } + + if (operationError) throw operationError; + return warnings; +} + +export async function installSkills({ + skillNames, + destination, + force = false, + dryRun = false, + packageRoot = PACKAGE_ROOT, +}) { + if (!dryRun) await mkdir(destination, { recursive: true }); + const results = []; + + for (const skillName of skillNames) { + const source = path.join(packageRoot, "skills", skillName); + const target = path.join(destination, skillName); + const exists = await pathExists(target); + + if (exists && !force) { + results.push({ name: skillName, status: "skipped" }); + continue; + } + if (dryRun) { + results.push({ name: skillName, status: exists ? "would-update" : "would-install" }); + continue; + } + + const warnings = await replaceDirectoryWithRollback(source, target, force, packageRoot); + results.push({ + name: skillName, + status: exists ? "updated" : "installed", + ...(warnings.length > 0 ? { warnings } : {}), + }); + } + + return results; +} + +function parseInstallArgs(args) { + const options = { + skillNames: [], + profileNames: [], + all: false, + force: false, + dryRun: false, + scope: "global", + }; + let explicitScope; + + for (let index = 0; index < args.length; index += 1) { + const value = args[index]; + if (value === "--profile") { + const profileName = args[index + 1]; + if (!profileName || profileName.startsWith("-")) { + throw new Error("--profile requires a profile name."); + } + options.profileNames.push(profileName); + index += 1; + } else if (value === "--all") { + options.all = true; + } else if (value === "--force") { + options.force = true; + } else if (value === "--dry-run") { + options.dryRun = true; + } else if (value === "--project" || value === "--global") { + const scope = value.slice(2); + if (explicitScope && explicitScope !== scope) { + throw new Error("Choose only one of --project or --global."); + } + explicitScope = scope; + options.scope = scope; + } else if (value === "--help" || value === "-h") { + options.help = true; + } else if (value.startsWith("-")) { + throw new Error(`Unknown option: ${value}`); + } else { + options.skillNames.push(value); + } + } + + return options; +} + +function printCatalog(catalog, skills, write) { + write("Profiles:\n"); + for (const [name, profile] of Object.entries(catalog.profiles)) { + write(` ${name.padEnd(16)} ${profile.description}\n`); + } + write("\nSkills:\n"); + for (const skill of skills) { + write(` ${skill.name.padEnd(42)} ${skill.description}\n`); + } +} + +export async function main(args = process.argv.slice(2), context = {}) { + const write = context.write || ((text) => process.stdout.write(text)); + const cwd = context.cwd || process.cwd(); + const home = context.home || os.homedir(); + const packageRoot = context.packageRoot || PACKAGE_ROOT; + const [command = "help", ...rest] = args; + + if (command === "help" || command === "--help" || command === "-h") { + write(`${USAGE}\n`); + return 0; + } + + const catalog = await loadCatalog(packageRoot); + const skills = await discoverSkills(packageRoot); + + if (command === "list") { + if (rest.length > 0) throw new Error(`Unknown list option: ${rest[0]}`); + printCatalog(catalog, skills, write); + return 0; + } + if (command !== "install") throw new Error(`Unknown command: ${command}`); + + const options = parseInstallArgs(rest); + if (options.help) { + write(`${USAGE}\n`); + return 0; + } + const selected = resolveSelection(options, catalog, skills.map((skill) => skill.name)); + const destination = options.scope === "project" + ? path.join(await resolveProjectRoot(cwd), ".agents", "skills") + : path.join(home, ".agents", "skills"); + const results = await installSkills({ + skillNames: selected, + destination, + force: options.force, + dryRun: options.dryRun, + packageRoot, + }); + + write(`${options.dryRun ? "Plan for" : "Selected"} ${results.length} skill(s) in ${destination}\n`); + for (const result of results) { + write(` ${result.status.padEnd(13)} ${result.name}\n`); + for (const warning of result.warnings || []) write(` warning ${warning}\n`); + } + if (!options.dryRun) { + write("Restart your agent if the new skills do not appear automatically.\n"); + } + return 0; +} + +export function isDirectInvocation(argvEntry, moduleUrl = import.meta.url) { + if (!argvEntry) return false; + try { + return fileURLToPath(moduleUrl) === realpathSync(argvEntry); + } catch { + return false; + } +} + +const invokedDirectly = isDirectInvocation(process.argv[1]); + +if (invokedDirectly) { + main().catch((error) => { + process.stderr.write(`Error: ${error.message}\n`); + process.exitCode = 1; + }); +} diff --git a/package.json b/package.json index 18db857..eea10f4 100644 --- a/package.json +++ b/package.json @@ -1,9 +1,16 @@ { "name": "opencode-power-pack", - "version": "0.3.0", + "version": "0.4.0", "description": "Fifty-five Claude Code workflows packaged for Codex, OpenCode, and Pi: code review, feature development, security review, frontend design, authoring, and project memory.", "type": "module", "main": ".opencode/plugins/opencode-power-pack.js", + "bin": { + "opencode-power-pack": "bin/opencode-power-pack.mjs" + }, + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, "engines": { "node": ">=20", "opencode": ">=1.18.7" @@ -12,13 +19,16 @@ "skills", ".codex-plugin", ".opencode", + "bin", "assets", + "skillsets.json", "UPSTREAMS.json", "THIRD_PARTY_NOTICES.md", "LICENSES" ], "scripts": { "test": "node --test", + "prepublishOnly": "npm test", "eval:behavioral": "node scripts/behavioral-evals.mjs run", "eval:behavioral:accept": "node scripts/behavioral-evals.mjs accept", "smoke:opencode": "node scripts/opencode-smoke.mjs 1.18.7" diff --git a/skills/code-review/agents/openai.yaml b/skills/code-review/agents/openai.yaml new file mode 100644 index 0000000..83da5c5 --- /dev/null +++ b/skills/code-review/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Comprehensive Code Review" + short_description: "Review a PR, branch, range, or complete change set." + default_prompt: "Use $code-review to review the complete change set." diff --git a/skills/code-reviewer/agents/openai.yaml b/skills/code-reviewer/agents/openai.yaml new file mode 100644 index 0000000..e33886f --- /dev/null +++ b/skills/code-reviewer/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Focused Code Review" + short_description: "Review one file, function, or small local change." + default_prompt: "Use $code-reviewer for a focused review of this change." diff --git a/skillsets.json b/skillsets.json new file mode 100644 index 0000000..f51911a --- /dev/null +++ b/skillsets.json @@ -0,0 +1,126 @@ +{ + "schemaVersion": 1, + "profiles": { + "recommended": { + "description": "A balanced software-development toolkit without the specialized security and ML catalogs.", + "skills": [ + "agents-md-improver", + "agents-md-revise", + "code-quality", + "code-review", + "feature-dev", + "frontend-design", + "mcp-builder", + "skill-creator" + ] + }, + "review": { + "description": "General code review, focused review, quality checks, and security-oriented differential review.", + "skills": [ + "code-quality", + "code-review", + "code-reviewer", + "differential-review" + ] + }, + "feature-dev": { + "description": "The end-to-end feature workflow and its explorer, architect, and reviewer specialists.", + "skills": [ + "feature-dev" + ] + }, + "frontend": { + "description": "Frontend implementation and anti-generic design critique.", + "skills": [ + "ai-slop", + "frontend-design" + ] + }, + "security": { + "description": "Security review, threat modeling, static analysis, finding validation, and reporting.", + "skills": [ + "agentic-actions-auditor", + "codeql", + "differential-review", + "fp-check", + "insecure-defaults", + "sarif-parsing", + "security-review", + "security-threat-model", + "semgrep", + "semgrep-rule-creator", + "semgrep-rule-variant-creator", + "sharp-edges", + "supply-chain-risk-auditor", + "variant-analysis", + "vuln-report", + "wooyun-legacy" + ] + }, + "huggingface": { + "description": "Hugging Face discovery, local inference, training, evaluation, Spaces, and AWS deployment workflows.", + "skills": [ + "hf-cli", + "hf-cloud-aws-context-discovery", + "hf-cloud-python-env-setup", + "hf-cloud-sagemaker-deployment-planner", + "hf-cloud-sagemaker-iam-preflight", + "hf-cloud-sagemaker-production-defaults", + "hf-cloud-serving-image-selection", + "hf-mem", + "huggingface-best", + "huggingface-community-evals", + "huggingface-datasets", + "huggingface-gradio", + "huggingface-llm-trainer", + "huggingface-local-models", + "huggingface-lora-space-builder", + "huggingface-paper-publisher", + "huggingface-papers", + "huggingface-spaces", + "huggingface-tool-builder", + "huggingface-trackio", + "huggingface-vision-trainer", + "huggingface-zerogpu", + "train-sentence-transformers", + "transformers-js", + "trl-training" + ] + }, + "authoring": { + "description": "Create reusable skills and MCP servers, and summarize technical papers.", + "skills": [ + "mcp-builder", + "paper-summarizer", + "skill-creator" + ] + }, + "project-memory": { + "description": "Audit and update durable AGENTS.md and CLAUDE.md project guidance.", + "skills": [ + "agents-md-improver", + "agents-md-revise" + ] + } + }, + "dependencies": { + "agents-md-revise": [ + "agents-md-improver" + ], + "feature-dev": [ + "code-architect", + "code-explorer", + "code-reviewer" + ], + "hf-cloud-sagemaker-deployment-planner": [ + "hf-cloud-aws-context-discovery", + "hf-cloud-python-env-setup", + "hf-cloud-sagemaker-iam-preflight", + "hf-cloud-serving-image-selection", + "hf-cloud-sagemaker-production-defaults" + ], + "semgrep-rule-variant-creator": [ + "semgrep-rule-creator" + ] + } +} diff --git a/tests/codex-plugin.test.mjs b/tests/codex-plugin.test.mjs index e2d2be3..ed22d1d 100644 --- a/tests/codex-plugin.test.mjs +++ b/tests/codex-plugin.test.mjs @@ -33,6 +33,23 @@ test("Codex plugin exposes every bundled skill with valid basic frontmatter", () } }); +test("overlapping code review skills have distinct Codex-facing identities", () => { + const comprehensive = readFileSync( + join(REPO, "skills", "code-review", "agents", "openai.yaml"), + "utf8", + ); + const focused = readFileSync( + join(REPO, "skills", "code-reviewer", "agents", "openai.yaml"), + "utf8", + ); + + assert.match(comprehensive, /display_name: "Comprehensive Code Review"/); + assert.match(comprehensive, /default_prompt: "Use \$code-review /); + assert.match(focused, /display_name: "Focused Code Review"/); + assert.match(focused, /default_prompt: "Use \$code-reviewer /); + assert.notEqual(comprehensive, focused); +}); + test("Codex manifest does not declare absent plugin components", () => { assert.equal("apps" in manifest, false); assert.equal("mcpServers" in manifest, false); diff --git a/tests/package-surface.test.mjs b/tests/package-surface.test.mjs index 4a88ec4..8c5a525 100644 --- a/tests/package-surface.test.mjs +++ b/tests/package-surface.test.mjs @@ -1,7 +1,16 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { execFileSync, spawnSync } from "node:child_process"; -import { existsSync, readdirSync } from "node:fs"; +import { + cpSync, + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; const REPO = process.env.REPO || process.cwd(); @@ -29,6 +38,16 @@ test("published package relies on native commands and ships every skill", () => "project-rule resolution matrix is published", ); assert.ok(packaged.has(".codex-plugin/plugin.json"), "Codex plugin manifest is published"); + assert.ok( + packaged.has("skills/code-review/agents/openai.yaml"), + "comprehensive review metadata is published", + ); + assert.ok( + packaged.has("skills/code-reviewer/agents/openai.yaml"), + "focused review metadata is published", + ); + assert.ok(packaged.has("bin/opencode-power-pack.mjs"), "selective installer is published"); + assert.ok(packaged.has("skillsets.json"), "selective profiles are published"); for (const prefix of ["evals/", "scripts/", "tests/", "docs/superpowers/"]) { assert.equal( files.some((file) => file.path.startsWith(prefix)), @@ -39,12 +58,65 @@ test("published package relies on native commands and ships every skill", () => }); test("plugin loads as an ES module without runtime warnings", () => { - const result = spawnSync( - process.execPath, - ["--input-type=module", "--eval", "await import('./.opencode/plugins/opencode-power-pack.js')"], - { cwd: REPO, encoding: "utf8" }, - ); + const packedRoot = mkdtempSync(join(tmpdir(), "opp-package-surface-")); + try { + mkdirSync(join(packedRoot, ".opencode"), { recursive: true }); + cpSync(join(REPO, ".opencode", "plugins"), join(packedRoot, ".opencode", "plugins"), { recursive: true }); + cpSync(join(REPO, "skills"), join(packedRoot, "skills"), { recursive: true }); + writeFileSync(join(packedRoot, "package.json"), '{"type":"module"}\n', "utf8"); - assert.equal(result.status, 0, result.stderr); - assert.equal(result.stderr, ""); + const result = spawnSync( + process.execPath, + ["--input-type=module", "--eval", "await import('./.opencode/plugins/opencode-power-pack.js')"], + { cwd: packedRoot, encoding: "utf8" }, + ); + + assert.equal(result.status, 0, result.stderr); + assert.equal(result.stderr, ""); + } finally { + rmSync(packedRoot, { recursive: true, force: true }); + } +}); + +test("packed npm artifact exposes a working selective-installer executable", () => { + const packedRoot = mkdtempSync(join(tmpdir(), "opp-packed-bin-")); + const installRoot = join(packedRoot, "consumer"); + const npmArtifactEnv = { + ...process.env, + npm_config_dry_run: "false", + npm_config_json: "false", + npm_config_loglevel: "silent", + }; + try { + mkdirSync(installRoot, { recursive: true }); + writeFileSync(join(installRoot, "package.json"), '{"private":true}\n', "utf8"); + const tarballName = execFileSync( + "npm", + ["pack", "--pack-destination", packedRoot], + { + cwd: REPO, + encoding: "utf8", + env: npmArtifactEnv, + }, + ).trim().split(/\r?\n/).at(-1); + const tarball = join(packedRoot, tarballName); + execFileSync( + "npm", + ["install", "--ignore-scripts", "--no-audit", "--no-fund", tarball], + { cwd: installRoot, encoding: "utf8", env: npmArtifactEnv }, + ); + + const executable = join( + installRoot, + "node_modules", + ".bin", + process.platform === "win32" ? "opencode-power-pack.cmd" : "opencode-power-pack", + ); + const output = execFileSync(executable, ["list"], { cwd: installRoot, encoding: "utf8" }); + assert.match(output, /Profiles:/); + assert.match(output, /recommended/); + assert.match(output, /code-review/); + } finally { + rmSync(packedRoot, { recursive: true, force: true }); + } }); diff --git a/tests/selective-installer.test.mjs b/tests/selective-installer.test.mjs new file mode 100644 index 0000000..13e06a5 --- /dev/null +++ b/tests/selective-installer.test.mjs @@ -0,0 +1,249 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + mkdtemp, + mkdir, + readFile, + readdir, + rm, + symlink, + writeFile, +} from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { + discoverSkills, + installSkills, + isDirectInvocation, + loadCatalog, + main, + resolveProjectRoot, + resolveSelection, +} from "../bin/opencode-power-pack.mjs"; + +const REPO = process.env.REPO || process.cwd(); + +async function withTempDir(run) { + const root = await mkdtemp(path.join(os.tmpdir(), "opp-installer-test-")); + try { + return await run(root); + } finally { + await rm(root, { recursive: true, force: true }); + } +} + +test("skill profiles and dependency edges reference packaged skills", async () => { + const catalog = await loadCatalog(REPO); + const skills = await discoverSkills(REPO); + const available = new Set(skills.map((skill) => skill.name)); + + assert.equal(catalog.schemaVersion, 1); + assert.ok(Object.keys(catalog.profiles).length > 0); + for (const profile of Object.values(catalog.profiles)) { + assert.match(profile.description, /\S/); + assert.ok(profile.skills.length > 0); + for (const skillName of profile.skills) assert.ok(available.has(skillName), skillName); + } + for (const [skillName, dependencies] of Object.entries(catalog.dependencies)) { + assert.ok(available.has(skillName), skillName); + for (const dependency of dependencies) assert.ok(available.has(dependency), dependency); + } +}); + +test("selection combines profiles and individual skills and expands dependencies", async () => { + const catalog = await loadCatalog(REPO); + const skills = await discoverSkills(REPO); + const selected = resolveSelection( + { skillNames: ["paper-summarizer"], profileNames: ["feature-dev"] }, + catalog, + skills.map((skill) => skill.name), + ); + + assert.deepEqual(selected, [ + "code-architect", + "code-explorer", + "code-reviewer", + "feature-dev", + "paper-summarizer", + ]); + assert.throws( + () => resolveSelection({ skillNames: ["missing"] }, catalog, skills.map((skill) => skill.name)), + /Unknown skill: missing/, + ); +}); + +test("coordinator selections include every required companion skill", async () => { + const catalog = await loadCatalog(REPO); + const skills = await discoverSkills(REPO); + const available = skills.map((skill) => skill.name); + + assert.deepEqual( + resolveSelection({ skillNames: ["agents-md-revise"] }, catalog, available), + ["agents-md-improver", "agents-md-revise"], + ); + assert.deepEqual( + resolveSelection( + { skillNames: ["hf-cloud-sagemaker-deployment-planner"] }, + catalog, + available, + ), + [ + "hf-cloud-aws-context-discovery", + "hf-cloud-python-env-setup", + "hf-cloud-sagemaker-deployment-planner", + "hf-cloud-sagemaker-iam-preflight", + "hf-cloud-sagemaker-production-defaults", + "hf-cloud-serving-image-selection", + ], + ); +}); + +test("installer copies only selected skills, skips existing skills, and replaces on force", async () => { + await withTempDir(async (root) => { + const destination = path.join(root, ".agents", "skills"); + let results = await installSkills({ + skillNames: ["code-review"], + destination, + packageRoot: REPO, + }); + assert.deepEqual(results, [{ name: "code-review", status: "installed" }]); + assert.match(await readFile(path.join(destination, "code-review", "SKILL.md"), "utf8"), /name: code-review/); + assert.deepEqual(await readdir(destination), ["code-review"]); + assert.match( + await readFile(path.join(destination, "code-review", "UPSTREAMS.json"), "utf8"), + /"name": "code-review"/, + ); + assert.match( + await readFile(path.join(destination, "code-review", "THIRD_PARTY_NOTICES.md"), "utf8"), + /Third-Party Notices/, + ); + assert.ok((await readdir(path.join(destination, "code-review", "LICENSES"))).length > 0); + + const sentinel = path.join(destination, "code-review", "stale.txt"); + await writeFile(sentinel, "stale", "utf8"); + results = await installSkills({ + skillNames: ["code-review"], + destination, + packageRoot: REPO, + }); + assert.deepEqual(results, [{ name: "code-review", status: "skipped" }]); + assert.equal(await readFile(sentinel, "utf8"), "stale"); + + results = await installSkills({ + skillNames: ["code-review"], + destination, + force: true, + packageRoot: REPO, + }); + assert.deepEqual(results, [{ name: "code-review", status: "updated" }]); + await assert.rejects(readFile(sentinel, "utf8"), { code: "ENOENT" }); + }); +}); + +test("dry-run reports actions without creating the destination", async () => { + await withTempDir(async (root) => { + const destination = path.join(root, "missing", "skills"); + const results = await installSkills({ + skillNames: ["code-review"], + destination, + dryRun: true, + packageRoot: REPO, + }); + + assert.deepEqual(results, [{ name: "code-review", status: "would-install" }]); + await assert.rejects(readdir(destination), { code: "ENOENT" }); + }); +}); + +test("installer rejects a concurrent update with an actionable lock path", async () => { + await withTempDir(async (root) => { + const destination = path.join(root, ".agents", "skills"); + const target = path.join(destination, "code-review"); + await mkdir(`${target}.opp-lock`, { recursive: true }); + + await assert.rejects( + installSkills({ skillNames: ["code-review"], destination, force: true, packageRoot: REPO }), + (error) => { + assert.match(error.message, /Another installation is updating code-review/); + assert.ok(error.message.includes(`${target}.opp-lock`)); + return true; + }, + ); + }); +}); + +test("CLI installs profiles project-locally and lists the catalog", async () => { + await withTempDir(async (root) => { + await mkdir(path.join(root, ".git")); + let output = ""; + const write = (text) => { output += text; }; + assert.equal(await main(["list"], { cwd: root, home: root, packageRoot: REPO, write }), 0); + assert.match(output, /Profiles:/); + assert.match(output, /recommended/); + assert.match(output, /code-review/); + + output = ""; + assert.equal(await main( + ["install", "--profile", "feature-dev", "--project"], + { cwd: root, home: root, packageRoot: REPO, write }, + ), 0); + assert.match(output, /Selected 4 skill\(s\)/); + assert.deepEqual( + await readdir(path.join(root, ".agents", "skills")), + ["code-architect", "code-explorer", "code-reviewer", "feature-dev"], + ); + }); +}); + +test("project scope resolves the Git root from a nested working directory", async () => { + await withTempDir(async (root) => { + const nested = path.join(root, "packages", "api"); + await mkdir(path.join(root, ".git")); + await mkdir(nested, { recursive: true }); + + assert.equal(await resolveProjectRoot(nested), root); + await main( + ["install", "code-review", "--project"], + { cwd: nested, home: root, packageRoot: REPO, write: () => {} }, + ); + assert.match( + await readFile(path.join(root, ".agents", "skills", "code-review", "SKILL.md"), "utf8"), + /name: code-review/, + ); + await assert.rejects(readdir(path.join(nested, ".agents", "skills")), { code: "ENOENT" }); + }); +}); + +test("CLI installs into the injected home by default", async () => { + await withTempDir(async (root) => { + const project = path.join(root, "project"); + let output = ""; + assert.equal(await main( + ["install", "code-review"], + { + cwd: project, + home: root, + packageRoot: REPO, + write: (text) => { output += text; }, + }, + ), 0); + + assert.ok(output.includes(path.join(root, ".agents", "skills"))); + assert.match( + await readFile(path.join(root, ".agents", "skills", "code-review", "SKILL.md"), "utf8"), + /name: code-review/, + ); + await assert.rejects(readdir(path.join(project, ".agents", "skills")), { code: "ENOENT" }); + }); +}); + +test("installed npm bin symlinks are recognized as direct CLI invocations", async () => { + await withTempDir(async (root) => { + const binLink = path.join(root, "opencode-power-pack"); + const binSource = path.join(REPO, "bin", "opencode-power-pack.mjs"); + await symlink(binSource, binLink); + + assert.equal(isDirectInvocation(binLink), true); + assert.equal(isDirectInvocation(path.join(root, "missing")), false); + }); +});