diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 846e52a..95e9ca0 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,7 @@ { "name": "ucsd-decorator", - "version": "1.0.0", + "version": "2.1.0", + "license": "MIT", "description": "Build and edit UC San Diego web pages on the Decorator 5 design system without damaging the shared page chrome. Provides one writable canvas, a pinned source of truth for markup, and a CI-checkable chrome contract.", "author": { "name": "Cristian Horta, Web Technology Services, UC San Diego" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 92c2fe0..bccb4c0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,4 +1,4 @@ -# The kit's own gate. Three things must hold on every push: +# The kit's own gate. Four things must hold on every push: # # * the committed CLAUDE.md / AGENTS.md / .cursorrules / # copilot-instructions.md are current with rules/ — they are generated, and a @@ -7,6 +7,8 @@ # cannot reach the public page in a shape that makes the sync throw # * `add` still refuses to write AGENTS.md, which is the property that keeps # this kit safe to run inside a repository that has its own agent contract +# * the npm tarball still ships every file the CLI reads at runtime — tested +# by installing it, since the rest of the suite runs from this checkout name: CI on: diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..fcf9f84 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,38 @@ +# Publishes ucsd-decorator-kit to npm when a GitHub release is published. +# +# Uses npm trusted publishing: npm exchanges this run's OIDC token for a +# short-lived publish credential, so there is no NPM_TOKEN secret to leak, and +# it attaches a provenance attestation tying the tarball to this commit and +# this workflow. The trusted publisher is configured on npmjs.com, not here — +# see RELEASING.md, including why the first publish is done by hand. +name: Publish + +on: + release: + types: [published] + +permissions: + contents: read + id-token: write + +jobs: + publish: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + # Trusted publishing needs npm 11.5.1 or later, which Node 22 does not + # bundle. No cache: npm advises against caching in release builds. + - uses: actions/setup-node@v4 + with: + node-version: 24 + registry-url: https://registry.npmjs.org + - name: Release tag matches package.json + run: | + expected="v$(node -p 'require("./package.json").version')" + if [ "$GITHUB_REF_NAME" != "$expected" ]; then + echo "::error::Release tag $GITHUB_REF_NAME does not match package.json ($expected). Bump the version in a pull request first." + exit 1 + fi + # prepublishOnly runs `npm test`, including test/package.test.mjs against + # the tarball this step is about to upload. + - run: npm publish diff --git a/CHANGELOG.md b/CHANGELOG.md index d3c01d1..dbc5cdd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## Unreleased +## 2.1.0 ### Added @@ -58,6 +58,42 @@ - Heading demotion in compiled rules no longer rewrites `# comment` lines inside fenced code blocks. +- `decorator-kit.json`'s `$schema` pointed at a GitHub URL that returned 404. + It now points at the schema in the kit version that wrote the file, on + jsDelivr: `https://cdn.jsdelivr.net/npm/ucsd-decorator-kit@/contracts/decorator-kit.schema.json`. +- **The Claude Code Stop hook reported a regression after every turn in + projects without the kit installed.** It ran `npx ucsd-decorator-kit verify + || exit 2`. With the kit not on npm, npx failed, the command exited 2, and + the agent was told the chrome gate had found a regression when nothing had + been checked. Now on npm, the same command would download the newest release + after every turn. The hook now runs the kit from `node_modules` and never + calls npx. When the kit is not installed, the gate skips and a second hook + tells the person, not the agent. +- **`add --with-ci`, `--with-hook`, and `--with-decorator` now install the + kit.** The workflow `--with-ci` wrote runs `npm run decorator:check`, but + only `--with-decorator` added that script, and no flag installed the kit it + calls. Each of the three now adds `ucsd-decorator-kit` as a devDependency, at + the version being run, plus the `decorator:*` scripts. A project that + already lists the kit keeps its version. `init` now installs the kit at the + version being run, too, rather than the newest. +- Re-running `add` on a project `init` set up dropped `AGENTS.md` from + `decorator-kit.json`, so `sync` stopped refreshing it. `add` now keeps it. + +### Packaging + +- First release published to npm. Later releases publish from a GitHub + release through trusted publishing, with a provenance attestation; see + `RELEASING.md`. +- Licensed under MIT. The package previously declared ISC and shipped no + license file. +- The tarball now includes `CHANGELOG.md`, and leaves out + `scripts/compile-rules.mjs`, `scripts/check-library.mjs`, and + `scripts/sync-library.mjs`, which only work from a checkout of this + repository. +- `npm test` installs the packed tarball into an empty project and runs `add`, + `check`, and `verify` from it, so a file missing from `files` fails CI. +- `.claude-plugin/plugin.json` carried version 1.0.0 through the 2.0.0 + release. It now matches `package.json`, and `npm test` fails if they differ. ### Upgrading @@ -67,6 +103,18 @@ an agent's. - Run `sync` after upgrading so the managed rule files carry the new rule; `check` fails until you do. +- **Projects set up before 2.1.0**, which most likely installed the kit + straight from GitHub, don't have it in `node_modules`. Install it, re-run + `add --with-hook` if the project uses the Claude Code hook, then sync: + + ```bash + npm install --save-dev ucsd-decorator-kit + npx ucsd-decorator-kit add --with-hook + npx ucsd-decorator-kit sync + ``` + + `add --with-hook` replaces the old hook, merges into the rest of + `.claude/settings.json`, and skips rule files that already exist. ## 2.0.0 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ad169f6 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 The Regents of the University of California + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index efdfde0..37cc135 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,9 @@ on this page also works straight from the repository, which is what CI uses: npx -y github:UCSD/decorator-kit init ``` +That runs whatever is on `main` at the time, released or not, so use it to try +a change, not to set up a site. + That installs `ucsd-decorator-v5` — the Decorator itself — plus this kit, writes the rules in the format each AI tool reads, installs the skill, wires Dependabot and a CI workflow, and — for Claude Code — adds a `Stop` hook that @@ -50,6 +53,11 @@ for the Claude Code Stop hook. The last one merges into an existing `.claude/settings.json` rather than overwriting it, so a project's own hooks and permissions survive. +Each of those three flags also adds `ucsd-decorator-kit` as a devDependency, +at the version you ran, along with the `decorator:*` npm scripts. The workflow +and the hook run the kit from `node_modules`, and without it installed they +have nothing to run. A project that already lists the kit keeps its version. + ### Staying current | Command | Does | @@ -61,7 +69,10 @@ and permissions survive. Both `ucsd-decorator-v5` and `ucsd-decorator-kit` are devDependencies, so Dependabot opens a pull request when either moves: the Decorator and the rules -update through one mechanism. `check` fails the build if a kit upgrade landed +update through one mechanism. With the kit installed, `npx ucsd-decorator-kit` +runs that installed copy. Without it, npx downloads the newest release on +every run, so the kit version changes whenever a release ships, not when you +upgrade. `check` fails the build if a kit upgrade landed without a `sync`, so a project cannot quietly run last year's rules. `drift` covers the gap Dependabot cannot see — a push to `UCSD/Decorator` or a @@ -221,8 +232,10 @@ contracts/ portable chrome regions, selector rules, and checks/ the chrome integrity gate: chrome-contract.mjs (CLI) and lib/ (tiers 1-4) — runs standalone, `bin/cli.mjs verify` is a thin wrapper around it -test/ including the AGENTS.md refusal and the replayed - chrome-regression incidents +test/ including the AGENTS.md refusal, the replayed + chrome-regression incidents, and an install of + the packed tarball +RELEASING.md how a version reaches npm ``` `CLAUDE.md`, `AGENTS.md`, `.cursorrules`, and `.github/copilot-instructions.md` diff --git a/RELEASING.md b/RELEASING.md new file mode 100644 index 0000000..2f3ef26 --- /dev/null +++ b/RELEASING.md @@ -0,0 +1,50 @@ +# Releasing + +`ucsd-decorator-kit` is published to npm from GitHub Actions, by +[`.github/workflows/publish.yml`](.github/workflows/publish.yml), when a GitHub +release is published. Nobody runs `npm publish` from a laptop after the first +release. + +## Cutting a release + +1. In a pull request: + - Set the new version in `package.json` and `.claude-plugin/plugin.json`. + `npm test` fails if the two differ. + - Move the `## Unreleased` entries in `CHANGELOG.md` under a heading for the + new version. +2. Merge it. +3. Create a GitHub release from `main` with the tag `v` — for example + `v2.1.0`. Publishing the release starts the workflow. + +The workflow refuses a tag that doesn't match `package.json`, and `npm publish` +runs `npm test` first (`prepublishOnly`). That includes +`test/package.test.mjs`, which packs the tarball, installs it into an empty +project, and runs `add`, `check`, and `verify` from the installed copy. + +To see exactly what will ship: + +```bash +npm pack --dry-run +``` + +## Ownership + +The package belongs to the `chorta` npm account, the same owner as +[`ucsd-decorator-v5`](https://www.npmjs.com/package/ucsd-decorator-v5). + +## First publish (one time) + +npm trusted publishing is configured from the package's settings page on +npmjs.com, which exists only once the package does. So the first version goes +up by hand: + +1. From a clean checkout of `main`, signed in to npm as `chorta` with + two-factor authentication on, run `npm publish`. +2. On npmjs.com, open the package's **Settings** and add a trusted publisher: + GitHub Actions, organization `UCSD`, repository `decorator-kit`, workflow + `publish.yml`. +3. On the same page, under publishing access, require two-factor + authentication and disallow tokens. Trusted publishing is unaffected, and no + long-lived token can publish the package. + +Every release after that goes through the steps above. diff --git a/bin/cli.mjs b/bin/cli.mjs index 6fc7c10..479496e 100755 --- a/bin/cli.mjs +++ b/bin/cli.mjs @@ -43,6 +43,15 @@ const SKILL_DEST = ".claude/skills/ucsd-decorator"; const PROJECT_CONTRACT = "AGENTS.md"; const DECORATOR_PACKAGE = "ucsd-decorator-v5"; const CLAUDE_SETTINGS = ".claude/settings.json"; +// Stop hook commands earlier releases installed. Before 2.1.0 was on npm this +// one failed in any project without the kit in node_modules, and the agent was +// told the gate had found a regression. Once it is on npm, that same project +// would fetch the newest release after every turn. `add --with-hook` replaces it. +const LEGACY_HOOK_COMMANDS = new Set(["npx ucsd-decorator-kit verify || exit 2"]); +// Each of these writes something that runs the kit from this project's +// node_modules — the workflow and scripts through `decorator:*`, the hook +// directly — so each also installs the kit as a devDependency. +const KIT_FLAGS = ["with-ci", "with-hook", "with-decorator"]; // Install-once, like the CI templates: both directories belong to the project's // developers, so their READMEs are never in `manages` and never overwritten. const CANVAS_RULES_README = `${CANVAS_RULES_DIR}/README.md`; @@ -67,6 +76,7 @@ const has = (name) => argv.includes(`--${name}`); const kitPackage = JSON.parse(await readFile(path.join(KIT_ROOT, "package.json"), "utf8")); const VERSION = kitPackage.version; +const KIT_SPEC = `${kitPackage.name}@${VERSION}`; const NOTE = ``; @@ -142,7 +152,9 @@ async function readManifest() { async function writeManifest(managed) { const previous = await readManifest(); const manifest = { - $schema: "https://github.com/UCSD/decorator-kit/contracts/decorator-kit.schema.json", + // Pinned to the version that wrote this file, so an editor validates it + // against the schema it was written for. + $schema: `https://cdn.jsdelivr.net/npm/${kitPackage.name}@${VERSION}/contracts/decorator-kit.schema.json`, kitVersion: VERSION, // The one writable region. Everything else on the page is chrome. A project // with a different shell — the Antigravity Code Kit uses div#ag-app-canvas — @@ -217,11 +229,15 @@ async function addScripts() { * * Three things get merged in: * - * - The Stop hook: `npx ucsd-decorator-kit verify` on Stop, backgrounded via - * `asyncRewake` so it never blocks the turn from ending, but if it finds a - * regression the agent is woken back up with the findings fed back as - * context — the exit-code-2 translation (`|| exit 2`) is what asyncRewake - * keys on. + * - Two Stop hooks. The first runs `verify` from this project's + * node_modules, backgrounded via `asyncRewake` so it never blocks the turn + * from ending, but if it finds a regression the agent is woken back up + * with the findings fed back as context — the exit-code-2 translation + * (`|| exit 2`) is what asyncRewake keys on. It never runs `npx`, which + * would fetch whatever release is newest on the registry after every turn. + * When the kit is not installed it exits 0, and the second hook tells the + * user instead: a non-blocking error, shown to the person, not the agent. + * Hooks an earlier release installed (LEGACY_HOOK_COMMANDS) are replaced. * - `permissions.deny` on Edit/Write of the three chrome `*.local.json` * files — a hard block, matching rules/00-canvas.md's unconditional "never * create or edit" language for the same files. @@ -235,7 +251,7 @@ async function addScripts() { async function installClaudeSettingsHook() { const template = JSON.parse(await readFile(path.join(TEMPLATES, "claude-settings.json"), "utf8")); const [stopGroup] = template.hooks.Stop; - const command = stopGroup.hooks[0].command; + const commands = stopGroup.hooks.map((hook) => hook.command); const absolute = path.join(cwd, CLAUDE_SETTINGS); const existingRaw = await readFile(absolute, "utf8").catch(() => null); @@ -252,8 +268,18 @@ async function installClaudeSettingsHook() { settings.hooks ??= {}; settings.hooks.Stop ??= []; - const hookInstalled = settings.hooks.Stop.some((group) => group.hooks?.some((hook) => hook.command === command)); - if (!hookInstalled) { + const installed = new Set(settings.hooks.Stop.flatMap((group) => group.hooks ?? []).map((hook) => hook.command)); + const current = commands.every((command) => installed.has(command)); + const legacy = [...LEGACY_HOOK_COMMANDS].some((command) => installed.has(command)); + if (!current || legacy) { + // Take out every hook this kit has ever installed, leaving the project's + // own hooks where they are, then add the current set as one group. + const ours = (hook) => commands.includes(hook.command) || LEGACY_HOOK_COMMANDS.has(hook.command); + settings.hooks.Stop = settings.hooks.Stop.flatMap((group) => { + if (!group.hooks?.some(ours)) return [group]; + const hooks = group.hooks.filter((hook) => !ours(hook)); + return hooks.length ? [{ ...group, hooks }] : []; + }); settings.hooks.Stop.push(stopGroup); changed = true; } @@ -299,6 +325,28 @@ function install(packages) { } } +/** + * Install the kit as a devDependency, at the version doing the installing. + * + * The same version, not the newest: the files this run just generated carry + * its version, and a newer kit would call them stale on the first `check`. + * A project that already declares the kit keeps the version it chose. + */ +async function installKit() { + const raw = await readFile(path.join(cwd, "package.json"), "utf8").catch(() => null); + const manifest = raw === null ? {} : JSON.parse(raw); + if (manifest.devDependencies?.[kitPackage.name] ?? manifest.dependencies?.[kitPackage.name]) return true; + return install([KIT_SPEC]); +} + +function printKitMissing() { + console.log(`${kitPackage.name} is not installed here. The decorator:* npm scripts, the CI`); + console.log("workflow, and the Claude Code hook all run it from node_modules, so until it"); + console.log("is installed they fail, and the hook skips the chrome gate. Install it:"); + console.log(""); + console.log(` npm install --save-dev ${KIT_SPEC}`); +} + async function decoratorSourcePresent() { if (await exists(path.join(cwd, "node_modules", DECORATOR_PACKAGE))) return `node_modules/${DECORATOR_PACKAGE}`; if (await exists(path.join(cwd, "vendor/decorator-5"))) return "vendor/decorator-5"; @@ -349,7 +397,7 @@ async function init() { // Two separate installs so one failure does not mask the other. The Decorator // is what agents read; the kit is what `sync` and `check` run from later. const decoratorInstalled = install([DECORATOR_PACKAGE]); - const kitInstalled = install([kitPackage.name]); + const kitInstalled = install([KIT_SPEC]); const outputs = await renderFor(true); for (const [relativePath, contents] of outputs) await put(relativePath, contents, { force: true }); @@ -376,11 +424,7 @@ async function init() { } if (!kitInstalled) { console.log(""); - console.log(`${kitPackage.name} is not installed here, so the decorator:* npm scripts`); - console.log("will not resolve. Run the commands through npx instead:"); - console.log(""); - console.log(" npx ucsd-decorator-kit@latest sync"); - console.log(" npx ucsd-decorator-kit@latest check"); + printKitMissing(); } console.log(""); console.log("Open your AI tool in this directory and describe the site you want. It will"); @@ -413,16 +457,27 @@ async function add() { } if (has("with-decorator")) { install([DECORATOR_PACKAGE]); + } + let kitInstalled = true; + if (KIT_FLAGS.some(has)) { + kitInstalled = await installKit(); await addScripts(); } - const managed = [...outputs.keys(), SKILL_DEST]; + // Re-running `add` on a project `init` set up must not drop AGENTS.md from + // `manages` — `sync` would silently stop refreshing it. const existing = await readManifest(); + const keepsContract = existing?.manages?.includes(PROJECT_CONTRACT) ? [PROJECT_CONTRACT] : []; + const managed = [...outputs.keys(), ...keepsContract, SKILL_DEST]; await writeManifest(managed); if (!existing) report.wrote.push(MANIFEST); console.log(""); printReport(); + if (!kitInstalled) { + console.log(""); + printKitMissing(); + } const source = await decoratorSourcePresent(); console.log(""); @@ -438,7 +493,8 @@ async function add() { if (!has("with-ci")) { console.log(""); console.log("CI was not touched. `add --with-ci` writes a Dependabot config and a"); - console.log("workflow that runs `check` on pull requests and watches upstream weekly."); + console.log("workflow that runs `check` on pull requests and watches upstream weekly,"); + console.log(`and adds ${kitPackage.name} as a devDependency for it to run.`); } if (!has("with-hook")) { console.log(""); @@ -446,7 +502,8 @@ async function add() { console.log("`verify` in the background after each turn and wakes the agent back up — not"); console.log("the user, and not blocking anything meanwhile — if it finds a regression. It"); console.log("also adds permission rules: denying edits to the chrome *.local.json files,"); - console.log("and requiring your approval before any Bash command matching --accept."); + console.log("and requiring your approval before any Bash command matching --accept. Like"); + console.log(`--with-ci, it adds ${kitPackage.name} as a devDependency for the hook to run.`); } } @@ -603,6 +660,8 @@ Flags for \`add\`: --with-ci also write .github/dependabot.yml and a workflow --with-hook also add a Claude Code Stop hook that runs \`verify\`, plus permission rules guarding the chrome *.local.json files and --accept +Each of the three also adds ${kitPackage.name} as a devDependency, and the +decorator:* npm scripts, because what it writes runs the kit from node_modules. Flags for \`verify\` (passed straight through to checks/chrome-contract.mjs): --check run all four tiers, exit 1 on any finding (default) diff --git a/checks/README.md b/checks/README.md index 5127719..837f382 100644 --- a/checks/README.md +++ b/checks/README.md @@ -45,14 +45,25 @@ produced the commit, since it runs on GitHub's infrastructure, not inside whatever session made the change. **A Claude Code Stop hook, plus permission guards** — `init`, or -`add --with-hook`, merges a `Stop` hook into `.claude/settings.json` (see -`templates/claude-settings.json`) that runs `npx ucsd-decorator-kit verify` -after every turn. It runs in the background — `asyncRewake: true` — so it -never blocks the turn from ending; if it finds a regression, the agent is -woken back up afterward with the findings fed back as context, in the same -turn that broke it, rather than waiting for CI or a human to notice. The -trigger is exit code 2, not `verify`'s own exit code 1, hence the hook -command being `npx ucsd-decorator-kit verify || exit 2`. The same template +`add --with-hook`, merges two `Stop` hooks into `.claude/settings.json` (see +`templates/claude-settings.json`). The first runs `verify` after every turn, +from `node_modules/.bin/ucsd-decorator-kit`. It runs in the background — +`asyncRewake: true` — so it never blocks the turn from ending; if it finds a +regression, the agent is woken back up afterward with the findings fed back as +context, in the same turn that broke it, rather than waiting for CI or a human +to notice. The trigger is exit code 2, not `verify`'s own exit code 1, hence +the command ending `verify || exit 2`. + +The hook never calls `npx`. In a project without the kit installed, npx would +download the newest release after every turn — and before the kit was on npm, +it failed, and the agent was told the gate had found a regression. Instead, +when the kit is missing the first hook exits 0 and the second prints a +non-blocking error saying so. That message goes to the person, because +installing a dependency is their call, not the agent's. `add --with-hook` also +installs the kit, and replaces the `npx ucsd-decorator-kit verify || exit 2` +hook earlier releases wrote. + +The same template also adds a `permissions` block: `deny` on editing the three chrome `*.local.json` files, and `ask` on any Bash command matching `--accept` — this only protects a project when the person working on it is using Claude diff --git a/contracts/decorator-kit.schema.json b/contracts/decorator-kit.schema.json index ecf1d0b..bce659c 100644 --- a/contracts/decorator-kit.schema.json +++ b/contracts/decorator-kit.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/UCSD/decorator-kit/contracts/decorator-kit.schema.json", + "$id": "https://cdn.jsdelivr.net/npm/ucsd-decorator-kit/contracts/decorator-kit.schema.json", "title": "decorator-kit.json", "description": "Written into a project by `ucsd-decorator-kit init` or `add`. Declares the writable canvas, where Decorator markup is read from, and exactly which files the kit owns in this project.", "type": "object", diff --git a/package.json b/package.json index 40a8733..74c4463 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ucsd-decorator-kit", - "version": "2.0.0", + "version": "2.1.0", "type": "module", "description": "Agent-facing contract for building on the UC San Diego Decorator 5 design system.", "keywords": [ @@ -21,26 +21,29 @@ "url": "https://github.com/UCSD/decorator-kit/issues" }, "bin": { - "ucsd-decorator-kit": "./bin/cli.mjs" + "ucsd-decorator-kit": "bin/cli.mjs" }, "files": [ "bin", - "scripts", + "scripts/lib", + "scripts/pin-decorator.mjs", "rules", "skills", "contracts", "checks", - "templates" + "templates", + "CHANGELOG.md" ], "scripts": { "compile": "node scripts/compile-rules.mjs", "check:library": "node scripts/check-library.mjs", "pin:decorator": "node scripts/pin-decorator.mjs", "test": "node scripts/compile-rules.mjs --check && node scripts/check-library.mjs && node --test test/*.test.mjs", - "sync:library": "node scripts/sync-library.mjs" + "sync:library": "node scripts/sync-library.mjs", + "prepublishOnly": "npm test" }, "engines": { "node": ">=22" }, - "license": "ISC" + "license": "MIT" } diff --git a/templates/claude-settings.json b/templates/claude-settings.json index c869481..5eae09b 100644 --- a/templates/claude-settings.json +++ b/templates/claude-settings.json @@ -18,10 +18,15 @@ "hooks": [ { "type": "command", - "command": "npx ucsd-decorator-kit verify || exit 2", + "command": "cd \"${CLAUDE_PROJECT_DIR:-.}\" && [ -x node_modules/.bin/ucsd-decorator-kit ] || exit 0; node_modules/.bin/ucsd-decorator-kit verify || exit 2", "asyncRewake": true, "rewakeSummary": "Chrome integrity gate found a regression — do not run verify --accept yourself; surface this to the user and stop.", "timeout": 120 + }, + { + "type": "command", + "command": "[ -x \"${CLAUDE_PROJECT_DIR:-.}/node_modules/.bin/ucsd-decorator-kit\" ] || { echo 'The chrome integrity gate did not run: ucsd-decorator-kit is not installed in this project. Install it with: npm install --save-dev ucsd-decorator-kit' >&2; exit 1; }", + "timeout": 10 } ] } diff --git a/test/cli.test.mjs b/test/cli.test.mjs index e183e44..84ca016 100644 --- a/test/cli.test.mjs +++ b/test/cli.test.mjs @@ -27,7 +27,15 @@ async function run(args, options = {}) { try { const { stdout, stderr } = await execFileAsync(process.execPath, [CLI, ...args], { cwd: options.cwd ?? workdir, - env: { ...process.env, npm_config_yes: "true" }, + // Offline against an empty cache: an `npm install` the CLI starts fails + // at once instead of reaching the registry. test/package.test.mjs covers + // an install that succeeds. + env: { + ...process.env, + npm_config_yes: "true", + npm_config_offline: "true", + npm_config_cache: path.join(workdir, "npm-cache"), + }, }); return { code: 0, stdout, stderr }; } catch (error) { @@ -131,6 +139,59 @@ describe("add", () => { assert.equal(await exists(path.join(project, ".github/workflows/decorator.yml")), false); assert.equal(await exists(path.join(project, ".claude/settings.json")), false); }); + + it("keeps AGENTS.md in the manifest of a project init set up", async () => { + const project = path.join(workdir, "add-over-init"); + await mkdir(project, { recursive: true }); + await run(["add"], { cwd: project }); + const manifestPath = path.join(project, "decorator-kit.json"); + const manifest = JSON.parse(await readFile(manifestPath, "utf8")); + manifest.manages.push(CONTRACT); + await writeFile(manifestPath, JSON.stringify(manifest, null, 2)); + + const result = await run(["add", "--with-hook"], { cwd: project }); + assert.equal(result.code, 0); + assert.ok(JSON.parse(await readFile(manifestPath, "utf8")).manages.includes(CONTRACT)); + }); +}); + +// The workflow `--with-ci` writes runs `npm run decorator:check`, and the hook +// `--with-hook` writes runs node_modules/.bin/ucsd-decorator-kit. Neither works +// unless the kit is a devDependency and the scripts exist. +describe("add installs what its flags run", () => { + for (const flag of ["--with-ci", "--with-hook", "--with-decorator"]) { + it(`${flag} adds the decorator:* scripts and says how to install the kit when it cannot`, async () => { + const project = path.join(workdir, `kit${flag}`); + await mkdir(project, { recursive: true }); + await writeFile(path.join(project, "package.json"), JSON.stringify({ name: "site", version: "1.0.0" }, null, 2)); + + const result = await run(["add", flag], { cwd: project }); + assert.equal(result.code, 0); + + const pkg = JSON.parse(await readFile(path.join(project, "package.json"), "utf8")); + assert.equal(pkg.scripts["decorator:check"], "ucsd-decorator-kit check"); + assert.equal(pkg.scripts["decorator:verify"], "ucsd-decorator-kit verify"); + const version = JSON.parse(await readFile(path.join(ROOT, "package.json"), "utf8")).version; + assert.match(result.stdout, new RegExp(`npm install --save-dev ucsd-decorator-kit@${version.replaceAll(".", "\\.")}`)); + }); + } + + it("leaves a kit version the project already declares alone", async () => { + const project = path.join(workdir, "kit-declared"); + await mkdir(project, { recursive: true }); + await writeFile( + path.join(project, "package.json"), + JSON.stringify({ name: "site", version: "1.0.0", devDependencies: { "ucsd-decorator-kit": "^2.0.0" } }, null, 2), + ); + + const result = await run(["add", "--with-ci"], { cwd: project }); + assert.equal(result.code, 0); + + const pkg = JSON.parse(await readFile(path.join(project, "package.json"), "utf8")); + assert.equal(pkg.devDependencies["ucsd-decorator-kit"], "^2.0.0"); + assert.doesNotMatch(result.stdout, /Installing ucsd-decorator-kit/); + assert.doesNotMatch(result.stdout, /is not installed here/); + }); }); describe("add --with-hook", () => { @@ -143,9 +204,34 @@ describe("add --with-hook", () => { const settings = JSON.parse(await readFile(path.join(project, ".claude/settings.json"), "utf8")); assert.equal(settings.hooks.Stop.length, 1); - const command = settings.hooks.Stop[0].hooks[0].command; - assert.match(command, /ucsd-decorator-kit verify/); - assert.equal(settings.hooks.Stop[0].hooks[0].asyncRewake, true, "must background, not block the turn"); + const [gate, notice] = settings.hooks.Stop[0].hooks; + assert.match(gate.command, /node_modules\/\.bin\/ucsd-decorator-kit verify \|\| exit 2/); + assert.equal(gate.asyncRewake, true, "must background, not block the turn"); + assert.equal(notice.asyncRewake, undefined, "a missing install is the user's to fix, not the agent's"); + for (const hook of [gate, notice]) { + assert.doesNotMatch(hook.command, /\bnpx\b/, "a hook must never fetch the kit from the registry"); + } + }); + + it("replaces the npx hook an earlier release installed, keeping the project's own hooks", async () => { + const project = path.join(workdir, "hook-legacy"); + await mkdir(path.join(project, ".claude"), { recursive: true }); + const legacy = { type: "command", command: "npx ucsd-decorator-kit verify || exit 2", asyncRewake: true }; + const own = { type: "command", command: "npm run lint" }; + await writeFile( + path.join(project, ".claude/settings.json"), + JSON.stringify({ hooks: { Stop: [{ hooks: [legacy] }, { hooks: [own, { ...legacy }] }] } }, null, 2), + ); + + const result = await run(["add", "--with-hook"], { cwd: project }); + assert.equal(result.code, 0); + + const settings = JSON.parse(await readFile(path.join(project, ".claude/settings.json"), "utf8")); + const commands = settings.hooks.Stop.flatMap((group) => group.hooks.map((hook) => hook.command)); + assert.ok(!commands.includes(legacy.command), "the legacy hook is gone from every group"); + assert.deepEqual(settings.hooks.Stop[0].hooks, [own], "the project's hook stays in its group"); + assert.equal(settings.hooks.Stop.length, 2, "the group that held only the legacy hook is removed"); + assert.equal(commands.filter((command) => /ucsd-decorator-kit verify/.test(command)).length, 1); }); it("merges into an existing settings.json without disturbing unrelated content", async () => { diff --git a/test/package.test.mjs b/test/package.test.mjs new file mode 100644 index 0000000..a59cea0 --- /dev/null +++ b/test/package.test.mjs @@ -0,0 +1,190 @@ +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, before, describe, it } from "node:test"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { decoratorPage } from "./fixtures/decorator-page.mjs"; + +// Every other test runs the kit from this checkout, where every file exists. +// A consumer runs it from the published tarball, which holds only what +// package.json `files` lets through. A path missing from that list passes the +// whole suite and breaks every project on the next `npx ucsd-decorator-kit` — +// so this packs the kit, installs the tarball into an empty project, and runs +// the installed copy. + +const execFileAsync = promisify(execFile); +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const kitPackage = JSON.parse(await readFile(path.join(ROOT, "package.json"), "utf8")); + +let workdir; +let packed; +let project; +let bin; + +const exists = (target) => stat(target).then(() => true).catch(() => false); + +async function npm(args, cwd) { + const { stdout } = await execFileAsync("npm", args, { + cwd, + env: { ...process.env, npm_config_update_notifier: "false", npm_config_fund: "false", npm_config_audit: "false" }, + }); + return stdout; +} + +async function run(args) { + try { + const { stdout, stderr } = await execFileAsync(bin, args, { cwd: project }); + return { code: 0, stdout, stderr }; + } catch (error) { + return { code: error.code ?? 1, stdout: error.stdout ?? "", stderr: error.stderr ?? "" }; + } +} + +before(async () => { + workdir = await mkdtemp(path.join(tmpdir(), "decorator-kit-package-test-")); + const [result] = JSON.parse(await npm(["pack", "--json", "--pack-destination", workdir], ROOT)); + packed = { tarball: path.join(workdir, result.filename), files: result.files.map((file) => file.path) }; + + project = path.join(workdir, "consumer"); + await mkdir(project); + await writeFile(path.join(project, "package.json"), `${JSON.stringify({ name: "consumer", private: true }, null, 2)}\n`); + // The kit has no dependencies, so this never needs the registry. + await npm(["install", "--save-dev", "--offline", packed.tarball], project); + bin = path.join(project, "node_modules/.bin/ucsd-decorator-kit"); +}); + +after(async () => { + await rm(workdir, { recursive: true, force: true }); +}); + +describe("published tarball", () => { + it("ships everything the CLI and the chrome gate read at runtime", () => { + for (const required of [ + "bin/cli.mjs", + "scripts/lib/rules.mjs", + "scripts/pin-decorator.mjs", + "checks/chrome-contract.mjs", + "checks/README.md", + "contracts/chrome-regions.json", + "contracts/chrome-styling.json", + "contracts/ucsd-decorator-5.json", + "contracts/decorator-kit.schema.json", + "rules/00-canvas.md", + "skills/ucsd-decorator/SKILL.md", + "templates/claude-settings.json", + "templates/decorator.yml", + "templates/dependabot.yml", + "templates/canvas-rules-README.md", + "templates/canvas-components-README.md", + "README.md", + "CHANGELOG.md", + "LICENSE", + ]) { + assert.ok(packed.files.includes(required), `${required} is missing from the tarball`); + } + }); + + it("leaves out the kit's own generated rule files, publishing staging, and dev scripts", () => { + // The root CLAUDE.md and AGENTS.md govern work on this repository. Shipped, + // they would sit in node_modules looking like rules for the consumer. + for (const excluded of [ + "CLAUDE.md", + "AGENTS.md", + ".cursorrules", + "scripts/compile-rules.mjs", + "scripts/check-library.mjs", + "scripts/sync-library.mjs", + ]) { + assert.ok(!packed.files.includes(excluded), `${excluded} should not be in the tarball`); + } + for (const prefix of ["library/", "test/", ".github/", ".claude-plugin/"]) { + assert.ok(!packed.files.some((file) => file.startsWith(prefix)), `${prefix} should not be in the tarball`); + } + }); + + it("links the bin, so the decorator:* npm scripts resolve", async () => { + const result = await run(["help"]); + assert.equal(result.code, 0); + assert.match(result.stdout, new RegExp(`ucsd-decorator-kit ${kitPackage.version.replaceAll(".", "\\.")}`)); + }); + + it("runs add, check, and the chrome gate from the installed copy", async () => { + const added = await run(["add"]); + assert.equal(added.code, 0, added.stderr); + assert.equal(await exists(path.join(project, "CLAUDE.md")), true); + assert.equal(await exists(path.join(project, ".claude/skills/ucsd-decorator/SKILL.md")), true); + + // The manifest's $schema points into this version's tarball on the CDN. + const manifest = JSON.parse(await readFile(path.join(project, "decorator-kit.json"), "utf8")); + const schemaPath = `contracts/decorator-kit.schema.json`; + assert.equal(manifest.$schema, `https://cdn.jsdelivr.net/npm/${kitPackage.name}@${kitPackage.version}/${schemaPath}`); + assert.ok(packed.files.includes(schemaPath)); + + const checked = await run(["check"]); + assert.equal(checked.code, 0, checked.stderr); + + await writeFile(path.join(project, "index.html"), decoratorPage("Home")); + await writeFile(path.join(project, "about.html"), decoratorPage("About")); + const accepted = await run(["verify", "--accept", "--reason", "initial baseline", "--yes"]); + assert.equal(accepted.code, 0, accepted.stderr); + const verified = await run(["verify"]); + assert.equal(verified.code, 0, verified.stderr); + assert.match(verified.stdout, /all four tiers pass/); + }); + + it("wires the decorator:* scripts and the Stop hooks to the installed copy", async () => { + const declared = JSON.parse(await readFile(path.join(project, "package.json"), "utf8")).devDependencies; + const added = await run(["add", "--with-ci", "--with-hook"]); + assert.equal(added.code, 0, added.stderr); + assert.deepEqual( + JSON.parse(await readFile(path.join(project, "package.json"), "utf8")).devDependencies, + declared, + "the kit the project installed is kept, not reinstalled", + ); + + // What the CI workflow runs. + await npm(["run", "decorator:check"], project); + await npm(["run", "decorator:verify"], project); + + // What Claude Code runs after each turn: `sh -c`, with CLAUDE_PROJECT_DIR set. + const settings = JSON.parse(await readFile(path.join(project, ".claude/settings.json"), "utf8")); + const [gate, notice] = settings.hooks.Stop[0].hooks.map((hook) => hook.command); + const hook = async (command, dir) => { + try { + const { stderr } = await execFileAsync("sh", ["-c", command], { cwd: tmpdir(), env: { ...process.env, CLAUDE_PROJECT_DIR: dir } }); + return { code: 0, stderr }; + } catch (error) { + return { code: error.code, stderr: error.stderr }; + } + }; + + assert.deepEqual(await hook(notice, project), { code: 0, stderr: "" }, "installed: nothing to tell the user"); + assert.equal((await hook(gate, project)).code, 0, "chrome intact: the agent is not woken"); + + await writeFile(path.join(project, "about.html"), decoratorPage("About", { searchAsLink: true })); + const regressed = await hook(gate, project); + assert.equal(regressed.code, 2, "a chrome regression wakes the agent"); + assert.match(regressed.stderr, /chrome\/structure/); + + // A project where the kit is not installed: the gate stands down and the + // user, not the agent, is told why. + const bare = path.join(workdir, "no-kit"); + await mkdir(bare); + assert.equal((await hook(gate, bare)).code, 0, "missing kit: the agent is not told of a regression"); + const missing = await hook(notice, bare); + assert.equal(missing.code, 1); + assert.match(missing.stderr, /not installed in this project/); + }); +}); + +describe("release metadata", () => { + it("gives the Claude Code plugin the same version as the npm package", async () => { + // Claude Code decides whether an installed plugin is out of date from this + // field. Left behind on a release, plugin users never see the update. + const plugin = JSON.parse(await readFile(path.join(ROOT, ".claude-plugin/plugin.json"), "utf8")); + assert.equal(plugin.version, kitPackage.version, "bump .claude-plugin/plugin.json along with package.json"); + }); +});