From cbc3cd07a327c743b853c563986b67361388c82b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 02:53:31 +0000 Subject: [PATCH 1/2] feat: generate the manifests from plugin.config.json; add Cursor Adopt rjstone/harness-plugin-template's generator (scripts/build.ts, generate.ts, types.ts, frontmatter.ts, tests/build.test.ts, tsconfig.json, scripts/release.sh). plugin.config.json is now the single source: it writes .claude-plugin/plugin.json, marketplace.json and icon.png (all unchanged), skills/index.json (unchanged; replaces scripts/build_skills_index.py), cliff.toml (the #10 preprocessor now comes from changelog.commitPreprocessors), package.json, and the new .cursor-plugin/plugin.json (logo assets/icon.png, default skill discovery). release.sh sets the version in the config and rebuilds. scripts/ci.sh runs the generator's tests, build --check and typecheck in place of the icon-copy and index checks; upstream-sync.yml rebuilds with node. AGENTS.md and README.md document the generator and a local Cursor install. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QT6szwxMB79y5MRzxuSau4 --- .cursor-plugin/plugin.json | 26 ++ .github/workflows/check.yml | 5 +- .github/workflows/upstream-sync.yml | 2 +- AGENTS.md | 53 ++-- README.md | 8 + cliff.toml | 3 +- package.json | 36 +++ plugin.config.json | 53 ++++ scripts/build.ts | 43 +++ scripts/build_skills_index.py | 92 ------ scripts/ci.sh | 12 +- scripts/frontmatter.ts | 57 ++++ scripts/generate.ts | 470 ++++++++++++++++++++++++++++ scripts/release.sh | 7 +- scripts/types.ts | 173 ++++++++++ tests/build.test.ts | 347 ++++++++++++++++++++ tsconfig.json | 15 + 17 files changed, 1276 insertions(+), 126 deletions(-) create mode 100644 .cursor-plugin/plugin.json create mode 100644 package.json create mode 100644 plugin.config.json create mode 100644 scripts/build.ts delete mode 100644 scripts/build_skills_index.py create mode 100644 scripts/frontmatter.ts create mode 100644 scripts/generate.ts create mode 100644 scripts/types.ts create mode 100644 tests/build.test.ts create mode 100644 tsconfig.json diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json new file mode 100644 index 0000000..540f3be --- /dev/null +++ b/.cursor-plugin/plugin.json @@ -0,0 +1,26 @@ +{ + "name": "github-ninja", + "version": "0.5.0", + "description": "GitHub know-how for coding agents: the gh CLI and API, issues, commits, branches and rebases, CI failure diagnosis, GitHub Actions hardening, efficiency and runtime upgrades, repo security settings audits, npm trusted publishing, Dependabot, secret scanning, CodeQL and file attachments.", + "author": { + "name": "rjstone" + }, + "homepage": "https://github.com/rjstone/github-ninja-plugin", + "repository": "https://github.com/rjstone/github-ninja-plugin", + "license": "MIT", + "keywords": [ + "ci", + "codeql", + "commits", + "dependabot", + "gh", + "git", + "github", + "github-actions", + "issues", + "npm", + "secret-scanning", + "security" + ], + "logo": "assets/icon.png" +} diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index fb078bc..db2348c 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -1,5 +1,6 @@ -# Runs this repo's checks (scripts/ci.sh: icon copy, skills/index.json up to date, skill version -# bumps, script tests, tool and action pins), Claude Code validation and, on main, the badges. +# Runs this repo's checks (scripts/ci.sh: generator tests, generated files up to date, types, +# skill version bumps, script tests, tool and action pins), Claude Code validation and, on main, +# the badges. # The steps live in rjstone/plugin-ci (reusable workflow, called at @main). name: check on: [push, pull_request, workflow_dispatch] # workflow_dispatch: release.yml starts it after a manual release diff --git a/.github/workflows/upstream-sync.yml b/.github/workflows/upstream-sync.yml index def2ceb..10bd84e 100644 --- a/.github/workflows/upstream-sync.yml +++ b/.github/workflows/upstream-sync.yml @@ -79,7 +79,7 @@ jobs: esac - name: Regenerate skills/index.json if: steps.sync.outputs.changed == 'true' - run: python3 scripts/build_skills_index.py + run: node scripts/build.ts - name: Repo checks if: steps.sync.outputs.changed == 'true' env: diff --git a/AGENTS.md b/AGENTS.md index d1af12b..21e3b30 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,22 +14,34 @@ only skills; commands, agents or hooks may follow. `skills//SKILL.md` (no per-harness copies, no symlinks: Windows needs admin rights for them). A format that needs files elsewhere points its manifest at `skills/` or has a script generate the copy. +- **Every manifest is generated** from `plugin.config.json` by `node scripts/build.ts` (Node + 22.18 or later; `--check` reports a stale or missing file). Never hand-edit a generated file: + change the config and rebuild. The generator comes from + [rjstone/harness-plugin-template](https://github.com/rjstone/harness-plugin-template): + `scripts/build.ts`, `generate.ts`, `types.ts`, `frontmatter.ts`, `tests/build.test.ts`, + `tsconfig.json` and `scripts/release.sh` are the template's files, so fix them there first, + then copy them here. Its `DESIGN.md` lists the files each harness looks for. Turn a harness on + in `harnesses` to add its manifest. - Per-format files: - Claude Code: `.claude-plugin/plugin.json` (the plugin) and `.claude-plugin/marketplace.json` - (a one-plugin local marketplace, source `./`). Skills are found in `skills/` by default. + (a one-plugin local marketplace, source `./`), both generated. Skills are found in `skills/` + by default. + - Cursor: `.cursor-plugin/plugin.json`, generated, with `"logo": "assets/icon.png"` and no + component path fields (a path field would replace Cursor's default `skills/` discovery). + There is no `.cursor-plugin/marketplace.json`: this is a single-plugin repo. - skills.sh (`npx skills add rjstone/github-ninja-plugin`): no manifest; it finds `skills/`. `skills.sh.json` (hand-written) only groups the skills on the repo's skills.sh page. Add a new skill to a group there; skills.sh re-reads the file when someone installs from the repo with the `skills` CLI, telemetry on. - - opencode HTTP catalog: `skills/index.json`, **generated** by - `python3 scripts/build_skills_index.py` (never hand-edit; `--check` reports it stale). + - opencode HTTP catalog: `skills/index.json`, generated (it lists each skill's files and + `metadata.version`). - Code that only one harness can run (an opencode plugin package, a Codex manifest if Codex stops reading the Claude one) goes in a top-level folder named after that harness (`opencode/`, `codex/`). - The plugin icon is `assets/icon.png` (square PNG, 512-2048 px, under 2 MB; no SVG or WebP), - the one to edit. An identical copy sits at `.claude-plugin/icon.png`, where Claude Code finds - it; CI fails if the copy differs. `.claude-plugin/plugin.json` has no `"icon"` key: the - claude.ai marketplace sync (Agent SDK) warns about it as an unknown key (2026-11-28). + the one to edit. The generator copies it to `.claude-plugin/icon.png` and points Cursor's + `logo` at it. `.claude-plugin/plugin.json` has no `"icon"` key: the claude.ai marketplace sync + (Agent SDK) warns about it as an unknown key (2026-11-28). - Keep `README.md`'s skill table and install section in sync with `skills/` and the formats. ## Skills @@ -77,7 +89,7 @@ only skills; commands, agents or hooks may follow. branch unless you mean to take it over. - **Every change to a skill bumps its `metadata.version`** (CI fails otherwise: `scripts/check_skill_versions.py`): major for breaking or rewritten guidance, minor for new - material, patch for fixes and upstream wording updates. Then regenerate `skills/index.json`. + material, patch for fixes and upstream wording updates. Then rebuild (`node scripts/build.ts`) to refresh `skills/index.json`. - Prefer stdlib-only Python for any script a skill ships, so it runs without an install step. ## Privacy and safety @@ -90,24 +102,25 @@ private repositories or machines. - **Conventional commits**: `feat:`, `fix:`, `docs:`, `refactor:`, `perf:`, `test:`, `chore:`/`ci:`/`build:`, optional scope (`feat(skills): ...`), `!` or a `BREAKING CHANGE:` footer for breaking changes. git-cliff groups the changelog by these (`cliff.toml`). -- The plugin version (`.claude-plugin/plugin.json` `version`) is the bundle's release version; +- The plugin version (`version` in `plugin.config.json`, written into every manifest) is the + bundle's release version; each skill also has its own `metadata.version`. Adding or removing a skill is at least a minor plugin bump. - **`CHANGELOG.md` is generated**: never edit it by hand (`npx git-cliff@2.14.2 -o CHANGELOG.md`). `cliff.toml` skips merge commits. A pull request that was squash-merged under GitHub's default - "Merge pull request #N" title is then skipped too: give it its real conventional title with a - `commit_preprocessors` line in `cliff.toml` (see the one for #10), or squash with a - conventional title in the first place. + "Merge pull request #N" title is then skipped too: give it its real conventional title in + `changelog.commitPreprocessors` in `plugin.config.json` (see the one for #10; the generator + writes it into `cliff.toml`), or squash with a conventional title in the first place. - Commit straight to `main` unless a change is large enough to want review on a branch. Releasing `vX.Y.Z`, either way: - **From a clone** (people and agents; no tag to push): - 1. `bash scripts/release.sh X.Y.Z`: sets `version` in `.claude-plugin/plugin.json` and - regenerates `CHANGELOG.md`. - 2. Commit both as `chore(release): vX.Y.Z` and push `main`, with that commit as the newest one - of the push. + 1. `bash scripts/release.sh X.Y.Z`: sets `version` in `plugin.config.json`, rebuilds the + generated files and regenerates `CHANGELOG.md`. + 2. Commit everything as `chore(release): vX.Y.Z` and push `main`, with that commit as the + newest one of the push. - **From GitHub**: Actions > release > Run workflow, with `bump` (patch, minor or major) or an exact `version`. The workflow runs `scripts/release.sh` and pushes the release commit itself. @@ -133,14 +146,16 @@ contract). On every push and pull request it runs `bash scripts/ci.sh`, then `fetch-depth: 0` because the skill version check needs history. `release.yml` and `notify-marketplace.yml` are thin callers too. -`scripts/ci.sh` holds this repo's own checks, in this order: the icon copy matches, -`skills/index.json` is up to date, changed skills bumped `metadata.version` (against -`CI_BASE_SHA`; no base means nothing to compare), the `tests/` unit tests, and `pins.py --check`. +`scripts/ci.sh` holds this repo's own checks, in this order: the generator's tests +(`npm test`), every generated file up to date (`node scripts/build.ts --check`: manifests, the +icon copy, `skills/index.json`, `cliff.toml`, `package.json`), `npm run typecheck`, changed +skills bumped `metadata.version` (against `CI_BASE_SHA`; no base means nothing to compare), the +`tests/` Python unit tests, and `pins.py --check`. When `CI_BADGES` is set it appends the `skills` badge line. It works with no environment set and never runs `claude plugin validate`. `upstream-sync.yml` runs the same checks before it pushes its branch: it regenerates -`skills/index.json`, runs `bash scripts/ci.sh` and then the shared `validate` action +`skills/index.json` (`node scripts/build.ts`), runs `bash scripts/ci.sh` and then the shared `validate` action (PRs pushed with `GITHUB_TOKEN` don't start `check.yml`; an optional GitHub App token does: variable `SYNC_APP_CLIENT_ID`, secret `SYNC_APP_PRIVATE_KEY`). With `GITHUB_TOKEN`, the repo setting "Allow GitHub Actions to create and approve pull requests" must be on. diff --git a/README.md b/README.md index 83c4b63..7239fa2 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,14 @@ uninstall the extension, if you don't want that. Or straight from this repository: `/plugin marketplace add rjstone/github-ninja-plugin`, then `/plugin install github-ninja@github-ninja`. +**Cursor** + +For a local install, clone this repository into `~/.cursor/plugins/local/github-ninja` and +reload the window. Cursor loads `.cursor-plugin/plugin.json` and finds the skills in `skills/` +by default. To submit the plugin for review, use the +[Cursor Marketplace publish form](https://cursor.com/marketplace/publish); it is not listed on +the marketplace yet. + **skills.sh** (Claude Code, Codex, Cursor, opencode and other agents) ``` diff --git a/cliff.toml b/cliff.toml index 4b9097a..d433b56 100644 --- a/cliff.toml +++ b/cliff.toml @@ -1,3 +1,4 @@ +# Generated from plugin.config.json by scripts/build.ts; don't edit by hand. Change the config and rebuild. # git-cliff config: https://git-cliff.org/docs/configuration # Generate: npx git-cliff@2.14.2 -o CHANGELOG.md (all releases + unreleased) # Release: npx git-cliff@2.14.2 --tag vX.Y.Z -o CHANGELOG.md (before tagging vX.Y.Z) @@ -35,8 +36,6 @@ conventional_commits = true filter_unconventional = false split_commits = false protect_breaking_commits = true -# A squash merge that kept GitHub's "Merge pull request" title has no conventional type. Give -# such a commit its real title here, above the rule that skips merge commits. commit_preprocessors = [ { pattern = "^Merge pull request #10 from rjstone/feature/workflows-actions-reuse", replace = "feat(skills): add workflows-actions-reuse (#10)" }, ] diff --git a/package.json b/package.json new file mode 100644 index 0000000..3d7287b --- /dev/null +++ b/package.json @@ -0,0 +1,36 @@ +{ + "name": "github-ninja", + "version": "0.5.0", + "description": "GitHub know-how for coding agents: the gh CLI and API, issues, commits, branches and rebases, CI failure diagnosis, GitHub Actions hardening, efficiency and runtime upgrades, repo security settings audits, npm trusted publishing, Dependabot, secret scanning, CodeQL and file attachments.", + "license": "MIT", + "author": "rjstone", + "homepage": "https://github.com/rjstone/github-ninja-plugin", + "repository": { + "type": "git", + "url": "git+https://github.com/rjstone/github-ninja-plugin.git" + }, + "type": "module", + "keywords": [ + "ci", + "codeql", + "commits", + "dependabot", + "gh", + "git", + "github", + "github-actions", + "issues", + "npm", + "secret-scanning", + "security" + ], + "engines": { + "node": ">=22.18" + }, + "scripts": { + "build": "node scripts/build.ts", + "check": "node scripts/build.ts --check", + "test": "node --test tests/*.test.ts", + "typecheck": "npm install --no-save --no-package-lock --silent typescript@5.9 @types/node@22 && tsc -p ." + } +} diff --git a/plugin.config.json b/plugin.config.json new file mode 100644 index 0000000..b26f5ac --- /dev/null +++ b/plugin.config.json @@ -0,0 +1,53 @@ +{ + "name": "github-ninja", + "displayName": "GitHub Ninja", + "version": "0.5.0", + "description": "GitHub know-how for coding agents: the gh CLI and API, issues, commits, branches and rebases, CI failure diagnosis, GitHub Actions hardening, efficiency and runtime upgrades, repo security settings audits, npm trusted publishing, Dependabot, secret scanning, CodeQL and file attachments.", + "shortDescription": "GitHub know-how for agents", + "author": { + "name": "rjstone" + }, + "homepage": "https://github.com/rjstone/github-ninja-plugin", + "repository": "https://github.com/rjstone/github-ninja-plugin", + "license": "MIT", + "keywords": [ + "ci", + "codeql", + "commits", + "dependabot", + "gh", + "git", + "github", + "github-actions", + "issues", + "npm", + "secret-scanning", + "security" + ], + "icon": "assets/icon.png", + "category": "Developer Tools", + "harnesses": { + "agentPlugins": false, + "claude": true, + "cursor": true, + "antigravity": false, + "gemini": false, + "copilotExtras": false, + "opencodeCatalog": true, + "opencode": false, + "pi": false, + "kimi": false, + "muse": false + }, + "claudeMarketplace": { + "description": "Single-plugin marketplace for github-ninja. The plugin is the repository root; its skills live in skills/." + }, + "changelog": { + "commitPreprocessors": [ + { + "pattern": "^Merge pull request #10 from rjstone/feature/workflows-actions-reuse", + "replace": "feat(skills): add workflows-actions-reuse (#10)" + } + ] + } +} diff --git a/scripts/build.ts b/scripts/build.ts new file mode 100644 index 0000000..20df74b --- /dev/null +++ b/scripts/build.ts @@ -0,0 +1,43 @@ +// Writes (or, with --check, verifies) every generated file. See AGENTS.md, "Generator". +// node scripts/build.ts [--check] [--root ] +// Exit codes: 0 ok, 1 stale files (--check) or content errors, 2 bad arguments. + +import { resolve } from 'node:path'; +import { diff, plan, write } from './generate.ts'; + +const args = process.argv.slice(2); +let check = false; +let root = resolve(import.meta.dirname, '..'); +for (let i = 0; i < args.length; i++) { + if (args[i] === '--check') check = true; + else if (args[i] === '--root' && args[i + 1]) root = resolve(args[++i]); + else { + console.error(`unknown argument: ${args[i]}\nusage: node scripts/build.ts [--check] [--root ]`); + process.exit(2); + } +} + +const p = plan(root); +for (const w of p.warnings) console.warn(`warning: ${w}`); +if (p.errors.length) { + for (const e of p.errors) console.error(`error: ${e}`); + process.exit(1); +} + +if (check) { + const d = diff(root, p); + const lines = [ + ...d.missing.map((x) => `missing: ${x}`), + ...d.stale.map((x) => `stale: ${x}`), + ...d.leftover.map((x) => `leftover: ${x} (its harness is off or its input is gone)`), + ]; + if (lines.length) { + console.error(`${lines.join('\n')}\nRun: node scripts/build.ts`); + process.exit(1); + } + console.log(`ok: ${p.files.size} generated files are up to date`); +} else { + const d = write(root, p); + const n = d.missing.length + d.stale.length; + console.log(`wrote ${n} file(s), removed ${d.leftover.length}; ${p.files.size} generated files in total`); +} diff --git a/scripts/build_skills_index.py b/scripts/build_skills_index.py deleted file mode 100644 index e38fb7d..0000000 --- a/scripts/build_skills_index.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env python3 -"""Build skills/index.json: the opencode HTTP skill catalog for this repo. - -opencode loads a `skills` config entry that is an http(s) URL as a catalog: -it fetches `index.json`, then each listed file from -`//`, and refreshes its cache only when `version` changes. -Served from https://raw.githubusercontent.com/rjstone/github-ninja-plugin/main/skills/ - - python3 scripts/build_skills_index.py # (re)write skills/index.json - python3 scripts/build_skills_index.py --check # exit 1 if missing or stale - -One entry per skills//SKILL.md, sorted by name; version is the skill's -metadata.version; files are every file in the skill folder (sorted, "/" -separators, no __pycache__/.pyc). Standard library only. -""" -import argparse -import json -import os -import re -import sys - -REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -VERSION = re.compile(r'^\s+version:\s*"?([^"\s]+)"?\s*$', re.M) -FRONTMATTER = re.compile(r"^---\r?\n(.*?)\r?\n---\r?\n", re.S) - - -def skill_version(skill_md_path): - with open(skill_md_path, encoding="utf-8") as f: - m = FRONTMATTER.match(f.read()) - v = VERSION.search(m.group(1)) if m else None - if not v: - raise SystemExit("no metadata.version in %s" % skill_md_path) - return v.group(1) - - -def skill_files(skill_dir): - out = [] - for dirpath, dirnames, filenames in os.walk(skill_dir): - dirnames[:] = sorted(d for d in dirnames if d != "__pycache__") - for name in filenames: - if name.endswith(".pyc"): - continue - rel = os.path.relpath(os.path.join(dirpath, name), skill_dir) - out.append(rel.replace(os.sep, "/")) - return sorted(out) - - -def build_index(skills_dir): - entries = [] - for name in sorted(os.listdir(skills_dir)): - d = os.path.join(skills_dir, name) - md = os.path.join(d, "SKILL.md") - if not os.path.isfile(md): - continue - entries.append({"name": name, "version": skill_version(md), "files": skill_files(d)}) - return {"skills": entries} - - -def render(index): - return json.dumps(index, indent=2, ensure_ascii=False) + "\n" - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--check", action="store_true", help="exit 1 if skills/index.json is missing or stale") - ap.add_argument("--skills-dir", default=os.path.join(REPO_ROOT, "skills")) - a = ap.parse_args(argv) - path = os.path.join(a.skills_dir, "index.json") - text = render(build_index(a.skills_dir)) - try: - with open(path, encoding="utf-8", newline="") as f: - current = f.read().replace("\r\n", "\n") - except FileNotFoundError: - current = None - if a.check: - if current == text: - print("skills/index.json is up to date") - return 0 - print("skills/index.json is %s: run python3 scripts/build_skills_index.py" - % ("missing" if current is None else "stale")) - return 1 - if current != text: - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(text) - print("wrote %s" % os.path.relpath(path, REPO_ROOT)) - else: - print("skills/index.json already up to date") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/scripts/ci.sh b/scripts/ci.sh index bbb440d..0c1e5f2 100755 --- a/scripts/ci.sh +++ b/scripts/ci.sh @@ -6,13 +6,11 @@ set -euo pipefail cd "$(dirname "$0")/.." -# assets/icon.png is the one to edit; Claude Code finds the copy in .claude-plugin/ (the -# manifest has no "icon" key: the claude.ai marketplace sync warns about it as unknown). -cmp assets/icon.png .claude-plugin/icon.png || { - echo "::error file=.claude-plugin/icon.png::differs from assets/icon.png (copy it again)" - exit 1 -} -python3 scripts/build_skills_index.py --check +# The generator's checks (from the template): its tests, every generated file up to date +# (manifests, .claude-plugin/icon.png, skills/index.json, cliff.toml, package.json), types. +npm test +node scripts/build.ts --check +npm run typecheck python3 scripts/check_skill_versions.py "${CI_BASE_SHA:-}" python3 -m unittest discover -s tests -v python3 scripts/pins.py --check diff --git a/scripts/frontmatter.ts b/scripts/frontmatter.ts new file mode 100644 index 0000000..64b9f32 --- /dev/null +++ b/scripts/frontmatter.ts @@ -0,0 +1,57 @@ +// A small reader for the YAML frontmatter of SKILL.md and agent files. It handles what those +// files use: `key: value`, quoted values, one nested level (`metadata:` + indented keys) and +// folded or literal block scalars (`>`, `>-`, `|`). Anything fancier is a reason to simplify the +// frontmatter, not to grow this parser. + +export type Frontmatter = Record>; + +export interface Parsed { + data: Frontmatter; + body: string; +} + +function unquote(v: string): string { + const t = v.trim(); + if (t.length >= 2 && ((t[0] === '"' && t.at(-1) === '"') || (t[0] === "'" && t.at(-1) === "'"))) { + if (t[0] === '"') return JSON.parse(t) as string; + return t.slice(1, -1).replaceAll("''", "'"); + } + return t; +} + +export function parseFrontmatter(text: string): Parsed | undefined { + const lines = text.replace(/^/, '').split(/\r?\n/); + if (lines[0]?.trim() !== '---') return undefined; + const end = lines.findIndex((l, i) => i > 0 && l.trim() === '---'); + if (end < 0) return undefined; + const data: Frontmatter = {}; + const head = lines.slice(1, end); + let i = 0; + while (i < head.length) { + const line = head[i]; + if (line.trim() === '' || line.trimStart().startsWith('#')) { i++; continue; } + const m = /^([A-Za-z0-9_.-]+):\s*(.*)$/.exec(line); + if (!m) { i++; continue; } + const [, key, rest] = m; + i++; + if (/^[>|]-?$/.test(rest)) { + const block: string[] = []; + while (i < head.length && (head[i].startsWith(' ') || head[i].trim() === '')) { + block.push(head[i].trim()); + i++; + } + data[key] = rest.startsWith('>') ? block.filter(Boolean).join(' ') : block.join('\n').trim(); + } else if (rest === '') { + const nested: Record = {}; + while (i < head.length && (head[i].startsWith(' ') || head[i].trim() === '')) { + const n = /^\s+([A-Za-z0-9_.-]+):\s*(.*)$/.exec(head[i]); + if (n) nested[n[1]] = unquote(n[2]); + i++; + } + data[key] = nested; + } else { + data[key] = unquote(rest); + } + } + return { data, body: lines.slice(end + 1).join('\n') }; +} diff --git a/scripts/generate.ts b/scripts/generate.ts new file mode 100644 index 0000000..3380ca2 --- /dev/null +++ b/scripts/generate.ts @@ -0,0 +1,470 @@ +// Computes every generated file from plugin.config.json and the repo's content folders, then +// writes them (write) or compares them with what is on disk (check). See AGENTS.md, "Generator". + +import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { basename, dirname, join, relative, sep } from 'node:path'; +import { parseFrontmatter } from './frontmatter.ts'; +import { nameProblem, repoNameOf, validateConfig } from './types.ts'; +import type { Config, Harness, McpServer, McpSource } from './types.ts'; + +export const AP_PLUGIN_SCHEMA = 'https://agent-plugins.org/schemas/1.0.0/plugin.schema.json'; +export const AP_MCP_SCHEMA = 'https://agent-plugins.org/schemas/1.0.0/mcp.schema.json'; +export const ANTIGRAVITY_SCHEMA = 'https://antigravity.google/schemas/v1/plugin.json'; + +// Every path the generator owns, with the harness that turns it on. A path whose harness is off +// (or whose input is missing) must not exist: write deletes it, check reports it. +const FIXED_OUTPUTS: Record = { + 'plugin.json': 'agentPlugins', + 'mcp.json': 'agentPlugins', + '.claude-plugin/plugin.json': 'claude', + '.claude-plugin/marketplace.json': 'claude', + '.claude-plugin/icon.png': 'claude', + '.mcp.json': 'claude', + '.cursor-plugin/plugin.json': 'cursor', + '.antigravity-plugin/plugin.json': 'antigravity', + 'mcp_config.json': 'antigravity', + 'gemini-extension.json': 'gemini', + 'skills/index.json': 'opencodeCatalog', + '.kimi-plugin/plugin.json': 'kimi', + '.muse-plugin/plugin.json': 'muse', + '.muse-plugin/marketplace.json': 'muse', + 'package.json': 'always', + 'cliff.toml': 'always', +}; +// Backticks are written as @@TICK@@ because the template is a String.raw literal. +const CLIFF_TEMPLATE = String.raw`# Generated from plugin.config.json by scripts/build.ts; don't edit by hand. Change the config and rebuild. +# git-cliff config: https://git-cliff.org/docs/configuration +# Generate: npx git-cliff@2.14.2 -o CHANGELOG.md (all releases + unreleased) +# Release: npx git-cliff@2.14.2 --tag vX.Y.Z -o CHANGELOG.md (before tagging vX.Y.Z) +# Notes: npx git-cliff@2.14.2 --latest --strip header (one release, for a GitHub release) + +[changelog] +header = """ +# Changelog + +All notable changes to this repository. Generated by [git-cliff](https://git-cliff.org) from the +commit history (see @@TICK@@cliff.toml@@TICK@@); don't edit by hand.\n +""" +body = """ +{% if version %}\ +## [{{ version | trim_start_matches(pat="v") }}] - {{ timestamp | date(format="%Y-%m-%d") }} +{% else %}\ +## [Unreleased] +{% endif %}\ +{% for group, commits in commits | group_by(attribute="group") %} +### {{ group | striptags | trim | upper_first }} +{% for commit in commits %} +- {% if commit.scope %}**{{ commit.scope }}:** {% endif %}\ +{% if commit.breaking %}**BREAKING** {% endif %}\ +{{ commit.message | split(pat="\n") | first | upper_first | trim }} \ +@@COMMIT@@ +{% endfor %} +{% endfor %}\n +""" +footer = "" +trim = true + +[git] +# Conventional commits (see AGENTS.md); anything else lands under "Changes". +conventional_commits = true +filter_unconventional = false +split_commits = false +protect_breaking_commits = true +commit_parsers = [ + { message = "^Initial commit", skip = true }, + { message = "^chore\\(release\\)", skip = true }, + { message = "^Merge (pull request|branch)", skip = true }, + { message = "^feat", group = "Features" }, + { message = "^fix", group = "Fixes" }, + { message = "^perf", group = "Performance" }, + { message = "^refactor", group = "Refactoring" }, + { message = "^docs", group = "Documentation" }, + { message = "^test", group = "Tests" }, + { message = "^(chore|ci|build)", group = "Maintenance" }, + { message = ".*", group = "Changes" }, +] +tag_pattern = "v[0-9]+\\.[0-9]+\\.[0-9]+$" +sort_commits = "oldest" +`; + +// cliff.toml (the git-cliff changelog config). The commit link and any commit preprocessors +// depend on the config. +function cliffToml(repository: string | undefined, pre: { pattern: string; replace: string }[] = []): string { + const short = '{{ commit.id | truncate(length=7, end="") }}'; + const base = repository?.replace(/(\.git|\/)+$/, ''); + const commit = base + ? `([${short}](${base}/commit/{{ commit.id }}))\\` + : `(${short})\\`; + // JSON string escapes are valid in TOML basic strings. + const preprocessors = pre.length + ? `commit_preprocessors = [\n${pre.map((p) => ` { pattern = ${JSON.stringify(p.pattern)}, replace = ${JSON.stringify(p.replace)} },`).join('\n')}\n]\n` + : ''; + return CLIFF_TEMPLATE.replaceAll('@@TICK@@', '`').replace('@@COMMIT@@', () => commit) + .replace('commit_parsers = [', () => `${preprocessors}commit_parsers = [`); +} +const COPILOT_AGENTS_DIR = 'com.github.copilot/agents'; + +export interface Skill { + name: string; + description: string; + version?: string; + files: string[]; +} + +export interface Plan { + files: Map; // repo-relative POSIX path -> content (Buffer for binary copies) + errors: string[]; + warnings: string[]; +} + +const posix = (p: string) => p.split(sep).join('/'); +const json = (v: unknown) => JSON.stringify(v, null, 2) + '\n'; + +function isObject(v: unknown): v is Record { + return typeof v === 'object' && v !== null && !Array.isArray(v); +} + +// Deep merge: objects merge key by key, everything else (arrays included) is replaced. +export function merge(base: Record, extra: Record | undefined) { + if (!extra) return base; + const out: Record = { ...base }; + for (const [k, v] of Object.entries(extra)) { + const b = out[k]; + out[k] = isObject(b) && isObject(v) ? merge(b, v) : v; + } + return out; +} + +// Drops undefined values so optional config fields leave no "key": null behind. +function clean>(o: T): T { + return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined)) as T; +} + +function listFiles(dir: string): string[] { + const out: string[] = []; + const walk = (d: string) => { + for (const e of readdirSync(d, { withFileTypes: true })) { + const p = join(d, e.name); + // Python caches appear whenever a skill's tests run: never list them. + if (e.isDirectory()) { if (e.name !== '__pycache__') walk(p); } + else if (e.isFile() && !e.name.endsWith('.pyc')) out.push(posix(relative(dir, p))); + } + }; + walk(dir); + return out.sort(); +} + +export function readSkills(root: string, needVersion: boolean, errors: string[]): Skill[] { + const dir = join(root, 'skills'); + if (!existsSync(dir)) return []; + const skills: Skill[] = []; + for (const e of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) { + if (!e.isDirectory()) continue; + const file = join(dir, e.name, 'SKILL.md'); + if (!existsSync(file)) { errors.push(`skills/${e.name}/ has no SKILL.md`); continue; } + const fm = parseFrontmatter(readFileSync(file, 'utf8')); + if (!fm) { errors.push(`skills/${e.name}/SKILL.md has no frontmatter`); continue; } + const { name, description, metadata } = fm.data; + if (name !== e.name) errors.push(`skills/${e.name}/SKILL.md: name must equal the folder name`); + const p = nameProblem(name); + if (p) errors.push(`skills/${e.name}/SKILL.md: name ${p}`); + if (typeof description !== 'string' || description === '' || description.length > 1024) { + errors.push(`skills/${e.name}/SKILL.md: description must be 1-1024 characters`); + } + const version = isObject(metadata) ? metadata.version : undefined; + if (needVersion && typeof version !== 'string') { + errors.push(`skills/${e.name}/SKILL.md: metadata.version is required (the opencode catalog uses it)`); + } + const nested = listFiles(join(dir, e.name)).filter((f) => f !== 'SKILL.md' && f.endsWith('/SKILL.md')); + if (nested.length) errors.push(`skills/${e.name}/ has a nested SKILL.md (${nested[0]}): Agent Plugins forbids nesting`); + skills.push({ + name: e.name, + description: typeof description === 'string' ? description : '', + version: typeof version === 'string' ? version : undefined, + files: listFiles(join(dir, e.name)), + }); + } + return skills; +} + +// --- MCP: one neutral source, one output per harness spelling ------------------------------ + +interface Vars { root: string; data?: string } + +function subst(s: string, v: Vars, where: string, errors: string[]): string { + if (s.includes('{data}') && v.data === undefined) { + errors.push(`${where}: {data} has no equivalent there; avoid it or turn that harness off`); + } + return s.replaceAll('{root}', v.root).replaceAll('{data}', v.data ?? ''); +} + +function substAll(value: T, v: Vars, where: string, errors: string[]): T { + if (typeof value === 'string') return subst(value, v, where, errors) as T; + if (Array.isArray(value)) return value.map((x) => substAll(x, v, where, errors)) as T; + if (isObject(value)) { + return Object.fromEntries(Object.entries(value).map(([k, x]) => [k, substAll(x, v, where, errors)])) as T; + } + return value; +} + +function validateMcp(src: unknown, errors: string[]): McpSource | undefined { + if (!isObject(src) || !isObject(src.servers)) { errors.push('mcp/servers.json must be {"servers": {...}}'); return undefined; } + for (const [name, s] of Object.entries(src.servers)) { + if (!isObject(s)) { errors.push(`mcp server ${name}: must be an object`); continue; } + if (s.type === 'stdio') { + if (typeof s.command !== 'string' || /\s|\{root\}|\{data\}/.test(s.command)) { + errors.push(`mcp server ${name}: command must be one bare token (Agent Plugins); put paths in args`); + } + } else if (s.type === 'http') { + if (typeof s.url !== 'string' || !s.url.startsWith('https://')) errors.push(`mcp server ${name}: url must be https://`); + } else { + errors.push(`mcp server ${name}: type must be "stdio" or "http"`); + } + } + return src as unknown as McpSource; +} + +type Target = 'agentPlugins' | 'claude' | 'antigravity' | 'gemini'; + +const VARS: Record = { + agentPlugins: { root: '${PLUGIN_ROOT}', data: '${PLUGIN_DATA}' }, + claude: { root: '${CLAUDE_PLUGIN_ROOT}', data: '${CLAUDE_PLUGIN_DATA}' }, + antigravity: { root: '${PLUGIN_ROOT}', data: '${PLUGIN_DATA}' }, + gemini: { root: '${extensionPath}' }, +}; + +function mcpServers(src: McpSource, t: Target, errors: string[]): Record { + const out: Record = {}; + for (const [name, s0] of Object.entries(src.servers)) { + const s = substAll(s0, VARS[t], `mcp server ${name} (${t})`, errors); + if (s.type === 'stdio') { + const base = clean({ command: s.command, args: s.args, env: s.env, cwd: s.cwd }); + out[name] = t === 'agentPlugins' ? { type: 'stdio', ...base } : base; + } else if (t === 'agentPlugins') { + out[name] = clean({ type: 'streamable-http', url: s.url, headers: s.headers }); + } else if (t === 'claude') { + out[name] = clean({ type: 'http', url: s.url, headers: s.headers }); + } else if (t === 'gemini') { + out[name] = clean({ httpUrl: s.url, headers: s.headers }); + } else { + out[name] = clean({ serverUrl: s.url, headers: s.headers }); + } + } + return out; +} + +// --- Agents -> Copilot *.agent.md ------------------------------------------------------------ + +function copilotAgents(root: string, errors: string[]): Map { + const out = new Map(); + const dir = join(root, 'agents'); + if (!existsSync(dir)) return out; + for (const f of readdirSync(dir).filter((x) => x.endsWith('.md')).sort()) { + const fm = parseFrontmatter(readFileSync(join(dir, f), 'utf8')); + const name = fm?.data.name; + const description = fm?.data.description; + if (!fm || typeof name !== 'string' || typeof description !== 'string') { + errors.push(`agents/${f}: frontmatter needs name and description`); + continue; + } + // Only name and description carry over: model and tool names differ between harnesses. + const head = `---\nname: ${JSON.stringify(name)}\ndescription: ${JSON.stringify(description)}\n---\n`; + out.set(`${COPILOT_AGENTS_DIR}/${f.replace(/\.md$/, '.agent.md')}`, head + fm.body.replace(/^\n+/, '\n')); + } + return out; +} + +// --- The plan --------------------------------------------------------------------------------- + +export function plan(root: string, configPath = join(root, 'plugin.config.json')): Plan { + const files = new Map(); + const errors: string[] = []; + const warnings: string[] = []; + let raw: unknown; + try { + raw = JSON.parse(readFileSync(configPath, 'utf8')); + } catch (e) { + return { files, errors: [`cannot read ${basename(configPath)}: ${(e as Error).message}`], warnings }; + } + const problems = validateConfig(raw); + if (problems.length) return { files, errors: problems.map((p) => `plugin.config.json: ${p}`), warnings }; + const c = raw as Config; + const on = c.harnesses; + const exists = (p: string) => existsSync(join(root, p)); + + if (c.icon in FIXED_OUTPUTS) { + errors.push(`icon must not be a generated file (${c.icon}): keep the source icon elsewhere, such as assets/icon.png`); + } else if (!exists(c.icon)) errors.push(`icon ${c.icon} does not exist`); + const skills = readSkills(root, on.opencodeCatalog, errors); + if (skills.length === 0) warnings.push('skills/ holds no skills'); + + let mcp: McpSource | undefined; + if (exists('mcp/servers.json')) { + try { + mcp = validateMcp(JSON.parse(readFileSync(join(root, 'mcp/servers.json'), 'utf8')), errors); + } catch (e) { + errors.push(`mcp/servers.json: ${(e as Error).message}`); + } + } + const author = clean({ name: c.author.name, email: c.author.email, url: c.author.url }); + const icon = `./${c.icon}`; + const common = clean({ + name: c.name, version: c.version, description: c.description, author, + homepage: c.homepage, repository: c.repository, license: c.license, keywords: c.keywords, + }); + + if (on.agentPlugins) { + // Codex reads the OpenAI settings here; `hooks: {}` stops it loading the Claude-schema + // hooks/hooks.json (AGENTS.md, conflict 12). + const openai = merge({ + interface: clean({ + displayName: c.displayName, shortDescription: c.shortDescription, longDescription: c.description, + developerName: c.author.name, category: c.category, capabilities: [], + websiteURL: c.homepage, composerIcon: icon, logo: icon, + }), + hooks: {}, + }, c.codex); + files.set('plugin.json', json(merge({ $schema: AP_PLUGIN_SCHEMA, ...common, extensions: { 'com.openai': openai } }, c.agentPlugins))); + if (mcp) files.set('mcp.json', json({ $schema: AP_MCP_SCHEMA, mcpServers: mcpServers(mcp, 'agentPlugins', errors) })); + } + if (on.claude) { + // No `icon` key: the claude.ai marketplace sync (Agent SDK) warns about it as an unknown key + // (2026-11-28); Claude's docs say only the directory listing reads it. The copy at + // .claude-plugin/icon.png is kept, though no Claude doc names that location [U]. + // (AGENTS.md, conflict 8.) + files.set('.claude-plugin/plugin.json', json(merge(common, c.claude))); + if (exists(c.icon)) { + files.set('.claude-plugin/icon.png', readFileSync(join(root, c.icon))); + } + files.set('.claude-plugin/marketplace.json', json(merge({ + name: c.name, + owner: clean({ name: c.author.name, email: c.author.email }), + description: `Single-plugin marketplace for ${c.name}. The plugin is the repository root.`, + plugins: [{ name: c.name, source: './', description: c.description }], + }, c.claudeMarketplace))); + } + if (mcp && (on.claude || on.cursor)) { + files.set('.mcp.json', json({ mcpServers: mcpServers(mcp, 'claude', errors) })); + } + if (on.cursor) { + files.set('.cursor-plugin/plugin.json', json(merge(clean({ + // Only documented fields: no `displayName`, `author` without `url`, and `logo` written + // as the docs show it (relative, no `./`). + ...common, author: clean({ name: c.author.name, email: c.author.email }), logo: c.icon, + // Cursor expands ${CLAUDE_PLUGIN_ROOT} but not ${PLUGIN_ROOT} (conflict 2). + mcpServers: mcp ? './.mcp.json' : undefined, + hooks: exists('hooks/hooks-cursor.json') ? './hooks/hooks-cursor.json' : undefined, + }), c.cursor))); + } + if (on.antigravity) { + const { keywords, ...rest } = common; + files.set('.antigravity-plugin/plugin.json', json(merge({ + $schema: ANTIGRAVITY_SCHEMA, ...rest, displayName: c.displayName, keywords, logo: c.icon, + }, c.antigravity))); + if (mcp) files.set('mcp_config.json', json({ mcpServers: mcpServers(mcp, 'antigravity', errors) })); + } + if (on.gemini) { + const repo = repoNameOf(c.repository); + const geminiName = repo?.endsWith('-plugin') ? repo : c.name; + files.set('gemini-extension.json', json(merge(clean({ + name: geminiName, version: c.version, description: c.description, + contextFileName: exists('GEMINI.md') ? 'GEMINI.md' : undefined, + mcpServers: mcp ? mcpServers(mcp, 'gemini', errors) : undefined, + }), c.gemini))); + } + if (on.copilotExtras) for (const [p, t] of copilotAgents(root, errors)) files.set(p, t); + if (on.opencodeCatalog) { + files.set('skills/index.json', json({ + skills: skills.map((s) => ({ name: s.name, version: s.version, files: s.files })), + })); + } + if (on.kimi) { + files.set('.kimi-plugin/plugin.json', json(merge(clean({ + name: c.name, version: c.version, description: c.description, author, + homepage: c.homepage, license: c.license, keywords: c.keywords, skills: './skills/', + interface: clean({ + displayName: c.displayName, shortDescription: c.shortDescription, longDescription: c.description, + developerName: c.author.name, websiteURL: c.homepage, + }), + }), c.kimi))); + } + if (on.muse) { + files.set('.muse-plugin/plugin.json', json(merge({ + schemaVersion: 1, name: c.name, displayName: c.displayName, version: c.version, description: c.description, + compat: { source: 'native', manifestDir: '.muse-plugin' }, + capabilities: { + skills: skills.map((s) => ({ id: s.name, path: `skills/${s.name}/SKILL.md` })), + commands: [], hooks: [], mcpServers: [], reminders: [], + }, + }, c.muse))); + files.set('.muse-plugin/marketplace.json', json({ + name: c.name, description: c.description, + owner: clean({ name: c.author.name, email: c.author.email }), + plugins: [{ name: c.name, description: c.description, version: c.version, source: './', author }], + })); + } + + // package.json: always written (it also holds the dev scripts); opencode and Pi add to it. + const opencodeEntry = `.opencode/plugins/${c.name}.js`; + if (on.opencode && !exists(opencodeEntry)) errors.push(`harnesses.opencode is on but ${opencodeEntry} does not exist`); + const piExtensions = exists('.pi/extensions') + ? listFiles(join(root, '.pi/extensions')).filter((f) => /\.(ts|js)$/.test(f)).map((f) => `./.pi/extensions/${f}`) + : []; + files.set('package.json', json(merge(clean({ + name: c.name, version: c.version, description: c.description, license: c.license, + author: c.author.name, homepage: c.homepage, + repository: c.repository ? { type: 'git', url: `git+${c.repository}.git` } : undefined, + type: 'module', + // opencode reads an `exports` map ("." is the server part); it documents no `main`. + exports: on.opencode ? { '.': `./${opencodeEntry}` } : undefined, + keywords: on.pi ? [...new Set([...c.keywords, 'pi-package'])] : c.keywords, + pi: on.pi ? clean({ extensions: piExtensions.length ? piExtensions : undefined, skills: ['./skills'] }) : undefined, + engines: { node: '>=22.18' }, + scripts: { + build: 'node scripts/build.ts', + check: 'node scripts/build.ts --check', + test: 'node --test tests/*.test.ts', + typecheck: 'npm install --no-save --no-package-lock --silent typescript@5.9 @types/node@22 && tsc -p .', + }, + }), c.packageJson))); + + // cliff.toml: always written; the commit link comes from `repository`. + files.set('cliff.toml', cliffToml(c.repository, c.changelog?.commitPreprocessors)); + + return { files, errors, warnings }; +} + +// Paths the generator owns that are on disk now (so check can report leftovers). +function ownedOnDisk(root: string): string[] { + const out = Object.keys(FIXED_OUTPUTS).filter((p) => existsSync(join(root, p))); + const agents = join(root, COPILOT_AGENTS_DIR); + if (existsSync(agents) && statSync(agents).isDirectory()) { + for (const f of readdirSync(agents)) if (f.endsWith('.agent.md')) out.push(`${COPILOT_AGENTS_DIR}/${f}`); + } + return out; +} + +export interface Diff { stale: string[]; missing: string[]; leftover: string[] } + +export function diff(root: string, p: Plan): Diff { + const d: Diff = { stale: [], missing: [], leftover: [] }; + for (const [path, content] of p.files) { + const full = join(root, path); + if (!existsSync(full)) d.missing.push(path); + else if (typeof content === 'string' ? readFileSync(full, 'utf8') !== content : !readFileSync(full).equals(content)) { + d.stale.push(path); + } + } + for (const path of ownedOnDisk(root)) if (!p.files.has(path)) d.leftover.push(path); + return d; +} + +export function write(root: string, p: Plan): Diff { + const d = diff(root, p); + for (const path of [...d.missing, ...d.stale]) { + mkdirSync(dirname(join(root, path)), { recursive: true }); + writeFileSync(join(root, path), p.files.get(path) as string | Buffer); + } + for (const path of d.leftover) rmSync(join(root, path)); + return d; +} diff --git a/scripts/release.sh b/scripts/release.sh index db2b866..f7856de 100644 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash -# Turns the working tree into release X.Y.Z: sets the version in the plugin manifest and -# regenerates CHANGELOG.md. It commits nothing. +# Turns the working tree into release X.Y.Z: sets the version in plugin.config.json, rebuilds the +# generated files and regenerates CHANGELOG.md. It commits nothing. # By hand: run it, commit everything as "chore(release): vX.Y.Z" and push main; the release # workflow tags and publishes. A manual run of that workflow runs this script itself. # Usage: bash scripts/release.sh X.Y.Z @@ -21,5 +21,6 @@ node -e ' process.exit(1); } fs.writeFileSync(file, text); -' .claude-plugin/plugin.json "$version" +' plugin.config.json "$version" +node scripts/build.ts npx -y git-cliff@2.14.2 --tag "v$version" -o CHANGELOG.md diff --git a/scripts/types.ts b/scripts/types.ts new file mode 100644 index 0000000..379d882 --- /dev/null +++ b/scripts/types.ts @@ -0,0 +1,173 @@ +// Shape of plugin.config.json, the single source of every generated manifest. +// Erasable TypeScript only (no enum, namespace or parameter properties): Node runs it directly. + +export const HARNESSES = [ + 'agentPlugins', // root plugin.json + mcp.json (Codex, Copilot, VS Code, Cursor, Kiro, Qwen, Hermes, Devin) + 'claude', // .claude-plugin/plugin.json + marketplace.json, .mcp.json + 'cursor', // .cursor-plugin/plugin.json + 'antigravity', // .antigravity-plugin/plugin.json + mcp_config.json + 'gemini', // gemini-extension.json + 'copilotExtras', // com.github.copilot/agents/*.agent.md + 'opencodeCatalog', // skills/index.json + 'opencode', // package.json "main" -> .opencode/plugins/.js + 'pi', // package.json "pi" key + "pi-package" keyword + 'kimi', // .kimi-plugin/plugin.json + 'muse', // .muse-plugin/plugin.json + marketplace.json +] as const; + +export type Harness = (typeof HARNESSES)[number]; + +export interface Author { + name: string; + email?: string; + url?: string; +} + +export interface Config { + name: string; + displayName: string; + version: string; + description: string; + shortDescription: string; + author: Author; + homepage?: string; + repository?: string; + license: string; + keywords: string[]; + icon: string; + category: string; + harnesses: Record; + // Per-harness extras, merged (deeply) into that harness's manifest only. + agentPlugins?: Record; + codex?: Record; // merged into plugin.json extensions["com.openai"] + claude?: Record; + claudeMarketplace?: Record; + cursor?: Record; + antigravity?: Record; + gemini?: Record; + kimi?: Record; + muse?: Record; + packageJson?: Record; + // cliff.toml extras: rewrite a commit message before parsing (for example, give a + // squash merge that kept GitHub's "Merge pull request" title its conventional title). + changelog?: { commitPreprocessors?: { pattern: string; replace: string }[] }; +} + +// mcp/servers.json: one neutral list; {root} and {data} become each harness's variables. +export interface StdioServer { + type: 'stdio'; + command: string; + args?: string[]; + env?: Record; + cwd?: string; +} + +export interface HttpServer { + type: 'http'; + url: string; + headers?: Record; +} + +export type McpServer = StdioServer | HttpServer; + +export interface McpSource { + servers: Record; +} + +// The name every harness accepts: Agent Plugins allows periods, Antigravity doesn't; Claude +// reserves some prefixes. Naming rule: a repository named "-plugin" holds a plugin named +// "", and every manifest carries ""; only Gemini's manifest carries the repository name +// (Gemini and Qwen expect the extension name to match the repository). Any other repository +// name puts no rule on the name. +export const NAME_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/; +const RESERVED_PREFIXES = ['claude-', 'anthropic-', 'cc-plugin-']; + +export function nameProblem(name: unknown): string | undefined { + if (typeof name !== 'string' || name.length === 0) return 'must be a non-empty string'; + if (name.length > 64) return 'must be at most 64 characters'; + if (!NAME_RE.test(name)) return 'must be lowercase letters, digits and single hyphens'; + if (name === 'claude' || RESERVED_PREFIXES.some((p) => name.startsWith(p))) { + return `must not be "claude" or start with ${RESERVED_PREFIXES.join(', ')} (Claude reserves them)`; + } + return undefined; +} + +// The last path segment of a repository URL, without a trailing "/" or ".git"; undefined if none. +export function repoNameOf(repository: unknown): string | undefined { + if (typeof repository !== 'string') return undefined; + let path: string; + try { + path = new URL(repository).pathname; + } catch { + return undefined; + } + const last = path.replace(/\/+$/, '').replace(/\.git$/, '').split('/').pop(); + return last ? last : undefined; +} + +const SEMVER_RE = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/; + +function isObject(v: unknown): v is Record { + return typeof v === 'object' && v !== null && !Array.isArray(v); +} + +// Returns a list of problems; empty means the config is usable. +export function validateConfig(raw: unknown): string[] { + const errors: string[] = []; + if (!isObject(raw)) return ['plugin.config.json must be a JSON object']; + const c = raw; + const p = nameProblem(c.name); + if (p) errors.push(`name ${p}`); + const str = (key: string, max?: number) => { + const v = c[key]; + if (typeof v !== 'string' || v.trim() === '') errors.push(`${key} must be a non-empty string`); + else if (max !== undefined && v.length > max) errors.push(`${key} must be at most ${max} characters`); + }; + str('displayName', 30); // Codex interface.displayName limit + str('shortDescription', 30); // Codex interface.shortDescription limit + str('description', 1024); // Copilot legacy limit; the smallest + str('license'); + str('icon'); + str('category'); + if (typeof c.version !== 'string' || !SEMVER_RE.test(c.version)) errors.push('version must be semver X.Y.Z'); + if (!isObject(c.author) || typeof c.author.name !== 'string' || c.author.name === '') { + errors.push('author.name is required'); + } + if (!Array.isArray(c.keywords) || c.keywords.some((k) => typeof k !== 'string')) { + errors.push('keywords must be an array of strings'); + } + for (const key of ['homepage', 'repository']) { + const v = c[key]; + if (v !== undefined && (typeof v !== 'string' || !v.startsWith('https://'))) { + errors.push(`${key} must be an https:// URL`); + } + } + const repo = repoNameOf(c.repository); + if (repo && repo.endsWith('-plugin') && repo.length > '-plugin'.length && typeof c.name === 'string') { + const short = repo.slice(0, -'-plugin'.length); + if (c.name !== short) { + errors.push(`name must be "${short}": the repository is "${repo}", and a plugin is named after its repository without "-plugin"`); + } + } + if (typeof c.icon === 'string' && (c.icon.startsWith('/') || c.icon.includes('..'))) { + errors.push('icon must be a path inside the repo'); + } + if (c.changelog !== undefined) { + const pre = isObject(c.changelog) ? c.changelog.commitPreprocessors : 'bad'; + if (pre !== undefined && (!Array.isArray(pre) || pre.some((p) => !isObject(p) + || typeof p.pattern !== 'string' || typeof p.replace !== 'string'))) { + errors.push('changelog.commitPreprocessors must be a list of {pattern, replace} strings'); + } + } + if (!isObject(c.harnesses)) { + errors.push('harnesses must be an object'); + } else { + for (const h of HARNESSES) { + if (typeof c.harnesses[h] !== 'boolean') errors.push(`harnesses.${h} must be true or false`); + } + for (const k of Object.keys(c.harnesses)) { + if (!(HARNESSES as readonly string[]).includes(k)) errors.push(`harnesses.${k} is not a known harness`); + } + } + return errors; +} diff --git a/tests/build.test.ts b/tests/build.test.ts new file mode 100644 index 0000000..4fc78b3 --- /dev/null +++ b/tests/build.test.ts @@ -0,0 +1,347 @@ +// Generator tests: each builds a throwaway plugin folder in the temp directory (no network). +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { diff, merge, plan, write } from '../scripts/generate.ts'; +import { parseFrontmatter } from '../scripts/frontmatter.ts'; +import { HARNESSES, nameProblem, repoNameOf } from '../scripts/types.ts'; + +const NAME = 'demo-plugin'; + +function config(over: Record = {}) { + return { + name: NAME, displayName: 'Demo', version: '1.2.3', description: 'A demo plugin.', + shortDescription: 'Demo', author: { name: 'someone' }, license: 'MIT', keywords: ['demo'], + icon: 'assets/icon.png', category: 'Developer Tools', + harnesses: Object.fromEntries(HARNESSES.map((h) => [h, true])), + ...over, + }; +} + +function put(root: string, path: string, content: string) { + mkdirSync(join(root, path, '..'), { recursive: true }); + writeFileSync(join(root, path), content); +} + +// A plugin folder named NAME (Gemini wants the folder to match), with one skill and an icon. +function fixture(cfg: Record = config()): string { + const root = join(mkdtempSync(join(tmpdir(), 'hpt-')), NAME); + mkdirSync(root); + put(root, 'plugin.config.json', JSON.stringify(cfg)); + put(root, 'assets/icon.png', 'png'); + put(root, 'skills/hello/SKILL.md', '---\nname: hello\ndescription: Use when testing.\nmetadata:\n version: "0.1.0"\n---\nBody\n'); + put(root, '.opencode/plugins/demo-plugin.js', 'export default {};\n'); + return root; +} + +const read = (root: string, p: string) => JSON.parse(readFileSync(join(root, p), 'utf8')); + +test('writes every enabled manifest, then --check is clean', () => { + const root = fixture(); + const p = plan(root); + assert.deepEqual(p.errors, []); + assert.deepEqual(p.warnings, []); + write(root, p); + for (const f of ['plugin.json', '.claude-plugin/plugin.json', '.claude-plugin/marketplace.json', + '.cursor-plugin/plugin.json', '.antigravity-plugin/plugin.json', 'gemini-extension.json', + 'skills/index.json', '.kimi-plugin/plugin.json', '.muse-plugin/plugin.json', 'package.json']) { + assert.ok(existsSync(join(root, f)), f); + } + assert.deepEqual(diff(root, plan(root)), { stale: [], missing: [], leftover: [] }); + const ap = read(root, 'plugin.json'); + assert.equal(ap.$schema, 'https://agent-plugins.org/schemas/1.0.0/plugin.schema.json'); + assert.deepEqual(ap.extensions['com.openai'].hooks, {}); + assert.equal(read(root, '.claude-plugin/plugin.json').version, '1.2.3'); + assert.equal(read(root, '.claude-plugin/marketplace.json').plugins[0].source, './'); + assert.deepEqual(read(root, 'skills/index.json'), { skills: [{ name: 'hello', version: '0.1.0', files: ['SKILL.md'] }] }); + const pkg = read(root, 'package.json'); + // opencode documents an `exports` map, not `main`. + assert.deepEqual(pkg.exports, { '.': './.opencode/plugins/demo-plugin.js' }); + assert.equal('main' in pkg, false); + assert.ok(pkg.keywords.includes('pi-package')); + assert.deepEqual(pkg.pi, { skills: ['./skills'] }); +}); + +test('Cursor and Kimi manifests carry only documented fields', () => { + const root = fixture(config({ author: { name: 'someone', email: 'a@b.c', url: 'https://b.c' } })); + put(root, '.opencode/plugins/demo-plugin.js', 'export default {};'); + write(root, plan(root)); + const cursor = read(root, '.cursor-plugin/plugin.json'); + assert.equal('displayName' in cursor, false); + assert.equal(cursor.logo, 'assets/icon.png'); + assert.deepEqual(cursor.author, { name: 'someone', email: 'a@b.c' }); + const kimi = read(root, '.kimi-plugin/plugin.json'); + assert.equal('capabilities' in kimi.interface, false); + assert.equal(kimi.skills, './skills/'); +}); + +test('copies the icon into .claude-plugin/ and leaves the icon key out of the Claude manifest', () => { + const root = fixture(); + write(root, plan(root)); + assert.equal(readFileSync(join(root, '.claude-plugin/icon.png'), 'utf8'), 'png'); + assert.equal('icon' in read(root, '.claude-plugin/plugin.json'), false); + put(root, 'assets/icon.png', 'new'); + assert.deepEqual(diff(root, plan(root)).stale, ['.claude-plugin/icon.png']); + write(root, plan(root)); + assert.equal(readFileSync(join(root, '.claude-plugin/icon.png'), 'utf8'), 'new'); + put(root, 'plugin.config.json', JSON.stringify(config({ harnesses: { ...config().harnesses, claude: false } }))); + write(root, plan(root)); + assert.equal(existsSync(join(root, '.claude-plugin/icon.png')), false); +}); + +test('the opencode catalog leaves out Python caches, so running tests cannot make it stale', () => { + const root = fixture(); + put(root, 'skills/hello/scripts/x.py', 'pass\n'); + write(root, plan(root)); + put(root, 'skills/hello/scripts/__pycache__/x.cpython-312.pyc', 'c'); + put(root, 'skills/hello/scripts/y.pyc', 'c'); + assert.deepEqual(read(root, 'skills/index.json').skills[0].files, ['SKILL.md', 'scripts/x.py']); + assert.deepEqual(diff(root, plan(root)).stale, []); +}); + +test('check reports a hand edit as stale', () => { + const root = fixture(); + write(root, plan(root)); + put(root, 'gemini-extension.json', '{}\n'); + assert.deepEqual(diff(root, plan(root)).stale, ['gemini-extension.json']); +}); + +test('turning a harness off removes its files', () => { + const root = fixture(); + write(root, plan(root)); + const off = config(); + (off.harnesses as Record).cursor = false; + put(root, 'plugin.config.json', JSON.stringify(off)); + const p = plan(root); + assert.deepEqual(diff(root, p).leftover, ['.cursor-plugin/plugin.json']); + write(root, p); + assert.ok(!existsSync(join(root, '.cursor-plugin/plugin.json'))); +}); + +test('MCP servers get each harness variable spelling', () => { + const root = fixture(); + put(root, 'mcp/servers.json', JSON.stringify({ servers: { + local: { type: 'stdio', command: 'node', args: ['{root}/mcp/server.js'], env: { DATA: '{data}' } }, + remote: { type: 'http', url: 'https://example.com/mcp' }, + } })); + // Gemini has no data variable, so it must be off for {data} to be allowed. + const cfg = config(); + (cfg.harnesses as Record).gemini = false; + put(root, 'plugin.config.json', JSON.stringify(cfg)); + const p = plan(root); + assert.deepEqual(p.errors, []); + write(root, p); + const ap = read(root, 'mcp.json'); + assert.equal(ap.$schema, 'https://agent-plugins.org/schemas/1.0.0/mcp.schema.json'); + assert.deepEqual(ap.mcpServers.local, { type: 'stdio', command: 'node', args: ['${PLUGIN_ROOT}/mcp/server.js'], env: { DATA: '${PLUGIN_DATA}' } }); + assert.deepEqual(ap.mcpServers.remote, { type: 'streamable-http', url: 'https://example.com/mcp' }); + const cl = read(root, '.mcp.json'); + assert.deepEqual(cl.mcpServers.local.args, ['${CLAUDE_PLUGIN_ROOT}/mcp/server.js']); + assert.equal(cl.mcpServers.remote.type, 'http'); + assert.equal(read(root, '.cursor-plugin/plugin.json').mcpServers, './.mcp.json'); + assert.deepEqual(read(root, 'mcp_config.json').mcpServers.local.args, ['${PLUGIN_ROOT}/mcp/server.js']); +}); + +test('{data} with Gemini on is an error, and so is a path in command', () => { + const root = fixture(); + put(root, 'mcp/servers.json', JSON.stringify({ servers: { + a: { type: 'stdio', command: 'node', args: ['{data}/x'] }, + b: { type: 'stdio', command: '{root}/bin/server' }, + } })); + const errors = plan(root).errors.join('\n'); + assert.match(errors, /a \(gemini\).*\{data\}/); + assert.match(errors, /server b: command must be one bare token/); +}); + +test('Gemini gets ${extensionPath} and a context file when GEMINI.md exists', () => { + const root = fixture(); + put(root, 'GEMINI.md', '# Context\n'); + put(root, 'mcp/servers.json', JSON.stringify({ servers: { s: { type: 'stdio', command: 'node', args: ['{root}/s.js'] } } })); + write(root, plan(root)); + const g = read(root, 'gemini-extension.json'); + assert.equal(g.contextFileName, 'GEMINI.md'); + assert.deepEqual(g.mcpServers.s.args, ['${extensionPath}/s.js']); +}); + +test('agents become Copilot .agent.md files with name and description only', () => { + const root = fixture(); + put(root, 'agents/reviewer.md', '---\nname: reviewer\ndescription: Reviews code.\nmodel: sonnet\n---\n\nYou review code.\n'); + write(root, plan(root)); + const out = readFileSync(join(root, 'com.github.copilot/agents/reviewer.agent.md'), 'utf8'); + assert.equal(out, '---\nname: "reviewer"\ndescription: "Reviews code."\n---\n\nYou review code.\n'); + put(root, 'agents/reviewer.md', 'no frontmatter'); + assert.match(plan(root).errors.join(), /agents\/reviewer.md/); +}); + +test('Cursor manifest points at hooks-cursor.json when it exists', () => { + const root = fixture(); + put(root, 'hooks/hooks-cursor.json', '{"version":1,"hooks":{}}\n'); + write(root, plan(root)); + assert.equal(read(root, '.cursor-plugin/plugin.json').hooks, './hooks/hooks-cursor.json'); +}); + +test('Pi extensions are listed from .pi/extensions', () => { + const root = fixture(); + put(root, '.pi/extensions/demo.ts', 'export default function () {}\n'); + write(root, plan(root)); + assert.deepEqual(read(root, 'package.json').pi.extensions, ['./.pi/extensions/demo.ts']); +}); + +test('config problems are reported, and nothing is generated', () => { + const root = fixture(config({ name: 'Bad_Name', version: '1', displayName: 'x'.repeat(31) })); + const p = plan(root); + assert.equal(p.files.size, 0); + const all = p.errors.join('\n'); + assert.match(all, /name must be lowercase/); + assert.match(all, /version must be semver/); + assert.match(all, /displayName must be at most 30/); +}); + +test('skill problems are reported', () => { + const root = fixture(); + put(root, 'skills/other/SKILL.md', '---\nname: wrong\ndescription: Use when.\n---\n'); + put(root, 'skills/empty/.keep', ''); + put(root, 'skills/hello/sub/SKILL.md', '---\nname: sub\ndescription: x\n---\n'); + const all = plan(root).errors.join('\n'); + assert.match(all, /skills\/other\/SKILL.md: name must equal the folder name/); + assert.match(all, /skills\/other\/SKILL.md: metadata.version is required/); + assert.match(all, /skills\/empty\/ has no SKILL.md/); + assert.match(all, /skills\/hello\/ has a nested SKILL.md/); +}); + +test('opencode on without its entry file is an error', () => { + const root = fixture(); + const cfg = config(); + put(root, 'plugin.config.json', JSON.stringify(cfg)); + writeFileSync(join(root, '.opencode/plugins/demo-plugin.js'), ''); + assert.deepEqual(plan(root).errors, []); + put(root, 'plugin.config.json', JSON.stringify(config({ name: 'other-name' }))); + assert.match(plan(root).errors.join(), /\.opencode\/plugins\/other-name\.js does not exist/); +}); + +test('per-harness blocks merge into one manifest only', () => { + const root = fixture(config({ claude: { userConfig: { k: { type: 'string', title: 'K', description: 'k' } } }, codex: { interface: { capabilities: ['Read'] } } })); + write(root, plan(root)); + assert.ok(read(root, '.claude-plugin/plugin.json').userConfig.k); + assert.equal(read(root, '.cursor-plugin/plugin.json').userConfig, undefined); + const openai = read(root, 'plugin.json').extensions['com.openai']; + assert.deepEqual(openai.interface.capabilities, ['Read']); + assert.equal(openai.interface.displayName, 'Demo'); +}); + +test('name rule and helpers', () => { + assert.equal(nameProblem('good-name-2'), undefined); + for (const bad of ['claude', 'claude-x', 'anthropic-x', 'a.b', 'a--b', '-a', 'A', 'x'.repeat(65)]) { + assert.ok(nameProblem(bad), bad); + } + assert.deepEqual(merge({ a: { b: 1, c: [1] } }, { a: { c: [2] } }), { a: { b: 1, c: [2] } }); + const fm = parseFrontmatter('---\nname: x\ndescription: >-\n one\n two\nmetadata:\n version: "1.0.0"\n---\nbody'); + assert.deepEqual(fm?.data, { name: 'x', description: 'one two', metadata: { version: '1.0.0' } }); + assert.equal(fm?.body, 'body'); +}); + +test('repoNameOf reads the last path segment of the repository URL', () => { + assert.equal(repoNameOf('https://github.com/o/x-plugin'), 'x-plugin'); + assert.equal(repoNameOf('https://github.com/o/x-plugin.git'), 'x-plugin'); + assert.equal(repoNameOf('https://github.com/o/x-plugin/'), 'x-plugin'); + assert.equal(repoNameOf('https://github.com/'), undefined); + assert.equal(repoNameOf(undefined), undefined); +}); + +test('a repo named -plugin: every manifest says , Gemini says the repo name', () => { + const root = fixture(config({ name: 'demo', repository: 'https://github.com/someone/demo-plugin' })); + put(root, '.opencode/plugins/demo.js', 'export default {};\n'); + const p = plan(root); + assert.deepEqual(p.errors, []); + assert.deepEqual(p.warnings, []); + write(root, p); + for (const f of ['plugin.json', '.claude-plugin/plugin.json', '.cursor-plugin/plugin.json', + '.antigravity-plugin/plugin.json', '.kimi-plugin/plugin.json', '.muse-plugin/plugin.json', 'package.json']) { + assert.equal(read(root, f).name, 'demo', f); + } + const m = read(root, '.claude-plugin/marketplace.json'); + assert.equal(m.name, 'demo'); + assert.equal(m.plugins[0].name, 'demo'); + assert.equal(read(root, 'gemini-extension.json').name, 'demo-plugin'); +}); + +test('a repo named -plugin with any other name is an error', () => { + const root = fixture(config({ repository: 'https://github.com/someone/demo-plugin' })); + assert.match(plan(root).errors.join('\n'), + /name must be "demo": the repository is "demo-plugin", and a plugin is named after its repository without "-plugin"/); +}); + +test('other repository names put no rule on the name, and Gemini uses the name', () => { + const root = fixture(config({ repository: 'https://github.com/someone/demo-tools' })); + const p = plan(root); + assert.deepEqual(p.errors, []); + write(root, p); + assert.equal(read(root, 'gemini-extension.json').name, 'demo-plugin'); +}); + +test('the folder a checkout sits in does not matter', () => { + const root = fixture(); + const moved = `${root}-worktree`; + renameSync(root, moved); + const p = plan(moved); + assert.deepEqual(p.errors, []); + assert.deepEqual(p.warnings, []); + write(moved, p); + assert.deepEqual(diff(moved, plan(moved)), { stale: [], missing: [], leftover: [] }); +}); + +test('an icon that is a generated path is a config error and the file is left alone', () => { + const root = fixture(config({ icon: '.claude-plugin/icon.png' })); + put(root, '.claude-plugin/icon.png', 'mine'); + const result = plan(root); + assert.ok(result.errors.some((e) => e.includes( + 'icon must not be a generated file (.claude-plugin/icon.png): keep the source icon elsewhere, such as assets/icon.png'))); + assert.equal(readFileSync(join(root, '.claude-plugin/icon.png'), 'utf8'), 'mine'); +}); + +test('cliff.toml is generated: commit link from repository, merge commits skipped', () => { + const root = fixture(config({ name: 'demo', repository: 'https://github.com/someone/demo-plugin.git' })); + put(root, '.opencode/plugins/demo.js', 'export default {};\n'); + const p = plan(root); + assert.deepEqual(p.errors, []); + write(root, p); + const toml = readFileSync(join(root, 'cliff.toml'), 'utf8'); + assert.match(toml, /^# Generated from plugin\.config\.json by scripts\/build\.ts; don't edit by hand\./); + assert.ok(toml.includes('](https://github.com/someone/demo-plugin/commit/{{ commit.id }})')); + assert.ok(toml.includes('{ message = "^Merge (pull request|branch)", skip = true },')); + assert.ok(toml.includes(String.raw`tag_pattern = "v[0-9]+\\.[0-9]+\\.[0-9]+$"`)); + assert.ok(toml.includes(String.raw`{ message = "^chore\\(release\\)", skip = true },`)); + assert.ok(toml.includes('{{ commit.message | split(pat="\\n") | first | upper_first | trim }} \\\n')); + assert.deepEqual(diff(root, plan(root)), { stale: [], missing: [], leftover: [] }); +}); + +test('cliff.toml without a repository prints the commit id as plain text', () => { + const root = fixture(); + write(root, plan(root)); + const toml = readFileSync(join(root, 'cliff.toml'), 'utf8'); + assert.ok(!toml.includes('/commit/')); + assert.ok(toml.includes('{{ commit.id | truncate(length=7, end="") }}')); +}); + +test('a hand-edited cliff.toml is stale', () => { + const root = fixture(); + write(root, plan(root)); + writeFileSync(join(root, 'cliff.toml'), readFileSync(join(root, 'cliff.toml'), 'utf8') + '# edit\n'); + assert.ok(diff(root, plan(root)).stale.includes('cliff.toml')); +}); + +test('changelog.commitPreprocessors go into cliff.toml before the commit parsers', () => { + const pre = [{ pattern: '^Merge pull request #10 from x/y', replace: 'feat(skills): add y (#10)' }]; + const root = fixture(config({ changelog: { commitPreprocessors: pre } })); + put(root, '.opencode/plugins/demo-plugin.js', 'export default {};'); + const p = plan(root); + assert.deepEqual(p.errors, []); + write(root, p); + const toml = readFileSync(join(root, 'cliff.toml'), 'utf8'); + const line = ' { pattern = "^Merge pull request #10 from x/y", replace = "feat(skills): add y (#10)" },'; + assert.ok(toml.includes(`commit_preprocessors = [\n${line}\n]\ncommit_parsers = [`), toml); + const bad = plan(fixture(config({ changelog: { commitPreprocessors: [{ pattern: 1 }] } }))); + assert.ok(bad.errors.some((e) => /changelog\.commitPreprocessors/.test(e)), bad.errors.join('\n')); +}); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..f0462e5 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ES2023", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "erasableSyntaxOnly": true, + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "types": ["node"] + }, + "include": ["scripts/**/*.ts", "tests/**/*.ts"] +} From 4d855297e5932c79648f316f52ddc0a48023d73c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 04:28:37 +0000 Subject: [PATCH 2/2] fix: Cursor manifest gets displayName (generator from the template) Copy the template's updated generator (rjstone/harness-plugin-template #5): Cursor's official plugin-template sets displayName, so the generated .cursor-plugin/plugin.json carries "GitHub Ninja" again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QT6szwxMB79y5MRzxuSau4 --- .cursor-plugin/plugin.json | 1 + AGENTS.md | 3 ++- scripts/generate.ts | 15 +++++++-------- tests/build.test.ts | 17 +++++++++++++++-- 4 files changed, 25 insertions(+), 11 deletions(-) diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json index 540f3be..36ac23b 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -22,5 +22,6 @@ "secret-scanning", "security" ], + "displayName": "GitHub Ninja", "logo": "assets/icon.png" } diff --git a/AGENTS.md b/AGENTS.md index 21e3b30..9bd7238 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,7 +26,8 @@ only skills; commands, agents or hooks may follow. - Claude Code: `.claude-plugin/plugin.json` (the plugin) and `.claude-plugin/marketplace.json` (a one-plugin local marketplace, source `./`), both generated. Skills are found in `skills/` by default. - - Cursor: `.cursor-plugin/plugin.json`, generated, with `"logo": "assets/icon.png"` and no + - Cursor: `.cursor-plugin/plugin.json`, generated, with `displayName` (as Cursor's official + plugin-template sets it), `"logo": "assets/icon.png"` and no component path fields (a path field would replace Cursor's default `skills/` discovery). There is no `.cursor-plugin/marketplace.json`: this is a single-plugin repo. - skills.sh (`npx skills add rjstone/github-ninja-plugin`): no manifest; it finds `skills/`. diff --git a/scripts/generate.ts b/scripts/generate.ts index 3380ca2..88d98d3 100644 --- a/scripts/generate.ts +++ b/scripts/generate.ts @@ -348,9 +348,10 @@ export function plan(root: string, configPath = join(root, 'plugin.config.json') } if (on.cursor) { files.set('.cursor-plugin/plugin.json', json(merge(clean({ - // Only documented fields: no `displayName`, `author` without `url`, and `logo` written - // as the docs show it (relative, no `./`). - ...common, author: clean({ name: c.author.name, email: c.author.email }), logo: c.icon, + // As the docs and Cursor's official plugin-template show: `displayName` (the template + // sets it), `author` without `url`, and `logo` relative with no `./`. + ...common, author: clean({ name: c.author.name, email: c.author.email }), + displayName: c.displayName, logo: c.icon, // Cursor expands ${CLAUDE_PLUGIN_ROOT} but not ${PLUGIN_ROOT} (conflict 2). mcpServers: mcp ? './.mcp.json' : undefined, hooks: exists('hooks/hooks-cursor.json') ? './hooks/hooks-cursor.json' : undefined, @@ -397,11 +398,9 @@ export function plan(root: string, configPath = join(root, 'plugin.config.json') commands: [], hooks: [], mcpServers: [], reminders: [], }, }, c.muse))); - files.set('.muse-plugin/marketplace.json', json({ - name: c.name, description: c.description, - owner: clean({ name: c.author.name, email: c.author.email }), - plugins: [{ name: c.name, description: c.description, version: c.version, source: './', author }], - })); + // No .muse-plugin/marketplace.json: Muse reads marketplace.json, .agents/plugins/ or + // .claude-plugin/marketplace.json (the last is generated for Claude). It stays in + // FIXED_OUTPUTS so a copy from an older build is removed as a leftover. } // package.json: always written (it also holds the dev scripts); opencode and Pi add to it. diff --git a/tests/build.test.ts b/tests/build.test.ts index 4fc78b3..29505be 100644 --- a/tests/build.test.ts +++ b/tests/build.test.ts @@ -64,12 +64,13 @@ test('writes every enabled manifest, then --check is clean', () => { assert.deepEqual(pkg.pi, { skills: ['./skills'] }); }); -test('Cursor and Kimi manifests carry only documented fields', () => { +test('Cursor and Kimi manifests carry the fields their docs and official examples use', () => { const root = fixture(config({ author: { name: 'someone', email: 'a@b.c', url: 'https://b.c' } })); put(root, '.opencode/plugins/demo-plugin.js', 'export default {};'); write(root, plan(root)); const cursor = read(root, '.cursor-plugin/plugin.json'); - assert.equal('displayName' in cursor, false); + // Cursor's official plugin-template sets displayName, though its reference page does not list it. + assert.equal(cursor.displayName, 'Demo'); assert.equal(cursor.logo, 'assets/icon.png'); assert.deepEqual(cursor.author, { name: 'someone', email: 'a@b.c' }); const kimi = read(root, '.kimi-plugin/plugin.json'); @@ -345,3 +346,15 @@ test('changelog.commitPreprocessors go into cliff.toml before the commit parsers const bad = plan(fixture(config({ changelog: { commitPreprocessors: [{ pattern: 1 }] } }))); assert.ok(bad.errors.some((e) => /changelog\.commitPreprocessors/.test(e)), bad.errors.join('\n')); }); + +test('Muse gets only .muse-plugin/plugin.json; an old .muse-plugin/marketplace.json is a leftover', () => { + const root = fixture(); + put(root, '.opencode/plugins/demo-plugin.js', 'export default {};'); + put(root, '.muse-plugin/marketplace.json', '{}'); + const p = plan(root); + assert.equal(p.files.has('.muse-plugin/marketplace.json'), false); + assert.deepEqual(diff(root, p).leftover, ['.muse-plugin/marketplace.json']); + write(root, p); + assert.equal(existsSync(join(root, '.muse-plugin/marketplace.json')), false); + assert.equal(read(root, '.muse-plugin/plugin.json').name, read(root, 'plugin.json').name); +});