From def529030b4dfded1283e51464afb23dabdca2d8 Mon Sep 17 00:00:00 2001 From: krugazul Date: Fri, 6 Nov 2026 12:17:06 +0200 Subject: [PATCH 1/2] refactor(mcp): convert the MCP tooling to TypeScript with Vitest tests BPS-12. CLAUDE.md says agent tooling in scripts/ is TypeScript, and the issue names a TypeScript MCP server as the preferred reference. - scripts/mcp/*.js become .mts ES modules that Node 24.18+ runs directly by stripping types (erasable syntax only, no build step). The .mts extension avoids Node re-parsing each file and warning on every start, without adding a nested package.json the pre-commit lint would reject. - generator.mts is the one typed wrapper around the CommonJS engine. - npm run mcp:server now runs scripts/mcp/server.mts; client configurations must point at server.mts. - Fix: a destination under a file (/plugin) is now UNSAFE_DESTINATION instead of an INTERNAL error (ENOTDIR from lstat). Tests use Vitest, not Jest (npm run test:mcp, @vitest/coverage-v8 added, 80% thresholds). 57 tests port the earlier scripted checks: engine boundary and CLI parity, configuration, preview, approval, expiry, destination rules, staging failure, the safe merge (Git, links, permissions, interruption, races) and the server over in-memory and stdio transports. Coverage is about 95%. Verified: the suite passes; Claude Code 2.1.220 ran all four tools against server.mts. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 +- CLAUDE.md | 1 + docs/MCP-PLUGIN-GENERATION.md | 12 +- package-lock.json | 104 +++++ package.json | 4 +- scripts/mcp/__tests__/engine.test.mts | 122 ++++++ scripts/mcp/__tests__/helpers.mts | 130 ++++++ scripts/mcp/__tests__/merge.test.mts | 343 +++++++++++++++ scripts/mcp/__tests__/preview.test.mts | 388 +++++++++++++++++ scripts/mcp/__tests__/server.test.mts | 179 ++++++++ .../mcp/__tests__/staging-failure.test.mts | 46 ++ scripts/mcp/{config.js => config.mts} | 88 ++-- scripts/mcp/errors.js | 52 --- scripts/mcp/errors.mts | 58 +++ scripts/mcp/generator.mts | 63 +++ scripts/mcp/{merge.js => merge.mts} | 98 +++-- scripts/mcp/{preview.js => preview.mts} | 407 +++++++++++------- scripts/mcp/{server.js => server.mts} | 65 +-- scripts/mcp/vitest.config.mts | 31 ++ 19 files changed, 1887 insertions(+), 312 deletions(-) create mode 100644 scripts/mcp/__tests__/engine.test.mts create mode 100644 scripts/mcp/__tests__/helpers.mts create mode 100644 scripts/mcp/__tests__/merge.test.mts create mode 100644 scripts/mcp/__tests__/preview.test.mts create mode 100644 scripts/mcp/__tests__/server.test.mts create mode 100644 scripts/mcp/__tests__/staging-failure.test.mts rename scripts/mcp/{config.js => config.mts} (74%) delete mode 100644 scripts/mcp/errors.js create mode 100644 scripts/mcp/errors.mts create mode 100644 scripts/mcp/generator.mts rename scripts/mcp/{merge.js => merge.mts} (72%) rename scripts/mcp/{preview.js => preview.mts} (64%) rename scripts/mcp/{server.js => server.mts} (79%) create mode 100644 scripts/mcp/vitest.config.mts diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b4c163..4539731 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,9 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Local MCP server for plugin generation (BPS-12, `scripts/mcp/server.js`, `npm run mcp:server`): `discover`, `validate_config`, `preview` and `generate` over stdio for Claude Desktop and Claude Code, built on the official `@modelcontextprotocol/sdk` (new dev dependency, with `zod`). `preview` returns a compact file list by default (every overwrite and conflict, new files counted by folder) and the full list with `detail: "full"`. Verified with Claude Code and Claude Desktop on macOS. -- Safe merge for local MCP generation (BPS-12, `scripts/mcp/merge.js`): after an approval matches its preview, `generate` writes only the planned paths into the destination. It never deletes, never touches Git paths or unrelated files, re-checks each path just before writing it, writes each file to a temporary name and renames it into place, backs up every file before overwriting it, and records each step in a journal. A failure part-way returns `PARTIAL_WRITE` with what was and was not written; previewing and generating again completes the rest. -- Preview and approval for local MCP generation (BPS-12, `scripts/mcp/`): `preview.js` checks the destination against the contract's rules, generates into a private staging folder, marks every planned path `create`, `overwrite`, `unchanged` or `conflict` (Git paths, symbolic links in the path and type clashes are conflicts), counts the files it leaves alone, and binds an approval hash to the configuration, destination and staged files. An approval is refused if it does not match, the preview expired (30 minutes) or was replaced, or the destination changed since. `config.js` validates with the generator's own rules and reports where each value came from. +- Vitest tests for the local MCP tooling (BPS-12): `npm run test:mcp` runs `scripts/mcp/__tests__/` with `@vitest/coverage-v8` (new dev dependency) and fails below 80% coverage. The tests generate real plugins into temporary folders and cover the engine boundary, preview, approval, destination rules, the safe merge and the server over in-memory and stdio transports. +- Local MCP server for plugin generation (BPS-12, `scripts/mcp/server.mts`, `npm run mcp:server`): `discover`, `validate_config`, `preview` and `generate` over stdio for Claude Desktop and Claude Code, built on the official `@modelcontextprotocol/sdk` (new dev dependency, with `zod`). `preview` returns a compact file list by default (every overwrite and conflict, new files counted by folder) and the full list with `detail: "full"`. Verified with Claude Code and Claude Desktop on macOS. +- Safe merge for local MCP generation (BPS-12, `scripts/mcp/merge.mts`): after an approval matches its preview, `generate` writes only the planned paths into the destination. It never deletes, never touches Git paths or unrelated files, re-checks each path just before writing it, writes each file to a temporary name and renames it into place, backs up every file before overwriting it, and records each step in a journal. A failure part-way returns `PARTIAL_WRITE` with what was and was not written; previewing and generating again completes the rest. +- Preview and approval for local MCP generation (BPS-12, `scripts/mcp/`): `preview.mts` checks the destination against the contract's rules, generates into a private staging folder, marks every planned path `create`, `overwrite`, `unchanged` or `conflict` (Git paths, symbolic links in the path and type clashes are conflicts), counts the files it leaves alone, and binds an approval hash to the configuration, destination and staged files. An approval is refused if it does not match, the preview expired (30 minutes) or was replaced, or the destination changed since. `config.js` validates with the generator's own rules and reports where each value came from. - `docs/MCP-PLUGIN-GENERATION.md` (BPS-12): the contract for generating plugins through a local MCP server in Claude Desktop and Claude Code. It covers responsibilities, transport, client setup, destination rules, the four operations, approval binding, merge rules, errors, recovery, the supported configuration where the schema, generator and validator disagree, and the WordPress and Figma skills. - Generated plugins get `package-lock.json` and `composer.lock` (BPS-10), written from the lockfiles proven in `lightspeedwp/ls-test` (`scripts/toolchain/standard-toolchain.package-lock.json` and `standard-toolchain.composer.lock`) with the plugin's name, version and Composer `content-hash`; for ls-test they are byte-identical to its own. `npm run toolchain:lockfiles` resolves them again after a toolchain change. `check:generation` installs with `npm ci` and runs `composer validate`, so a lockfile that no longer matches fails, then `composer install`, PHPCS, PHPStan and PHPUnit in each generated plugin; the CI job sets up PHP 8.4. - Generated plugins get `guidelines/` (BPS-10, adapted from ThisOneTimeOnAcidCom): CSS architecture, an accessibility checklist, the testing strategy, and prompt and report guides. `compare-toolchain.js` compares `guidelines/`. @@ -75,6 +76,7 @@ All components use mustache placeholders and follow WordPress accessibility and ### Changed +- The local MCP tooling in `scripts/mcp/` is TypeScript (`.mts`, run directly by Node 24.18+ with no build step), following the repository rule for agent tooling. Its behaviour is unchanged apart from one fix: a destination under a file now gives `UNSAFE_DESTINATION` instead of an internal error. Claude Desktop and Claude Code configurations must point at `scripts/mcp/server.mts`. - `generatePlugin()` can be called repeatedly from one process (BPS-12). It takes options (`outputDir` for the exact folder, `outputBaseDir`, `force`, `now`, `logFile`, `output`; `generatePlugin(config, true)` still means template mode), reads nothing from `process.argv`, writes diagnostics to standard error instead of standard output, and keeps a separate log per call, written when the call ends. Importing the module no longer creates `logs/` or registers exit and Ctrl+C handlers; only the CLI does. The CLI's output and generated files are unchanged, and `generate-plugin.agent.js` passes `--force` through. - The generated `AGENTS.md` and `CLAUDE.md` describe the full branch rule, `{type}/{scope}-{title}`, instead of only the type prefix. - `npm run format` in generated plugins writes YAML with two spaces, as `.editorconfig` asks, instead of four, and a new `.prettierignore` leaves `.specify/`, the generator's `*-config.json`, the centrally managed `dependency-automation.yml` and generated folders alone. `styles/blocks/button-primary.json` is formatted to match, and `compare-toolchain.js` compares `.prettierignore`. diff --git a/CLAUDE.md b/CLAUDE.md index 5148bed..97fa1d3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -5,5 +5,6 @@ - Skills in `.claude/skills/` are symlinks to `.agents/skills/` (see `.agents/README.md`). The WordPress skills are vendored from WordPress/agent-skills at the commit in `.agents/skills/VENDORED.md`; refresh them with `npm run sync:agent-skills`, never by editing them. - `plugin-template/` is the source of generated plugins and has its own `.claude/`, `.agents/` and `CLAUDE.md`. `scripts/agent-skills.json` updates both, and `scripts/generate-plugin.js` copies the vendored skills without rendering them. - Agent tooling in `scripts/` is TypeScript. `scripts/sync-agent-skills.ts` runs on Node 24.18+ directly (type stripping), with Jest tests in `scripts/__tests__/` (`npm run test:agent-skills`, 80% coverage enforced). Do not add shell scripts. +- The local MCP generation tooling in `scripts/mcp/` is TypeScript too (`.mts`, ES modules, run directly by Node). Its tests use Vitest, not Jest: `npm run test:mcp` (80% coverage enforced). See `docs/MCP-PLUGIN-GENERATION.md`. - Put machine-specific settings in `.claude/settings.local.json`, which Git ignores. - `.claude/settings.json` enables the `ls-claude-agents-router` plugin from the `lightspeedwp` marketplace, which routes the organisation agents in `lightspeedwp/.github` into Claude Code. Claude Code offers to install it when you trust this folder. It needs `~/.github` cloned (on `develop`) and Git access to the private repository (`gh auth login`, then `gh auth setup-git`). diff --git a/docs/MCP-PLUGIN-GENERATION.md b/docs/MCP-PLUGIN-GENERATION.md index e24905b..b0a157a 100644 --- a/docs/MCP-PLUGIN-GENERATION.md +++ b/docs/MCP-PLUGIN-GENERATION.md @@ -9,7 +9,7 @@ date: 2026-11-06 This document defines how an AI client generates a plugin from this scaffold through a local [Model Context Protocol](https://modelcontextprotocol.io/) (MCP) server (BPS-12), and records how it was verified. -**Status:** implemented in `scripts/mcp/` (`server.js`, `config.js`, `preview.js`, `merge.js`, `errors.js`). Verified with Claude Code and Claude Desktop on macOS (see [Verification record](#verification-record)). The CLI in [GENERATE_PLUGIN.md](GENERATE_PLUGIN.md) works as before. +**Status:** implemented in TypeScript in `scripts/mcp/` (`server.mts`, `config.mts`, `preview.mts`, `merge.mts`, `errors.mts`, and `generator.mts`, the typed wrapper around `scripts/generate-plugin.js`), with Vitest tests in `scripts/mcp/__tests__/` (`npm run test:mcp`). Verified with Claude Code and Claude Desktop on macOS (see [Verification record](#verification-record)). The CLI in [GENERATE_PLUGIN.md](GENERATE_PLUGIN.md) works as before. ## Responsibilities @@ -27,7 +27,7 @@ Approval always comes from the person using the client. The adapter checks that - **Standard output is reserved for protocol messages.** The engine and adapter write diagnostics to standard error and to the per-request log file only. One stray `console.log` breaks the connection, so the engine must not print to standard output when called by the adapter. - **SDK:** the official [`@modelcontextprotocol/sdk`](https://www.npmjs.com/package/@modelcontextprotocol/sdk) (1.32.x at the time of writing). - **Runtime:** Node `>=24.18.0`, the same as the scaffold. -- **Entry point:** `scripts/mcp/server.js` (also `npm run mcp:server`), run from a checkout after `npm install`. There is no npm package or Claude Desktop extension (`.mcpb`) in this scope. +- **Entry point:** `scripts/mcp/server.mts` (also `npm run mcp:server`), run from a checkout after `npm install`. Node 24.18+ runs the TypeScript directly by stripping the types, so there is no build step; the `.mts` extension tells Node the files are ES modules. There is no npm package or Claude Desktop extension (`.mcpb`) in this scope. - **Platform:** macOS. Other platforms are not verified. ## Client setup @@ -47,7 +47,7 @@ pwd # run in your block-plugin-scaffold checkout **Claude Code** (user scope, available in every project): ```bash -claude mcp add --scope user block-plugin-scaffold -- /absolute/path/to/node /absolute/path/to/block-plugin-scaffold/scripts/mcp/server.js +claude mcp add --scope user block-plugin-scaffold -- /absolute/path/to/node /absolute/path/to/block-plugin-scaffold/scripts/mcp/server.mts ``` **Claude Desktop:** add an entry to `~/Library/Application Support/Claude/claude_desktop_config.json`, then quit and reopen Claude Desktop: @@ -58,7 +58,7 @@ claude mcp add --scope user block-plugin-scaffold -- /absolute/path/to/node /abs "block-plugin-scaffold": { "command": "/absolute/path/to/node", "args": [ - "/absolute/path/to/block-plugin-scaffold/scripts/mcp/server.js" + "/absolute/path/to/block-plugin-scaffold/scripts/mcp/server.mts" ] } } @@ -239,7 +239,7 @@ Fixing the schema and the standalone validator is outside this contract; the iss ## Verification -Each phase is verified by generating plugins and checking the generated output, not by running the scaffold's own test suite: +`npm run test:mcp` runs the Vitest suite in `scripts/mcp/__tests__/`, which generates real plugins into temporary folders and enforces 80% coverage of the MCP modules. It does not use Jest. Each phase was also verified by generating plugins and checking the generated output: - **Parity:** with a fixed clock, a plugin generated through MCP matches one generated by the CLI for the same configuration. - **Preservation:** fixture destinations containing `.git` files and folders, unrelated JavaScript and PHP, links and read-only files are unchanged after `generate`, apart from the planned paths. @@ -262,3 +262,5 @@ Recorded on 6 November 2026 on macOS with Node 24.21.0, `@modelcontextprotocol/s | Claude Code 2.1.220 | `claude -p` with `--mcp-config` and `--strict-mcp-config`: `discover`, `validate_config`, `preview`, `generate` | Pass; 551 files written; no tool errors | | Claude Desktop | Run by Warwick in the Claude Desktop chat window on macOS, 6 November 2026, with the configuration in [Client setup](#client-setup) | Pass: `discover` listed the fields, and a test plugin was previewed, approved and generated. `validate_config` was not separately confirmed | | Local WordPress site | Generated `bps12-mcp-check` through MCP into a WordPress Studio site's plugins folder and built it | Generation and build pass; activation refused because the site runs ACF Pro, not Secure Custom Fields (see [Limitations](#limitations)); the plugin was left inactive | + +After the TypeScript conversion (6 November 2026, branch `refactor/bps-12-mcp-typescript`): the Vitest suite passes (57 tests; about 95% statement, branch, function and line coverage of the MCP modules), and Claude Code 2.1.220 ran all four tools against `server.mts` with no errors. The conversion also fixed a destination under a file (for example `/plugin`) being reported as `INTERNAL` instead of `UNSAFE_DESTINATION`. diff --git a/package-lock.json b/package-lock.json index ac6a8e3..dce8111 100644 --- a/package-lock.json +++ b/package-lock.json @@ -36,6 +36,7 @@ "@testing-library/jest-dom": "^6.9.1", "@testing-library/react": "^16.3.1", "@vitejs/plugin-react-swc": "^4.3.3", + "@vitest/coverage-v8": "^5.0.5", "@wordpress/babel-plugin-makepot": "^6.57.0", "@wordpress/babel-preset-default": "^8.55.0", "@wordpress/e2e-test-utils-playwright": "^3.0.0", @@ -9974,6 +9975,45 @@ "vite": "^4 || ^5 || ^6 || ^7 || ^8" } }, + "node_modules/@vitest/coverage-v8": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-5.0.5.tgz", + "integrity": "sha512-4KpkGdIrSqBihx/JyP/e+S+IKB98etg1XDQiLAxksLfcShnwi1VReGeOT9NI43hLHbknosKp/1CCLn9Zgcs8mg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@bcoe/v8-coverage": "^1.0.2", + "@vitest/istanbul-lib-coverage": "^1.0.2", + "@vitest/istanbul-lib-report": "^1.0.2", + "ast-v8-to-istanbul": "^1.0.7", + "magicast": "^0.5.5", + "obug": "^3.0.0", + "std-env": "^4.3.0", + "tinyrainbow": "^3.2.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@vitest/browser": "5.0.5", + "vitest": "5.0.5" + }, + "peerDependenciesMeta": { + "@vitest/browser": { + "optional": true + } + } + }, + "node_modules/@vitest/coverage-v8/node_modules/@bcoe/v8-coverage": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz", + "integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/@vitest/eslint-plugin": { "version": "1.6.27", "resolved": "https://registry.npmjs.org/@vitest/eslint-plugin/-/eslint-plugin-1.6.27.tgz", @@ -10005,6 +10045,29 @@ } } }, + "node_modules/@vitest/istanbul-lib-coverage": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@vitest/istanbul-lib-coverage/-/istanbul-lib-coverage-1.0.2.tgz", + "integrity": "sha512-9J/JMwOf9AoJhAywhrn7ScKTL38hsWQP/qPG60OtaAFcQ5OXPwKsxZFlbnuCKmZ61m8/lGgHYnFpdyQZUvG/iA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22" + } + }, + "node_modules/@vitest/istanbul-lib-report": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@vitest/istanbul-lib-report/-/istanbul-lib-report-1.0.2.tgz", + "integrity": "sha512-gUsfXZJbzPamoIY5TvHFiMMoXESBrUMo+xqaj+rYrWI69+EnvRlYBlP96ZnHPY4vX8kyUpgAnFUCg5wZG/HkDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/istanbul-lib-coverage": "1.0.2" + }, + "engines": { + "node": ">=22" + } + }, "node_modules/@vitest/mocker": { "version": "5.0.5", "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.5.tgz", @@ -14017,6 +14080,25 @@ "dev": true, "license": "MIT" }, + "node_modules/ast-v8-to-istanbul": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.7.tgz", + "integrity": "sha512-kFL68AG6ajd8fg248zwM9GQrUWEp79gsmjum34OEXjs4yHuUMZfYKwOLW9GMmB4oNvVrj+EAGxsP7ye2UR9UlA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.31", + "estree-walker": "^3.0.3", + "js-tokens": "^10.0.0" + } + }, + "node_modules/ast-v8-to-istanbul/node_modules/js-tokens": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", + "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", + "dev": true, + "license": "MIT" + }, "node_modules/astral-regex": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", @@ -24011,6 +24093,18 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/magicast": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.5.tgz", + "integrity": "sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7", + "source-map-js": "^1.2.1" + } + }, "node_modules/make-dir": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", @@ -31589,6 +31683,16 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/tinyrainbow": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.2.0.tgz", + "integrity": "sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/tldts": { "version": "7.4.18", "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.18.tgz", diff --git a/package.json b/package.json index 50dab46..9eb4ab3 100644 --- a/package.json +++ b/package.json @@ -52,6 +52,7 @@ "@testing-library/jest-dom": "^6.9.1", "@testing-library/react": "^16.3.1", "@vitejs/plugin-react-swc": "^4.3.3", + "@vitest/coverage-v8": "^5.0.5", "@wordpress/babel-plugin-makepot": "^6.57.0", "@wordpress/babel-preset-default": "^8.55.0", "@wordpress/e2e-test-utils-playwright": "^3.0.0", @@ -85,7 +86,7 @@ "check-engines": "wp-scripts check-engines", "check-licenses": "wp-scripts check-licenses", "check:generation": "node scripts/toolchain/check-generation.js", - "mcp:server": "node scripts/mcp/server.js", + "mcp:server": "node scripts/mcp/server.mts", "check:markdown-references": "node scripts/check-markdown-references.js", "check:toolchain": "jest scripts/__tests__/generate-plugin.toolchain.test.js", "clean:gh-references": "node scripts/clean-github-references.js", @@ -158,6 +159,7 @@ "zip": "wp-scripts plugin-zip", "sync:agent-skills": "node scripts/sync-agent-skills.ts", "sync:agent-skills:check": "node scripts/sync-agent-skills.ts --check", + "test:mcp": "vitest run --config scripts/mcp/vitest.config.mts --coverage", "test:agent-skills": "wp-scripts test-unit-jest scripts/__tests__/sync-agent-skills.test.ts --coverage --collectCoverageFrom=scripts/sync-agent-skills.ts --coverageThreshold={\"global\":{\"statements\":80,\"branches\":80,\"functions\":80,\"lines\":80}}" }, "lint-staged": { diff --git a/scripts/mcp/__tests__/engine.test.mts b/scripts/mcp/__tests__/engine.test.mts new file mode 100644 index 0000000..56984d8 --- /dev/null +++ b/scripts/mcp/__tests__/engine.test.mts @@ -0,0 +1,122 @@ +/** + * The generator engine as the MCP server uses it (BPS-12, T2): no side + * effects on import, nothing on standard output, a log per call, and output + * that matches the CLI. + */ + +import { execFileSync, spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; +import { afterAll, describe, expect, it } from 'vitest'; + +import { generatePlugin } from '../generator.mts'; +import { SCAFFOLD, diffTrees, fixedNow, fixture, tempDir } from './helpers.mts'; + +const work = tempDir( 'engine' ); +afterAll( () => fs.rmSync( work, { recursive: true, force: true } ) ); + +describe( 'engine boundary', () => { + it( 'writes nothing and registers no process handlers on import', () => { + const probe = ` +const fs = await import('node:fs'); +const calls = []; +for (const k of ['mkdirSync', 'writeFileSync', 'rmSync', 'mkdtempSync']) { + const original = fs.default[k]; + fs.default[k] = (...a) => { calls.push(k + ' ' + a[0]); return original(...a); }; +} +const handlers = []; +const on = process.on.bind(process); +process.on = (e, ...r) => { handlers.push(e); return on(e, ...r); }; +await import(${ JSON.stringify( + path.join( SCAFFOLD, 'scripts/mcp/preview.mts' ) + ) }); +process.stdout.write(JSON.stringify({ calls, handlers }));`; + const out = execFileSync( + process.execPath, + [ '--input-type=module', '-e', probe ], + { encoding: 'utf8' } + ); + expect( JSON.parse( out ) ).toEqual( { calls: [], handlers: [] } ); + } ); + + it( 'keeps standard output empty and logs each call separately', () => { + const one = path.join( work, 'one.log' ); + const two = path.join( work, 'two.log' ); + const script = ` +import engine from ${ JSON.stringify( + path.join( SCAFFOLD, 'scripts/generate-plugin.js' ) + ) }; +const cfg = ${ JSON.stringify( fixture() ) }; +const now = () => new Date('2026-01-02T03:04:05.000Z'); +engine.generatePlugin({ ...cfg, slug: 'probe-one' }, { outputDir: ${ JSON.stringify( + path.join( work, 'probe-one' ) + ) }, now, logFile: ${ JSON.stringify( one ) } }); +engine.generatePlugin({ ...cfg, slug: 'probe-two' }, { outputDir: ${ JSON.stringify( + path.join( work, 'probe-two' ) + ) }, now, logFile: ${ JSON.stringify( two ) } });`; + const child = spawnSync( + process.execPath, + [ '--input-type=module', '-e', script ], + { encoding: 'utf8' } + ); + expect( child.status ).toBe( 0 ); + expect( child.stdout ).toBe( '' ); + + const first = fs.readFileSync( one, 'utf8' ); + const second = fs.readFileSync( two, 'utf8' ); + expect( first ).toContain( 'probe-one' ); + expect( first ).not.toContain( 'probe-two' ); + expect( second ).toContain( 'probe-two' ); + expect( second ).not.toContain( 'probe-one' ); + for ( const entry of JSON.parse( first ) ) { + expect( entry.timestamp ).toBe( '2026-01-02T03:04:05.000Z' ); + } + } ); + + it( 'produces identical output for the same configuration and clock', () => { + const options = { now: fixedNow, output: false as const }; + const a = generatePlugin( fixture(), { + ...options, + outputDir: path.join( work, 'a', 'gen-check' ), + logFile: path.join( work, 'a.log' ), + } ); + const b = generatePlugin( fixture(), { + ...options, + outputDir: path.join( work, 'b', 'gen-check' ), + logFile: path.join( work, 'b.log' ), + } ); + expect( diffTrees( a, b ) ).toEqual( [] ); + } ); + + it( 'matches the CLI apart from the .pot creation date', () => { + const config = path.join( work, 'cli-config.json' ); + fs.writeFileSync( config, JSON.stringify( fixture() ) ); + const cliBase = path.join( work, 'cli' ); + const cli = spawnSync( + process.execPath, + [ + path.join( SCAFFOLD, 'scripts/generate-plugin.js' ), + '--config', + config, + '--output-dir', + cliBase, + ], + { encoding: 'utf8', cwd: SCAFFOLD } + ); + expect( cli.status ).toBe( 0 ); + const library = generatePlugin( fixture(), { + now: fixedNow, + output: false, + outputDir: path.join( work, 'library', 'gen-check' ), + logFile: path.join( work, 'library.log' ), + } ); + const differences = diffTrees( + library, + path.join( cliBase, 'gen-check' ) + ).filter( + ( line ) => + ! /POT-Creation-Date|^diff -r|^---$|^\d+c\d+$/.test( line ) + ); + expect( differences ).toEqual( [] ); + } ); +} ); diff --git a/scripts/mcp/__tests__/helpers.mts b/scripts/mcp/__tests__/helpers.mts new file mode 100644 index 0000000..c9f72aa --- /dev/null +++ b/scripts/mcp/__tests__/helpers.mts @@ -0,0 +1,130 @@ +/** + * Shared helpers for the MCP generation tests (BPS-12). + */ + +import { execFileSync } from 'node:child_process'; +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +export const SCAFFOLD = path.resolve( import.meta.dirname, '../../..' ); + +/** A fixed clock, so generated output can be compared exactly. */ +export const fixedNow = () => new Date( '2026-01-02T03:04:05.000Z' ); + +/** + * The default generation fixture, with optional overrides. + * + * @param overrides Values to replace. + * @return Configuration. + */ +export function fixture( + overrides: Record< string, unknown > = {} +): Record< string, unknown > { + const base = JSON.parse( + fs.readFileSync( + path.join( SCAFFOLD, 'tests/fixtures/generation/default.json' ), + 'utf8' + ) + ); + return { ...base, ...overrides }; +} + +/** + * A new empty temporary folder (its real path). + * + * @param prefix Folder name prefix. + * @return Path. + */ +export function tempDir( prefix: string ): string { + return fs.realpathSync( + fs.mkdtempSync( path.join( os.tmpdir(), `bps-test-${ prefix }-` ) ) + ); +} + +/** + * Every path in a tree, with its type, content hash, mode and (optionally) + * modification time, without following links. + * + * @param root Folder. + * @param options Whether to include modification times. + * @return Signature per relative path. + */ +export function snapshot( + root: string, + { mtime = true }: { mtime?: boolean } = {} +): Record< string, string > { + const out: Record< string, string > = {}; + const walk = ( dir: string ) => { + for ( const name of fs.readdirSync( dir ) ) { + const full = path.join( dir, name ); + const rel = path.relative( root, full ); + const stat = fs.lstatSync( full ); + let sig: string; + if ( stat.isSymbolicLink() ) { + sig = `link:${ fs.readlinkSync( full ) }`; + } else if ( stat.isDirectory() ) { + sig = 'dir'; + } else { + sig = `file:${ crypto + .createHash( 'sha256' ) + .update( fs.readFileSync( full ) ) + .digest( 'hex' ) }`; + } + const time = + mtime && ! stat.isDirectory() ? `:${ stat.mtimeMs }` : ''; + out[ rel ] = `${ sig }:${ ( stat.mode & 0o7777 ).toString( + 8 + ) }${ time }`; + if ( stat.isDirectory() && ! stat.isSymbolicLink() ) { + walk( full ); + } + } + }; + walk( root ); + return out; +} + +/** + * Lines of `diff -r` between two trees, comparing links as links. + * + * @param a First folder. + * @param b Second folder. + * @return Differences; empty when identical. + */ +export function diffTrees( a: string, b: string ): string[] { + try { + execFileSync( 'diff', [ '-r', '--no-dereference', a, b ], { + encoding: 'utf8', + } ); + return []; + } catch ( error ) { + return String( ( error as { stdout?: string } ).stdout || '' ) + .split( '\n' ) + .filter( Boolean ); + } +} + +/** + * Call a function and return what it threw. + * + * @param fn Function. + * @return The thrown value, with its contract code if any. + */ +export function thrown( fn: () => unknown ): { + code?: string; + message: string; + details?: Record< string, any >; +} { + try { + fn(); + } catch ( error ) { + return error as { + code?: string; + message: string; + details?: Record< string, any >; + }; + } + throw new Error( 'Expected an error, but none was thrown' ); +} diff --git a/scripts/mcp/__tests__/merge.test.mts b/scripts/mcp/__tests__/merge.test.mts new file mode 100644 index 0000000..258aac2 --- /dev/null +++ b/scripts/mcp/__tests__/merge.test.mts @@ -0,0 +1,343 @@ +/** + * Preservation-safe merge into the destination (BPS-12, T4). + */ + +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +import { generatePlugin } from '../generator.mts'; +import { generateFromPreview } from '../merge.mts'; +import { createPreview } from '../preview.mts'; +import { + diffTrees, + fixedNow, + fixture, + snapshot, + tempDir, + thrown, +} from './helpers.mts'; + +type Preview = Record< string, any >; + +const work = tempDir( 'merge' ); +afterAll( () => fs.rmSync( work, { recursive: true, force: true } ) ); + +const cfg = fixture( { + slug: 'tsp-merge', + repository_url: 'https://github.com/lightspeedwp/tsp-merge', +} ); +const now = fixedNow; +const approve = ( p: Preview ) => ( { + previewId: p.previewId, + approvalHash: p.approvalHash, + approved: true, +} ); +const preview = ( destination: string ): Preview => + createPreview( { config: cfg, destination, detail: 'full' }, { now } ); + +let reference: string; +beforeAll( () => { + reference = generatePlugin( cfg, { + outputDir: path.join( work, 'reference', 'tsp-merge' ), + now, + output: false, + logFile: path.join( work, 'reference.log' ), + } ); +} ); + +describe( 'a new destination', () => { + const dest = path.join( work, 'fresh' ); + let first: Preview; + + it( 'matches the generator output exactly', () => { + first = preview( dest ); + const result = generateFromPreview( approve( first ), { now } ); + expect( diffTrees( reference, dest ) ).toEqual( [] ); + expect( result.written ).toHaveLength( first.summary.create ); + expect( result.backupFolder ).toBeNull(); + expect( fs.existsSync( first.processEffects.stagingFolder ) ).toBe( + false + ); + const journal = fs.readFileSync( result.journal, 'utf8' ).trim(); + expect( journal.split( '\n' ).pop() ).toContain( '"op":"done"' ); + const link = '.claude/skills/test'; + expect( fs.lstatSync( path.join( dest, link ) ).isSymbolicLink() ).toBe( + true + ); + expect( fs.readlinkSync( path.join( dest, link ) ) ).toBe( + fs.readlinkSync( path.join( reference, link ) ) + ); + } ); + + it( 'refuses to replay a used approval', () => { + expect( + thrown( () => generateFromPreview( approve( first ), { now } ) ) + .code + ).toBe( 'PREVIEW_NOT_FOUND' ); + } ); + + it( 'changes nothing, not even modification times, when run again', () => { + const before = snapshot( dest ); + const again = preview( dest ); + expect( again.summary.unchanged ).toBe( again.files.length ); + const result = generateFromPreview( approve( again ), { now } ); + expect( result.written ).toEqual( [] ); + expect( snapshot( dest ) ).toEqual( before ); + } ); +} ); + +describe( 'an existing Git repository', () => { + it( 'overwrites planned files, backs them up, and leaves the rest alone', () => { + const repo = path.join( work, 'repo' ); + fs.mkdirSync( repo ); + execFileSync( 'git', [ 'init', '-q', repo ] ); + fs.writeFileSync( path.join( repo, 'README.md' ), 'client readme\n' ); + fs.mkdirSync( path.join( repo, 'src' ) ); + fs.writeFileSync( + path.join( repo, 'src', 'custom.js' ), + 'export const custom = 1;\n' + ); + fs.writeFileSync( path.join( repo, 'notes.md' ), 'keep me\n' ); + fs.mkdirSync( path.join( repo, 'vendor-local' ) ); + fs.writeFileSync( + path.join( repo, 'vendor-local', 'tool.sh' ), + '#!/bin/sh\n' + ); + fs.chmodSync( path.join( repo, 'vendor-local', 'tool.sh' ), 0o755 ); + fs.writeFileSync( + path.join( repo, 'package.json' ), + '{"name":"old"}\n' + ); + fs.chmodSync( path.join( repo, 'package.json' ), 0o444 ); + fs.mkdirSync( path.join( repo, 'sub', '.git' ), { recursive: true } ); + fs.writeFileSync( + path.join( repo, 'sub', '.git', 'config' ), + '[core]\n' + ); + fs.writeFileSync( + path.join( repo, '.gitmodules' ), + '[submodule "x"]\n' + ); + execFileSync( 'git', [ '-C', repo, 'add', '-A' ] ); + execFileSync( 'git', [ + '-C', + repo, + '-c', + 'user.email=t@example.com', + '-c', + 'user.name=t', + 'commit', + '-qm', + 'client', + ] ); + const gitBefore = snapshot( path.join( repo, '.git' ) ); + const subGitBefore = snapshot( path.join( repo, 'sub', '.git' ) ); + const unrelated = [ + 'src/custom.js', + 'notes.md', + 'vendor-local/tool.sh', + '.gitmodules', + ]; + const before = snapshot( repo ); + + const p = preview( repo ); + const files = Object.fromEntries( + p.files.map( ( f: Preview ) => [ f.path, f ] ) + ); + expect( files[ 'README.md' ].action ).toBe( 'overwrite' ); + expect( files[ 'package.json' ].action ).toBe( 'overwrite' ); + expect( p.summary.conflict ).toBe( 0 ); + + const result = generateFromPreview( approve( p ), { now } ); + const after = snapshot( repo ); + expect( snapshot( path.join( repo, '.git' ) ) ).toEqual( gitBefore ); + expect( snapshot( path.join( repo, 'sub', '.git' ) ) ).toEqual( + subGitBefore + ); + for ( const file of unrelated ) { + expect( after[ file ] ).toBe( before[ file ] ); + } + expect( + fs.readFileSync( + path.join( result.backupFolder as string, 'README.md' ), + 'utf8' + ) + ).toBe( 'client readme\n' ); + expect( + fs.readFileSync( + path.join( result.backupFolder as string, 'package.json' ), + 'utf8' + ) + ).toBe( '{"name":"old"}\n' ); + expect( + fs.readFileSync( path.join( repo, 'README.md' ), 'utf8' ) + ).toBe( + fs.readFileSync( path.join( reference, 'README.md' ), 'utf8' ) + ); + const status = execFileSync( + 'git', + [ '-C', repo, 'status', '--porcelain' ], + { encoding: 'utf8' } + ); + expect( + status.split( '\n' ).filter( ( l ) => /^ D|^D /.test( l ) ) + ).toEqual( [] ); + expect( + Object.keys( snapshot( repo, { mtime: false } ) ).filter( ( f ) => + f.includes( '.bps-' ) + ) + ).toEqual( [] ); + } ); +} ); + +describe( 'links and failures', () => { + it( 'blocks on links and writes nothing through them', () => { + const linked = path.join( work, 'linked' ); + const outside = path.join( work, 'outside' ); + fs.mkdirSync( path.join( linked, 'src' ), { recursive: true } ); + fs.mkdirSync( outside ); + fs.writeFileSync( path.join( outside, 'keep.txt' ), 'outside\n' ); + fs.symlinkSync( outside, path.join( linked, 'src', 'blocks' ) ); + fs.symlinkSync( + path.join( outside, 'keep.txt' ), + path.join( linked, 'README.md' ) + ); + const linkedBefore = snapshot( linked ); + const outsideBefore = snapshot( outside ); + + const p = preview( linked ); + const failure = thrown( () => + generateFromPreview( approve( p ), { now } ) + ); + expect( failure.code ).toBe( 'CONFLICT' ); + expect( failure.details?.conflicts.length ).toBeGreaterThan( 1 ); + expect( snapshot( linked ) ).toEqual( linkedBefore ); + expect( snapshot( outside ) ).toEqual( outsideBefore ); + } ); + + it( 'stops with PARTIAL_WRITE at a read-only folder, then completes', () => { + const dest = path.join( work, 'perm' ); + fs.mkdirSync( path.join( dest, 'src' ), { recursive: true } ); + fs.writeFileSync( path.join( dest, 'README.md' ), 'perm readme\n' ); + const p = preview( dest ); + fs.chmodSync( path.join( dest, 'src' ), 0o555 ); + let failure; + try { + failure = thrown( () => + generateFromPreview( approve( p ), { now } ) + ); + } finally { + fs.chmodSync( path.join( dest, 'src' ), 0o755 ); + } + expect( failure.code ).toBe( 'PARTIAL_WRITE' ); + expect( failure.details?.failedAt.startsWith( 'src' ) ).toBe( true ); + expect( failure.details?.written.length ).toBeGreaterThan( 0 ); + expect( failure.details?.notWritten.length ).toBeGreaterThan( 0 ); + expect( + fs.readFileSync( + path.join( failure.details?.backupFolder, 'README.md' ), + 'utf8' + ) + ).toBe( 'perm readme\n' ); + expect( fs.readFileSync( failure.details?.journal, 'utf8' ) ).toContain( + '"op":"failed"' + ); + + const retry = preview( dest ); + generateFromPreview( approve( retry ), { now } ); + expect( diffTrees( reference, dest ) ).toEqual( [] ); + } ); + + it( 'leaves every file old or new when interrupted', () => { + const dest = path.join( work, 'interrupted' ); + fs.mkdirSync( dest ); + fs.writeFileSync( path.join( dest, 'README.md' ), 'old\n' ); + const p = preview( dest ); + let count = 0; + const failure = thrown( () => + generateFromPreview( approve( p ), { + now, + beforeWrite: () => { + count++; + if ( count === 40 ) { + throw new Error( 'simulated crash' ); + } + }, + } ) + ); + expect( failure.code ).toBe( 'PARTIAL_WRITE' ); + expect( failure.details?.written ).toHaveLength( 39 ); + for ( const rel of [ + ...failure.details?.written, + ...failure.details?.notWritten, + ] ) { + const target = path.join( dest, rel ); + if ( + ! fs.existsSync( target ) || + fs.lstatSync( target ).isDirectory() || + fs.lstatSync( target ).isSymbolicLink() + ) { + continue; + } + expect( [ + fs.readFileSync( path.join( reference, rel ), 'utf8' ), + 'old\n', + ] ).toContain( fs.readFileSync( target, 'utf8' ) ); + } + } ); + + it( 'does not overwrite a file edited while generating', () => { + const dest = path.join( work, 'race' ); + fs.mkdirSync( dest ); + fs.writeFileSync( path.join( dest, 'README.md' ), 'before\n' ); + const p = preview( dest ); + const failure = thrown( () => + generateFromPreview( approve( p ), { + now, + beforeWrite: ( rel ) => { + if ( rel === 'README.md' ) { + fs.writeFileSync( + path.join( dest, 'README.md' ), + 'edited mid-write\n' + ); + } + }, + } ) + ); + expect( failure.code ).toBe( 'PARTIAL_WRITE' ); + expect( + fs.readFileSync( path.join( dest, 'README.md' ), 'utf8' ) + ).toBe( 'edited mid-write\n' ); + } ); + + it( 'stops when a folder on the way becomes a link mid-write', () => { + const dest = path.join( work, 'race-link' ); + fs.mkdirSync( dest ); + const outside = path.join( work, 'race-outside' ); + fs.mkdirSync( outside ); + const p = preview( dest ); + const failure = thrown( () => + generateFromPreview( approve( p ), { + now, + beforeWrite: ( rel ) => { + if ( rel === 'bin' ) { + fs.symlinkSync( outside, path.join( dest, 'bin' ) ); + } + }, + } ) + ); + expect( failure.code ).toBe( 'PARTIAL_WRITE' ); + expect( fs.readdirSync( outside ) ).toEqual( [] ); + } ); + + it( 'is stale when the destination appears after the preview', () => { + const dest = path.join( work, 'appears' ); + const p = preview( dest ); + fs.mkdirSync( dest ); + expect( + thrown( () => generateFromPreview( approve( p ), { now } ) ).code + ).toBe( 'STALE_PREVIEW' ); + } ); +} ); diff --git a/scripts/mcp/__tests__/preview.test.mts b/scripts/mcp/__tests__/preview.test.mts new file mode 100644 index 0000000..e6f8b90 --- /dev/null +++ b/scripts/mcp/__tests__/preview.test.mts @@ -0,0 +1,388 @@ +/** + * Preview, approval and destination rules (BPS-12, T3). + */ + +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterAll, describe, expect, it } from 'vitest'; + +import { describeConfiguration, validateConfiguration } from '../config.mts'; +import { + PREVIEW_TTL_MS, + assertPreviewCurrent, + canonicalJson, + createPreview, + discardPreview, + getApprovedPreview, + resolveDestination, +} from '../preview.mts'; +import { SCAFFOLD, fixture, tempDir, thrown } from './helpers.mts'; + +type Preview = Record< string, any >; + +const work = tempDir( 'preview' ); +afterAll( () => fs.rmSync( work, { recursive: true, force: true } ) ); + +const cfg = fixture( { slug: 'tsp-preview' } ); +const approve = ( p: Preview ) => ( { + previewId: p.previewId, + approvalHash: p.approvalHash, + approved: true, +} ); +const preview = ( destination: string, overrides = {} ): Preview => + createPreview( { + config: { ...cfg, ...overrides }, + destination, + detail: 'full', + } ); +const byPath = ( p: Preview ) => + Object.fromEntries( + p.files.map( ( file: Preview ) => [ file.path, file ] ) + ); + +describe( 'configuration', () => { + it( 'reports the generator defaults, not the schema defaults', () => { + const fields = describeConfiguration().fields as Preview; + expect( fields.blocks.default ).toEqual( [] ); + expect( fields.author.required ).toBe( true ); + expect( fields.author.default ).toBeNull(); + expect( fields.content_model.default ).toBe( 'custom' ); + expect( fields.namespace.default ).toEqual( { + derived: 'the slug, with hyphens replaced by underscores', + } ); + } ); + + it( 'marks each value supplied, derived or default', () => { + const result = validateConfiguration( cfg ); + expect( result.valid ).toBe( true ); + expect( result.normalised.slug.source ).toBe( 'supplied' ); + expect( result.normalised.textdomain.source ).toBe( 'derived' ); + expect( result.normalised.requires_wp.source ).toBe( 'default' ); + expect( + result.warnings.some( ( w ) => w.path === '/repository_url' ) + ).toBe( true ); + } ); + + it( 'warns about legacy and unknown fields', () => { + const result = validateConfiguration( { + ...cfg, + cpt_slug: 'tour', + not_a_field: true, + } ); + const paths = result.warnings.map( ( w ) => w.path ); + expect( paths ).toContain( '/cpt_slug' ); + expect( paths ).toContain( '/not_a_field' ); + expect( result.normalised.cpt_slug.source ).toBe( 'supplied' ); + } ); + + it( 'rejects a configuration that is not an object', () => { + for ( const value of [ null, 'text', [ 1 ] ] ) { + expect( validateConfiguration( value ).valid ).toBe( false ); + } + } ); + + it( 'lists every broken rule', () => { + const result = validateConfiguration( { + slug: 'Bad Slug', + name: 'X', + } ); + expect( result.valid ).toBe( false ); + expect( result.errors.length ).toBeGreaterThanOrEqual( 2 ); + } ); + + it( 'hashes equal values equally, whatever the key order', () => { + expect( canonicalJson( { b: 1, a: [ { d: undefined, c: 2 } ] } ) ).toBe( + canonicalJson( { a: [ { c: 2, d: null } ], b: 1 } ) + ); + } ); +} ); + +describe( 'preview into a new folder', () => { + const dest = path.join( work, 'dest-new' ); + let first: Preview; + + it( 'plans every path as create and touches nothing', () => { + first = preview( dest ); + expect( first.destination.exists ).toBe( false ); + expect( first.summary.create ).toBe( first.files.length ); + expect( first.summary.conflict ).toBe( 0 ); + expect( first.processEffects.stagingFolder ).toBeTruthy(); + expect( fs.existsSync( dest ) ).toBe( false ); + } ); + + it( 'accepts only the matching approval', () => { + expect( getApprovedPreview( approve( first ) ).previewId ).toBe( + first.previewId + ); + assertPreviewCurrent( getApprovedPreview( approve( first ) ) ); + for ( const bad of [ + { ...approve( first ), approvalHash: 'x' }, + { ...approve( first ), approved: false }, + { ...approve( first ), approved: 'yes' as unknown as boolean }, + ] ) { + expect( thrown( () => getApprovedPreview( bad ) ).code ).toBe( + 'APPROVAL_MISMATCH' + ); + } + expect( + thrown( () => + getApprovedPreview( { ...approve( first ), previewId: 'nope' } ) + ).code + ).toBe( 'PREVIEW_NOT_FOUND' ); + } ); + + it( 'lists configuration changes and replaces the older preview', () => { + const second = createPreview( { + config: { ...cfg, name: 'TSP Preview Renamed' }, + destination: dest, + previousPreviewId: first.previewId, + } ) as Preview; + expect( + second.configuration.changesSincePreviousPreview.map( + ( c: Preview ) => c.field + ) + ).toContain( 'name' ); + expect( second.approvalHash ).not.toBe( first.approvalHash ); + expect( fs.existsSync( first.processEffects.stagingFolder ) ).toBe( + false + ); + expect( + thrown( () => getApprovedPreview( approve( first ) ) ).code + ).toBe( 'PREVIEW_NOT_FOUND' ); + + // The default summary is compact: no create paths, counts by folder. + expect( second.files ).toEqual( [] ); + expect( Object.keys( second.createByFolder ).length ).toBeGreaterThan( + 0 + ); + expect( JSON.stringify( second ).length ).toBeLessThan( 20000 ); + discardPreview( second.previewId ); + discardPreview( 'unknown' ); + } ); + + it( 'reports nothing when the earlier preview is unknown', () => { + const p = createPreview( { + config: cfg, + destination: path.join( work, 'dest-unknown-previous' ), + previousPreviewId: 'unknown', + } ) as Preview; + expect( p.configuration.changesSincePreviousPreview ).toBeNull(); + discardPreview( p.previewId ); + } ); +} ); + +describe( 'preview into an existing folder', () => { + it( 'classifies changed, identical, clashing and linked paths', () => { + const dest = path.join( work, 'dest-existing' ); + fs.mkdirSync( path.join( dest, '.git' ), { recursive: true } ); + fs.writeFileSync( path.join( dest, '.git', 'HEAD' ), 'ref\n' ); + fs.writeFileSync( path.join( dest, 'notes.txt' ), 'mine\n' ); + fs.mkdirSync( path.join( dest, 'src' ) ); + fs.writeFileSync( path.join( dest, 'src', 'custom.js' ), 'x\n' ); + fs.writeFileSync( path.join( dest, 'README.md' ), 'old\n' ); + fs.mkdirSync( path.join( dest, 'composer.json' ) ); + fs.writeFileSync( path.join( dest, 'bin' ), 'a file\n' ); + const elsewhere = path.join( work, 'elsewhere' ); + fs.mkdirSync( elsewhere ); + fs.symlinkSync( elsewhere, path.join( dest, 'src', 'blocks' ) ); + fs.symlinkSync( elsewhere, path.join( dest, 'uninstall.php' ) ); + + const reference = preview( path.join( work, 'reference' ) ); + const staged = path.join( + reference.processEffects.stagingFolder, + 'plugin' + ); + fs.copyFileSync( + path.join( staged, 'package.json' ), + path.join( dest, 'package.json' ) + ); + + const p = preview( dest ); + const files = byPath( p ); + expect( files[ 'README.md' ].action ).toBe( 'overwrite' ); + expect( files[ 'package.json' ].action ).toBe( 'unchanged' ); + expect( files[ 'composer.json' ].action ).toBe( 'conflict' ); + expect( files[ 'uninstall.php' ].action ).toBe( 'conflict' ); + expect( files.bin.action ).toBe( 'conflict' ); + const underFile = p.files.filter( ( f: Preview ) => + f.path.startsWith( 'bin/' ) + ); + expect( underFile.length ).toBeGreaterThan( 0 ); + expect( + underFile.every( ( f: Preview ) => f.action === 'conflict' ) + ).toBe( true ); + const linked = p.files.filter( ( f: Preview ) => + f.path.startsWith( 'src/blocks' ) + ); + expect( linked.length ).toBeGreaterThan( 1 ); + expect( + linked.every( ( f: Preview ) => f.action === 'conflict' ) + ).toBe( true ); + expect( p.preserved.hasGit ).toBe( true ); + expect( p.preserved.count ).toBeGreaterThanOrEqual( 2 ); + expect( + fs.readFileSync( path.join( dest, 'README.md' ), 'utf8' ) + ).toBe( 'old\n' ); + + expect( + thrown( () => + assertPreviewCurrent( getApprovedPreview( approve( p ) ) ) + ).code + ).toBe( 'CONFLICT' ); + } ); + + it( 'goes stale when a planned path changes, not an unrelated one', () => { + const dest = path.join( work, 'dest-clean' ); + fs.mkdirSync( dest ); + fs.writeFileSync( path.join( dest, 'README.md' ), 'old\n' ); + fs.writeFileSync( path.join( dest, 'unrelated.txt' ), 'keep\n' ); + + let p = preview( dest ); + fs.rmSync( path.join( dest, 'unrelated.txt' ) ); + assertPreviewCurrent( getApprovedPreview( approve( p ) ) ); + fs.writeFileSync( path.join( dest, 'README.md' ), 'edited\n' ); + expect( + thrown( () => + assertPreviewCurrent( getApprovedPreview( approve( p ) ) ) + ).code + ).toBe( 'STALE_PREVIEW' ); + + p = preview( dest ); + fs.writeFileSync( path.join( dest, 'composer.json' ), '{}\n' ); + expect( + thrown( () => + assertPreviewCurrent( getApprovedPreview( approve( p ) ) ) + ).code + ).toBe( 'STALE_PREVIEW' ); + + p = preview( dest ); + fs.renameSync( dest, `${ dest }-moved` ); + fs.symlinkSync( `${ dest }-moved`, dest ); + expect( + thrown( () => + assertPreviewCurrent( getApprovedPreview( approve( p ) ) ) + ).code + ).toBe( 'STALE_PREVIEW' ); + discardPreview( p.previewId ); + } ); +} ); + +describe( 'preview lifetime and failures', () => { + it( 'expires after 30 minutes and removes its staging folder', () => { + const p = preview( path.join( work, 'dest-expiry' ) ); + const later = () => new Date( Date.now() + PREVIEW_TTL_MS + 60000 ); + expect( + thrown( () => getApprovedPreview( approve( p ), { now: later } ) ) + .code + ).toBe( 'PREVIEW_NOT_FOUND' ); + expect( fs.existsSync( p.processEffects.stagingFolder ) ).toBe( false ); + } ); + + it( 'reports invalid configuration and staging failures', () => { + const dest = path.join( work, 'x' ); + expect( + thrown( () => + createPreview( { + config: { slug: 'x-plugin', name: 'X' }, + destination: dest, + } ) + ).code + ).toBe( 'INVALID_CONFIG' ); + expect( + thrown( () => + createPreview( { + config: { ...cfg, content_model: 'none' }, + destination: dest, + } ) + ).code + ).toBe( 'INVALID_CONFIG' ); + expect( + thrown( () => + createPreview( + { config: cfg, destination: dest }, + { tmpDir: path.join( work, 'no-such-folder' ) } + ) + ).code + ).toBe( 'STAGING_FAILED' ); + expect( + thrown( () => + createPreview( { + config: { ...cfg, blocks: [ 'not-a-block' ] }, + destination: dest, + } ) + ).code + ).toBe( 'INVALID_CONFIG' ); + } ); +} ); + +describe( 'destination rules', () => { + const home = os.homedir(); + const linkDest = path.join( work, 'link-dest' ); + const aFile = path.join( work, 'a-file' ); + fs.symlinkSync( work, linkDest ); + fs.writeFileSync( aFile, '' ); + + it.each( [ + [ 'an empty path', '' ], + [ 'a non-string', 42 ], + [ 'a relative path', 'plugins/tsp' ], + [ 'a ".." segment', `${ work }/../escape` ], + [ 'the filesystem root', '/' ], + [ 'the home folder', home ], + [ 'the home folder via ~', '~' ], + [ '/System', '/System/tsp' ], + [ '/Library', '/Library/tsp' ], + [ '/usr/local', '/usr/local/tsp' ], + [ '/private/etc', '/private/etc/tsp' ], + [ 'the scaffold root', SCAFFOLD ], + [ 'scaffold scripts', path.join( SCAFFOLD, 'scripts', 'tsp' ) ], + [ + 'generated-plugins itself', + path.join( SCAFFOLD, 'generated-plugins' ), + ], + [ 'a symbolic link', linkDest ], + [ 'an existing file', aFile ], + [ 'a missing parent', path.join( work, 'no', 'such', 'tsp' ) ], + [ 'a file as parent', path.join( aFile, 'tsp' ) ], + ] )( 'refuses %s', ( _label, destination ) => { + expect( + thrown( () => resolveDestination( destination, 'tsp' ) ).code + ).toBe( 'UNSAFE_DESTINATION' ); + } ); + + it.each( [ + [ + 'the default', + undefined, + path.join( + fs.realpathSync( SCAFFOLD ), + 'generated-plugins', + 'tsp' + ), + ], + [ + 'a folder in generated-plugins', + path.join( SCAFFOLD, 'generated-plugins', 'tsp' ), + path.join( + fs.realpathSync( SCAFFOLD ), + 'generated-plugins', + 'tsp' + ), + ], + [ + 'a home subfolder via ~/', + '~/tsp-plugin', + path.join( fs.realpathSync( home ), 'tsp-plugin' ), + ], + [ + 'the temporary folder, by its real path', + path.join( os.tmpdir(), 'tsp' ), + path.join( fs.realpathSync( os.tmpdir() ), 'tsp' ), + ], + ] )( 'allows %s', ( _label, destination, expected ) => { + expect( resolveDestination( destination, 'tsp' ).path ).toBe( + expected + ); + } ); +} ); diff --git a/scripts/mcp/__tests__/server.test.mts b/scripts/mcp/__tests__/server.test.mts new file mode 100644 index 0000000..a72cc60 --- /dev/null +++ b/scripts/mcp/__tests__/server.test.mts @@ -0,0 +1,179 @@ +/** + * The MCP server and its four tools (BPS-12, T5). + */ + +import fs from 'node:fs'; +import path from 'node:path'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; + +import { createServer, run } from '../server.mts'; +import { SCAFFOLD, fixture, tempDir } from './helpers.mts'; + +type Json = Record< string, any >; +type CallResult = { isError?: boolean; content: { text: string }[] }; + +const work = tempDir( 'server' ); +afterAll( () => fs.rmSync( work, { recursive: true, force: true } ) ); + +const config = fixture( { + slug: 'tsp-mcp', + name: 'TSP MCP', + repository_url: 'https://github.com/lightspeedwp/tsp-mcp', +} ); +const parse = ( result: unknown ): Json => + JSON.parse( ( result as CallResult ).content[ 0 ].text ); + +describe( 'tool results', () => { + it( 'turns unexpected errors into INTERNAL results, with the stack on standard error', () => { + const stderr = vi + .spyOn( process.stderr, 'write' ) + .mockImplementation( () => true ); + const result = run( () => { + throw new Error( 'boom' ); + } ); + expect( stderr ).toHaveBeenCalledWith( + expect.stringContaining( 'Error: boom' ) + ); + stderr.mockRestore(); + expect( result.isError ).toBe( true ); + expect( parse( result ).error.code ).toBe( 'INTERNAL' ); + } ); +} ); + +describe( 'server over an in-memory transport', () => { + const client = new Client( { name: 'bps12-test', version: '1.0.0' } ); + + beforeAll( async () => { + const [ clientSide, serverSide ] = InMemoryTransport.createLinkedPair(); + await createServer().connect( serverSide ); + await client.connect( clientSide ); + } ); + afterAll( () => client.close() ); + + const call = ( name: string, args: Json = {} ) => + client.callTool( { name, arguments: args } ) as Promise< CallResult >; + + it( 'lists four annotated tools', async () => { + const { tools } = await client.listTools(); + const byName = Object.fromEntries( + tools.map( ( t ) => [ t.name, t ] ) + ); + expect( Object.keys( byName ).sort() ).toEqual( [ + 'discover', + 'generate', + 'preview', + 'validate_config', + ] ); + expect( byName.discover.annotations?.readOnlyHint ).toBe( true ); + expect( byName.validate_config.annotations?.readOnlyHint ).toBe( true ); + expect( byName.preview.annotations?.destructiveHint ).toBe( false ); + expect( byName.generate.annotations?.destructiveHint ).toBe( true ); + } ); + + it( 'discovers and validates', async () => { + expect( + parse( await call( 'discover' ) ).fields.blocks.default + ).toEqual( [] ); + expect( + parse( await call( 'validate_config', { config } ) ).valid + ).toBe( true ); + const invalid = parse( + await call( 'validate_config', { + config: { slug: 'Bad Slug', name: 'X' }, + } ) + ); + expect( invalid.valid ).toBe( false ); + } ); + + it( 'refuses unsafe destinations and unapproved generation', async () => { + const unsafe = await call( 'preview', { + config, + destination: 'relative/folder', + } ); + expect( unsafe.isError ).toBe( true ); + expect( parse( unsafe ).error.code ).toBe( 'UNSAFE_DESTINATION' ); + + const dest = path.join( work, 'refused' ); + const p = parse( + await call( 'preview', { config, destination: dest } ) + ); + const refused = await call( 'generate', { + previewId: p.previewId, + approvalHash: p.approvalHash, + approved: false, + } ); + expect( parse( refused ).error.code ).toBe( 'APPROVAL_MISMATCH' ); + expect( fs.existsSync( dest ) ).toBe( false ); + } ); + + it( 'previews compactly and generates twice in one server', async () => { + const dest = path.join( work, 'tsp-mcp' ); + const raw = await call( 'preview', { config, destination: dest } ); + const p = parse( raw ); + expect( raw.content[ 0 ].text.length ).toBeLessThan( 20000 ); + expect( p.summary.conflict ).toBe( 0 ); + + const approval = { + previewId: p.previewId, + approvalHash: p.approvalHash, + approved: true, + }; + const generated = parse( await call( 'generate', approval ) ); + expect( generated.written ).toHaveLength( p.summary.create ); + expect( fs.existsSync( path.join( dest, 'tsp-mcp.php' ) ) ).toBe( + true + ); + expect( parse( await call( 'generate', approval ) ).error.code ).toBe( + 'PREVIEW_NOT_FOUND' + ); + + const second = { ...config, slug: 'tsp-mcp-two', name: 'TSP Two' }; + const p2 = parse( + await call( 'preview', { + config: second, + destination: path.join( work, 'two' ), + detail: 'full', + } ) + ); + expect( p2.files.length ).toBe( p2.summary.create ); + await call( 'generate', { + previewId: p2.previewId, + approvalHash: p2.approvalHash, + approved: true, + } ); + expect( + fs.existsSync( path.join( work, 'two', 'tsp-mcp-two.php' ) ) + ).toBe( true ); + const log = fs.readFileSync( p2.processEffects.logFile, 'utf8' ); + expect( log ).not.toContain( '"tsp-mcp"' ); + } ); +} ); + +describe( 'server over stdio', () => { + it( 'starts from / and keeps standard output for the protocol', async () => { + let stderr = ''; + const transport = new StdioClientTransport( { + command: process.execPath, + args: [ path.join( SCAFFOLD, 'scripts/mcp/server.mts' ) ], + // Claude Desktop does not start servers in the scaffold. + cwd: '/', + stderr: 'pipe', + } ); + transport.stderr?.on( 'data', ( chunk ) => ( stderr += chunk ) ); + const client = new Client( { name: 'bps12-stdio', version: '1.0.0' } ); + await client.connect( transport ); + const result = ( await client.callTool( { + name: 'discover', + arguments: {}, + } ) ) as CallResult; + expect( parse( result ).contract ).toBe( + 'docs/MCP-PLUGIN-GENERATION.md' + ); + await client.close(); + expect( stderr ).toContain( 'ready on stdio' ); + expect( stderr ).not.toContain( 'MODULE_TYPELESS_PACKAGE_JSON' ); + } ); +} ); diff --git a/scripts/mcp/__tests__/staging-failure.test.mts b/scripts/mcp/__tests__/staging-failure.test.mts new file mode 100644 index 0000000..aef913a --- /dev/null +++ b/scripts/mcp/__tests__/staging-failure.test.mts @@ -0,0 +1,46 @@ +/** + * A generator failure during preview is reported as STAGING_FAILED and + * leaves no staging folder (BPS-12, T3). The generator is replaced with one + * that throws, so this lives in its own file. + */ + +import fs from 'node:fs'; +import path from 'node:path'; +import { afterAll, describe, expect, it, vi } from 'vitest'; + +import { fixture, tempDir, thrown } from './helpers.mts'; + +vi.mock( '../generator.mts', async ( original ) => ( { + ...( await original< typeof import( '../generator.mts' ) >() ), + generatePlugin: () => { + throw new Error( 'simulated generator failure' ); + }, +} ) ); + +const { createPreview } = await import( '../preview.mts' ); + +const work = tempDir( 'staging-failure' ); +const staging = tempDir( 'staging-parent' ); +afterAll( () => { + fs.rmSync( work, { recursive: true, force: true } ); + fs.rmSync( staging, { recursive: true, force: true } ); +} ); + +describe( 'staging failure', () => { + it( 'reports STAGING_FAILED with the log, and removes the staging folder', () => { + const failure = thrown( () => + createPreview( + { + config: fixture( { slug: 'tsp-fail' } ), + destination: path.join( work, 'dest' ), + }, + { tmpDir: staging } + ) + ); + expect( failure.code ).toBe( 'STAGING_FAILED' ); + expect( failure.message ).toContain( 'simulated generator failure' ); + expect( failure.details?.logFile ).toMatch( /mcp-tsp-fail-.*\.log$/ ); + expect( fs.readdirSync( staging ) ).toEqual( [] ); + expect( fs.existsSync( path.join( work, 'dest' ) ) ).toBe( false ); + } ); +} ); diff --git a/scripts/mcp/config.js b/scripts/mcp/config.mts similarity index 74% rename from scripts/mcp/config.js rename to scripts/mcp/config.mts index 3962eae..dd58113 100644 --- a/scripts/mcp/config.js +++ b/scripts/mcp/config.mts @@ -5,15 +5,35 @@ * Uses the generator's own defaults and validation, not the standalone * validator, whose field and taxonomy checks contradict the schema (see * "Supported configuration" in docs/MCP-PLUGIN-GENERATION.md). - * - * @package */ -const { +import { applyDefaults, loadSchema, validateConfig, -} = require( '../generate-plugin' ); + type PluginConfig, +} from './generator.mts'; + +export type ValueSource = 'supplied' | 'derived' | 'default'; + +export interface Issue { + path: string; + message: string; +} + +export interface ValidationResult { + valid: boolean; + errors: Issue[]; + warnings: Issue[]; + normalised: Record< string, { value: unknown; source: ValueSource } >; + values: Record< string, unknown >; +} + +export interface ValueChange { + field: string; + before: unknown; + after: unknown; +} // Values the generator works out from other values rather than defaulting. const DERIVED = new Set( [ @@ -26,7 +46,7 @@ const DERIVED = new Set( [ ] ); // How each derived value is worked out, for discover. -const DERIVED_FROM = { +const DERIVED_FROM: Record< string, string > = { textdomain: 'the slug', namespace: 'the slug, with hyphens replaced by underscores', license_uri: 'the licence', @@ -46,16 +66,10 @@ const LEGACY = new Set( [ /** * Validate a configuration and describe where each value comes from. * - * @param {*} config Configuration from the client. - * @return {{ - * valid: boolean, - * errors: {path: string, message: string}[], - * warnings: {path: string, message: string}[], - * normalised: Object, - * values: Object - * }} Result. + * @param config Configuration from the client. + * @return Result. */ -function validateConfiguration( config ) { +export function validateConfiguration( config: unknown ): ValidationResult { if ( ! config || typeof config !== 'object' || Array.isArray( config ) ) { return { valid: false, @@ -65,23 +79,24 @@ function validateConfiguration( config ) { values: {}, }; } + const input = config as PluginConfig; const schema = loadSchema(); - const full = applyDefaults( config ); + const full = applyDefaults( input ); const validation = validateConfig( full ); const errors = ( validation.errors || [] ).map( ( error ) => ( { path: error.instancePath || '', - message: error.message, + message: error.message || 'invalid', } ) ); - const supplied = ( key ) => Object.hasOwn( config, key ); - const normalised = {}; - const values = {}; + const supplied = ( key: string ) => Object.hasOwn( input, key ); + const normalised: ValidationResult[ 'normalised' ] = {}; + const values: ValidationResult[ 'values' ] = {}; for ( const key of Object.keys( schema.properties ) ) { if ( key === '_comment' || full[ key ] === undefined ) { continue; } - let source = 'default'; + let source: ValueSource = 'default'; if ( supplied( key ) ) { source = 'supplied'; } else if ( DERIVED.has( key ) ) { @@ -91,22 +106,24 @@ function validateConfiguration( config ) { values[ key ] = full[ key ]; } - const warnings = []; + const warnings: Issue[] = []; if ( ! supplied( 'repository_url' ) ) { warnings.push( { path: '/repository_url', - message: `Not supplied, so it defaults to ${ full.repository_url }. Set it if the plugin lives elsewhere.`, + message: `Not supplied, so it defaults to ${ String( + full.repository_url + ) }. Set it if the plugin lives elsewhere.`, } ); } - for ( const key of Object.keys( config ) ) { + for ( const key of Object.keys( input ) ) { if ( LEGACY.has( key ) ) { warnings.push( { path: `/${ key }`, message: 'Legacy single-post-type field; use post_types instead.', } ); - normalised[ key ] = { value: config[ key ], source: 'supplied' }; - values[ key ] = config[ key ]; + normalised[ key ] = { value: input[ key ], source: 'supplied' }; + values[ key ] = input[ key ]; } else if ( ! Object.hasOwn( schema.properties, key ) ) { warnings.push( { path: `/${ key }`, @@ -127,11 +144,14 @@ function validateConfiguration( config ) { /** * List the configuration values that differ between two previews. * - * @param {Object} before Values from the earlier preview. - * @param {Object} after Values from this preview. - * @return {{field: string, before: *, after: *}[]} Changes. + * @param before Values from the earlier preview. + * @param after Values from this preview. + * @return Changes. */ -function diffValues( before, after ) { +export function diffValues( + before: Record< string, unknown >, + after: Record< string, unknown > +): ValueChange[] { const keys = new Set( [ ...Object.keys( before ), ...Object.keys( after ), @@ -156,21 +176,21 @@ function diffValues( before, after ) { * Defaults are the generator's own (applyDefaults), not the schema's * `default` values, which differ for blocks, author and author_uri. * - * @return {Object} Description. + * @return Description. */ -function describeConfiguration() { +export function describeConfiguration(): Record< string, unknown > { const schema = loadSchema(); const required = new Set( schema.required || [] ); // Apply defaults to a minimal configuration to read the generator's own. const sample = { slug: 'example-plugin', name: 'Example', author: 'A' }; const defaults = applyDefaults( sample ); - const fields = {}; + const fields: Record< string, Record< string, unknown > > = {}; for ( const [ key, property ] of Object.entries( schema.properties ) ) { if ( key === '_comment' ) { continue; } - const field = { + const field: Record< string, unknown > = { type: property.type, required: required.has( key ), description: property.description, @@ -223,5 +243,3 @@ function describeConfiguration() { contract: 'docs/MCP-PLUGIN-GENERATION.md', }; } - -module.exports = { validateConfiguration, diffValues, describeConfiguration }; diff --git a/scripts/mcp/errors.js b/scripts/mcp/errors.js deleted file mode 100644 index 894bb02..0000000 --- a/scripts/mcp/errors.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Errors for local MCP plugin generation (BPS-12). - * - * Every failure the MCP tools report carries one of the codes defined in - * docs/MCP-PLUGIN-GENERATION.md, so the consuming skill can act on it. - * - * @package - */ - -const CODES = Object.freeze( { - INVALID_CONFIG: 'INVALID_CONFIG', - UNSAFE_DESTINATION: 'UNSAFE_DESTINATION', - CONFLICT: 'CONFLICT', - PREVIEW_NOT_FOUND: 'PREVIEW_NOT_FOUND', - APPROVAL_MISMATCH: 'APPROVAL_MISMATCH', - STALE_PREVIEW: 'STALE_PREVIEW', - STAGING_FAILED: 'STAGING_FAILED', - PARTIAL_WRITE: 'PARTIAL_WRITE', - INTERNAL: 'INTERNAL', -} ); - -/** - * An error with a contract code and structured details. - */ -class GenerationError extends Error { - /** - * @param {string} code One of CODES. - * @param {string} message Human-readable message. - * @param {Object} [details] Structured details for the client. - */ - constructor( code, message, details = {} ) { - super( message ); - this.name = 'GenerationError'; - this.code = code; - this.details = details; - } - - /** - * The error as JSON for a tool result. - * - * @return {{code: string, message: string, details: Object}} Error. - */ - toJSON() { - return { - code: this.code, - message: this.message, - details: this.details, - }; - } -} - -module.exports = { CODES, GenerationError }; diff --git a/scripts/mcp/errors.mts b/scripts/mcp/errors.mts new file mode 100644 index 0000000..50ea4c1 --- /dev/null +++ b/scripts/mcp/errors.mts @@ -0,0 +1,58 @@ +/** + * Errors for local MCP plugin generation (BPS-12). + * + * Every failure the MCP tools report carries one of the codes defined in + * docs/MCP-PLUGIN-GENERATION.md, so the consuming skill can act on it. + * + * Node 24.18+ runs this file directly (type stripping), so it uses only + * erasable TypeScript syntax. + */ + +export const CODES = Object.freeze( { + INVALID_CONFIG: 'INVALID_CONFIG', + UNSAFE_DESTINATION: 'UNSAFE_DESTINATION', + CONFLICT: 'CONFLICT', + PREVIEW_NOT_FOUND: 'PREVIEW_NOT_FOUND', + APPROVAL_MISMATCH: 'APPROVAL_MISMATCH', + STALE_PREVIEW: 'STALE_PREVIEW', + STAGING_FAILED: 'STAGING_FAILED', + PARTIAL_WRITE: 'PARTIAL_WRITE', + INTERNAL: 'INTERNAL', +} as const ); + +export type ErrorCode = ( typeof CODES )[ keyof typeof CODES ]; + +/** An error with a contract code and structured details. */ +export class GenerationError extends Error { + code: ErrorCode; + details: Record< string, unknown >; + + /** + * @param code One of CODES. + * @param message Human-readable message. + * @param details Structured details for the client. + */ + constructor( + code: ErrorCode, + message: string, + details: Record< string, unknown > = {} + ) { + super( message ); + this.name = 'GenerationError'; + this.code = code; + this.details = details; + } + + /** The error as JSON for a tool result. */ + toJSON(): { + code: ErrorCode; + message: string; + details: Record< string, unknown >; + } { + return { + code: this.code, + message: this.message, + details: this.details, + }; + } +} diff --git a/scripts/mcp/generator.mts b/scripts/mcp/generator.mts new file mode 100644 index 0000000..722463f --- /dev/null +++ b/scripts/mcp/generator.mts @@ -0,0 +1,63 @@ +/** + * Typed access to the generator engine (scripts/generate-plugin.js) for the + * MCP modules (BPS-12). + * + * The engine is CommonJS JavaScript; this is the one place the MCP code + * imports it, so its types are declared once. + */ + +import engine from '../generate-plugin.js'; + +export type PluginConfig = Record< string, unknown >; + +/** A diagnostic writer, or false for none. */ +export type Output = ( ( level: string, message: string ) => void ) | false; + +export interface GenerateOptions { + inPlace?: boolean; + outputDir?: string; + outputBaseDir?: string; + force?: boolean; + now?: () => Date; + logFile?: string; + output?: Output; +} + +export interface SchemaProperty { + type?: string | string[]; + description?: string; + [ rule: string ]: unknown; +} + +export interface ConfigSchema { + required?: string[]; + properties: Record< string, SchemaProperty >; +} + +export interface SchemaError { + instancePath?: string; + message?: string; +} + +interface Engine { + generatePlugin: ( + config: PluginConfig, + options?: GenerateOptions | boolean + ) => string; + applyDefaults: ( + config: PluginConfig, + now?: Date + ) => Record< string, unknown >; + validateConfig: ( config: Record< string, unknown > ) => { + valid: boolean; + errors: SchemaError[] | null; + }; + loadSchema: () => ConfigSchema; +} + +const typed = engine as Engine; + +export const generatePlugin = typed.generatePlugin; +export const applyDefaults = typed.applyDefaults; +export const validateConfig = typed.validateConfig; +export const loadSchema = typed.loadSchema; diff --git a/scripts/mcp/merge.js b/scripts/mcp/merge.mts similarity index 72% rename from scripts/mcp/merge.js rename to scripts/mcp/merge.mts index 8f93754..b230a9c 100644 --- a/scripts/mcp/merge.js +++ b/scripts/mcp/merge.mts @@ -5,29 +5,46 @@ * overwrite only planned files, leave everything else (and every Git path) * alone, never write through links, write each file atomically, and back up * every file before overwriting it. - * - * @package */ -const crypto = require( 'crypto' ); -const fs = require( 'fs' ); -const path = require( 'path' ); +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; -const { +import { CODES, GenerationError } from './errors.mts'; +import { assertPreviewCurrent, describePath, discardPreview, getApprovedPreview, -} = require( './preview' ); -const { CODES, GenerationError } = require( './errors' ); + type Action, + type ApprovalRequest, + type Clock, + type PlannedFile, + type StoredPreview, +} from './preview.mts'; + +export interface MergeOptions extends Clock { + /** Called with each path before it is written; for fault-injection checks. */ + beforeWrite?: ( file: string ) => void; +} + +export interface MergeResult { + destination: string; + written: { path: string; action: Action }[]; + unchanged: number; + backupFolder: string | null; + journal: string; + logFile: string; +} /** * Append one line to the journal. * - * @param {string} journal Journal file. - * @param {Object} entry Entry. + * @param journal Journal file. + * @param entry Entry. */ -function record( journal, entry ) { +function record( journal: string, entry: Record< string, unknown > ): void { fs.appendFileSync( journal, `${ JSON.stringify( entry ) }\n`, 'utf8' ); } @@ -35,10 +52,13 @@ function record( journal, entry ) { * Check that a path is still in the state the preview saw, just before * writing it, and that no folder on the way has become a link. * - * @param {string} destRoot Destination folder. - * @param {Object} file Planned file from the preview. + * @param destRoot Destination folder. + * @param file Planned file from the preview. */ -function assertUnchangedSincePreview( destRoot, file ) { +function assertUnchangedSincePreview( + destRoot: string, + file: PlannedFile +): void { const parts = file.path.split( '/' ); for ( let i = 1; i < parts.length; i++ ) { const ancestor = describePath( @@ -50,10 +70,10 @@ function assertUnchangedSincePreview( destRoot, file ) { ); } } - const now = describePath( path.join( destRoot, ...parts ) ); + const current = describePath( path.join( destRoot, ...parts ) ); const expected = file.action === 'create' ? { type: 'missing', hash: null } : file.state; - if ( now.type !== expected.type || now.hash !== expected.hash ) { + if ( current.type !== expected.type || current.hash !== expected.hash ) { throw new Error( `${ file.path } changed after the preview` ); } } @@ -62,10 +82,10 @@ function assertUnchangedSincePreview( destRoot, file ) { * Write one staged file into place: a temporary file beside the target, * then a rename, so the target is never half-written. * - * @param {string} source Staged file. - * @param {string} target Destination path. + * @param source Staged file. + * @param target Destination path. */ -function writeAtomically( source, target ) { +function writeAtomically( source: string, target: string ): void { const temp = path.join( path.dirname( target ), `.${ path.basename( target ) }.bps-${ crypto @@ -86,13 +106,14 @@ function writeAtomically( source, target ) { /** * Copy an approved preview's files into its destination. * - * @param {Object} preview Stored preview, already approved. - * @param {Object} [options] - * @param {Function} [options.now] Clock returning a Date. - * @param {Function} [options.beforeWrite] Called with each path before it is written; for fault-injection checks. - * @return {Object} Result for the client. + * @param preview Stored preview, already approved. + * @param options Clock and fault-injection hook. + * @return Result for the client. */ -function applyPreview( preview, options = {} ) { +export function applyPreview( + preview: StoredPreview, + options: MergeOptions = {} +): MergeResult { const now = options.now || ( () => new Date() ); assertPreviewCurrent( preview ); @@ -114,9 +135,9 @@ function applyPreview( preview, options = {} ) { ( file ) => file.action === 'create' || file.action === 'overwrite' ) .sort( ( a, b ) => ( a.path < b.path ? -1 : 1 ) ); - const written = []; - const backedUp = []; - let current = null; + const written: string[] = []; + const backedUp: string[] = []; + let current: string | null = null; try { if ( ! preview.destinationExisted ) { @@ -172,6 +193,7 @@ function applyPreview( preview, options = {} ) { } ); } } catch ( error ) { + const message = ( error as Error ).message; const done = new Set( written ); const notWritten = planned .map( ( file ) => file.path ) @@ -180,11 +202,11 @@ function applyPreview( preview, options = {} ) { op: 'failed', at: now().toISOString(), path: current, - error: error.message, + error: message, } ); throw new GenerationError( CODES.PARTIAL_WRITE, - `Writing stopped at ${ current }: ${ error.message }`, + `Writing stopped at ${ current }: ${ message }`, { failedAt: current, written, @@ -218,16 +240,14 @@ function applyPreview( preview, options = {} ) { /** * The generate operation: check the approval, then merge. * - * @param {Object} request - * @param {string} request.previewId Preview ID. - * @param {string} request.approvalHash Approval hash from the preview. - * @param {boolean} request.approved Must be true. - * @param {Object} [options] See applyPreview(). - * @return {Object} Result for the client. + * @param request Preview ID, approval hash and approved flag. + * @param options See applyPreview(). + * @return Result for the client. */ -function generateFromPreview( request, options = {} ) { +export function generateFromPreview( + request: ApprovalRequest, + options: MergeOptions = {} +): MergeResult { const preview = getApprovedPreview( request, options ); return applyPreview( preview, options ); } - -module.exports = { applyPreview, generateFromPreview }; diff --git a/scripts/mcp/preview.js b/scripts/mcp/preview.mts similarity index 64% rename from scripts/mcp/preview.js rename to scripts/mcp/preview.mts index 86ab6ff..28aac9a 100644 --- a/scripts/mcp/preview.js +++ b/scripts/mcp/preview.mts @@ -3,24 +3,28 @@ * * A preview generates the plugin into a private staging folder, compares every * staged path with the destination, and binds an approval hash to the - * configuration, the destination and the staged files. generate (phase 3) - * copies from the stored preview only after its approval and freshness checks - * pass. The rules are in docs/MCP-PLUGIN-GENERATION.md. - * - * @package + * configuration, the destination and the staged files. generate copies from + * the stored preview only after its approval and freshness checks pass. The + * rules are in docs/MCP-PLUGIN-GENERATION.md. */ -const crypto = require( 'crypto' ); -const fs = require( 'fs' ); -const os = require( 'os' ); -const path = require( 'path' ); - -const { generatePlugin } = require( '../generate-plugin' ); -const { validateConfiguration, diffValues } = require( './config' ); -const { CODES, GenerationError } = require( './errors' ); - -const SCAFFOLD_DIR = path.resolve( __dirname, '../..' ); -const PREVIEW_TTL_MS = 30 * 60 * 1000; +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { + diffValues, + validateConfiguration, + type Issue, + type ValidationResult, + type ValueChange, +} from './config.mts'; +import { CODES, GenerationError } from './errors.mts'; +import { generatePlugin } from './generator.mts'; + +export const SCAFFOLD_DIR = path.resolve( import.meta.dirname, '../..' ); +export const PREVIEW_TTL_MS = 30 * 60 * 1000; const PRESERVED_COUNT_LIMIT = 50000; // Destinations refused outright, with everything inside them. @@ -38,16 +42,86 @@ const SYSTEM_DIRS = [ '/private/var/db', ]; +export type PathType = 'missing' | 'file' | 'symlink' | 'dir' | 'other' | 'n/a'; +export type Action = 'create' | 'overwrite' | 'unchanged' | 'conflict'; +export type Detail = 'summary' | 'full'; + +export interface PathState { + type: PathType; + hash: string | null; +} + +export interface StagedEntry extends PathState { + path: string; +} + +export interface PlannedFile extends StagedEntry { + action: Action; + reason?: string; + /** The destination state the action relied on. */ + state: PathState; +} + +export interface Destination { + path: string; + exists: boolean; +} + +export interface Clock { + now?: () => Date; +} + +export interface PreviewOptions extends Clock { + scaffoldDir?: string; + homeDir?: string; + tmpDir?: string; +} + +export interface PreviewRequest { + config: unknown; + destination?: string; + previousPreviewId?: string; + detail?: Detail; +} + +export interface ApprovalRequest { + previewId: string; + approvalHash: string; + approved: boolean; +} + +/** A preview as stored in memory. */ +export interface StoredPreview { + previewId: string; + approvalHash: string; + destination: string; + destinationExisted: boolean; + values: Record< string, unknown >; + files: PlannedFile[]; + stagingDir: string; + stagedPlugin: string; + logFile: string; + expiresAt: number; + scaffoldDir: string; + homeDir?: string; +} + +export interface PreservedSummary { + count: number; + capped: boolean; + hasGit: boolean; +} + // Previews by ID. A preview lives in memory and in its staging folder only. -const previews = new Map(); +const previews = new Map< string, StoredPreview >(); /** * Throw UNSAFE_DESTINATION. * - * @param {string} destination Path as supplied or resolved. - * @param {string} reason Why it is refused. + * @param destination Path as supplied or resolved. + * @param reason Why it is refused. */ -function refuse( destination, reason ) { +function refuse( destination: string, reason: string ): never { throw new GenerationError( CODES.UNSAFE_DESTINATION, `Destination refused: ${ reason }`, @@ -58,25 +132,37 @@ function refuse( destination, reason ) { /** * Whether a path is a folder or inside it. * - * @param {string} child Absolute path. - * @param {string} parent Absolute folder. - * @return {boolean} Inside or equal. + * @param child Absolute path. + * @param parent Absolute folder. + * @return Inside or equal. */ -function isWithin( child, parent ) { +function isWithin( child: string, parent: string ): boolean { return child === parent || child.startsWith( `${ parent }${ path.sep }` ); } +/** + * The error code of a failed filesystem call. + * + * @param error Caught value. + * @return Code, if any. + */ +function errorCode( error: unknown ): string | undefined { + return ( error as NodeJS.ErrnoException )?.code; +} + /** * Resolve and check a destination folder. * - * @param {string|undefined} destination Folder from the client, or undefined for the default. - * @param {string} slug Plugin slug, for the default. - * @param {Object} [options] - * @param {string} [options.scaffoldDir] Scaffold checkout. - * @param {string} [options.homeDir] Home folder. - * @return {{path: string, exists: boolean}} Real absolute path, and whether it exists. + * @param destination Folder from the client, or undefined for the default. + * @param slug Plugin slug, for the default. + * @param options Scaffold and home folders. + * @return Real absolute path, and whether it exists. */ -function resolveDestination( destination, slug, options = {} ) { +export function resolveDestination( + destination: unknown, + slug: string, + options: { scaffoldDir?: string; homeDir?: string } = {} +): Destination { const scaffoldDir = options.scaffoldDir || SCAFFOLD_DIR; const homeDir = options.homeDir || os.homedir(); @@ -98,16 +184,18 @@ function resolveDestination( destination, slug, options = {} ) { } const absolute = path.resolve( raw ); - let stat = null; + let stat: fs.Stats | null = null; try { stat = fs.lstatSync( absolute ); } catch ( error ) { - if ( error.code !== 'ENOENT' ) { + // ENOTDIR: something on the way is a file; the parent check refuses it. + const code = errorCode( error ); + if ( code !== 'ENOENT' && code !== 'ENOTDIR' ) { throw error; } } - let real; + let real: string; if ( stat ) { if ( stat.isSymbolicLink() ) { refuse( absolute, 'it is a symbolic link' ); @@ -118,10 +206,10 @@ function resolveDestination( destination, slug, options = {} ) { real = fs.realpathSync( absolute ); } else { const parent = path.dirname( absolute ); - let parentStat; + let parentStat: fs.Stats; try { parentStat = fs.statSync( parent ); - } catch ( error ) { + } catch { refuse( absolute, 'its parent folder does not exist' ); } if ( ! parentStat.isDirectory() ) { @@ -166,29 +254,32 @@ function resolveDestination( destination, slug, options = {} ) { /** * SHA-256 of a string or buffer, as hex. * - * @param {string|Buffer} value Value. - * @return {string} Hash. + * @param value Value. + * @return Hash. */ -function sha256( value ) { +function sha256( value: string | Buffer ): string { return crypto.createHash( 'sha256' ).update( value ).digest( 'hex' ); } /** * JSON with object keys sorted at every level, so equal values hash equally. * - * @param {*} value Value. - * @return {string} Canonical JSON. + * @param value Value. + * @return Canonical JSON. */ -function canonicalJson( value ) { +export function canonicalJson( value: unknown ): string { if ( Array.isArray( value ) ) { return `[${ value.map( canonicalJson ).join( ',' ) }]`; } if ( value && typeof value === 'object' ) { - return `{${ Object.keys( value ) + const record = value as Record< string, unknown >; + return `{${ Object.keys( record ) .sort() .map( ( key ) => - `${ JSON.stringify( key ) }:${ canonicalJson( value[ key ] ) }` + `${ JSON.stringify( key ) }:${ canonicalJson( + record[ key ] + ) }` ) .join( ',' ) }}`; } @@ -198,15 +289,16 @@ function canonicalJson( value ) { /** * Describe a path on disk without following links. * - * @param {string} fullPath Absolute path. - * @return {{type: string, hash: string|null}} 'missing', 'file', 'symlink', 'dir' or 'other'. + * @param fullPath Absolute path. + * @return Its type, and a hash for files and links. */ -function describePath( fullPath ) { - let stat; +export function describePath( fullPath: string ): PathState { + let stat: fs.Stats; try { stat = fs.lstatSync( fullPath ); } catch ( error ) { - if ( error.code === 'ENOENT' || error.code === 'ENOTDIR' ) { + const code = errorCode( error ); + if ( code === 'ENOENT' || code === 'ENOTDIR' ) { return { type: 'missing', hash: null }; } throw error; @@ -229,12 +321,12 @@ function describePath( fullPath ) { /** * List every file, link and folder in the staged plugin. * - * @param {string} root Staged plugin folder. - * @return {{path: string, type: string, hash: string|null}[]} Entries, sorted, with POSIX paths. + * @param root Staged plugin folder. + * @return Entries, sorted, with POSIX paths. */ -function listStaged( root ) { - const entries = []; - const walk = ( dir ) => { +function listStaged( root: string ): StagedEntry[] { + const entries: StagedEntry[] = []; + const walk = ( dir: string ) => { for ( const name of fs.readdirSync( dir ).sort() ) { const full = path.join( dir, name ); const rel = path @@ -255,11 +347,14 @@ function listStaged( root ) { /** * Decide what generate would do with one staged entry. * - * @param {string} destRoot Destination folder (real path). - * @param {Object} entry Staged entry. - * @return {{action: string, reason?: string, state: Object}} Action, any conflict reason, and the destination state it relied on. + * @param destRoot Destination folder (real path). + * @param entry Staged entry. + * @return Action, any conflict reason, and the destination state it relied on. */ -function classify( destRoot, entry ) { +function classify( + destRoot: string, + entry: StagedEntry +): { action: Action; reason?: string; state: PathState } { const parts = entry.path.split( '/' ); if ( parts.includes( '.git' ) ) { return { @@ -340,17 +435,24 @@ function classify( destRoot, entry ) { /** * Count destination files the plugin does not contain, and look for Git. * - * @param {string} destRoot Destination folder. - * @param {Set} planned Planned paths. - * @return {{count: number, capped: boolean, hasGit: boolean}} Summary. + * @param destRoot Destination folder. + * @param planned Planned paths. + * @return Summary. */ -function summarisePreserved( destRoot, planned ) { - const summary = { count: 0, capped: false, hasGit: false }; - const walk = ( dir ) => { - let names; +function summarisePreserved( + destRoot: string, + planned: Set< string > +): PreservedSummary { + const summary: PreservedSummary = { + count: 0, + capped: false, + hasGit: false, + }; + const walk = ( dir: string ) => { + let names: string[]; try { names = fs.readdirSync( dir ); - } catch ( error ) { + } catch { return; } for ( const name of names ) { @@ -384,12 +486,16 @@ function summarisePreserved( destRoot, planned ) { /** * The approval hash for a preview. * - * @param {Object} values Normalised configuration values. - * @param {string} destination Destination real path. - * @param {Object[]} files Planned files. - * @return {string} SHA-256 hex. + * @param values Normalised configuration values. + * @param destination Destination real path. + * @param files Planned files. + * @return SHA-256 hex. */ -function approvalHashFor( values, destination, files ) { +function approvalHashFor( + values: Record< string, unknown >, + destination: string, + files: PlannedFile[] +): string { return sha256( canonicalJson( { config: values, @@ -407,9 +513,9 @@ function approvalHashFor( values, destination, files ) { /** * Delete a preview and its staging folder. * - * @param {string} previewId Preview ID. + * @param previewId Preview ID. */ -function discardPreview( previewId ) { +export function discardPreview( previewId: string ): void { const preview = previews.get( previewId ); if ( ! preview ) { return; @@ -421,9 +527,9 @@ function discardPreview( previewId ) { /** * Delete expired previews. * - * @param {Date} now Current time. + * @param now Current time. */ -function sweepExpired( now ) { +function sweepExpired( now: Date ): void { for ( const [ id, preview ] of previews ) { if ( preview.expiresAt <= now.getTime() ) { discardPreview( id ); @@ -438,25 +544,21 @@ function sweepExpired( now ) { * runs Prettier there, and writes a log file in /logs/. Reads, but * never writes, the destination. * - * @param {Object} request - * @param {Object} request.config Plugin configuration. - * @param {string} [request.destination] Final folder; defaults to generated-plugins/. - * @param {string} [request.previousPreviewId] Earlier preview to compare the configuration with. - * @param {string} [request.detail] "summary" (default) or "full" file list. - * @param {Object} [options] - * @param {Function} [options.now] Clock returning a Date. - * @param {string} [options.scaffoldDir] Scaffold checkout. - * @param {string} [options.homeDir] Home folder. - * @param {string} [options.tmpDir] Parent of staging folders. - * @return {Object} The preview as reported to the client. + * @param request Configuration, destination, previous preview and detail. + * @param options Clock, scaffold, home and temporary folders. + * @return The preview as reported to the client. */ -function createPreview( request, options = {} ) { +export function createPreview( + request: PreviewRequest, + options: PreviewOptions = {} +): Record< string, unknown > { const now = options.now || ( () => new Date() ); const scaffoldDir = options.scaffoldDir || SCAFFOLD_DIR; const startedAt = now(); sweepExpired( startedAt ); - const { config, destination, previousPreviewId, detail } = request || {}; + const { config, destination, previousPreviewId, detail } = + request || ( {} as PreviewRequest ); const validation = validateConfiguration( config ); if ( ! validation.valid ) { throw new GenerationError( @@ -465,14 +567,14 @@ function createPreview( request, options = {} ) { { errors: validation.errors, warnings: validation.warnings } ); } - const slug = validation.values.slug; + const slug = String( validation.values.slug ); const dest = resolveDestination( destination, slug, { scaffoldDir, homeDir: options.homeDir, } ); const previewId = crypto.randomUUID(); - let stagingDir; + let stagingDir: string; try { stagingDir = fs.mkdtempSync( path.join( options.tmpDir || os.tmpdir(), 'bps-preview-' ) @@ -480,7 +582,9 @@ function createPreview( request, options = {} ) { } catch ( error ) { throw new GenerationError( CODES.STAGING_FAILED, - `Creating the staging folder failed: ${ error.message }`, + `Creating the staging folder failed: ${ + ( error as Error ).message + }`, {} ); } @@ -494,7 +598,7 @@ function createPreview( request, options = {} ) { ); try { - generatePlugin( config, { + generatePlugin( config as Record< string, unknown >, { outputDir: stagedPlugin, now, logFile, @@ -504,19 +608,19 @@ function createPreview( request, options = {} ) { fs.rmSync( stagingDir, { recursive: true, force: true } ); throw new GenerationError( CODES.STAGING_FAILED, - `Generating into staging failed: ${ error.message }`, + `Generating into staging failed: ${ ( error as Error ).message }`, { logFile } ); } - const files = listStaged( stagedPlugin ).map( ( entry ) => { + const files: PlannedFile[] = listStaged( stagedPlugin ).map( ( entry ) => { const { action, reason, state } = classify( dest.path, entry ); return { ...entry, action, ...( reason && { reason } ), state }; } ); const planned = new Set( files.map( ( file ) => file.path ) ); const preserved = summarisePreserved( dest.path, planned ); - let configurationChanges = null; + let configurationChanges: ValueChange[] | null = null; if ( previousPreviewId ) { const previous = previews.get( previousPreviewId ); configurationChanges = previous @@ -531,11 +635,9 @@ function createPreview( request, options = {} ) { } } - const approvalHash = approvalHashFor( validation.values, dest.path, files ); - const expiresAt = startedAt.getTime() + PREVIEW_TTL_MS; - previews.set( previewId, { + const stored: StoredPreview = { previewId, - approvalHash, + approvalHash: approvalHashFor( validation.values, dest.path, files ), destination: dest.path, destinationExisted: dest.exists, values: validation.values, @@ -543,12 +645,13 @@ function createPreview( request, options = {} ) { stagingDir, stagedPlugin, logFile, - expiresAt, + expiresAt: startedAt.getTime() + PREVIEW_TTL_MS, scaffoldDir, homeDir: options.homeDir, - } ); + }; + previews.set( previewId, stored ); - return publicPreview( previews.get( previewId ), { + return publicPreview( stored, { normalised: validation.normalised, warnings: validation.warnings, configurationChanges, @@ -563,12 +666,20 @@ function createPreview( request, options = {} ) { * folder, so the result stays small enough for a client to read in full. * "full" lists every path. * - * @param {Object[]} files Planned files. - * @param {string} detail "summary" or "full". - * @return {Object} files, and for summary, createByFolder and unchangedByFolder. + * @param files Planned files. + * @param detail "summary" or "full". + * @return files, and for summary, createByFolder and unchangedByFolder. */ -function listFiles( files, detail ) { - const toClient = ( { path: file, type, action, reason } ) => ( { +function listFiles( + files: PlannedFile[], + detail: Detail | undefined +): Record< string, unknown > { + const toClient = ( { + path: file, + type, + action, + reason, + }: PlannedFile ) => ( { path: file, type, action, @@ -577,8 +688,8 @@ function listFiles( files, detail ) { if ( detail === 'full' ) { return { files: files.map( toClient ) }; } - const byFolder = ( action ) => { - const counts = {}; + const byFolder = ( action: Action ) => { + const counts: Record< string, number > = {}; for ( const file of files ) { if ( file.action === action && file.type !== 'dir' ) { const top = file.path.includes( '/' ) @@ -605,12 +716,21 @@ function listFiles( files, detail ) { /** * The client's view of a stored preview. * - * @param {Object} preview Stored preview. - * @param {Object} extra Values only known when the preview was made. - * @return {Object} Preview for the client. + * @param preview Stored preview. + * @param extra Values only known when the preview was made. + * @return Preview for the client. */ -function publicPreview( preview, extra ) { - const count = ( action ) => +function publicPreview( + preview: StoredPreview, + extra: { + normalised: ValidationResult[ 'normalised' ]; + warnings: Issue[]; + configurationChanges: ValueChange[] | null; + preserved: PreservedSummary; + detail: Detail | undefined; + } +): Record< string, unknown > { + const count = ( action: Action ) => preview.files.filter( ( file ) => file.action === action ).length; return { previewId: preview.previewId, @@ -647,18 +767,18 @@ function publicPreview( preview, extra ) { /** * Return a preview if the approval matches it exactly. * - * @param {Object} request - * @param {string} request.previewId Preview ID. - * @param {string} request.approvalHash Hash from the preview. - * @param {boolean} request.approved Must be true. - * @param {Object} [options] - * @param {Function} [options.now] Clock returning a Date. - * @return {Object} Stored preview. + * @param request Preview ID, approval hash and approved flag. + * @param options Clock. + * @return Stored preview. */ -function getApprovedPreview( request, options = {} ) { +export function getApprovedPreview( + request: ApprovalRequest, + options: Clock = {} +): StoredPreview { const now = options.now || ( () => new Date() ); sweepExpired( now() ); - const { previewId, approvalHash, approved } = request || {}; + const { previewId, approvalHash, approved } = + request || ( {} as ApprovalRequest ); const preview = previews.get( previewId ); if ( ! preview ) { throw new GenerationError( @@ -692,9 +812,9 @@ function getApprovedPreview( request, options = {} ) { * Throws CONFLICT if the preview had conflicts, and STALE_PREVIEW if the * destination changed in any way the preview relied on. * - * @param {Object} preview Stored preview. + * @param preview Stored preview. */ -function assertPreviewCurrent( preview ) { +export function assertPreviewCurrent( preview: StoredPreview ): void { const conflicts = preview.files.filter( ( file ) => file.action === 'conflict' ); @@ -711,20 +831,24 @@ function assertPreviewCurrent( preview ) { ); } - let dest; + let dest: Destination; try { - dest = resolveDestination( preview.destination, preview.values.slug, { - scaffoldDir: preview.scaffoldDir, - homeDir: preview.homeDir, - } ); + dest = resolveDestination( + preview.destination, + String( preview.values.slug ), + { + scaffoldDir: preview.scaffoldDir, + homeDir: preview.homeDir, + } + ); } catch ( error ) { throw new GenerationError( CODES.STALE_PREVIEW, 'The destination changed after the preview. Preview again and ask again.', - { reason: error.message } + { reason: ( error as Error ).message } ); } - const changed = []; + const changed: string[] = []; if ( dest.path !== preview.destination || dest.exists !== preview.destinationExisted @@ -732,11 +856,11 @@ function assertPreviewCurrent( preview ) { changed.push( '.' ); } for ( const file of preview.files ) { - const now = classify( dest.path, file ); + const current = classify( dest.path, file ); if ( - now.action !== file.action || - now.state.type !== file.state.type || - now.state.hash !== file.state.hash + current.action !== file.action || + current.state.type !== file.state.type || + current.state.hash !== file.state.hash ) { changed.push( file.path ); } @@ -749,14 +873,3 @@ function assertPreviewCurrent( preview ) { ); } } - -module.exports = { - PREVIEW_TTL_MS, - resolveDestination, - createPreview, - getApprovedPreview, - assertPreviewCurrent, - discardPreview, - canonicalJson, - describePath, -}; diff --git a/scripts/mcp/server.js b/scripts/mcp/server.mts similarity index 79% rename from scripts/mcp/server.js rename to scripts/mcp/server.mts index a41b144..c333239 100755 --- a/scripts/mcp/server.js +++ b/scripts/mcp/server.mts @@ -7,30 +7,33 @@ * only; everything else goes to standard error or the log files. The * contract is in docs/MCP-PLUGIN-GENERATION.md. * - * Run: node scripts/mcp/server.js - * - * @package + * Run: node scripts/mcp/server.ts (Node 24.18+ runs it directly, stripping + * the types, so it uses only erasable TypeScript syntax). */ -const { McpServer } = require( '@modelcontextprotocol/sdk/server/mcp.js' ); -const { - StdioServerTransport, -} = require( '@modelcontextprotocol/sdk/server/stdio.js' ); -const { z } = require( 'zod' ); +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; +import { z } from 'zod'; + +import pkg from '../../package.json' with { type: 'json' }; +import { describeConfiguration, validateConfiguration } from './config.mts'; +import { CODES, GenerationError } from './errors.mts'; +import { generateFromPreview } from './merge.mts'; +import { createPreview } from './preview.mts'; -const { describeConfiguration, validateConfiguration } = require( './config' ); -const { CODES, GenerationError } = require( './errors' ); -const { generateFromPreview } = require( './merge' ); -const { createPreview } = require( './preview' ); -const { version } = require( '../../package.json' ); +export interface ToolResult { + [ key: string ]: unknown; + isError?: boolean; + content: { type: 'text'; text: string }[]; +} /** * A successful tool result. * - * @param {Object} value Result. - * @return {Object} MCP tool result. + * @param value Result. + * @return MCP tool result. */ -function ok( value ) { +function ok( value: unknown ): ToolResult { return { content: [ { type: 'text', text: JSON.stringify( value, null, 2 ) } ], }; @@ -39,19 +42,23 @@ function ok( value ) { /** * Run a tool body and turn errors into contract error results. * - * @param {Function} body Tool body. - * @return {Object} MCP tool result. + * @param body Tool body. + * @return MCP tool result. */ -function run( body ) { +export function run( body: () => unknown ): ToolResult { try { return ok( body() ); } catch ( error ) { const known = error instanceof GenerationError ? error - : new GenerationError( CODES.INTERNAL, error.message, {} ); + : new GenerationError( + CODES.INTERNAL, + ( error as Error ).message, + {} + ); if ( ! ( error instanceof GenerationError ) ) { - process.stderr.write( `${ error.stack }\n` ); + process.stderr.write( `${ ( error as Error ).stack }\n` ); } return { isError: true, @@ -74,12 +81,12 @@ const configSchema = z /** * Build the server with its four tools. * - * @return {McpServer} Server. + * @return Server. */ -function createServer() { +export function createServer(): McpServer { const server = new McpServer( { name: 'block-plugin-scaffold', - version, + version: pkg.version, } ); server.registerTool( @@ -186,22 +193,20 @@ function createServer() { /** * Start the server on stdio. */ -async function main() { +async function main(): Promise< void > { process.on( 'uncaughtException', ( error ) => { process.stderr.write( `Uncaught: ${ error.stack }\n` ); } ); const server = createServer(); await server.connect( new StdioServerTransport() ); process.stderr.write( - `block-plugin-scaffold MCP server ${ version } ready on stdio\n` + `block-plugin-scaffold MCP server ${ pkg.version } ready on stdio\n` ); } -if ( require.main === module ) { - main().catch( ( error ) => { +if ( import.meta.main ) { + main().catch( ( error: Error ) => { process.stderr.write( `Failed to start: ${ error.stack }\n` ); process.exit( 1 ); } ); } - -module.exports = { createServer }; diff --git a/scripts/mcp/vitest.config.mts b/scripts/mcp/vitest.config.mts new file mode 100644 index 0000000..3c31abb --- /dev/null +++ b/scripts/mcp/vitest.config.mts @@ -0,0 +1,31 @@ +/** + * Vitest configuration for the local MCP generation tooling (BPS-12). + * + * Run with `npm run test:mcp`. The tests generate real plugins into temporary + * folders, so they are slower than unit tests; coverage must stay at 80% or + * more for the MCP modules. + */ + +import { defineConfig } from 'vitest/config'; + +export default defineConfig( { + test: { + root: import.meta.dirname, + include: [ '__tests__/**/*.test.mts' ], + environment: 'node', + testTimeout: 180000, + hookTimeout: 180000, + coverage: { + provider: 'v8', + include: [ '*.mts' ], + exclude: [ 'vitest.config.mts' ], + reporter: [ 'text-summary', 'text' ], + thresholds: { + statements: 80, + branches: 80, + functions: 80, + lines: 80, + }, + }, + }, +} ); From a9f85c785c208064c84e4fc77112d49743e15faa Mon Sep 17 00:00:00 2001 From: krugazul Date: Fri, 6 Nov 2026 14:13:25 +0200 Subject: [PATCH 2/2] fix(mcp): address CodeRabbit review of the MCP contract - The default destination works on a fresh checkout: generate creates the Git-ignored generated-plugins/ folder (that folder only, and only for the default); preview reports createsParentFolder. - Preview compares each file's executable bit as well as its contents, so a script that lost its bit is an overwrite and gets it back. The bit is part of the approval manifest and the freshness checks. - Docs: a planned link that already points at the same target is unchanged; legacy cpt_slug and name_singular are rejected with content_model "none". Vitest: 60 tests pass (three new). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + docs/MCP-PLUGIN-GENERATION.md | 48 +++++------ scripts/mcp/__tests__/merge.test.mts | 43 ++++++++++ scripts/mcp/__tests__/preview.test.mts | 27 ++++++ scripts/mcp/merge.mts | 31 ++++++- scripts/mcp/preview.mts | 110 +++++++++++++++++++------ 6 files changed, 208 insertions(+), 52 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4539731..4988191 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -113,6 +113,7 @@ All components use mustache placeholders and follow WordPress accessibility and ### Fixed +- Local MCP generation (BPS-12, CodeRabbit review on #66): on a fresh checkout, the default destination works: `generate` creates the Git-ignored `generated-plugins/` folder (that folder only, and only for the default; `preview` reports `createsParentFolder: true`). `preview` compares each file's executable bit as well as its contents, so a script that lost its bit is `overwrite` and gets it back. The contract now says a planned link already pointing at the same target is `unchanged`, and that legacy `cpt_slug` and `name_singular` are rejected with `content_model: "none"`. - The tag scanner (`scripts/utils/scan.js`) reads mustache dotted filter tags such as `{{upper.namespace}}` as the variable they filter, and skips GitHub Actions `${{ ... }}` expressions. Counts use the same grammar, so `{{ upper.slug }}` counts too, and `.mustacheignore` skips `.specify/workflows/` and `.gemini/commands/`, which the generator copies without rendering. `scripts/mustache-variables-registry.json` is regenerated: it lists the tags templates use now, without the old `{{name|filter}}` forms or the theme tags no file uses. - Collection blocks in generated plugins render: `block.json` named a PHP function as `render`, which WordPress reads as a file path, so the blocks output nothing. It now points at `file:./render.php`, which echoes the documented render function, as the slider block does (BPS-10). - Generated block patterns name the plugin in their header comment instead of "ExamplePlugin", and their array arrows are aligned, so PHPCS passes on plugins with post types (BPS-10). diff --git a/docs/MCP-PLUGIN-GENERATION.md b/docs/MCP-PLUGIN-GENERATION.md index b0a157a..99dcfaf 100644 --- a/docs/MCP-PLUGIN-GENERATION.md +++ b/docs/MCP-PLUGIN-GENERATION.md @@ -73,7 +73,7 @@ To try the server in Claude Code without changing its configuration, put the sam `destination` is the **final folder** the plugin's files go into. The adapter does not add the slug to it. (The CLI's `--output-dir` differs: it treats the folder as a parent and adds `/`.) -When `destination` is omitted, the default is `/generated-plugins/`, resolved from the scaffold's own location, never from the process's working folder. +When `destination` is omitted, the default is `/generated-plugins/`, resolved from the scaffold's own location, never from the process's working folder. Git ignores `generated-plugins/`, so a fresh checkout does not have it: for the default destination only, `preview` reports `createsParentFolder: true` and `generate` creates that one folder too. The adapter resolves the destination to an absolute real path and refuses it (`UNSAFE_DESTINATION`) when it: @@ -83,11 +83,11 @@ The adapter resolves the destination to an absolute real path and refuses it (`U - is, or is inside, this scaffold checkout, other than a folder inside `generated-plugins/`; - is itself a symbolic link; - exists and is not a folder; -- does not exist and its parent folder does not exist either. +- does not exist and its parent folder does not exist either (except `generated-plugins/` for the default destination, above). Symbolic links above the destination are resolved, so `/tmp/plugin` is checked as `/private/tmp/plugin`. -The destination may already exist and may be a Git repository. If it does not exist, `generate` creates it (and only it; its parent must exist). +The destination may already exist and may be a Git repository. If it does not exist, `generate` creates it (and only it; its parent must exist, except for the default destination). ## Operations @@ -117,10 +117,10 @@ Generates the plugin into a private staging folder and reports exactly what `gen - **Input:** `config`; optional `destination`; optional `previousPreviewId` (to show what changed since an earlier preview); optional `detail`, `summary` (the default) or `full`. - **Output:** - `previewId` and `approvalHash`; - - `destination` (the resolved absolute path) and whether it exists; + - `destination` (the resolved absolute path), whether it exists, and `createsParentFolder: true` when `generate` will also create `generated-plugins/`; - `configuration`: the normalised configuration, and the differences from `previousPreviewId` when given; - - `summary`: how many paths are `create`, `overwrite` (contents differ), `unchanged` (identical) and `conflict`; - - `files`: with `detail: "summary"`, every `overwrite` and `conflict` path, plus `createByFolder` and `unchangedByFolder` counts by top-level folder, which keeps the result small enough for a client to read in full; with `detail: "full"`, every path the plugin contains; + - `summary`: how many paths are `create`, `overwrite` (contents differ, or a file's executable bit differs), `unchanged` (identical contents and executable bit) and `conflict`; + - `files`: with `detail: "summary"`, every `overwrite` and `conflict` path, plus `createByFolder` and `unchangedByFolder` counts by top-level folder, which keeps the result small enough for a client to read in full; with `detail: "full"`, every path the plugin contains. Executable files are marked `executable: true`; - `preserved`: a count of destination files the plugin does not contain, which `generate` leaves untouched, and whether a `.git` folder or file is present; - `processEffects`: the staging folder path and the processes run (Node, Prettier); - `expiresAt`. @@ -132,7 +132,7 @@ Generates the plugin into a private staging folder and reports exactly what `gen Copies the staged files into the destination. - **Input:** `previewId`, `approvalHash`, `approved: true`. -- **Before writing,** the adapter re-checks the destination. If anything the preview relied on has changed (the destination's real path, the type or contents of any planned path, or a new file at a planned path), it returns `STALE_PREVIEW` and writes nothing. Preview again and ask again. +- **Before writing,** the adapter re-checks the destination. If anything the preview relied on has changed (the destination's real path, the type, contents or executable bit of any planned path, or a new file at a planned path), it returns `STALE_PREVIEW` and writes nothing. Preview again and ask again. - **Side effects:** writes only the paths listed in the preview's `files` (`create` and `overwrite`). Creates the destination folder if needed. Deletes the staging folder on success. - **Output:** the files written, the files left unchanged, and the location of the log. @@ -142,7 +142,7 @@ Copies the staged files into the destination. - the normalised configuration; - the destination's resolved real path; -- the file manifest: each planned path, its action, and the SHA-256 of its staged contents. +- the file manifest: each planned path, its action, the SHA-256 of its staged contents and, for files, whether it is executable. `generate` recomputes the hash from the stored preview and refuses a mismatch (`APPROVAL_MISMATCH`). A different configuration or destination needs a new preview and a new approval. @@ -151,10 +151,10 @@ Copies the staged files into the destination. These rules implement "overwrite matching files; preserve everything else": 1. **Never delete.** `generate` never removes a file or folder from the destination, and never removes the destination. -2. **Overwrite matching paths.** A planned file whose path already exists as a regular file is overwritten without stopping, because the person approved it in the preview. +2. **Overwrite matching paths.** A planned file whose path already exists as a regular file is overwritten without stopping, because the person approved it in the preview. It is written with the staged file's permissions, so a script that lost its executable bit gets it back. 3. **Leave everything else alone.** Files in the destination that the plugin does not contain are not read for formatting, rewritten or moved. 4. **Protect Git.** Any path with a `.git` segment, file or folder, is never written. If the plugin would write one, the preview marks it `conflict`. -5. **Do not write through links.** If any part of a planned path in the destination is a symbolic link, the path is a `conflict`. Writes never follow a link. +5. **Do not write through links.** If a folder on the way to a planned path is a symbolic link in the destination, the path is a `conflict`. Writes never follow a link. A planned link (such as `.claude/skills/`) that already exists in the destination as a link to the same target is `unchanged`, so regenerating a plugin does not stop on its own links; the target is compared as text, without following it. A link with a different target is a `conflict`. 6. **Type clashes block.** A planned file where the destination has a folder, or a planned folder or link where it has a file, is a `conflict`: resolving it would need a delete. 7. **Write each file safely.** Each file is written to a temporary name beside its target and renamed into place, so no file is left half-written. @@ -188,20 +188,20 @@ A preview with any `conflict` cannot be generated. The person resolves the confl The schema (`.github/schemas/plugin-config.schema.json`), the generator's defaults and the standalone validator (`scripts/validation/validate-plugin-config.js`) disagree in places. Checked at `2e2acfa`, `discover` and `validate_config` resolve them as follows: -| Field or rule | Schema | Generator | Standalone validator | Contract | -| ---------------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | ------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | -| `blocks` default | `["collection", "slider"]`, but the allowed values are only `collection`, so the default fails its own schema | `[]` | Warns when empty | Default `[]`; allowed value `collection` | -| `fields` entries | Field groups: `{ post_type, field_group: [ fields ] }` | Field groups | Checks each entry as if it were a single field, so it rejects every valid field group | Schema rules; the validator's field check is not used | -| Taxonomy slug length | Up to 32 characters (the WordPress limit) | — | Up to 20 | Up to 32 | -| `author` | Required, but also has a placeholder default | Required | — | Required; no default offered | -| `author_uri` | Default `https://example.com` | Optional, empty when unset | — | Optional; no default | -| `description` | Optional | Default `A WordPress multi-block plugin.` | — | Optional; generator default reported | -| `repository_url` | Optional | Default `https://github.com/lightspeedwp/` | — | Optional; default reported, and flagged as a warning, because client plugins usually live elsewhere | -| `textdomain`, `namespace` | Optional | Derived from `slug` | — | Derived; reported as `derived` | -| `requires_wp`, `requires_php` | Defaults `6.5`, `8.0` | Same | — | Same | -| Legacy `cpt_slug`, `name_singular` | Allowed (extra properties are allowed) | Converted to a post type | Rejected with `content_model: "none"` | Accepted with a warning; not advertised by `discover` | -| "No templates defined" | No `templates` field | — | Warns | Not reported | -| Schema dialect | Draft 2020-12 | Ajv 2020 | Ajv default with formats | Draft 2020-12, as the generator | +| Field or rule | Schema | Generator | Standalone validator | Contract | +| ---------------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | +| `blocks` default | `["collection", "slider"]`, but the allowed values are only `collection`, so the default fails its own schema | `[]` | Warns when empty | Default `[]`; allowed value `collection` | +| `fields` entries | Field groups: `{ post_type, field_group: [ fields ] }` | Field groups | Checks each entry as if it were a single field, so it rejects every valid field group | Schema rules; the validator's field check is not used | +| Taxonomy slug length | Up to 32 characters (the WordPress limit) | — | Up to 20 | Up to 32 | +| `author` | Required, but also has a placeholder default | Required | — | Required; no default offered | +| `author_uri` | Default `https://example.com` | Optional, empty when unset | — | Optional; no default | +| `description` | Optional | Default `A WordPress multi-block plugin.` | — | Optional; generator default reported | +| `repository_url` | Optional | Default `https://github.com/lightspeedwp/` | — | Optional; default reported, and flagged as a warning, because client plugins usually live elsewhere | +| `textdomain`, `namespace` | Optional | Derived from `slug` | — | Derived; reported as `derived` | +| `requires_wp`, `requires_php` | Defaults `6.5`, `8.0` | Same | — | Same | +| Legacy `cpt_slug`, `name_singular` | Allowed (extra properties are allowed) | Converted to a post type | Rejected with `content_model: "none"` | Rejected with `content_model: "none"`; otherwise accepted with a warning; not advertised by `discover` | +| "No templates defined" | No `templates` field | — | Warns | Not reported | +| Schema dialect | Draft 2020-12 | Ajv 2020 | Ajv default with formats | Draft 2020-12, as the generator | Fixing the schema and the standalone validator is outside this contract; the issue proposes no schema change. diff --git a/scripts/mcp/__tests__/merge.test.mts b/scripts/mcp/__tests__/merge.test.mts index 258aac2..d0052b3 100644 --- a/scripts/mcp/__tests__/merge.test.mts +++ b/scripts/mcp/__tests__/merge.test.mts @@ -332,6 +332,49 @@ describe( 'links and failures', () => { expect( fs.readdirSync( outside ) ).toEqual( [] ); } ); + it( 'restores an executable bit when the contents are unchanged', () => { + const dest = path.join( work, 'modes' ); + const first = preview( dest ); + generateFromPreview( approve( first ), { now } ); + const script = first.files.find( + ( f: Preview ) => f.type === 'file' && f.executable + ); + expect( script ).toBeDefined(); + const target = path.join( dest, script.path ); + fs.chmodSync( target, 0o644 ); + + const again = preview( dest ); + const planned = again.files.find( + ( f: Preview ) => f.path === script.path + ); + expect( planned.action ).toBe( 'overwrite' ); + expect( again.summary.overwrite ).toBe( 1 ); + generateFromPreview( approve( again ), { now } ); + expect( fs.statSync( target ).mode & 0o111 ).not.toBe( 0 ); + expect( diffTrees( reference, dest ) ).toEqual( [] ); + } ); + + it( 'creates generated-plugins/ for the default destination on a fresh checkout', () => { + const fresh = path.join( work, 'fresh-checkout' ); + fs.mkdirSync( fresh ); + const p = createPreview( + { config: cfg, detail: 'full' }, + { now, scaffoldDir: fresh } + ); + const dest = path.join( fresh, 'generated-plugins', 'tsp-merge' ); + expect( p.destination ).toEqual( { + path: dest, + exists: false, + createsParentFolder: true, + } ); + expect( fs.existsSync( path.dirname( dest ) ) ).toBe( false ); + const result = generateFromPreview( approve( p ), { now } ); + expect( diffTrees( reference, dest ) ).toEqual( [] ); + expect( fs.readFileSync( result.journal, 'utf8' ) ).toContain( + '"path":".."' + ); + } ); + it( 'is stale when the destination appears after the preview', () => { const dest = path.join( work, 'appears' ); const p = preview( dest ); diff --git a/scripts/mcp/__tests__/preview.test.mts b/scripts/mcp/__tests__/preview.test.mts index e6f8b90..37cf638 100644 --- a/scripts/mcp/__tests__/preview.test.mts +++ b/scripts/mcp/__tests__/preview.test.mts @@ -385,4 +385,31 @@ describe( 'destination rules', () => { expected ); } ); + it( 'creates generated-plugins/ for the default on a fresh checkout only', () => { + const fresh = path.join( work, 'fresh-checkout' ); + fs.mkdirSync( fresh ); + const resolved = resolveDestination( undefined, 'tsp', { + scaffoldDir: fresh, + } ); + expect( resolved ).toEqual( { + path: path.join( fresh, 'generated-plugins', 'tsp' ), + exists: false, + createParent: true, + } ); + expect( fs.existsSync( path.join( fresh, 'generated-plugins' ) ) ).toBe( + false + ); + expect( + thrown( () => + resolveDestination( + path.join( fresh, 'generated-plugins', 'tsp' ), + 'tsp', + { scaffoldDir: fresh } + ) + ).code + ).toBe( 'UNSAFE_DESTINATION' ); + expect( resolveDestination( undefined, 'tsp' ).createParent ).toBe( + false + ); + } ); } ); diff --git a/scripts/mcp/merge.mts b/scripts/mcp/merge.mts index b230a9c..fead150 100644 --- a/scripts/mcp/merge.mts +++ b/scripts/mcp/merge.mts @@ -17,9 +17,11 @@ import { describePath, discardPreview, getApprovedPreview, + sameState, type Action, type ApprovalRequest, type Clock, + type PathState, type PlannedFile, type StoredPreview, } from './preview.mts'; @@ -71,13 +73,33 @@ function assertUnchangedSincePreview( } } const current = describePath( path.join( destRoot, ...parts ) ); - const expected = + const expected: PathState = file.action === 'create' ? { type: 'missing', hash: null } : file.state; - if ( current.type !== expected.type || current.hash !== expected.hash ) { + if ( ! sameState( current, expected ) ) { throw new Error( `${ file.path } changed after the preview` ); } } +/** + * Create the scaffold's generated-plugins/ folder for the default destination. + * Only that one folder is created; if something appeared there since the + * preview, it must be a real folder. + * + * @param folder generated-plugins/ path. + */ +function createGeneratedPluginsFolder( folder: string ): void { + try { + fs.mkdirSync( folder ); + } catch ( error ) { + if ( ( error as NodeJS.ErrnoException ).code !== 'EEXIST' ) { + throw error; + } + } + if ( ! fs.lstatSync( folder ).isDirectory() ) { + throw new Error( `${ folder } is not a folder` ); + } +} + /** * Write one staged file into place: a temporary file beside the target, * then a rename, so the target is never half-written. @@ -140,6 +162,11 @@ export function applyPreview( let current: string | null = null; try { + if ( preview.createParent ) { + current = '..'; + createGeneratedPluginsFolder( path.dirname( destRoot ) ); + record( journal, { op: 'mkdir', path: '..' } ); + } if ( ! preview.destinationExisted ) { current = '.'; // Not recursive: only the destination itself is created. diff --git a/scripts/mcp/preview.mts b/scripts/mcp/preview.mts index 28aac9a..f019b41 100644 --- a/scripts/mcp/preview.mts +++ b/scripts/mcp/preview.mts @@ -49,6 +49,8 @@ export type Detail = 'summary' | 'full'; export interface PathState { type: PathType; hash: string | null; + /** Files only: whether any execute bit is set. */ + executable?: boolean; } export interface StagedEntry extends PathState { @@ -65,6 +67,8 @@ export interface PlannedFile extends StagedEntry { export interface Destination { path: string; exists: boolean; + /** The default destination's generated-plugins/ folder must be created too. */ + createParent: boolean; } export interface Clock { @@ -96,6 +100,7 @@ export interface StoredPreview { approvalHash: string; destination: string; destinationExisted: boolean; + createParent: boolean; values: Record< string, unknown >; files: PlannedFile[]; stagingDir: string; @@ -166,10 +171,10 @@ export function resolveDestination( const scaffoldDir = options.scaffoldDir || SCAFFOLD_DIR; const homeDir = options.homeDir || os.homedir(); - let raw = - destination === undefined || destination === null - ? path.join( scaffoldDir, 'generated-plugins', slug ) - : destination; + const isDefault = destination === undefined || destination === null; + let raw = isDefault + ? path.join( scaffoldDir, 'generated-plugins', slug ) + : destination; if ( typeof raw !== 'string' || ! raw.trim() ) { refuse( String( raw ), 'it must be a non-empty path' ); } @@ -196,6 +201,7 @@ export function resolveDestination( } let real: string; + let createParent = false; if ( stat ) { if ( stat.isSymbolicLink() ) { refuse( absolute, 'it is a symbolic link' ); @@ -206,19 +212,39 @@ export function resolveDestination( real = fs.realpathSync( absolute ); } else { const parent = path.dirname( absolute ); - let parentStat: fs.Stats; + let parentStat: fs.Stats | null = null; try { - parentStat = fs.statSync( parent ); - } catch { - refuse( absolute, 'its parent folder does not exist' ); + parentStat = fs.lstatSync( parent ); + } catch ( error ) { + const code = errorCode( error ); + if ( code !== 'ENOENT' && code !== 'ENOTDIR' ) { + throw error; + } } - if ( ! parentStat.isDirectory() ) { - refuse( absolute, 'its parent is not a folder' ); + if ( ! parentStat && isDefault ) { + // A fresh checkout has no generated-plugins/ (Git ignores it), so + // generate creates it for the default destination only. + createParent = true; + real = path.join( + fs.realpathSync( scaffoldDir ), + 'generated-plugins', + path.basename( absolute ) + ); + } else { + if ( ! parentStat ) { + refuse( absolute, 'its parent folder does not exist' ); + } + if ( parentStat.isSymbolicLink() ) { + parentStat = fs.statSync( parent ); + } + if ( ! parentStat.isDirectory() ) { + refuse( absolute, 'its parent is not a folder' ); + } + real = path.join( + fs.realpathSync( parent ), + path.basename( absolute ) + ); } - real = path.join( - fs.realpathSync( parent ), - path.basename( absolute ) - ); } const realHome = fs.realpathSync( homeDir ); @@ -248,7 +274,7 @@ export function resolveDestination( ); } - return { path: real, exists: Boolean( stat ) }; + return { path: real, exists: Boolean( stat ), createParent }; } /** @@ -313,11 +339,31 @@ export function describePath( fullPath: string ): PathState { return { type: 'dir', hash: null }; } if ( stat.isFile() ) { - return { type: 'file', hash: sha256( fs.readFileSync( fullPath ) ) }; + return { + type: 'file', + hash: sha256( fs.readFileSync( fullPath ) ), + executable: ( stat.mode & 0o111 ) !== 0, + }; } return { type: 'other', hash: null }; } +/** + * Whether two path states are the same: type, contents and, for files, + * whether they are executable. + * + * @param a First state. + * @param b Second state. + * @return True when equal. + */ +export function sameState( a: PathState, b: PathState ): boolean { + return ( + a.type === b.type && + a.hash === b.hash && + Boolean( a.executable ) === Boolean( b.executable ) + ); +} + /** * List every file, link and folder in the staged plugin. * @@ -395,7 +441,8 @@ function classify( if ( entry.type === 'file' ) { if ( state.type === 'file' ) { return { - action: state.hash === entry.hash ? 'unchanged' : 'overwrite', + // An executable bit that differs is restored, like contents. + action: sameState( state, entry ) ? 'unchanged' : 'overwrite', state, }; } @@ -500,12 +547,17 @@ function approvalHashFor( canonicalJson( { config: values, destination, - manifest: files.map( ( { path: file, type, action, hash } ) => ( { - path: file, - type, - action, - hash, - } ) ), + manifest: files.map( + ( { path: file, type, action, hash, executable } ) => ( { + path: file, + type, + action, + hash, + ...( type === 'file' && { + executable: Boolean( executable ), + } ), + } ) + ), } ) ); } @@ -640,6 +692,7 @@ export function createPreview( approvalHash: approvalHashFor( validation.values, dest.path, files ), destination: dest.path, destinationExisted: dest.exists, + createParent: dest.createParent, values: validation.values, files, stagingDir, @@ -679,10 +732,12 @@ function listFiles( type, action, reason, + executable, }: PlannedFile ) => ( { path: file, type, action, + ...( executable && { executable } ), ...( reason && { reason } ), } ); if ( detail === 'full' ) { @@ -738,6 +793,8 @@ function publicPreview( destination: { path: preview.destination, exists: preview.destinationExisted, + // Shown only when generate also creates generated-plugins/. + ...( preview.createParent && { createsParentFolder: true } ), }, configuration: { normalised: extra.normalised, @@ -834,7 +891,9 @@ export function assertPreviewCurrent( preview: StoredPreview ): void { let dest: Destination; try { dest = resolveDestination( - preview.destination, + // Resolve the default again as the default, so it may still + // create generated-plugins/. + preview.createParent ? undefined : preview.destination, String( preview.values.slug ), { scaffoldDir: preview.scaffoldDir, @@ -859,8 +918,7 @@ export function assertPreviewCurrent( preview: StoredPreview ): void { const current = classify( dest.path, file ); if ( current.action !== file.action || - current.state.type !== file.state.type || - current.state.hash !== file.state.hash + ! sameState( current.state, file.state ) ) { changed.push( file.path ); }