From 3312dd33895c1e30e2491a56da7795868264032b Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Tue, 27 Oct 2026 14:08:58 +0000 Subject: [PATCH] fix(dev-tooling): apply upstream tooling fixes on Cursor Path-scoped JS lint was still calling package scripts Shopware does not define, so a scoped run could miss the local binary or fall through to a global one. Those calls now run npm exec --no against node_modules/.bin and refuse when that binary is absent. Config reads that parsed as non-objects, named an unknown environment, or kept a relative MCP_*_CONFIG path were continuing with a default; they now fail closed. Native worktrees with an absolute gitdir pointer were refused even though that pointer is valid on the host, while docker, docker-compose, vagrant, and ddev still refuse it. shopware-env 2.1.1 takes the same shared config, environment, and hook copies. plugin-setup 2.0.1 stops listing gh-tooling, which this plugin no longer sets up. Cursor packaging stays in place. Versions are dev-tooling 5.0.1, shopware-env 2.1.1, and plugin-setup 2.0.1. Co-authored-by: ROBJkE --- plugin-tests/README.md | 5 +- .../fixtures/shopware-trunk/README.md | 20 + .../administration-package-scripts.json | 49 ++ .../fixtures/shopware-trunk/regenerate.sh | 30 + .../storefront-package-scripts.json | 23 + plugin-tests/dev-tooling/js_admin_tools.bats | 130 +++- .../dev-tooling/js_storefront_tools.bats | 104 ++- .../dev-tooling/mcp_tool_console.bats | 69 ++ .../dev-tooling/mcp_tool_js_admin.bats | 643 +++++++++++++----- .../dev-tooling/mcp_tool_js_storefront.bats | 626 ++++++++++++----- .../dev-tooling/mcp_tool_phpunit.bats | 9 + .../mcp_tool_phpunit_coverage.bats | 12 + plugin-tests/dev-tooling/mcp_tool_rector.bats | 42 +- plugin-tests/dev-tooling/php_tools.bats | 54 +- .../dev-tooling/phpstan_baseline.bats | 41 ++ plugin-tests/dev-tooling/scope_js_tools.bats | 149 +++- plugin-tests/dev-tooling/scope_php_tools.bats | 95 +++ .../dev-tooling/scope_resolution.bats | 49 ++ plugin-tests/dev-tooling/session_start.bats | 64 ++ .../dev-tooling/test_helper/common_setup.bash | 227 +++++++ plugin-tests/dev-tooling/tool_schema.bats | 15 + .../dev-tooling/worktree_conformance.bats | 2 + plugin-tests/dev-tooling/worktree_hook.bats | 12 + .../dev-tooling/worktree_js_tools.bats | 78 ++- .../dev-tooling/worktree_php_tools.bats | 1 + .../dev-tooling/worktree_resolution.bats | 102 ++- plugin-tests/dev-tooling/worktree_state.bats | 1 + plugin-tests/mcp-shared/config.bats | 107 ++- plugin-tests/mcp-shared/docker_compose.bats | 77 ++- plugin-tests/mcp-shared/environment.bats | 194 +++++- plugin-tests/mcp-shared/scope_wrap.bats | 61 +- .../shopware-env/config_fallback.bats | 88 +++ .../shopware-env/hook_enforcement.bats | 22 +- .../shopware-env/lifecycle_startup.bats | 79 +++ .../test_helper/common_setup.bash | 20 + .../dev-tooling/.cursor-plugin/plugin.json | 2 +- plugins/dev-tooling/AGENTS.md | 39 +- plugins/dev-tooling/CHANGELOG.md | 17 + plugins/dev-tooling/README.md | 11 +- plugins/dev-tooling/SETUP.md | 6 +- plugins/dev-tooling/docs/configuration.md | 16 +- plugins/dev-tooling/docs/mcp-enforcement.md | 96 +-- plugins/dev-tooling/docs/reference.md | 161 +++-- .../hooks/prompts/mcp-tool-directives.md | 14 +- .../hooks/scripts/check-js-admin-tools.sh | 97 +-- .../scripts/check-js-storefront-tools.sh | 122 ++-- .../hooks/scripts/check-php-tools.sh | 48 +- .../hooks/scripts/check-phpstan-baseline.sh | 3 + .../dev-tooling/hooks/scripts/lib/common.sh | 27 +- .../hooks/scripts/lib/js_binary.sh | 24 + .../hooks/scripts/session-start.sh | 7 +- .../hooks/scripts/worktree-directives.sh | 2 +- .../mcp-server-js-admin/lib/build.sh | 9 +- .../mcp-server-js-admin/lib/eslint.sh | 56 +- .../mcp-server-js-admin/lib/jest.sh | 109 ++- .../mcp-server-js-admin/lib/lint-all.sh | 27 +- .../mcp-server-js-admin/lib/prettier.sh | 100 +-- .../mcp-server-js-admin/lib/stylelint.sh | 120 ++-- .../mcp-server-js-admin/lib/tsc.sh | 24 +- .../dev-tooling/mcp-server-js-admin/server.sh | 49 +- .../mcp-server-js-admin/tools.json | 16 +- .../mcp-server-js-storefront/lib/build.sh | 28 +- .../mcp-server-js-storefront/lib/eslint.sh | 157 +++-- .../mcp-server-js-storefront/lib/jest.sh | 126 ++-- .../mcp-server-js-storefront/lib/stylelint.sh | 122 ++-- .../mcp-server-js-storefront/lib/vitest.sh | 15 +- .../mcp-server-js-storefront/server.sh | 49 +- .../mcp-server-js-storefront/tools.json | 20 +- .../dev-tooling/mcp-server-php/lib/console.sh | 57 +- plugins/dev-tooling/mcp-server-php/lib/ecs.sh | 36 +- .../dev-tooling/mcp-server-php/lib/phpstan.sh | 38 +- .../dev-tooling/mcp-server-php/lib/phpunit.sh | 10 +- .../mcp-server-php/lib/phpunit_coverage.sh | 15 +- .../dev-tooling/mcp-server-php/lib/rector.sh | 84 ++- plugins/dev-tooling/mcp-server-php/server.sh | 46 +- plugins/dev-tooling/mcp-server-php/tools.json | 18 +- plugins/dev-tooling/shared/config.sh | 80 ++- plugins/dev-tooling/shared/docker-compose.sh | 31 +- plugins/dev-tooling/shared/environment.sh | 140 ++-- plugins/dev-tooling/shared/js_paths.sh | 325 +++++++++ plugins/dev-tooling/shared/launch.sh | 95 +++ .../shared/mcp-js-tooling.schema.json | 2 +- plugins/dev-tooling/shared/scope.sh | 227 ++++++- plugins/dev-tooling/shared/worktree.sh | 524 +++++++++++--- .../plugin-setup/.cursor-plugin/plugin.json | 5 +- plugins/plugin-setup/AGENTS.md | 6 +- plugins/plugin-setup/CHANGELOG.md | 5 + .../SKILL.md | 2 +- .../skills/dev-tooling-setting-up/SKILL.md | 2 +- .../references/plugin-setup.md | 6 +- .../shopware-env/.cursor-plugin/plugin.json | 2 +- plugins/shopware-env/AGENTS.md | 20 +- plugins/shopware-env/CHANGELOG.md | 10 + plugins/shopware-env/README.md | 6 +- .../hooks/scripts/check-lifecycle-tools.sh | 29 +- .../shopware-env/hooks/scripts/lib/common.sh | 27 +- .../mcp-server-lifecycle/lib/resolve_env.sh | 51 +- .../mcp-server-lifecycle/server.sh | 14 +- .../mcp-server-lifecycle/tools.json | 16 +- plugins/shopware-env/shared/config.sh | 80 ++- plugins/shopware-env/shared/docker-compose.sh | 31 +- plugins/shopware-env/shared/environment.sh | 140 ++-- .../dev-environment-bootstrapping/SKILL.md | 2 +- templates/README.md | 2 + templates/hooks-shared/common.sh | 27 +- templates/mcp-shared/config.sh | 80 ++- templates/mcp-shared/docker-compose.sh | 31 +- templates/mcp-shared/environment.sh | 140 ++-- 108 files changed, 5539 insertions(+), 1942 deletions(-) create mode 100644 plugin-tests/dev-tooling/fixtures/shopware-trunk/README.md create mode 100644 plugin-tests/dev-tooling/fixtures/shopware-trunk/administration-package-scripts.json create mode 100755 plugin-tests/dev-tooling/fixtures/shopware-trunk/regenerate.sh create mode 100644 plugin-tests/dev-tooling/fixtures/shopware-trunk/storefront-package-scripts.json create mode 100644 plugin-tests/shopware-env/lifecycle_startup.bats create mode 100644 plugins/dev-tooling/hooks/scripts/lib/js_binary.sh create mode 100644 plugins/dev-tooling/shared/js_paths.sh create mode 100644 plugins/dev-tooling/shared/launch.sh diff --git a/plugin-tests/README.md b/plugin-tests/README.md index 750ef1f0..fc05304d 100644 --- a/plugin-tests/README.md +++ b/plugin-tests/README.md @@ -52,7 +52,7 @@ plugin-tests/ ├── test_helper/ │ └── common_setup.bash # Shared core fixtures ├── mcp-shared/ # Suites for templates/mcp-shared/ modules -│ ├── config.bats # Config filename and env-var prefix parameterization +│ ├── config.bats # Config filename and env-var derivation from CONFIG_PREFIX │ ├── docker_compose.bats # Docker Compose call-time container/workdir resolution │ ├── environment.bats # Environment wrapping │ └── scope_wrap.bats # Scope-aware command wrapping per environment @@ -93,6 +93,7 @@ plugin-tests/ ├── shopware-env/ │ ├── config_fallback.bats │ ├── hook_enforcement.bats +│ ├── lifecycle_startup.bats │ ├── lifecycle_tools.bats │ ├── session_start.bats │ └── test_helper/ @@ -177,7 +178,7 @@ The MCP protocol handler (`plugins/*/shared/mcpserver_core.sh`) has no suite her ## 🔄 CI -Tests run via GitHub Actions (`.github/workflows/ci.yml`) on changes to `plugins/**`, `plugin-tests/**`, `pyproject.toml`, `uv.lock`, `.shellcheckrc`, `.github/workflows/ci.yml`, or `.github/scripts/**`. +Tests run via GitHub Actions (`.github/workflows/ci.yml`) on changes to `plugins/**`, `plugin-tests/**`, `pyproject.toml`, `uv.lock`, `.mcp-sdk.lock`, `.shellcheckrc`, `.github/workflows/ci.yml`, or `.github/scripts/**`. ## 📌 Dependencies diff --git a/plugin-tests/dev-tooling/fixtures/shopware-trunk/README.md b/plugin-tests/dev-tooling/fixtures/shopware-trunk/README.md new file mode 100644 index 00000000..be4e5ad5 --- /dev/null +++ b/plugin-tests/dev-tooling/fixtures/shopware-trunk/README.md @@ -0,0 +1,20 @@ +# Shopware Trunk Fixtures + +## 🔖 Source + +The `scripts` blocks of two `package.json` files from [shopware/shopware](https://github.com/shopware/shopware), commit `c59a7d3484c`: + +| Fixture | Mirrors | +|---------------------------------------|----------------------------------------------------------------| +| `administration-package-scripts.json` | `src/Administration/Resources/app/administration/package.json` | +| `storefront-package-scripts.json` | `src/Storefront/Resources/app/storefront/package.json` | + +Only the `scripts` block is kept, in the key order of the source. The JS tool suites answer `npm pkg get "scripts."` probes from these files through `shopware_trunk_script_body` in `test_helper/common_setup.bash`, so a route naming a script trunk does not define fails as it would on a real checkout. + +## ♻️ Regeneration + +```bash +./regenerate.sh /path/to/shopware [output-dir] +``` + +The script reads the checkout and writes both files into `output-dir`, by default this directory. Check out the commit named above first to reproduce the committed files; a newer trunk can change the scripts. diff --git a/plugin-tests/dev-tooling/fixtures/shopware-trunk/administration-package-scripts.json b/plugin-tests/dev-tooling/fixtures/shopware-trunk/administration-package-scripts.json new file mode 100644 index 00000000..5c505ada --- /dev/null +++ b/plugin-tests/dev-tooling/fixtures/shopware-trunk/administration-package-scripts.json @@ -0,0 +1,49 @@ +{ + "build": "export VITE_MODE=production && ts-node -T build.ts", + "code-mods": "node code-mods.js", + "codemod:js-vue3-feature-flag-removal": "ts-node --transpileOnly ./scripts/codemods/js-vue3-feature-flag-removal/index.ts", + "codemod:twig-feature-flag-removal": "ts-node --transpileOnly ./scripts/codemods/twig-feature-flag-removal/index.ts", + "codemod:twig-remove-blocks": "ts-node --transpileOnly ./scripts/codemods/twig-block-removal/index.ts", + "codemod:sfc-migration": "ts-node --transpileOnly ./scripts/codemods/sfc-migration/run-sfc-migration.ts", + "convert-entity-schema": "ts-node --transpileOnly ./scripts/entitySchemaConverter/convert-schema.ts", + "create-test": "node ./scripts/create-spec-file/index.mjs", + "dev": "export VITE_MODE=development && ts-node -T build.ts", + "extension-tooling:check": "ts-node --transpileOnly ./scripts/extensionTooling/check.ts", + "extension-tooling:setup": "ts-node --transpileOnly ./scripts/extensionTooling/setup.ts", + "format": "prettier --check \"src/**/*.{js,ts}\" \"test/**/*.{js,ts}\" \"extension-tooling/**/*.mjs\" \"scripts/extensionTooling/**/*.ts\" \"scripts/codemods/**/*.ts\" \"scripts/generate-shopware-modules/**/*.ts\" \"build/vite-plugins/**/*.{js,ts}\" \"build/vue-setup-transform/**/*.{js,ts}\" \"build/plugins.vite.ts\" \"build.ts\"", + "format:fix": "prettier --write \"src/**/*.{js,ts}\" \"test/**/*.{js,ts}\" \"extension-tooling/**/*.mjs\" \"scripts/extensionTooling/**/*.ts\" \"scripts/codemods/**/*.ts\" \"scripts/generate-shopware-modules/**/*.ts\" \"build/vite-plugins/**/*.{js,ts}\" \"build/vue-setup-transform/**/*.{js,ts}\" \"build/plugins.vite.ts\" \"build.ts\" --cache", + "generate-api-docs": "./node_modules/.bin/jsdoc src -r -c jsdoc.config.js", + "generate-component-import-resolver-map": "ts-node --transpileOnly ./scripts/componentImportResolver/generate.ts", + "generate-data-set-list": "ts-node --transpileOnly ./scripts/generate-data-set-list/index.ts", + "generate-blocks-list": "ts-node --transpileOnly ./scripts/generate-block-list/index.ts", + "generate-entity-schema-package": "ts-node --transpileOnly ./scripts/entitySchemaConverter/generate-package.ts", + "generate-position-identifier-list": "ts-node --transpileOnly ./scripts/generate-position-identifier-list/index.ts", + "generate-shopware-modules": "ts-node --transpileOnly ./scripts/generate-shopware-modules/index.ts", + "preinstall": "node ./scripts/validate-package-json/index.mjs", + "postinstall": "patch-package", + "lint": "eslint src test build/vue-setup-transform build/vite-plugins/virtual-shopware-modules extension-tooling scripts/extensionTooling scripts/generate-shopware-modules scripts/codemods build.ts --cache", + "lint:all": "npm run lint:types && npm run lint && npm run lint:scss && npm run format", + "lint:debugging": "eslint", + "lint:deprecations": "FILES=$(git status -s | awk '/(js|ts|vue|html\\.twig)$/ {print $2}'); [ -z \"$FILES\" ] || eslint --rule '\"sw-deprecation-rules/private-feature-declarations\": \"error\"' $FILES", + "lint:fix": "npm run lint -- --fix", + "lint:junit": "eslint --format junit src test build/vite-plugins/virtual-shopware-modules extension-tooling scripts/extensionTooling scripts/generate-shopware-modules scripts/codemods build.ts > eslint.junit.xml", + "lint:scss": "stylelint **/*.scss --cache", + "lint:scss-fix": "npm run lint:scss -- --fix", + "lint:snippets": "eslint \"src/**/snippet/*.json\" --no-cache", + "lint:snippets:all": "SNIPPET_ALLOW_LIST_DISABLED=1 eslint \"src/**/snippet/*.json\" --no-cache", + "lint:test-parser": "eslint test/eslint/error-reference.html.twig --no-ignore", + "lint:twig": "eslint src", + "lint:types": "tsc", + "lint-fix": "eslint --fix src test build/vite-plugins/virtual-shopware-modules extension-tooling scripts/extensionTooling scripts/generate-shopware-modules scripts/codemods build.ts", + "security-check": "./node_modules/.bin/nsp check", + "test-debug": "node --inspect-brk TZ=UTC node_modules/.bin/jest --watch --config jest.config.js --runInBand --no-cache", + "unit": "jest --config jest.config.js --ci", + "unit:extension-tooling-e2e": "EXTENSION_TOOLING_E2E=1 jest --config jest.config.js --ci --coverage=false scripts/extensionTooling/e2e.spec", + "unit-setup": "npm run generate-component-import-resolver-map", + "unit-watch": "jest --config jest.config.js --watch", + "vite": "vite", + "vite:build": "vite build", + "perf": "lhci autorun --config=./lighthouserc.js", + "perf:collect": "lhci collect --config=./lighthouserc.js", + "perf:assert": "lhci assert --config=./lighthouserc.js" +} diff --git a/plugin-tests/dev-tooling/fixtures/shopware-trunk/regenerate.sh b/plugin-tests/dev-tooling/fixtures/shopware-trunk/regenerate.sh new file mode 100755 index 00000000..7b3a9066 --- /dev/null +++ b/plugin-tests/dev-tooling/fixtures/shopware-trunk/regenerate.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Rewrites the two package-scripts fixtures from a shopware/shopware checkout. +# Usage: regenerate.sh [output-dir] +# The output directory defaults to the directory of this script. The checkout +# is only read. +set -euo pipefail + +if [[ $# -lt 1 || $# -gt 2 ]]; then + printf 'Usage: %s [output-dir]\n' "${0##*/}" >&2 + exit 64 +fi + +checkout="$1" +output_dir="${2:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}" + +# fixture file name -> package.json below the checkout +declare -A sources=( + [administration-package-scripts.json]="src/Administration/Resources/app/administration/package.json" + [storefront-package-scripts.json]="src/Storefront/Resources/app/storefront/package.json" +) + +for fixture in "${!sources[@]}"; do + package_json="${checkout}/${sources[${fixture}]}" + if [[ ! -f "${package_json}" ]]; then + printf 'No package.json at %s\n' "${package_json}" >&2 + exit 66 + fi + # No -S: the fixtures keep the key order of the package.json. + jq '.scripts' "${package_json}" > "${output_dir}/${fixture}" +done diff --git a/plugin-tests/dev-tooling/fixtures/shopware-trunk/storefront-package-scripts.json b/plugin-tests/dev-tooling/fixtures/shopware-trunk/storefront-package-scripts.json new file mode 100644 index 00000000..115e97ab --- /dev/null +++ b/plugin-tests/dev-tooling/fixtures/shopware-trunk/storefront-package-scripts.json @@ -0,0 +1,23 @@ +{ + "build:shopware": "vite build --config vite.shopware.config.mts", + "build:components": "node build/vite/build-components.js", + "dev:server": "vite --config vite.components.config.mts", + "development": "NODE_ENV=development webpack --config webpack.config.js", + "hot": "NODE_ENV=development MODE=hot webpack-dev-server --config webpack.config.js", + "hot-proxy": "NODE_ENV=development MODE=hot node ./build/start-hot-reload.js", + "lint": "eslint --no-error-on-unmatched-pattern --report-unused-disable-directives ./src --cache && stylelint --config stylelint.config.js ./src/scss --cache", + "lint-fix": "npm run lint:js:fix && npm run lint:scss-fix", + "lint:js": "eslint --no-error-on-unmatched-pattern --report-unused-disable-directives ./src ./build && (cd ../.. && eslint --no-error-on-unmatched-pattern --config ./app/storefront/eslint.config.js --report-unused-disable-directives views/components)", + "lint:js:fix": "eslint --no-error-on-unmatched-pattern --fix --report-unused-disable-directives ./src ./build && (cd ../.. && eslint --no-error-on-unmatched-pattern --fix --config ./app/storefront/eslint.config.js --report-unused-disable-directives views/components)", + "lint:scss": "stylelint --config stylelint.config.js ./src/scss --cache", + "lint:scss-fix": "npm run lint:scss -- --fix", + "production": "NODE_ENV=production webpack --config webpack.config.js && npm run build:shopware && npm run build:components", + "unit": "jest --config jest.config.js --ci", + "unit-watch": "jest --config jest.config.js --watch", + "unit:components": "vitest run --config vitest.config.mts", + "unit:components:watch": "vitest --config vitest.config.mts", + "unit:components:coverage": "vitest run --coverage --config vitest.config.mts", + "postinstall": "patch-package && node build/link-component-node-modules.js", + "storybook": "storybook dev -p 6006", + "build-storybook": "storybook build" +} diff --git a/plugin-tests/dev-tooling/js_admin_tools.bats b/plugin-tests/dev-tooling/js_admin_tools.bats index 61a037a5..0b84a79d 100644 --- a/plugin-tests/dev-tooling/js_admin_tools.bats +++ b/plugin-tests/dev-tooling/js_admin_tools.bats @@ -19,7 +19,32 @@ CONFIG_PREFIX="js-tooling" assert_success } -js_admin_hook_blocks() { assert_hook_blocks "check-js-admin-tools.sh" "$1" "$2"; } +# The block message names the tool and its server; neither host's mcp__ form. +js_admin_hook_blocks() { + assert_hook_blocks "check-js-admin-tools.sh" "$1" "$2" + assert_output --partial "on the \`js-admin-tooling\` MCP server" + refute_output --partial "mcp__" +} + +# bats test_tags=cwd +@test "reads the config from the hook input cwd when CURSOR_PROJECT_DIR is unset" { + unset CURSOR_PROJECT_DIR + local project + project=$(make_cwd_project "js-tooling" "ddev") + run_hook_with_cwd "check-js-admin-tools.sh" "npm run lint" "$project" + assert_failure 2 + assert_output --partial "'ddev' environment" +} + +# bats test_tags=cwd +@test "CURSOR_PROJECT_DIR wins over the hook input cwd when both are set" { + local project + project=$(make_cwd_project "js-tooling" "ddev") + run_hook_with_cwd "check-js-admin-tools.sh" "npm run lint" "$project" + assert_failure 2 + assert_output --partial "'native' environment" + refute_output --partial "'ddev' environment" +} # bats test_tags=blocking bats_test_function --description "blocks npm run lint:scss → suggests stylelint_check" \ @@ -39,9 +64,9 @@ bats_test_function --description "blocks npx eslint → suggests eslint_check" \ bats_test_function --description "blocks npx jest → suggests jest_run" \ -- js_admin_hook_blocks "npx jest --watch" "jest_run" -# The target-less base scripts the MCP tools route path-scoped runs at. None of -# them matched a pattern before: `:` is not in the `(\s|--|$)` tail the shorter -# names use, so `npm run lint` never covered `npm run lint:debugging`. +# The target-less base scripts. No MCP tool calls them. Shopware's +# Administration package.json defines lint:debugging only, and the redirects +# stay for a project that defines the others. # bats test_tags=blocking,base-scripts bats_test_function --description "blocks npm run lint:debugging → suggests eslint_check" \ -- js_admin_hook_blocks "npm run lint:debugging" "eslint_check" @@ -52,14 +77,78 @@ bats_test_function --description "blocks npm run prettier:base → suggests pret bats_test_function --description "blocks npm run jest:base → suggests jest_run" \ -- js_admin_hook_blocks "npm run jest:base" "jest_run" +# A linter binary run through `npx`, `npm exec` or its node_modules/.bin path. +# The MCP servers run the binaries themselves through `npm exec --no --`, so an +# agent that copies that form from a server log reaches the hook with it. +# bats test_tags=blocking,binaries +for _entry in eslint:eslint_check stylelint:stylelint_check prettier:prettier_check \ + jest:jest_run tsc:tsc_check; do + _binary="${_entry%%:*}" + _tool="${_entry##*:}" + for _form in "${JS_HOOK_BINARY_FORMS[@]}"; do + _command="${_form//BIN/${_binary}} src/module" + bats_test_function --description "blocks ${_command} → suggests ${_tool}" \ + -- js_admin_hook_blocks "${_command}" "${_tool}" + done + bats_test_function --description "blocks ${_binary} run through npm exec in the Administration tree → suggests ${_tool}" \ + -- js_admin_hook_blocks \ + "cd src/Administration/Resources/app/administration && npm exec --no -- ${_binary} src/module" "${_tool}" +done +unset _entry _binary _tool _form _command + +# The binary forms follow the same context rule as the scripts: a command that +# names the Storefront tree belongs to the Storefront hook. +# bats test_tags=context,allow +admin_hook_allows_storefront_binary() { + run_hook "check-js-admin-tools.sh" "cd src/Storefront/Resources/app/storefront && npm exec --no -- $1 src" + assert_success +} +bats_test_function --description "allows npm exec eslint when the command names the Storefront tree" \ + -- admin_hook_allows_storefront_binary eslint +bats_test_function --description "allows npm exec stylelint when the command names the Storefront tree" \ + -- admin_hook_allows_storefront_binary stylelint +bats_test_function --description "allows npm exec prettier when the command names the Storefront tree" \ + -- admin_hook_allows_storefront_binary prettier +bats_test_function --description "allows npm exec jest when the command names the Storefront tree" \ + -- admin_hook_allows_storefront_binary jest +bats_test_function --description "allows npm exec tsc when the command names the Storefront tree" \ + -- admin_hook_allows_storefront_binary tsc + +# `npx` and `npm exec` run other packages too, and a binary's name turns up in +# arguments and quoted text. None of these invokes a linter. +# bats test_tags=allow +admin_hook_allows() { + run_hook "check-js-admin-tools.sh" "$1" + assert_success +} +bats_test_function --description "allows npm exec vitest, which the Administration server has no tool for" \ + -- admin_hook_allows "npm exec -- vitest src" +bats_test_function --description "allows npm exec running another tool" \ + -- admin_hook_allows "npm exec -- some-other-tool src" +# `--package` takes a value, so the linter name after it is not the command. +bats_test_function --description "allows npm exec --package naming a linter but running another tool" \ + -- admin_hook_allows "npm exec --package eslint some-other-tool" +bats_test_function --description "allows npx running another tool" \ + -- admin_hook_allows "npx --yes some-other-tool src" +bats_test_function --description "allows a linter name after another tool in an npx command" \ + -- admin_hook_allows "npx --yes some-other-tool eslint" +bats_test_function --description "allows npm exec running a package whose name starts with eslint" \ + -- admin_hook_allows "npm exec -- eslint-plugin-foo" +bats_test_function --description "allows installing a linter" \ + -- admin_hook_allows "npm install eslint" +bats_test_function --description "allows reading a linter binary" \ + -- admin_hook_allows "cat node_modules/.bin/eslint" +bats_test_function --description "allows a linter name inside quoted text after a semicolon" \ + -- admin_hook_allows 'git commit -m "tidy; eslint config"' + # bats test_tags=context,allow -@test "allows npm run stylelint:app, which only the Storefront package declares" { +@test "allows npm run stylelint:app, a Storefront script name" { run_hook "check-js-admin-tools.sh" "npm run stylelint:app" assert_success } # bats test_tags=context,allow -@test "allows npm run eslint:app, which only the Storefront package declares" { +@test "allows npm run eslint:app, a Storefront script name" { run_hook "check-js-admin-tools.sh" "npm run eslint:app" assert_success } @@ -82,3 +171,32 @@ bats_test_function --description "blocks npm run jest:base → suggests jest_run run_hook "check-js-admin-tools.sh" "npm run lint" assert_success } + +# `npm x` is the alias of `npm exec`; the -c / --call form runs a command +# string, and a binary at a command position inside it is blocked. +# bats test_tags=binary,blocking +for spec in "eslint eslint_check" "stylelint stylelint_check" "prettier prettier_check" "jest jest_run" "tsc tsc_check"; do + read -r bin tool <<<"$spec" + bats_test_function --description "blocks npm x running ${bin}" \ + -- js_admin_hook_blocks "npm x -- ${bin} src" "$tool" + bats_test_function --description "blocks npm exec -c running ${bin} after cd" \ + -- js_admin_hook_blocks "npm exec --no -c \"cd ../.. && ${bin} src\"" "$tool" +done +bats_test_function --description "blocks the npm exec -c form the MCP tools run for the components tree" \ + -- js_admin_hook_blocks 'npm exec --no -c "cd ../.. && eslint views/components"' "eslint_check" +bats_test_function --description "blocks npx -c with a single-quoted string running stylelint" \ + -- js_admin_hook_blocks "npx -c 'stylelint src'" "stylelint_check" +bats_test_function --description "blocks npm exec --call running jest" \ + -- js_admin_hook_blocks 'npm exec --call "jest src"' "jest_run" +bats_test_function --description "blocks npm exec -c after --package with its value" \ + -- js_admin_hook_blocks 'npm exec --package foo -c "eslint src"' "eslint_check" +bats_test_function --description "blocks npm exec -c with leading blanks in the string" \ + -- js_admin_hook_blocks 'npm exec -c " eslint src"' "eslint_check" +bats_test_function --description "blocks npm exec -c with a variable assignment before the binary" \ + -- js_admin_hook_blocks 'npm exec -c "NODE_ENV=test jest src"' "jest_run" + +# bats test_tags=binary,allow +bats_test_function --description "allows npm exec -c naming a linter as an argument" \ + -- admin_hook_allows 'npm exec -c "echo eslint"' +bats_test_function --description "allows npm x running another tool" \ + -- admin_hook_allows "npm x -- some-other-tool src" diff --git a/plugin-tests/dev-tooling/js_storefront_tools.bats b/plugin-tests/dev-tooling/js_storefront_tools.bats index 0da57592..2035a906 100644 --- a/plugin-tests/dev-tooling/js_storefront_tools.bats +++ b/plugin-tests/dev-tooling/js_storefront_tools.bats @@ -19,7 +19,32 @@ CONFIG_PREFIX="js-tooling" assert_output --partial "eslint_check" } -js_storefront_hook_blocks() { assert_hook_blocks "check-js-storefront-tools.sh" "$1" "$2"; } +# The block message names the tool and its server; neither host's mcp__ form. +js_storefront_hook_blocks() { + assert_hook_blocks "check-js-storefront-tools.sh" "$1" "$2" + assert_output --partial "on the \`js-storefront-tooling\` MCP server" + refute_output --partial "mcp__" +} + +# bats test_tags=cwd +@test "reads the config from the hook input cwd when CURSOR_PROJECT_DIR is unset" { + unset CURSOR_PROJECT_DIR + local project + project=$(make_cwd_project "js-tooling" "ddev") + run_hook_with_cwd "check-js-storefront-tools.sh" "cd src/Storefront && npm run lint:js" "$project" + assert_failure 2 + assert_output --partial "'ddev' environment" +} + +# bats test_tags=cwd +@test "CURSOR_PROJECT_DIR wins over the hook input cwd when both are set" { + local project + project=$(make_cwd_project "js-tooling" "ddev") + run_hook_with_cwd "check-js-storefront-tools.sh" "cd src/Storefront && npm run lint:js" "$project" + assert_failure 2 + assert_output --partial "'native' environment" + refute_output --partial "'ddev' environment" +} # bats test_tags=blocking bats_test_function --description "blocks npm run lint:scss → suggests stylelint_check" \ @@ -31,8 +56,7 @@ bats_test_function --description "blocks npm run production → suggests webpack bats_test_function --description "blocks npm run lint:js in Storefront context → suggests eslint_check" \ -- js_storefront_hook_blocks "cd src/Storefront && npm run lint:js" "eslint_check" # `lint:js:fix` carries a colon where the context detector's trailing -# alternation expects whitespace or end-of-string, so a bare invocation used to -# miss the detector entirely and reach neither hook's block. +# alternation expects whitespace or end-of-string. bats_test_function --description "blocks a bare npm run lint:js:fix → suggests eslint_fix" \ -- js_storefront_hook_blocks "npm run lint:js:fix" "eslint_fix" bats_test_function --description "blocks a bare npm run lint:js → suggests eslint_check" \ @@ -63,11 +87,8 @@ bats_test_function --description "blocks composer ludtwig:storefront:fix → sug -- js_storefront_hook_blocks "composer ludtwig:storefront:fix" "ludtwig_fix" bats_test_function --description "blocks a bare ludtwig invocation → suggests ludtwig_check" \ -- js_storefront_hook_blocks "ludtwig ." "ludtwig_check" -# The bare-ludtwig block pattern's leading boundary used to require ^, ;, &&, -# or |, so ludtwig invoked through a wrapper (e.g. "composer exec ludtwig") -# passed the context detector but was never blocked. The fix recognizes a -# fixed list of package runners immediately before the token rather than any -# whitespace boundary — a plain-whitespace boundary over-blocks (see the +# The bare-ludtwig block pattern recognizes a fixed list of package runners +# immediately before the token: a plain-whitespace boundary over-blocks (see the # commit-message case below). bats_test_function --description "blocks ludtwig invoked via a known runner (composer exec) → suggests ludtwig_check" \ -- js_storefront_hook_blocks "composer exec ludtwig" "ludtwig_check" @@ -81,10 +102,14 @@ bats_test_function --description "blocks a runner passing its own flag before lu -- js_storefront_hook_blocks "npx -y ludtwig" "ludtwig_check" bats_test_function --description "blocks a runner passing a flag and -- before ludtwig (pnpm dlx) → suggests ludtwig_check" \ -- js_storefront_hook_blocks "pnpm dlx --silent -- ludtwig" "ludtwig_check" - -# The target-less base scripts the MCP tools route path-scoped runs at. -# eslint:app, eslint:components and stylelint:app are Storefront-only names, so -# they are also Storefront context signals in their own right. +bats_test_function --description "blocks npm x running ludtwig" \ + -- js_storefront_hook_blocks "npm x ludtwig src/Storefront/Resources/views" "ludtwig_check" + +# The target-less base scripts. Shopware's Storefront package.json defines none +# of them and no MCP tool calls them; the redirects stay for a project that +# defines them. eslint:app, eslint:components and +# stylelint:app are Storefront names, so they are also Storefront context +# signals in their own right. # bats test_tags=blocking,base-scripts bats_test_function --description "blocks npm run eslint:app → suggests eslint_check" \ -- js_storefront_hook_blocks "npm run eslint:app" "eslint_check" @@ -95,7 +120,49 @@ bats_test_function --description "blocks npm run stylelint:app → suggests styl bats_test_function --description "blocks npm run jest:base in Storefront context → suggests jest_run" \ -- js_storefront_hook_blocks "cd src/Storefront && npm run jest:base" "jest_run" -# jest:base is declared by both packages. The Admin hook's unknown-context +# A linter binary run through `npx`, `npm exec` or its node_modules/.bin path. +# The MCP servers run the binaries themselves through `npm exec --no --`, so an +# agent that copies that form from a server log reaches the hook with it. +# The Storefront server has no prettier and no tsc tool, so neither is here. +# bats test_tags=blocking,binaries +for _entry in eslint:eslint_check stylelint:stylelint_check jest:jest_run vitest:vitest_run; do + _binary="${_entry%%:*}" + _tool="${_entry##*:}" + for _form in "${JS_HOOK_BINARY_FORMS[@]}"; do + _command="cd src/Storefront/Resources/app/storefront && ${_form//BIN/${_binary}} src/js" + bats_test_function --description "blocks ${_command} → suggests ${_tool}" \ + -- js_storefront_hook_blocks "${_command}" "${_tool}" + done +done +unset _entry _binary _tool _form _command + +# Without a Storefront marker the command belongs to the Admin hook, and a +# command that names the Administration tree is never claimed here. +# bats test_tags=context,allow +storefront_hook_allows() { + run_hook "check-js-storefront-tools.sh" "$1" + assert_success +} +bats_test_function --description "allows npm exec eslint when no tree is named, which the Admin hook owns" \ + -- storefront_hook_allows "npm exec --no -- eslint src" +bats_test_function --description "allows npm exec stylelint in the Administration tree" \ + -- storefront_hook_allows "cd src/Administration/Resources/app/administration && npm exec --no -- stylelint src" +bats_test_function --description "allows npm exec tsc in the Storefront tree, which has no tsc tool" \ + -- storefront_hook_allows "cd src/Storefront/Resources/app/storefront && npm exec --no -- tsc src" +bats_test_function --description "allows npm exec vitest in the Administration tree" \ + -- storefront_hook_allows "cd src/Administration/Resources/app/administration && npm exec --no -- vitest src" +bats_test_function --description "allows npm exec prettier in the Storefront tree, which has no prettier tool" \ + -- storefront_hook_allows "cd src/Storefront/Resources/app/storefront && npm exec --no -- prettier --check src" +bats_test_function --description "allows npm exec running another tool in the Storefront tree" \ + -- storefront_hook_allows "cd src/Storefront/Resources/app/storefront && npm exec -- some-other-tool src" +bats_test_function --description "allows npm exec --package naming a linter but running another tool in the Storefront tree" \ + -- storefront_hook_allows "cd src/Storefront/Resources/app/storefront && npm exec --package stylelint some-other-tool" +bats_test_function --description "allows a linter name after another tool in an npx command in the Storefront tree" \ + -- storefront_hook_allows "cd src/Storefront/Resources/app/storefront && npx --yes some-other-tool eslint" +bats_test_function --description "allows a linter name inside quoted text after a semicolon in the Storefront tree" \ + -- storefront_hook_allows 'cd src/Storefront && git commit -m "tidy; eslint config"' + +# jest:base carries no side-specific marker. The Admin hook's unknown-context # fallback owns the bare form, so this hook must decline it or the command # would be blocked twice with two different tool names. # bats test_tags=context,allow @@ -167,3 +234,14 @@ bats_test_function --description "blocks npm run jest:base in Storefront context run_hook "check-js-storefront-tools.sh" "cd Storefront && npm run lint:js" assert_success } + +# `npm x` is the alias of `npm exec`; the -c / --call form runs a command +# string, and a binary at a command position inside it is blocked. +# bats test_tags=binary,blocking +for spec in "eslint eslint_check" "stylelint stylelint_check" "jest jest_run" "vitest vitest_run"; do + read -r bin tool <<<"$spec" + bats_test_function --description "blocks npm x running ${bin} in the Storefront tree" \ + -- js_storefront_hook_blocks "cd src/Storefront && npm x -- ${bin} src" "$tool" + bats_test_function --description "blocks npm exec -c running ${bin} in the Storefront tree" \ + -- js_storefront_hook_blocks "cd src/Storefront && npm exec --no -c \"cd ../.. && ${bin} src\"" "$tool" +done diff --git a/plugin-tests/dev-tooling/mcp_tool_console.bats b/plugin-tests/dev-tooling/mcp_tool_console.bats index f8a9d6c3..16e871bb 100644 --- a/plugin-tests/dev-tooling/mcp_tool_console.bats +++ b/plugin-tests/dev-tooling/mcp_tool_console.bats @@ -75,6 +75,12 @@ _validate_console_run() { assert_output --partial '"My Plugin"' } +@test "console: an empty positional argument is kept as an empty quoted argument" { + run tool_console_run '{"command":"config:set","arguments":["key",""]}' + assert_success + assert_line 'bin/console "config:set" "key" ""' +} + # --- Environment and verbosity --- @test "console: env option adds --env flag" { @@ -152,6 +158,27 @@ _validate_console_run() { assert_output --partial "--no-interaction" } +@test "console: no_debug=false overrides a configured .console.no_debug of true" { + printf '%s\n' '{"environment":"native","console":{"no_debug":true}}' > "${LINT_CONFIG_FILE}" + run tool_console_run '{"command":"cache:clear","no_debug":false}' + assert_success + refute_output --partial "--no-debug" +} + +@test "console: no_interaction=false overrides a configured .console.no_interaction of true" { + printf '%s\n' '{"environment":"native","console":{"no_interaction":true}}' > "${LINT_CONFIG_FILE}" + run tool_console_run '{"command":"cache:clear","no_interaction":false}' + assert_success + refute_output --partial "--no-interaction" +} + +@test "console: a configured .console.no_debug of true applies when no_debug is absent" { + printf '%s\n' '{"environment":"native","console":{"no_debug":true}}' > "${LINT_CONFIG_FILE}" + run tool_console_run '{"command":"cache:clear"}' + assert_success + assert_output --partial "--no-debug" +} + # --- Options object types --- @test "console: boolean option true becomes --flag" { @@ -184,6 +211,21 @@ _validate_console_run() { assert_output --partial -- '--"tag"="my tag"' } +@test "console: array option holding a null element is refused naming the key" { + run tool_console_run '{"command":"cache:clear","options":{"tag":["ok",null]}}' + assert_failure + assert_output --partial 'console option "tag" holds a null element' + refute_output --partial "bin/console" +} + +# The vendored validator does not enforce the oneOf on "options", so the tool refuses other types. +@test "console: a number option value is refused naming the key and type" { + run tool_console_run '{"command":"cache:clear","options":{"limit":5}}' + assert_failure + assert_output --partial 'Refusing to run: console option "limit" has type number' + refute_output --partial "bin/console" +} + # --- Values that cannot be quoted safely are refused --- console_refuses_single_quote() { @@ -489,3 +531,30 @@ _stub_compose_resolution() { assert_failure assert_output --partial 'Refusing to run: the tool call'"'"'s own arguments do not parse as a JSON object, so "project_root" could not be read from them.' } + +@test "console list: a failing command's output comes back with its exit status" { + exec_command() { printf '%s\n' "PHP Fatal error: boom"; return 7; } + run tool_console_list '{}' + assert_failure 7 + assert_output --partial "PHP Fatal error: boom" +} + +@test "console list: output that is not the list JSON is refused and shown raw" { + exec_command() { printf '%s\n' "not json at all"; } + run tool_console_list '{}' + assert_failure + assert_output --partial "The output of bin/console list is not the expected JSON; raw output follows." + assert_line "not json at all" +} + +@test "console list: the llm format groups commands by namespace" { + exec_command() { + printf '%s\n' '{"commands":[{"name":"cache:clear","description":"Clears the cache","hidden":false},{"name":"plugin:install","description":"Installs a plugin"}]}' + } + run tool_console_list '{}' + assert_success + assert_line "[cache]" + assert_line " cache:clear: Clears the cache" + assert_line "[plugin]" + assert_line " plugin:install: Installs a plugin" +} diff --git a/plugin-tests/dev-tooling/mcp_tool_js_admin.bats b/plugin-tests/dev-tooling/mcp_tool_js_admin.bats index eb2ddafe..58958ef8 100644 --- a/plugin-tests/dev-tooling/mcp_tool_js_admin.bats +++ b/plugin-tests/dev-tooling/mcp_tool_js_admin.bats @@ -6,12 +6,8 @@ load 'test_helper/common_setup' PLUGIN_DIR="${REPO_ROOT}/plugins/dev-tooling" -# Answers the `npm pkg get "scripts."` probe with the body the Shopware -# Administration package.json declares. Quoted glob arguments are reproduced -# unquoted: the append gate reads command shape, not quoting, and embedded -# double quotes would need escaping through this fake's own JSON-ish string. -# FAKE_ABSENT_SCRIPTS makes a script look undefined; FAKE_BODY_NAME/FAKE_BODY -# makes one report a different body. +# Answers the `npm pkg get "scripts."` probe from the trunk fixture; see +# shopware_trunk_script_body and the FAKE_* list in common_setup.bash. _fake_admin_script_body() { local name="$1" @@ -24,45 +20,7 @@ _fake_admin_script_body() { return fi - case "${name}" in - lint) - printf '%s\n' '"eslint src test build.ts --cache"' ;; - lint:fix) - printf '%s\n' '"npm run lint -- --fix"' ;; - lint:debugging) - printf '%s\n' '"eslint"' ;; - stylelint:base) - printf '%s\n' '"stylelint --cache"' ;; - lint:scss) - printf '%s\n' '"npm run stylelint:base -- **/*.scss"' ;; - lint:scss-fix) - printf '%s\n' '"npm run lint:scss -- --fix"' ;; - prettier:base) - printf '%s\n' '"prettier"' ;; - format) - printf '%s\n' '"npm run prettier:base -- --check src/**/*.{js,ts} build.ts"' ;; - format:fix) - printf '%s\n' '"npm run prettier:base -- --write src/**/*.{js,ts} build.ts --cache"' ;; - jest:base) - printf '%s\n' '"jest --config jest.config.js"' ;; - lint:types) - printf '%s\n' '"tsc"' ;; - build) - printf '%s\n' '"export VITE_MODE=production && ts-node -T build.ts"' ;; - unit) - # A package that declares jest:base writes "unit" in terms of it. - # A package that does not — the pre-refactor layout the fallback - # route exists for — spells the runner out instead. Keying on - # FAKE_ABSENT_SCRIPTS keeps both configurations describing a - # package.json that could actually exist. - case " ${FAKE_ABSENT_SCRIPTS} " in - *" jest:base "*) printf '%s\n' '"jest --config jest.config.js --ci"' ;; - *) printf '%s\n' '"npm run jest:base -- --ci"' ;; - esac - ;; - *) - printf '%s\n' '{}' ;; - esac + shopware_trunk_script_body administration "${name}" } # Builds a Jest JSON report body carrying the counts a test needs. @@ -78,28 +36,26 @@ setup() { LINT_CONFIG_FILE="${BATS_TEST_TMPDIR}/.mcp-js-tooling.json" echo '{"environment":"native"}' > "${LINT_CONFIG_FILE}" JS_CONTEXT="admin" + # The FAKE_* variables are listed in common_setup.bash. FAKE_ABSENT_SCRIPTS="" FAKE_BODY_NAME="" FAKE_BODY="" FAKE_PROBE_OUTPUT="" FAKE_PROBE_FILE="${BATS_TEST_TMPDIR}/probe.txt" - # The report path the jest tool uses is modelled as a real file rather than - # a canned answer, so a report left behind by an earlier run and a report - # written by this one are distinguishable: the run writes - # FAKE_REPORT_OUTPUT into the store (unless FAKE_RUN_WRITES_REPORT is 0), - # the delete removes it, and the read returns whatever is there. FAKE_REPORT_OUTPUT="$(_jest_report 13 13 0 1 0)" FAKE_REPORT_STORE="${BATS_TEST_TMPDIR}/jest-report-store.json" FAKE_RUN_WRITES_REPORT=1 - # Records the command that read the report, so a test can assert its shape. FAKE_REPORT_READ_FILE="${BATS_TEST_TMPDIR}/report-read.txt" - # Every wrapped command in order, so a test can assert call sequence. FAKE_CALL_LOG="${BATS_TEST_TMPDIR}/npm-calls.log" FAKE_CLEAR_EXIT=0 FAKE_CLEAR_OUTPUT="" FAKE_RUN_EXIT=0 + FAKE_MISSING_BINARIES="" + FAKE_BINARY_PROBE_ERROR="" + FAKE_DIRECTORY_PROBE_ERROR="" log() { :; } source "${PLUGIN_DIR}/shared/environment.sh" + source "${PLUGIN_DIR}/shared/js_paths.sh" source "${PLUGIN_DIR}/shared/scope.sh" PROJECT_ROOT="${BATS_TEST_TMPDIR}" export PROJECT_ROOT @@ -109,6 +65,11 @@ setup() { exec_npm_command() { local cmd="$1" printf '%s\n' "${cmd}" >> "${FAKE_CALL_LOG}" + local probe_code=0 + js_fake_npm_probe "${cmd}" "/var/www/html/src/Administration/Resources/app/administration" || probe_code=$? + if [[ "${probe_code}" -ne "${JS_FAKE_NPM_PROBE_UNHANDLED}" ]]; then + return "${probe_code}" + fi case "${cmd}" in 'npm pkg get "scripts.'*) local name="${cmd#npm pkg get \"scripts.}" @@ -131,6 +92,15 @@ setup() { cat -- "${FAKE_REPORT_STORE}" ;; *) + # npm refuses an undefined script before running anything. + if [[ "${cmd}" == "npm run "* ]]; then + local script="${cmd#npm run }" + script="${script%% *}" + if [[ "$(_fake_admin_script_body "${script}")" == "{}" ]]; then + printf '%s\n' "npm error Missing script: \"${script}\"" + return 1 + fi + fi if [[ "${FAKE_RUN_WRITES_REPORT}" == "1" ]]; then printf '%s\n' "${FAKE_REPORT_OUTPUT}" > "${FAKE_REPORT_STORE}" fi @@ -154,7 +124,7 @@ teardown() { SCOPE_JS_SUBDIR FAKE_ABSENT_SCRIPTS FAKE_BODY_NAME FAKE_BODY FAKE_PROBE_OUTPUT \ FAKE_PROBE_FILE FAKE_REPORT_OUTPUT FAKE_REPORT_STORE FAKE_RUN_WRITES_REPORT \ FAKE_REPORT_READ_FILE FAKE_CALL_LOG FAKE_CLEAR_EXIT FAKE_CLEAR_OUTPUT FAKE_RUN_EXIT \ - PROJECT_ROOT DEV_TOOLING_STATE_FILE + FAKE_MISSING_BINARIES FAKE_BINARY_PROBE_ERROR FAKE_DIRECTORY_PROBE_ERROR PROJECT_ROOT DEV_TOOLING_STATE_FILE } # --- ESLint: no paths keeps the aggregate script --- @@ -177,24 +147,24 @@ teardown() { assert_line "npm run lint:fix -- --fix" } -# --- ESLint: paths route at the target-less base script --- +# --- ESLint: paths run the package's own binary as the only targets --- -@test "admin eslint check: paths route at lint:debugging as the only targets" { +@test "admin eslint check: paths run the local eslint as the only targets" { run tool_eslint_check '{"paths":["src/app/component"]}' assert_success - assert_line 'npm run lint:debugging -- -f stylish "src/app/component"' + assert_line 'npm exec --no -- eslint -f stylish "src/app/component"' } @test "admin eslint check: a path-scoped run carries no hardcoded upstream target" { run tool_eslint_check '{"paths":["src/app/component"]}' assert_success - refute_output --partial "src test build.ts" + refute_output --partial "build/vue-setup-transform" } -@test "admin eslint fix: paths route at lint:debugging with --fix" { +@test "admin eslint fix: paths run the local eslint with --fix" { run tool_eslint_fix '{"paths":["src/app/component"]}' assert_success - assert_line 'npm run lint:debugging -- --fix "src/app/component"' + assert_line 'npm exec --no -- eslint --fix "src/app/component"' } @test "admin eslint fix: a path-scoped run never reaches the aggregate lint:fix script" { @@ -206,39 +176,35 @@ teardown() { @test "admin eslint check: repo-root-relative path is rebased onto the package dir" { run tool_eslint_check '{"paths":["src/Administration/Resources/app/administration/src/app/foo.ts"]}' assert_success - assert_line 'npm run lint:debugging -- -f stylish "src/app/foo.ts"' + assert_line 'npm exec --no -- eslint -f stylish "src/app/foo.ts"' } @test "admin eslint check: keeps a path containing a space in one argument" { run tool_eslint_check '{"paths":["src/app/my component"]}' assert_success - assert_line 'npm run lint:debugging -- -f stylish "src/app/my component"' + assert_line 'npm exec --no -- eslint -f stylish "src/app/my component"' } -# --- ESLint: hard failures instead of widening --- - -@test "admin eslint check: refuses rather than falling back to the aggregate script" { - FAKE_ABSENT_SCRIPTS="lint:debugging" - run tool_eslint_check '{"paths":["src/app/component"]}' - assert_failure - assert_output --partial "lint:debugging" - refute_output --partial "npm run lint" +# A plugin package defines its own scripts; SwagCommercial defines no "lint:debugging". +@test "admin eslint check: paths lint under a plugin scope whose package defines no lint:debugging" { + cat > "${LINT_CONFIG_FILE}" <<'JSON' +{"environment":"native","scopes":{"plugin-x":{"cwd":"custom/plugins/X"}}} +JSON + run tool_eslint_check '{"scope":"plugin-x","paths":["src/main.ts"]}' + assert_success + assert_line 'npm exec --no -- eslint -f stylish "src/main.ts"' } -@test "admin eslint fix: refuses rather than falling back to the aggregate fix script" { - FAKE_ABSENT_SCRIPTS="lint:debugging" +# --- ESLint: hard failures instead of widening --- + +@test "admin eslint fix: refuses with paths when the package has no local eslint" { + FAKE_MISSING_BINARIES="eslint" run tool_eslint_fix '{"paths":["src/app/component"]}' assert_failure - assert_output --partial "lint:debugging" + assert_output --partial '"node_modules/.bin/eslint" is not installed' + run cat "${FAKE_CALL_LOG}" refute_output --partial "npm run lint" -} - -@test "admin eslint check: fails when lint:debugging cannot take appended arguments" { - FAKE_BODY_NAME="lint:debugging" - FAKE_BODY="a && (cd .. && eslint)" - run tool_eslint_check '{"paths":["src/app/component"]}' - assert_failure - assert_output --partial "cannot take appended arguments" + refute_output --partial "npm exec --no -- eslint" } @test "admin eslint check: refuses a path that holds no file ESLint reads" { @@ -314,30 +280,25 @@ teardown() { refute_output --partial "--fix" } -# --- Stylelint: paths route at the target-less base script --- - -@test "admin stylelint check: paths route at stylelint:base as the only targets" { - run tool_stylelint_check '{"paths":["src/app/assets/scss/base.scss"]}' +@test "admin stylelint fix: a scoped config without paths is appended to the aggregate script" { + _use_stylelint_scope_config + run tool_stylelint_fix '{"scope":"plugin-x"}' assert_success - assert_line 'npm run stylelint:base -- -f string "src/app/assets/scss/base.scss"' + assert_line "npm run lint:scss-fix -- --config \".stylelintrc.plugin\"" } -@test "admin stylelint fix: paths route at stylelint:base as the only targets" { - run tool_stylelint_fix '{"paths":["src/app/assets/scss/base.scss"]}' - assert_success - assert_line 'npm run stylelint:base -- --fix "src/app/assets/scss/base.scss"' -} +# --- Stylelint: paths run the package's own binary as the only targets --- -@test "admin stylelint fix: paths route carries --fix, which the base script body lacks" { - run tool_stylelint_fix '{"paths":["src/app/assets/scss/base.scss"]}' +@test "admin stylelint check: paths run the local stylelint with the lint:scss flags" { + run tool_stylelint_check '{"paths":["src/app/assets/scss/base.scss"]}' assert_success - assert_output --partial "-- --fix " + assert_line 'npm exec --no -- stylelint --cache -f string "src/app/assets/scss/base.scss"' } -@test "admin stylelint check: paths route carries no --fix" { - run tool_stylelint_check '{"paths":["src/app/assets/scss/base.scss"]}' +@test "admin stylelint fix: paths run the local stylelint with --fix" { + run tool_stylelint_fix '{"paths":["src/app/assets/scss/base.scss"]}' assert_success - refute_output --partial "--fix" + assert_line 'npm exec --no -- stylelint --cache --fix "src/app/assets/scss/base.scss"' } @test "admin stylelint fix: a path-scoped run never reaches the aggregate fix script" { @@ -346,18 +307,27 @@ teardown() { refute_output --partial "lint:scss-fix" } -@test "admin stylelint fix: fails when stylelint:base is absent and paths were supplied" { - FAKE_ABSENT_SCRIPTS="stylelint:base" +@test "admin stylelint check: a scoped config follows the lint:scss flags" { + _use_stylelint_scope_config + run tool_stylelint_check '{"scope":"plugin-x","paths":["src/scss/base.scss"]}' + assert_success + assert_line 'npm exec --no -- stylelint --cache -f string --config ".stylelintrc.plugin" "src/scss/base.scss"' +} + +@test "admin stylelint fix: refuses with paths when the package has no local stylelint" { + FAKE_MISSING_BINARIES="stylelint" run tool_stylelint_fix '{"paths":["src/app/assets/scss/base.scss"]}' assert_failure - assert_output --partial "stylelint:base" + assert_output --partial "\"node_modules/.bin/stylelint\" is not installed in the package directory \"/var/www/html/src/Administration/Resources/app/administration\"" } -@test "admin stylelint fix: refuses rather than falling back to the aggregate fix script" { - FAKE_ABSENT_SCRIPTS="stylelint:base" +@test "admin stylelint fix: runs neither stylelint nor the aggregate when the local stylelint is missing" { + FAKE_MISSING_BINARIES="stylelint" run tool_stylelint_fix '{"paths":["src/app/assets/scss/base.scss"]}' assert_failure - refute_output --partial "npm run lint:scss" + run cat "${FAKE_CALL_LOG}" + refute_output --partial "-- stylelint" + refute_output --partial "npm run" } @test "admin stylelint check: refuses a path that holds no file Stylelint reads" { @@ -371,13 +341,7 @@ teardown() { FAKE_PROBE_OUTPUT="MISSING:src/**/*.scss" run tool_stylelint_check '{"paths":["src/**/*.scss"]}' assert_success - assert_line 'npm run stylelint:base -- -f string "src/**/*.scss"' -} - -@test "admin stylelint check: a glob path is quoted so the shell cannot expand it" { - run tool_stylelint_check '{"paths":["src/**/*.scss"]}' - assert_success - assert_output --partial '"src/**/*.scss"' + assert_line 'npm exec --no -- stylelint --cache -f string "src/**/*.scss"' } @test "admin stylelint check: a literal path alongside a glob still passes the guard" { @@ -401,18 +365,18 @@ teardown() { assert_line "npm run format:fix" } -# --- Prettier: paths route at the target-less base script --- +# --- Prettier: paths run the package's own binary as the only targets --- -@test "admin prettier check: paths route at prettier:base with --check" { +@test "admin prettier check: paths run the local prettier with --check" { run tool_prettier_check '{"paths":["src/app/main.ts"]}' assert_success - assert_line 'npm run prettier:base -- --check "src/app/main.ts"' + assert_line 'npm exec --no -- prettier --check "src/app/main.ts"' } -@test "admin prettier fix: paths route at prettier:base with --write" { +@test "admin prettier fix: paths run the local prettier with the format:fix flags" { run tool_prettier_fix '{"paths":["src/app/main.ts"]}' assert_success - assert_line 'npm run prettier:base -- --write "src/app/main.ts"' + assert_line 'npm exec --no -- prettier --write --cache "src/app/main.ts"' } @test "admin prettier fix: a path-scoped run never reaches the aggregate format script" { @@ -421,18 +385,29 @@ teardown() { refute_output --partial "npm run format" } -@test "admin prettier check: fails when prettier:base is absent and paths were supplied" { - FAKE_ABSENT_SCRIPTS="prettier:base" +@test "admin prettier check: a scoped config follows the mode flag" { + cat > "${LINT_CONFIG_FILE}" <<'JSON' +{"environment":"native","scopes":{"plugin-x":{"cwd":"custom/plugins/X","prettier":{"config":".prettierrc.plugin"}}}} +JSON + run tool_prettier_check '{"scope":"plugin-x","paths":["src/main.ts"]}' + assert_success + assert_line 'npm exec --no -- prettier --check --config ".prettierrc.plugin" "src/main.ts"' +} + +@test "admin prettier check: refuses with paths when the package has no local prettier" { + FAKE_MISSING_BINARIES="prettier" run tool_prettier_check '{"paths":["src/app/main.ts"]}' assert_failure - assert_output --partial "prettier:base" + assert_output --partial "\"node_modules/.bin/prettier\" is not installed in the package directory \"/var/www/html/src/Administration/Resources/app/administration\"" } -@test "admin prettier check: refuses rather than falling back to the aggregate script" { - FAKE_ABSENT_SCRIPTS="prettier:base" - run tool_prettier_check '{"paths":["src/app/main.ts"]}' +@test "admin prettier fix: runs neither prettier nor the aggregate when the local prettier is missing" { + FAKE_MISSING_BINARIES="prettier" + run tool_prettier_fix '{"paths":["src/app/main.ts"]}' assert_failure - refute_output --partial "npm run format" + run cat "${FAKE_CALL_LOG}" + refute_output --partial "-- prettier" + refute_output --partial "npm run" } @test "admin prettier check: refuses a path that holds no file Prettier reads" { @@ -442,11 +417,304 @@ teardown() { assert_output --partial "Accepted extensions" } +@test "admin prettier check: probes for the extensions the format scripts cover" { + run tool_prettier_check '{"paths":["extension-tooling/index.mjs"]}' + assert_success + run cat "${FAKE_PROBE_FILE}" + assert_output --partial '*.js|*.ts|*.mjs)' +} + @test "admin prettier check: a glob path skips the existence guard" { FAKE_PROBE_OUTPUT="MISSING:src/**/*.ts" run tool_prettier_check '{"paths":["src/**/*.ts"]}' assert_success - assert_line 'npm run prettier:base -- --check "src/**/*.ts"' + assert_line 'npm exec --no -- prettier --check "src/**/*.ts"' +} + +@test "admin stylelint check: probes a path for .scss files only, as lint:scss does" { + run tool_stylelint_check '{"paths":["src/app/assets"]}' + assert_success + run cat "${FAKE_PROBE_FILE}" + assert_output --partial 'in *.scss)' +} + +@test "admin stylelint check: a directory reaches Stylelint as its .scss files only" { + local dir="${BATS_TEST_TMPDIR}/src/Administration/Resources/app/administration/src/sty" + mkdir -p "${dir}/nested" + touch "${dir}/a.scss" "${dir}/nested/b.scss" "${dir}/c.css" "${dir}/e.js" "${dir}/f.json" "${dir}/g.twig" "${dir}/notes.txt" + tool_stylelint_check '{"paths":["src/sty"]}' > /dev/null + run js_execute_in_env native "$(grep '^npm exec --no -- stylelint ' "${FAKE_CALL_LOG}")" + assert_success + assert_line '[src/sty/**/*.scss]' + run grep '^match:' <<< "${output}" + assert_output "match:src/sty/a.scss +match:src/sty/nested/b.scss" +} + +@test "admin prettier fix: a directory reaches Prettier as its .js, .ts and .mjs files only" { + local dir="${BATS_TEST_TMPDIR}/src/Administration/Resources/app/administration/src/app/component" + mkdir -p "${dir}" + touch "${dir}/a.js" "${dir}/b.json" "${dir}/c.scss" "${dir}/d.md" "${dir}/e.vue" "${dir}/f.ts" "${dir}/g.mjs" + tool_prettier_fix '{"paths":["src/app/component/"]}' > /dev/null + run js_execute_in_env native "$(grep '^npm exec --no -- prettier ' "${FAKE_CALL_LOG}")" + assert_success + assert_line '[src/app/component/**/*.{js,ts,mjs}]' + run grep '^match:' <<< "${output}" + assert_output "match:src/app/component/a.js +match:src/app/component/f.ts +match:src/app/component/g.mjs" +} + +@test "admin prettier check: a literal file path passes through unchanged" { + run tool_prettier_check '{"paths":["extension-tooling/index.mjs"]}' + assert_success + assert_line 'npm exec --no -- prettier --check "extension-tooling/index.mjs"' +} + +# Under ddev `ddev exec` re-parses the command in the container's +# bash and leaves a value without space, quote or "#" unquoted, so the bash +# there would expand a directory's glob before the tool sees it. +# A directory named like a file is still a directory: Stylelint and Prettier +# given it bare would read every file in it. +@test "admin stylelint check: a directory named like a .scss file reaches Stylelint as its .scss files" { + mkdir -p "${BATS_TEST_TMPDIR}/src/Administration/Resources/app/administration/src/legacy.scss" + run tool_stylelint_check '{"paths":["src/legacy.scss"]}' + assert_success + assert_line 'npm exec --no -- stylelint --cache -f string "src/legacy.scss/**/*.scss"' +} + +@test "admin prettier check: a directory named like a .mjs file reaches Prettier as its .js, .ts and .mjs files" { + mkdir -p "${BATS_TEST_TMPDIR}/src/Administration/Resources/app/administration/src/lib.mjs" + run tool_prettier_check '{"paths":["src/lib.mjs"]}' + assert_success + assert_line 'npm exec --no -- prettier --check "src/lib.mjs/**/*.{js,ts,mjs}"' +} + +@test "admin prettier check: refuses when the directory test itself fails" { + FAKE_DIRECTORY_PROBE_ERROR='Error response from daemon: container shopware-web-1 is not running' + run tool_prettier_check '{"paths":["src/app/main.ts"]}' + assert_failure + assert_output --partial "could not check which of them are directories; the probe exited with 1. Probe output: Error response from daemon" +} + +@test "admin stylelint fix: a directory path is refused under ddev on a worktree" { + _as_ddev_worktree_call + run tool_stylelint_fix '{"paths":["src/app/assets/"]}' + assert_failure + assert_output --partial "under ddev these paths would reach Stylelint as glob patterns" +} + +@test "admin prettier fix: a directory path is refused under ddev on a worktree" { + _as_ddev_worktree_call + run tool_prettier_fix '{"paths":["src/app/component/"]}' + assert_failure + assert_output --partial "under ddev these paths would reach Prettier as glob patterns" +} + +@test "admin stylelint fix: a glob path is refused under ddev on a worktree" { + _as_ddev_worktree_call + run tool_stylelint_fix '{"paths":["src/**/*.scss"]}' + assert_failure + assert_output --partial "these paths would reach Stylelint as glob patterns the container shell expands first: src/**/*.scss" +} + +# ddev double-quotes an argument holding a space, so the container shell leaves +# such a pattern to Stylelint. +@test "admin stylelint fix: a glob path holding a space still runs under ddev on a worktree" { + _as_ddev_worktree_call + run tool_stylelint_fix '{"paths":["src/my styles/**/*.scss"]}' + assert_success + assert_line 'npm exec --no -- stylelint --cache --fix "src/my styles/**/*.scss"' +} + +@test "admin stylelint fix: a directory path is refused under ddev at the launch root" { + LINT_ENV="ddev" + run tool_stylelint_fix '{"paths":["src/app/assets/"]}' + assert_failure + assert_output --partial "under ddev these paths would reach Stylelint as glob patterns the container shell expands first: src/app/assets/" +} + +@test "admin prettier fix: a file path still runs under ddev on a worktree" { + _as_ddev_worktree_call + run tool_prettier_fix '{"paths":["src/app/main.ts"]}' + assert_success + assert_line 'npm exec --no -- prettier --write --cache "src/app/main.ts"' +} + +# --- Admin Stylelint and Prettier: the built commands executed through each environment wrapper --- + +_admin_command() { + "tool_$1" "{\"paths\":[\"$2\"]}" > /dev/null + grep "^npm exec --no -- ${1%%_*} " "${FAKE_CALL_LOG}" +} + +_assert_admin_stylelint_check_runs_in_package_dir() { + run js_execute_in_env "$1" "$(_admin_command stylelint_check "src/app/my dir/base.scss")" + assert_success + assert_output "cwd=${BATS_TEST_TMPDIR}/src/Administration/Resources/app/administration +[--cache] +[-f] +[string] +[src/app/my dir/base.scss]" +} + +_assert_admin_prettier_check_runs_in_package_dir() { + run js_execute_in_env "$1" "$(_admin_command prettier_check "src/app/my dir/main.ts")" + assert_success + assert_output "cwd=${BATS_TEST_TMPDIR}/src/Administration/Resources/app/administration +[--check] +[src/app/my dir/main.ts]" +} + +_admin_prettier_probe_command() { + tool_prettier_check '{"paths":["src/app/main.ts"]}' > /dev/null + grep '^npm exec --no -c "test -x node_modules/.bin/prettier ' "${FAKE_CALL_LOG}" +} + +# The package installs prettier, so the probe finds it and prints nothing. +_assert_admin_prettier_probe_finds_binary() { + run js_execute_in_env "$1" "$(_admin_prettier_probe_command)" + assert_success + assert_output "" +} + +# The package installs no prettier, so the probe misses. +_assert_admin_prettier_probe_reports_missing_binary() { + JS_FAKE_BINARIES="eslint stylelint" + run js_execute_in_env "$1" "$(_admin_prettier_probe_command)" + assert_failure 3 + assert_output "LOCAL_BINARY_MISSING_IN +${BATS_TEST_TMPDIR}/src/Administration/Resources/app/administration" +} + +@test "admin stylelint command: runs in the package dir with its paths intact under native" { + _assert_admin_stylelint_check_runs_in_package_dir native +} + +@test "admin stylelint command: runs in the package dir with its paths intact under docker" { + _assert_admin_stylelint_check_runs_in_package_dir docker +} + +@test "admin stylelint command: runs in the package dir with its paths intact under docker-compose" { + _assert_admin_stylelint_check_runs_in_package_dir docker-compose +} + +@test "admin stylelint command: runs in the package dir with its paths intact under vagrant" { + _assert_admin_stylelint_check_runs_in_package_dir vagrant +} + +@test "admin stylelint command: runs in the package dir with its paths intact under ddev" { + _assert_admin_stylelint_check_runs_in_package_dir ddev +} + +@test "admin stylelint command: runs in the package dir with its paths intact under ddev on a worktree" { + _assert_admin_stylelint_check_runs_in_package_dir ddev-worktree +} + +@test "admin prettier command: runs in the package dir with its paths intact under native" { + _assert_admin_prettier_check_runs_in_package_dir native +} + +@test "admin prettier command: runs in the package dir with its paths intact under docker" { + _assert_admin_prettier_check_runs_in_package_dir docker +} + +@test "admin prettier command: runs in the package dir with its paths intact under docker-compose" { + _assert_admin_prettier_check_runs_in_package_dir docker-compose +} + +@test "admin prettier command: runs in the package dir with its paths intact under vagrant" { + _assert_admin_prettier_check_runs_in_package_dir vagrant +} + +@test "admin prettier command: runs in the package dir with its paths intact under ddev" { + _assert_admin_prettier_check_runs_in_package_dir ddev +} + +@test "admin prettier command: runs in the package dir with its paths intact under ddev on a worktree" { + _assert_admin_prettier_check_runs_in_package_dir ddev-worktree +} + +@test "admin local-binary probe: finds the package's prettier under native" { + _assert_admin_prettier_probe_finds_binary native +} + +@test "admin local-binary probe: finds the package's prettier under docker" { + _assert_admin_prettier_probe_finds_binary docker +} + +@test "admin local-binary probe: finds the package's prettier under docker-compose" { + _assert_admin_prettier_probe_finds_binary docker-compose +} + +@test "admin local-binary probe: finds the package's prettier under vagrant" { + _assert_admin_prettier_probe_finds_binary vagrant +} + +@test "admin local-binary probe: finds the package's prettier under ddev" { + _assert_admin_prettier_probe_finds_binary ddev +} + +@test "admin local-binary probe: finds the package's prettier under ddev on a worktree" { + _assert_admin_prettier_probe_finds_binary ddev-worktree +} + +@test "admin local-binary probe: reports the missing prettier and its directory under native" { + _assert_admin_prettier_probe_reports_missing_binary native +} + +@test "admin local-binary probe: reports the missing prettier and its directory under docker" { + _assert_admin_prettier_probe_reports_missing_binary docker +} + +@test "admin local-binary probe: reports the missing prettier and its directory under docker-compose" { + _assert_admin_prettier_probe_reports_missing_binary docker-compose +} + +@test "admin local-binary probe: reports the missing prettier and its directory under vagrant" { + _assert_admin_prettier_probe_reports_missing_binary vagrant +} + +@test "admin local-binary probe: reports the missing prettier and its directory under ddev" { + _assert_admin_prettier_probe_reports_missing_binary ddev +} + +@test "admin local-binary probe: reports the missing prettier and its directory under ddev on a worktree" { + _assert_admin_prettier_probe_reports_missing_binary ddev-worktree +} + +# --- Every tool with a paths parameter, against the trunk package.json --- + +# A path-scoped route that names an npm script Shopware does not define refuses +# every call on a real checkout. The tool list comes from tools.json, so a tool +# that gains a paths parameter is covered without an edit here. +@test "admin tools: no path-scoped call names an npm script the trunk package.json lacks" { + local -a tools=() + local tool + while IFS= read -r tool; do + tools+=("${tool}") + done < <(jq -r '.tools[] | select(.inputSchema.properties.paths) | .name' \ + "${PLUGIN_DIR}/mcp-server-js-admin/tools.json") + + local refused="" + for tool in "${tools[@]}"; do + "tool_${tool}" '{"paths":["src/app/main.ts"]}' > "${BATS_TEST_TMPDIR}/out.txt" 2>&1 \ + || refused="${refused} ${tool}: $(cat "${BATS_TEST_TMPDIR}/out.txt")" + done + + local line script undefined="" + while IFS= read -r line; do + script="${line#npm run }" + script="${script%% *}" + if [[ "$(shopware_trunk_script_body administration "${script}")" == "{}" ]]; then + undefined="${undefined} ${script}" + fi + done < <(grep '^npm run ' "${FAKE_CALL_LOG}" || true) + + # An empty enumeration would pass the loops above without running a tool. + assert [ "${#tools[@]}" -ge 6 ] + assert_equal "${refused}" "" + assert_equal "${undefined}" "" } # --- TypeScript --- @@ -467,6 +735,80 @@ JSON assert_output --partial "lint:types" } +# --- Scope config paths reach each tool as one argument --- + +# Every config path holds a space, which splits an unquoted path into two +# arguments when the wrapped command is parsed. +_set_spaced_scope_configs() { + cat > "${LINT_CONFIG_FILE}" <<'JSON' +{"environment":"native","scopes":{"plugin-x":{"cwd":"custom/plugins/X", + "eslint":{"config":"my conf.mjs"}, + "stylelint":{"config":"my conf.json"}, + "prettier":{"config":"my conf.json"}, + "tsc":{"config":"my tsconfig.json"}}}} +JSON +} + +@test "admin eslint check: a scope config path with a space stays one argument" { + _set_spaced_scope_configs + run tool_eslint_check '{"scope":"plugin-x"}' + assert_success + assert_line 'npm run lint -- -f stylish --config "my conf.mjs"' +} + +@test "admin eslint fix: a scope config path with a space stays one argument" { + _set_spaced_scope_configs + run tool_eslint_fix '{"scope":"plugin-x","paths":["src/main.ts"]}' + assert_success + assert_line 'npm exec --no -- eslint --fix --config "my conf.mjs" "src/main.ts"' +} + +@test "admin eslint check: a scope config path with a single quote is refused before anything runs" { + cat > "${LINT_CONFIG_FILE}" <<'JSON' +{"environment":"native","scopes":{"plugin-x":{"cwd":"custom/plugins/X","eslint":{"config":"it's.mjs"}}}} +JSON + run tool_eslint_check '{"scope":"plugin-x"}' + assert_failure + assert_output --partial "Refusing to run: ESLint configuration \"it's.mjs\" contains a single quote" + run cat "${FAKE_CALL_LOG}" + refute_output --partial "npm run lint" +} + +@test "admin stylelint check: a scope config path with a space stays one argument" { + _set_spaced_scope_configs + run tool_stylelint_check '{"scope":"plugin-x","paths":["src/scss/base.scss"]}' + assert_success + assert_line 'npm exec --no -- stylelint --cache -f string --config "my conf.json" "src/scss/base.scss"' +} + +@test "admin stylelint fix: a scope config path with a space stays one argument" { + _set_spaced_scope_configs + run tool_stylelint_fix '{"scope":"plugin-x"}' + assert_success + assert_line 'npm run lint:scss-fix -- --config "my conf.json"' +} + +@test "admin prettier check: a scope config path with a space stays one argument without paths" { + _set_spaced_scope_configs + run tool_prettier_check '{"scope":"plugin-x"}' + assert_success + assert_line 'npm run format -- --config "my conf.json"' +} + +@test "admin prettier fix: a scope config path with a space stays one argument with paths" { + _set_spaced_scope_configs + run tool_prettier_fix '{"scope":"plugin-x","paths":["src/main.ts"]}' + assert_success + assert_line 'npm exec --no -- prettier --write --cache --config "my conf.json" "src/main.ts"' +} + +@test "admin tsc check: a scope config path with a space stays one argument" { + _set_spaced_scope_configs + run tool_tsc_check '{"scope":"plugin-x"}' + assert_success + assert_line 'npm run lint:types -- --project "my tsconfig.json"' +} + # --- Lint all / Twig --- @test "admin lint_all: uses npm run lint:all" { @@ -481,30 +823,36 @@ JSON assert_output --partial "npm run lint:twig" } +# A core-only tool ignores default_scope, but worktree_prepare honors it and +# would install into the plugin package instead of the core one. +@test "admin lint_all: a worktree dependency refusal under a plugin default_scope sends worktree_prepare to scope shopware" { + cat > "${LINT_CONFIG_FILE}" <<'JSON' +{"environment":"native","default_scope":"plugin-x","scopes":{"plugin-x":{"cwd":"custom/plugins/X"}}} +JSON + worktree_enter() { WORKTREE_EFFECTIVE_ROOT="${BATS_TEST_TMPDIR}/linked-worktree"; WORKTREE_ENV_WORKDIR=""; } + run tool_lint_all '{}' + assert_failure + assert_output --partial 'call worktree_prepare with scope "shopware"' +} + # --- Jest --- -@test "admin jest: base command routes at jest:base and asks for the JSON report" { +@test "admin jest: runs the unit script and asks for the JSON report" { run tool_jest_run '{}' assert_success - assert_line --index 2 "npm run jest:base -- --json --outputFile=\"${ADMIN_JEST_REPORT_FILE}\"" + assert_line --index 2 "npm run unit -- --json --outputFile=\"${ADMIN_JEST_REPORT_FILE}\"" } -@test "admin jest: default run appends no --ci" { +@test "admin jest: a run prints no script-fallback notice" { run tool_jest_run '{}' assert_success - refute_output --partial "--ci" -} - -@test "admin jest: ci=true appends --ci and still asks for the JSON report" { - run tool_jest_run '{"ci":true}' - assert_success - assert_line --index 2 "npm run jest:base -- --ci --json --outputFile=\"${ADMIN_JEST_REPORT_FILE}\"" + refute_output --partial "Notice:" } @test "admin jest: testPathPatterns flag added when provided" { run tool_jest_run '{"testPathPatterns":"CartService"}' assert_success - assert_line --index 2 --partial 'npm run jest:base -- --testPathPatterns="CartService" --json' + assert_line --index 2 --partial 'npm run unit -- --testPathPatterns="CartService" --json' } @test "admin jest: coverage flag added when coverage=true" { @@ -516,7 +864,7 @@ JSON @test "admin jest: keeps a multi-word test name pattern in one argument" { run tool_jest_run '{"testNamePattern":"adds to cart"}' assert_success - assert_line --index 2 --partial 'npm run jest:base -- --testNamePattern="adds to cart" --json' + assert_line --index 2 --partial 'npm run unit -- --testNamePattern="adds to cart" --json' } @test "admin jest: refuses a test name pattern containing a single quote" { @@ -539,27 +887,6 @@ JSON refute_output --partial "npm run" } -@test "admin jest: falls back to npm run unit when jest:base is absent" { - FAKE_ABSENT_SCRIPTS="jest:base" - run tool_jest_run '{}' - assert_success - assert_line --index 3 "npm run unit -- --json --outputFile=\"${ADMIN_JEST_REPORT_FILE}\"" -} - -@test "admin jest: the jest:base fallback announces that --ci is forced" { - FAKE_ABSENT_SCRIPTS="jest:base" - run tool_jest_run '{}' - assert_success - assert_line --partial "Notice: the npm script \"jest:base\" is unavailable" -} - -@test "admin jest: the jest:base fallback announces the suppressed summary" { - FAKE_ABSENT_SCRIPTS="jest:base" - run tool_jest_run '{}' - assert_success - assert_line --partial "jest-silent-reporter" -} - # --- Jest: the result comes from the JSON report, not the exit code --- @test "admin jest: the counts summary precedes the command output" { @@ -582,7 +909,7 @@ JSON assert_success run cat "${FAKE_CALL_LOG}" assert_line --index 1 "rm -f -- \"${ADMIN_JEST_REPORT_FILE}\"" - assert_line --index 2 "npm run jest:base -- --json --outputFile=\"${ADMIN_JEST_REPORT_FILE}\"" + assert_line --index 2 "npm run unit -- --json --outputFile=\"${ADMIN_JEST_REPORT_FILE}\"" } @test "admin jest: a run that writes no report fails instead of reusing the report left by the previous run" { @@ -608,7 +935,7 @@ JSON run tool_jest_run '{}' assert_failure 1 run cat "${FAKE_CALL_LOG}" - refute_output --partial "npm run jest:base --" + refute_output --partial "npm run unit --" } @test "admin jest: failed tests in the report fail the tool even when the process exited 0" { @@ -664,7 +991,7 @@ JSON @test "admin jest: all tests passed with a non-zero process exit keeps the command output" { FAKE_RUN_EXIT=7 run tool_jest_run '{}' - assert_line --index 3 --partial "npm run jest:base" + assert_line --index 3 --partial "npm run unit" } @test "admin jest: a report that is not JSON propagates the process exit code" { diff --git a/plugin-tests/dev-tooling/mcp_tool_js_storefront.bats b/plugin-tests/dev-tooling/mcp_tool_js_storefront.bats index cda86b1f..cd718eee 100644 --- a/plugin-tests/dev-tooling/mcp_tool_js_storefront.bats +++ b/plugin-tests/dev-tooling/mcp_tool_js_storefront.bats @@ -6,9 +6,8 @@ load 'test_helper/common_setup' PLUGIN_DIR="${REPO_ROOT}/plugins/dev-tooling" -# Answers the `npm pkg get "scripts."` probe with the body the Shopware -# Storefront package.json declares. FAKE_ABSENT_SCRIPTS makes a script look -# undefined; FAKE_BODY_NAME/FAKE_BODY makes one report a different body. +# Answers the `npm pkg get "scripts."` probe from the trunk fixture; see +# shopware_trunk_script_body and the FAKE_* list in common_setup.bash. _fake_script_body() { local name="$1" @@ -21,41 +20,7 @@ _fake_script_body() { return fi - case "${name}" in - eslint:app) - printf '%s\n' '"eslint --no-error-on-unmatched-pattern --report-unused-disable-directives"' ;; - eslint:components) - printf '%s\n' '"cd ../.. && eslint --no-error-on-unmatched-pattern --config ./app/storefront/eslint.config.js --report-unused-disable-directives"' ;; - lint:js) - printf '%s\n' '"npm run lint:js:app && npm run lint:js:components"' ;; - lint:js:fix) - printf '%s\n' '"npm run lint:js:app:fix && npm run lint:js:components:fix"' ;; - stylelint:app) - printf '%s\n' '"stylelint --config stylelint.config.js --cache"' ;; - lint:scss) - printf '%s\n' '"npm run stylelint:app -- ./src/scss"' ;; - lint:scss-fix) - printf '%s\n' '"npm run lint:scss -- --fix"' ;; - jest:base) - printf '%s\n' '"jest --config jest.config.js"' ;; - unit) - # A package that declares jest:base writes "unit" in terms of it. - # A package that does not — the pre-refactor layout the fallback - # route exists for — spells the runner out instead. Keying on - # FAKE_ABSENT_SCRIPTS keeps both configurations describing a - # package.json that could actually exist. - case " ${FAKE_ABSENT_SCRIPTS} " in - *" jest:base "*) printf '%s\n' '"jest --config jest.config.js --ci"' ;; - *) printf '%s\n' '"npm run jest:base -- --ci"' ;; - esac - ;; - unit:components) - printf '%s\n' '"vitest run --config vitest.config.mts"' ;; - unit:components:coverage) - printf '%s\n' '"vitest run --coverage --config vitest.config.mts"' ;; - *) - printf '%s\n' '{}' ;; - esac + shopware_trunk_script_body storefront "${name}" } # Builds a Jest JSON report body carrying the counts a test needs. @@ -71,28 +36,26 @@ setup() { LINT_CONFIG_FILE="${BATS_TEST_TMPDIR}/.mcp-js-tooling.json" echo '{"environment":"native"}' > "${LINT_CONFIG_FILE}" JS_CONTEXT="storefront" + # The FAKE_* variables are listed in common_setup.bash. FAKE_ABSENT_SCRIPTS="" FAKE_BODY_NAME="" FAKE_BODY="" FAKE_PROBE_OUTPUT="" FAKE_PROBE_FILE="${BATS_TEST_TMPDIR}/probe.txt" - # The report path the jest tool uses is modelled as a real file rather than - # a canned answer, so a report left behind by an earlier run and a report - # written by this one are distinguishable: the run writes - # FAKE_REPORT_OUTPUT into the store (unless FAKE_RUN_WRITES_REPORT is 0), - # the delete removes it, and the read returns whatever is there. FAKE_REPORT_OUTPUT="$(_jest_report 13 13 0 1 0)" FAKE_REPORT_STORE="${BATS_TEST_TMPDIR}/jest-report-store.json" FAKE_RUN_WRITES_REPORT=1 - # Records the command that read the report, so a test can assert its shape. FAKE_REPORT_READ_FILE="${BATS_TEST_TMPDIR}/report-read.txt" - # Every wrapped command in order, so a test can assert call sequence. FAKE_CALL_LOG="${BATS_TEST_TMPDIR}/npm-calls.log" FAKE_CLEAR_EXIT=0 FAKE_CLEAR_OUTPUT="" FAKE_RUN_EXIT=0 + FAKE_MISSING_BINARIES="" + FAKE_BINARY_PROBE_ERROR="" + FAKE_DIRECTORY_PROBE_ERROR="" log() { :; } source "${PLUGIN_DIR}/shared/environment.sh" + source "${PLUGIN_DIR}/shared/js_paths.sh" source "${PLUGIN_DIR}/shared/scope.sh" PROJECT_ROOT="${BATS_TEST_TMPDIR}" export PROJECT_ROOT @@ -102,6 +65,11 @@ setup() { exec_npm_command() { local cmd="$1" printf '%s\n' "${cmd}" >> "${FAKE_CALL_LOG}" + local probe_code=0 + js_fake_npm_probe "${cmd}" "/var/www/html/src/Storefront/Resources/app/storefront" || probe_code=$? + if [[ "${probe_code}" -ne "${JS_FAKE_NPM_PROBE_UNHANDLED}" ]]; then + return "${probe_code}" + fi case "${cmd}" in 'npm pkg get "scripts.'*) local name="${cmd#npm pkg get \"scripts.}" @@ -124,6 +92,15 @@ setup() { cat -- "${FAKE_REPORT_STORE}" ;; *) + # npm refuses an undefined script before running anything. + if [[ "${cmd}" == "npm run "* ]]; then + local script="${cmd#npm run }" + script="${script%% *}" + if [[ "$(_fake_script_body "${script}")" == "{}" ]]; then + printf '%s\n' "npm error Missing script: \"${script}\"" + return 1 + fi + fi if [[ "${FAKE_RUN_WRITES_REPORT}" == "1" ]]; then printf '%s\n' "${FAKE_REPORT_OUTPUT}" > "${FAKE_REPORT_STORE}" fi @@ -147,9 +124,25 @@ teardown() { SCOPE_JS_SUBDIR FAKE_ABSENT_SCRIPTS FAKE_BODY_NAME FAKE_BODY FAKE_PROBE_OUTPUT \ FAKE_PROBE_FILE FAKE_REPORT_OUTPUT FAKE_REPORT_STORE FAKE_RUN_WRITES_REPORT \ FAKE_REPORT_READ_FILE FAKE_CALL_LOG FAKE_CLEAR_EXIT FAKE_CLEAR_OUTPUT FAKE_RUN_EXIT \ - PROJECT_ROOT DEV_TOOLING_STATE_FILE + FAKE_MISSING_BINARIES FAKE_BINARY_PROBE_ERROR FAKE_DIRECTORY_PROBE_ERROR PROJECT_ROOT DEV_TOOLING_STATE_FILE +} + +storefront_tool_refuses_string_section() { + local function_name="$1" section="$2" + printf '{"environment":"native","scopes":{"plugin-x":{"cwd":"custom/plugins/X","%s":"invalid"}}}\n' "${section}" > "${LINT_CONFIG_FILE}" + run "${function_name}" '{"scope":"plugin-x"}' + assert_failure + assert_output --partial 'Config error: jq could not evaluate' + assert_output --partial 'Cannot index string' + [ ! -e "${FAKE_CALL_LOG}" ] } +bats_test_function --description "storefront eslint_check: string section refuses without executing" -- storefront_tool_refuses_string_section tool_eslint_check eslint +bats_test_function --description "storefront eslint_fix: string section refuses without executing" -- storefront_tool_refuses_string_section tool_eslint_fix eslint +bats_test_function --description "storefront stylelint_check: string section refuses without executing" -- storefront_tool_refuses_string_section tool_stylelint_check stylelint +bats_test_function --description "storefront stylelint_fix: string section refuses without executing" -- storefront_tool_refuses_string_section tool_stylelint_fix stylelint +bats_test_function --description "storefront jest_run: string section refuses without executing" -- storefront_tool_refuses_string_section tool_jest_run jest + # --- ESLint: no paths runs the aggregate script bare --- @test "storefront eslint check: no paths runs lint:js bare" { @@ -164,37 +157,49 @@ teardown() { assert_line "npm run lint:js:fix" } -# --- ESLint: tree routing and rebasing --- +# --- ESLint: paths run the package's own binary, one call per tree --- -@test "storefront eslint check: app-tree path uses eslint:app rebased to the package dir" { +@test "storefront eslint check: app-tree path runs the local eslint rebased to the package dir" { run tool_eslint_check '{"paths":["src/Storefront/Resources/app/storefront/src/plugin/cart.plugin.js"]}' assert_success - assert_output --partial 'npm run eslint:app -- -f stylish "src/plugin/cart.plugin.js"' + assert_line 'npm exec --no -- eslint --no-error-on-unmatched-pattern --report-unused-disable-directives -f stylish "src/plugin/cart.plugin.js"' +} + +@test "storefront eslint fix: app-tree path runs the local eslint with --fix" { + run tool_eslint_fix '{"paths":["src/plugin/cart.plugin.js"]}' + assert_success + assert_line 'npm exec --no -- eslint --no-error-on-unmatched-pattern --report-unused-disable-directives --fix "src/plugin/cart.plugin.js"' } @test "storefront eslint check: tree-relative app path is passed through unchanged" { run tool_eslint_check '{"paths":["build/webpack/config.js"]}' assert_success - assert_output --partial 'npm run eslint:app -- -f stylish "build/webpack/config.js"' + assert_output --partial '-f stylish "build/webpack/config.js"' } -@test "storefront eslint check: components path uses eslint:components rebased to the resources dir" { +@test "storefront eslint check: components path runs from ../.. with the components config" { run tool_eslint_check '{"paths":["src/Storefront/Resources/views/components/checkout/cart.js"]}' assert_success - assert_output --partial 'npm run eslint:components -- -f stylish "views/components/checkout/cart.js"' + assert_line 'npm exec --no -c "cd ../.. && eslint --no-error-on-unmatched-pattern --report-unused-disable-directives --config ./app/storefront/eslint.config.js -f stylish \"views/components/checkout/cart.js\""' +} + +@test "storefront eslint fix: components path runs from ../.. with --fix" { + run tool_eslint_fix '{"paths":["views/components/checkout/cart.js"]}' + assert_success + assert_line 'npm exec --no -c "cd ../.. && eslint --no-error-on-unmatched-pattern --report-unused-disable-directives --config ./app/storefront/eslint.config.js --fix \"views/components/checkout/cart.js\""' } @test "storefront eslint check: tree-relative components path keeps its views/components prefix" { run tool_eslint_check '{"paths":["views/components/checkout/cart.js"]}' assert_success - assert_output --partial 'npm run eslint:components -- -f stylish "views/components/checkout/cart.js"' + assert_output --partial '-f stylish \"views/components/checkout/cart.js\""' } -@test "storefront eslint check: mixed paths run both the app and components trees" { +@test "storefront eslint check: mixed paths run each tree on its own paths only" { run tool_eslint_check '{"paths":["src/plugin/cart.plugin.js","views/components/checkout/cart.js"]}' assert_success - assert_output --partial 'npm run eslint:app -- -f stylish "src/plugin/cart.plugin.js"' - assert_output --partial 'npm run eslint:components -- -f stylish "views/components/checkout/cart.js"' + assert_line 'npm exec --no -- eslint --no-error-on-unmatched-pattern --report-unused-disable-directives -f stylish "src/plugin/cart.plugin.js"' + assert_line 'npm exec --no -c "cd ../.. && eslint --no-error-on-unmatched-pattern --report-unused-disable-directives --config ./app/storefront/eslint.config.js -f stylish \"views/components/checkout/cart.js\""' } @test "storefront eslint check: json format applied when paths are supplied" { @@ -203,56 +208,268 @@ teardown() { assert_output --partial "-f json" } -@test "storefront eslint fix: appends --fix ahead of the paths" { - run tool_eslint_fix '{"paths":["src/plugin/cart.plugin.js"]}' +_set_eslint_scope() { + cat > "${LINT_CONFIG_FILE}" <<'JSON' +{"environment":"native","scopes":{"plugin-x":{"cwd":"custom/plugins/X","eslint":{"config":"eslint.config.mjs"}}}} +JSON +} + +@test "storefront eslint check: an app path under a scope runs with the scope config" { + _set_eslint_scope + run tool_eslint_check '{"scope":"plugin-x","paths":["src/main.js"]}' + assert_success + assert_line 'npm exec --no -- eslint --no-error-on-unmatched-pattern --report-unused-disable-directives -f stylish --config "eslint.config.mjs" "src/main.js"' +} + +@test "storefront eslint check: a components path under a scope refuses" { + _set_eslint_scope + run tool_eslint_check '{"scope":"plugin-x","paths":["views/components/checkout/cart.js"]}' + assert_failure + assert_output --partial 'scope "plugin-x" runs in "custom/plugins/X", but these paths route to the core Storefront components tree' +} + +@test "storefront eslint fix: a refused components path under a scope runs nothing" { + _set_eslint_scope + run tool_eslint_fix '{"scope":"plugin-x","paths":["src/main.js","views/components/checkout/cart.js"]}' + assert_failure + run cat "${FAKE_CALL_LOG}" + refute_output --partial "npm exec" +} + +# The scope runs in the plugin root, so a plugin's own storefront tree is a path +# below that root and gets no rebase onto the core package directory. +@test "storefront eslint check: a repo-root path under the scope cwd keeps its path below the plugin root" { + _set_eslint_scope + run tool_eslint_check '{"scope":"plugin-x","paths":["custom/plugins/X/src/Resources/app/storefront/src/x.js"]}' assert_success - assert_output --partial 'npm run eslint:app -- --fix "src/plugin/cart.plugin.js"' + assert_line --regexp '^npm exec --no -- eslint .* "src/Resources/app/storefront/src/x\.js"$' } -# --- ESLint: fallback and hard failures --- +# Every config path holds a space, which splits an unquoted path into two +# arguments when the wrapped command is parsed. +_set_spaced_scope_configs() { + cat > "${LINT_CONFIG_FILE}" <<'JSON' +{"environment":"native","scopes":{"plugin-x":{"cwd":"custom/plugins/X", + "eslint":{"config":"my conf.mjs"}, + "stylelint":{"config":"my conf.json"}}}} +JSON +} + +@test "storefront eslint check: a scope config path with a space stays one argument" { + _set_spaced_scope_configs + run tool_eslint_check '{"scope":"plugin-x","paths":["src/main.js"]}' + assert_success + assert_line 'npm exec --no -- eslint --no-error-on-unmatched-pattern --report-unused-disable-directives -f stylish --config "my conf.mjs" "src/main.js"' +} -@test "storefront eslint check: refuses a path-scoped app-tree run when eslint:app is absent" { - FAKE_ABSENT_SCRIPTS="eslint:app" +@test "storefront eslint fix: a scope config path with a space stays one argument" { + _set_spaced_scope_configs + run tool_eslint_fix '{"scope":"plugin-x","paths":["src/main.js"]}' + assert_success + assert_line 'npm exec --no -- eslint --no-error-on-unmatched-pattern --report-unused-disable-directives --fix --config "my conf.mjs" "src/main.js"' +} + +@test "storefront stylelint check: a scope config path with a space stays one argument" { + _set_spaced_scope_configs + run tool_stylelint_check '{"scope":"plugin-x","paths":["src/scss/base.scss"]}' + assert_success + assert_line 'npm exec --no -- stylelint --cache -f string --config "my conf.json" "src/scss/base.scss"' +} + +@test "storefront stylelint fix: a scope config path with a space stays one argument" { + _set_spaced_scope_configs + run tool_stylelint_fix '{"scope":"plugin-x","paths":["src/scss/base.scss"]}' + assert_success + assert_line 'npm exec --no -- stylelint --cache --config "my conf.json" --fix "src/scss/base.scss"' +} + +@test "storefront eslint check: refuses with paths when the package has no local eslint" { + FAKE_MISSING_BINARIES="eslint" run tool_eslint_check '{"paths":["src/plugin/cart.plugin.js"]}' assert_failure - assert_output --partial "Refusing to lint the app tree with paths" - assert_output --partial '"eslint:app"' + assert_output --partial "\"node_modules/.bin/eslint\" is not installed in the package directory \"/var/www/html/src/Storefront/Resources/app/storefront\"" } -@test "storefront eslint check: refuses a path-scoped components-tree run when eslint:components is absent" { - FAKE_ABSENT_SCRIPTS="eslint:components" - run tool_eslint_check '{"paths":["views/components/checkout/cart.js"]}' +@test "storefront eslint fix: runs neither eslint nor the aggregate when the local eslint is missing" { + FAKE_MISSING_BINARIES="eslint" + run tool_eslint_fix '{"paths":["src/plugin/cart.plugin.js","views/components/checkout/cart.js"]}' assert_failure - assert_output --partial "Refusing to lint the components tree with paths" - assert_output --partial '"eslint:components"' + run cat "${FAKE_CALL_LOG}" + refute_output --partial "eslint --no-error-on-unmatched-pattern" + refute_output --partial "npm run" } -@test "storefront eslint check: never substitutes the lint:js aggregate even when it would accept arguments" { - FAKE_ABSENT_SCRIPTS="eslint:app" - FAKE_BODY_NAME="lint:js" - FAKE_BODY="eslint --no-error-on-unmatched-pattern" +@test "storefront eslint check: a probe that fails before testing is not reported as a missing binary" { + FAKE_BINARY_PROBE_ERROR='Error response from daemon: container shopware-web-1 is not running' run tool_eslint_check '{"paths":["src/plugin/cart.plugin.js"]}' assert_failure - assert_output --partial 'The aggregate "lint:js" script is not a substitute' - refute_output --partial "npm run" + assert_output --partial "could not check whether the package's own eslint binary is installed; the probe exited with 1. Probe output: Error response from daemon" + refute_output --partial "is not installed" } @test "storefront eslint fix: names lint:js:fix as the aggregate it will not substitute" { - FAKE_ABSENT_SCRIPTS="eslint:app" + FAKE_MISSING_BINARIES="eslint" run tool_eslint_fix '{"paths":["src/plugin/cart.plugin.js"]}' assert_failure - assert_output --partial 'The aggregate "lint:js:fix" script is not a substitute' + assert_output --partial 'the aggregate "lint:js:fix" script is not a substitute' } -@test "storefront eslint check: fails hard when the selected script cannot take arguments" { - FAKE_BODY_NAME="eslint:app" - FAKE_BODY="a && (cd .. && b)" - run tool_eslint_check '{"paths":["src/plugin/cart.plugin.js"]}' - assert_failure - assert_output --partial "eslint:app" - assert_output --partial "cannot take appended arguments" +# --- ESLint: the built commands executed through each environment wrapper --- + +_components_check_command() { + tool_eslint_check '{"paths":["views/components/my dir/cart.js"]}' > /dev/null + grep '^npm exec --no -c "cd ../.. ' "${FAKE_CALL_LOG}" +} + +_assert_components_run_from_resources() { + assert_success + assert_output "cwd=${BATS_TEST_TMPDIR}/src/Storefront/Resources +[--no-error-on-unmatched-pattern] +[--report-unused-disable-directives] +[--config] +[./app/storefront/eslint.config.js] +[-f] +[stylish] +[views/components/my dir/cart.js]" +} + +@test "storefront eslint components command: runs from ../.. with its paths intact under native" { + run js_execute_in_env native "$(_components_check_command)" + _assert_components_run_from_resources +} + +@test "storefront eslint components command: runs from ../.. with its paths intact under docker" { + run js_execute_in_env docker "$(_components_check_command)" + _assert_components_run_from_resources +} + +@test "storefront eslint components command: runs from ../.. with its paths intact under docker-compose" { + run js_execute_in_env docker-compose "$(_components_check_command)" + _assert_components_run_from_resources +} + +@test "storefront eslint components command: runs from ../.. with its paths intact under vagrant" { + run js_execute_in_env vagrant "$(_components_check_command)" + _assert_components_run_from_resources +} + +@test "storefront eslint components command: runs from ../.. with its paths intact under ddev" { + run js_execute_in_env ddev "$(_components_check_command)" + _assert_components_run_from_resources +} + +@test "storefront eslint components command: runs from ../.. with its paths intact under ddev on a worktree" { + run js_execute_in_env ddev-worktree "$(_components_check_command)" + _assert_components_run_from_resources +} + +# --- Stylelint: the built commands executed through each environment wrapper --- + +_stylelint_probe_command() { + tool_stylelint_check '{"paths":["src/scss/base.scss"]}' > /dev/null + grep '^npm exec --no -c "test -x node_modules/.bin/stylelint ' "${FAKE_CALL_LOG}" +} + +_stylelint_check_command() { + tool_stylelint_check '{"paths":["src/scss/my dir/base.scss"]}' > /dev/null + grep '^npm exec --no -- stylelint ' "${FAKE_CALL_LOG}" +} + +# The package installs no stylelint, so the probe misses. +_assert_probe_reports_missing_stylelint() { + JS_FAKE_BINARIES="eslint" + run js_execute_in_env "$1" "$(_stylelint_probe_command)" + assert_failure 3 + assert_output "LOCAL_BINARY_MISSING_IN +${BATS_TEST_TMPDIR}/src/Storefront/Resources/app/storefront" +} + +_assert_stylelint_check_runs_in_package_dir() { + run js_execute_in_env "$1" "$(_stylelint_check_command)" + assert_success + assert_output "cwd=${BATS_TEST_TMPDIR}/src/Storefront/Resources/app/storefront +[--config] +[stylelint.config.js] +[--cache] +[-f] +[string] +[src/scss/my dir/base.scss]" +} + +@test "storefront local-binary probe: reports the missing stylelint and its directory under native" { + _assert_probe_reports_missing_stylelint native +} + +@test "storefront local-binary probe: reports the missing stylelint and its directory under docker" { + _assert_probe_reports_missing_stylelint docker +} + +@test "storefront local-binary probe: reports the missing stylelint and its directory under docker-compose" { + _assert_probe_reports_missing_stylelint docker-compose +} + +@test "storefront local-binary probe: reports the missing stylelint and its directory under vagrant" { + _assert_probe_reports_missing_stylelint vagrant +} + +@test "storefront local-binary probe: reports the missing stylelint and its directory under ddev" { + _assert_probe_reports_missing_stylelint ddev +} + +@test "storefront local-binary probe: reports the missing stylelint and its directory under ddev on a worktree" { + _assert_probe_reports_missing_stylelint ddev-worktree +} + +@test "storefront stylelint command: runs in the package dir with its paths intact under native" { + _assert_stylelint_check_runs_in_package_dir native +} + +@test "storefront stylelint command: runs in the package dir with its paths intact under docker" { + _assert_stylelint_check_runs_in_package_dir docker +} + +@test "storefront stylelint command: runs in the package dir with its paths intact under docker-compose" { + _assert_stylelint_check_runs_in_package_dir docker-compose +} + +@test "storefront stylelint command: runs in the package dir with its paths intact under vagrant" { + _assert_stylelint_check_runs_in_package_dir vagrant +} + +@test "storefront stylelint command: runs in the package dir with its paths intact under ddev" { + _assert_stylelint_check_runs_in_package_dir ddev } +@test "storefront stylelint command: runs in the package dir with its paths intact under ddev on a worktree" { + _assert_stylelint_check_runs_in_package_dir ddev-worktree +} + +@test "storefront stylelint check: a directory reaches Stylelint as its .scss and .css files only" { + local dir="${BATS_TEST_TMPDIR}/src/Storefront/Resources/app/storefront/src/sty" + mkdir -p "${dir}/nested" + touch "${dir}/a.scss" "${dir}/nested/b.css" "${dir}/e.js" "${dir}/f.json" "${dir}/g.twig" "${dir}/h.md" "${dir}/notes.txt" + tool_stylelint_check '{"paths":["src/sty/"]}' > /dev/null + run js_execute_in_env native "$(grep '^npm exec --no -- stylelint ' "${FAKE_CALL_LOG}")" + assert_success + assert_line '[src/sty/**/*.{scss,css}]' + run grep '^match:' <<< "${output}" + assert_output "match:src/sty/a.scss +match:src/sty/nested/b.css" +} + +@test "storefront eslint app command: runs in the package dir with its paths intact under ddev on a worktree" { + tool_eslint_check '{"paths":["src/my plugin/cart.plugin.js"]}' > /dev/null + run js_execute_in_env ddev-worktree "$(grep '^npm exec --no -- eslint ' "${FAKE_CALL_LOG}")" + assert_success + assert_output "cwd=${BATS_TEST_TMPDIR}/src/Storefront/Resources/app/storefront +[--no-error-on-unmatched-pattern] +[--report-unused-disable-directives] +[-f] +[stylish] +[src/my plugin/cart.plugin.js]" +} + + @test "storefront eslint check: refuses to lint a path that does not exist" { FAKE_PROBE_OUTPUT="MISSING:src/gone.js" run tool_eslint_check '{"paths":["src/gone.js"]}' @@ -280,7 +497,7 @@ teardown() { @test "storefront eslint check: keeps a path containing a space in one argument" { run tool_eslint_check '{"paths":["src/plugin/cart plugin.js"]}' assert_success - assert_output --partial 'npm run eslint:app -- -f stylish "src/plugin/cart plugin.js"' + assert_output --partial '-f stylish "src/plugin/cart plugin.js"' } @test "storefront eslint check: refuses a path containing a single quote" { @@ -340,50 +557,79 @@ JSON refute_output --partial "--fix" } -# --- Stylelint: paths route at the target-less base script --- +# --- Stylelint: paths run the package's own binary as the only targets --- -@test "storefront stylelint check: paths route at stylelint:app as the only targets" { +@test "storefront stylelint check: paths run the local stylelint with the lint:scss flags" { run tool_stylelint_check '{"paths":["src/scss/base.scss"]}' assert_success - assert_line 'npm run stylelint:app -- -f string "src/scss/base.scss"' + assert_line 'npm exec --no -- stylelint --config stylelint.config.js --cache -f string "src/scss/base.scss"' } -@test "storefront stylelint fix: paths route at stylelint:app as the only targets" { +@test "storefront stylelint fix: paths run the local stylelint with --fix" { run tool_stylelint_fix '{"paths":["src/scss/base.scss"]}' assert_success - assert_line 'npm run stylelint:app -- --fix "src/scss/base.scss"' + assert_line 'npm exec --no -- stylelint --config stylelint.config.js --cache --fix "src/scss/base.scss"' } -@test "storefront stylelint fix: paths route carries --fix, which the base script body lacks" { +@test "storefront stylelint fix: a path-scoped run never reaches the aggregate fix script" { run tool_stylelint_fix '{"paths":["src/scss/base.scss"]}' assert_success - assert_output --partial "-- --fix " + refute_output --partial "lint:scss-fix" } -@test "storefront stylelint check: paths route carries no --fix" { - run tool_stylelint_check '{"paths":["src/scss/base.scss"]}' +# A second --config is refused, so the scoped one replaces the package's. +@test "storefront stylelint fix: a scoped config replaces stylelint.config.js" { + _use_stylelint_scope_config + run tool_stylelint_fix '{"scope":"plugin-x","paths":["src/scss/base.scss"]}' assert_success - refute_output --partial "--fix" + assert_line 'npm exec --no -- stylelint --cache --config ".stylelintrc.plugin" --fix "src/scss/base.scss"' } -@test "storefront stylelint fix: a path-scoped run never reaches the aggregate fix script" { - run tool_stylelint_fix '{"paths":["src/scss/base.scss"]}' +@test "storefront stylelint fix: a directory path is refused under ddev on a worktree" { + _as_ddev_worktree_call + run tool_stylelint_fix '{"paths":["src/scss/"]}' + assert_failure + assert_output --partial "under ddev these paths would reach Stylelint as glob patterns" +} + +@test "storefront stylelint fix: a directory path is refused under ddev at the launch root" { + LINT_ENV="ddev" + run tool_stylelint_fix '{"paths":["src/scss/"]}' + assert_failure + assert_output --partial "under ddev these paths would reach Stylelint as glob patterns" +} + +@test "storefront stylelint check: a directory named like a .css file reaches Stylelint as its .scss and .css files" { + mkdir -p "${BATS_TEST_TMPDIR}/src/Storefront/Resources/app/storefront/src/legacy.css" + run tool_stylelint_check '{"paths":["src/legacy.css"]}' assert_success - refute_output --partial "lint:scss-fix" + assert_line 'npm exec --no -- stylelint --config stylelint.config.js --cache -f string "src/legacy.css/**/*.{scss,css}"' } -@test "storefront stylelint fix: fails when stylelint:app is absent and paths were supplied" { - FAKE_ABSENT_SCRIPTS="stylelint:app" + +@test "storefront stylelint check: a scope without a Stylelint config names no --config" { + cat > "${LINT_CONFIG_FILE}" <<'JSON' +{"environment":"native","scopes":{"plugin-x":{"cwd":"custom/plugins/X"}}} +JSON + run tool_stylelint_check '{"scope":"plugin-x","paths":["src/scss/base.scss"]}' + assert_success + assert_line 'npm exec --no -- stylelint --cache -f string "src/scss/base.scss"' +} + +@test "storefront stylelint fix: refuses with paths when the package has no local stylelint" { + FAKE_MISSING_BINARIES="stylelint" run tool_stylelint_fix '{"paths":["src/scss/base.scss"]}' assert_failure - assert_output --partial "stylelint:app" + assert_output --partial "\"node_modules/.bin/stylelint\" is not installed in the package directory \"/var/www/html/src/Storefront/Resources/app/storefront\"" } -@test "storefront stylelint fix: refuses rather than falling back to the aggregate fix script" { - FAKE_ABSENT_SCRIPTS="stylelint:app" +@test "storefront stylelint fix: runs neither stylelint nor the aggregate when the local stylelint is missing" { + FAKE_MISSING_BINARIES="stylelint" run tool_stylelint_fix '{"paths":["src/scss/base.scss"]}' assert_failure - refute_output --partial "npm run lint:scss" + run cat "${FAKE_CALL_LOG}" + refute_output --partial "-- stylelint" + refute_output --partial "npm run" } @test "storefront stylelint check: refuses a path that holds no file Stylelint reads" { @@ -397,13 +643,7 @@ JSON FAKE_PROBE_OUTPUT="MISSING:src/**/*.scss" run tool_stylelint_check '{"paths":["src/**/*.scss"]}' assert_success - assert_line 'npm run stylelint:app -- -f string "src/**/*.scss"' -} - -@test "storefront stylelint check: a glob path is quoted so the shell cannot expand it" { - run tool_stylelint_check '{"paths":["src/**/*.scss"]}' - assert_success - assert_output --partial '"src/**/*.scss"' + assert_line 'npm exec --no -- stylelint --config stylelint.config.js --cache -f string "src/**/*.scss"' } @test "storefront stylelint check: a literal path alongside a glob still passes the guard" { @@ -413,30 +653,58 @@ JSON assert_output --partial "src/plugin" } +# --- Every tool with a paths parameter, against the trunk package.json --- + +# A path-scoped route that names an npm script Shopware does not define refuses +# every call on a real checkout. The tool list comes from tools.json, so a tool +# that gains a paths parameter is covered without an edit here. +@test "storefront tools: no path-scoped call names an npm script the trunk package.json lacks" { + local -a tools=() + local tool + while IFS= read -r tool; do + tools+=("${tool}") + done < <(jq -r '.tools[] | select(.inputSchema.properties.paths) | .name' \ + "${PLUGIN_DIR}/mcp-server-js-storefront/tools.json") + + local refused="" + for tool in "${tools[@]}"; do + "tool_${tool}" '{"paths":["views/components/checkout/cart.js"]}' > "${BATS_TEST_TMPDIR}/out.txt" 2>&1 \ + || refused="${refused} ${tool}: $(cat "${BATS_TEST_TMPDIR}/out.txt")" + done + + local line script undefined="" + while IFS= read -r line; do + script="${line#npm run }" + script="${script%% *}" + if [[ "$(shopware_trunk_script_body storefront "${script}")" == "{}" ]]; then + undefined="${undefined} ${script}" + fi + done < <(grep '^npm run ' "${FAKE_CALL_LOG}" || true) + + # An empty enumeration would pass the loops above without running a tool. + assert [ "${#tools[@]}" -ge 5 ] + assert_equal "${refused}" "" + assert_equal "${undefined}" "" +} + # --- Jest --- -@test "storefront jest: base command routes at jest:base and asks for the JSON report" { +@test "storefront jest: runs the unit script and asks for the JSON report" { run tool_jest_run '{}' assert_success - assert_line --index 2 "npm run jest:base -- --json --outputFile=\"${STOREFRONT_JEST_REPORT_FILE}\"" + assert_line --index 2 "npm run unit -- --json --outputFile=\"${STOREFRONT_JEST_REPORT_FILE}\"" } -@test "storefront jest: default run appends no --ci" { +@test "storefront jest: a run prints no script-fallback notice" { run tool_jest_run '{}' assert_success - refute_output --partial "--ci" -} - -@test "storefront jest: ci=true appends --ci and still asks for the JSON report" { - run tool_jest_run '{"ci":true}' - assert_success - assert_line --index 2 "npm run jest:base -- --ci --json --outputFile=\"${STOREFRONT_JEST_REPORT_FILE}\"" + refute_output --partial "Notice:" } @test "storefront jest: testPathPatterns flag added when provided" { run tool_jest_run '{"testPathPatterns":"CartPlugin"}' assert_success - assert_line --index 2 --partial 'npm run jest:base -- --testPathPatterns="CartPlugin" --json' + assert_line --index 2 --partial 'npm run unit -- --testPathPatterns="CartPlugin" --json' } @test "storefront jest: coverage flag added when coverage=true" { @@ -448,11 +716,10 @@ JSON @test "storefront jest: keeps a multi-word test name pattern in one argument" { run tool_jest_run '{"testNamePattern":"adds to cart"}' assert_success - assert_line --index 2 --partial 'npm run jest:base -- --testNamePattern="adds to cart" --json' + assert_line --index 2 --partial 'npm run unit -- --testNamePattern="adds to cart" --json' } -@test "storefront jest: fails hard when the unit fallback cannot take arguments" { - FAKE_ABSENT_SCRIPTS="jest:base" +@test "storefront jest: fails hard when the unit script cannot take arguments" { FAKE_BODY_NAME="unit" FAKE_BODY="npm run unit:ci" run tool_jest_run '{"testNamePattern":"adds to cart"}' @@ -460,39 +727,11 @@ JSON assert_output --partial "cannot take appended arguments" } -@test "storefront jest: falls back to npm run unit when jest:base is absent" { - FAKE_ABSENT_SCRIPTS="jest:base" - run tool_jest_run '{}' - assert_success - assert_line --index 3 "npm run unit -- --json --outputFile=\"${STOREFRONT_JEST_REPORT_FILE}\"" -} - -@test "storefront jest: the jest:base fallback announces that --ci is forced" { - FAKE_ABSENT_SCRIPTS="jest:base" - run tool_jest_run '{}' - assert_success - assert_line --partial "Notice: the npm script \"jest:base\" is unavailable" -} - -@test "storefront jest: the jest:base fallback announces the lost new snapshots" { - FAKE_ABSENT_SCRIPTS="jest:base" - run tool_jest_run '{}' +# "unit" passes --ci, under which Jest writes a snapshot only when asked to. +@test "storefront jest: updateSnapshots appends --updateSnapshot to the unit script" { + run tool_jest_run '{"updateSnapshots":true}' assert_success - assert_line --partial "writes no new snapshots where it otherwise would have" -} - -@test "storefront jest: the jest:base fallback states that updateSnapshots still applies" { - FAKE_ABSENT_SCRIPTS="jest:base" - run tool_jest_run '{}' - assert_success - assert_line --partial "\"updateSnapshots\" itself still takes effect" -} - -@test "storefront jest: ci and updateSnapshots together keep --updateSnapshot, which wins over --ci" { - run tool_jest_run '{"ci":true,"updateSnapshots":true}' - assert_success - assert_line --index 2 --partial "--updateSnapshot" - assert_line --index 2 --partial "--ci" + assert_line --index 2 --partial "npm run unit -- --updateSnapshot --json" } @test "storefront jest: refuses a test path pattern containing a single quote" { @@ -513,6 +752,48 @@ JSON assert_output --partial "vitest_run" } +# Writes a plugin-x scope whose jest block is $1, and the scope's jest working +# directory without node_modules. +_set_jest_scope() { + jq -n --argjson jest "$1" \ + '{"environment":"native","scopes":{"plugin-x":{"cwd":"custom/plugins/X","jest":({"cwd":"tests/jest/storefront"} + $jest)}}}' \ + > "${LINT_CONFIG_FILE}" + mkdir -p "${BATS_TEST_TMPDIR}/custom/plugins/X/tests/jest/storefront" +} + +# A plugin's own Jest tree may hold a components/ directory; only the core +# Storefront keeps its component tests apart under Vitest. +@test "storefront jest: a components/ test path pattern runs under a plugin scope" { + _set_jest_scope '{}' + run tool_jest_run '{"scope":"plugin-x","testPathPatterns":"src/components/foo"}' + assert_success + assert_output --partial '--testPathPatterns="src/components/foo"' +} + +@test "storefront jest: a views/components test path pattern is still rejected under a plugin scope" { + _set_jest_scope '{}' + run tool_jest_run '{"scope":"plugin-x","testPathPatterns":"views/components/checkout"}' + assert_failure + assert_output --partial "vitest_run" +} + +@test "storefront jest: a refused test path pattern installs nothing" { + _set_jest_scope '{"install_if_missing":true}' + touch "${FAKE_CALL_LOG}" + run tool_jest_run '{"scope":"plugin-x","testPathPatterns":"a\nb"}' + assert_failure + assert_output --partial "contains a line break" + run cat "${FAKE_CALL_LOG}" + refute_output --partial "npm ci" +} + +@test "storefront jest: a scope env map given as a string is refused" { + _set_jest_scope '{"env":"FOO=1"}' + run tool_jest_run '{"scope":"plugin-x"}' + assert_failure + assert_output --partial 'string ("FOO=1") has no keys' +} + # --- Jest: the result comes from the JSON report, not the exit code --- @test "storefront jest: the counts summary precedes the command output" { @@ -535,7 +816,7 @@ JSON assert_success run cat "${FAKE_CALL_LOG}" assert_line --index 1 "rm -f -- \"${STOREFRONT_JEST_REPORT_FILE}\"" - assert_line --index 2 "npm run jest:base -- --json --outputFile=\"${STOREFRONT_JEST_REPORT_FILE}\"" + assert_line --index 2 "npm run unit -- --json --outputFile=\"${STOREFRONT_JEST_REPORT_FILE}\"" } @test "storefront jest: a run that writes no report fails instead of reusing the report left by the previous run" { @@ -561,7 +842,7 @@ JSON run tool_jest_run '{}' assert_failure 1 run cat "${FAKE_CALL_LOG}" - refute_output --partial "npm run jest:base --" + refute_output --partial "npm run unit --" } @test "storefront jest: failed tests in the report fail the tool even when the process exited 0" { @@ -617,7 +898,7 @@ JSON @test "storefront jest: all tests passed with a non-zero process exit keeps the command output" { FAKE_RUN_EXIT=7 run tool_jest_run '{}' - assert_line --index 3 --partial "npm run jest:base" + assert_line --index 3 --partial "npm run unit" } @test "storefront jest: a report that is not JSON propagates the process exit code" { @@ -698,6 +979,25 @@ $(_jest_report 13 13 0 1 0)" assert_output --partial "do not exist" } +@test "storefront vitest: refuses a plugin scope before running anything" { + _set_jest_scope '{}' + run tool_vitest_run '{"scope":"plugin-x"}' + assert_failure + assert_output --partial 'Refusing to run vitest_run under scope "plugin-x"' + run cat "${FAKE_CALL_LOG}" + refute_output --partial "unit:components" +} + +@test "storefront vitest: a configured default_scope does not move the run out of the project root" { + _set_jest_scope '{}' + jq '.default_scope = "plugin-x"' "${LINT_CONFIG_FILE}" > "${BATS_TEST_TMPDIR}/with-default.json" + mv "${BATS_TEST_TMPDIR}/with-default.json" "${LINT_CONFIG_FILE}" + exec_npm_command() { printf '%s\n' "[scope=${SCOPE_CWD:-}] $1"; } + run tool_vitest_run '{}' + assert_success + assert_line '[scope=] npm run unit:components' +} + # --- ludtwig --- @test "storefront ludtwig check: runs composer ludtwig:storefront" { @@ -725,9 +1025,3 @@ $(_jest_report 13 13 0 1 0)" assert_success assert_output --partial "npm run development" } - -@test "storefront webpack build: watch/hot mode is rejected" { - run tool_webpack_build '{"mode":"hot"}' - assert_failure - assert_output --partial "Watch mode is not supported" -} diff --git a/plugin-tests/dev-tooling/mcp_tool_phpunit.bats b/plugin-tests/dev-tooling/mcp_tool_phpunit.bats index 5bc8a2b2..502dcf38 100644 --- a/plugin-tests/dev-tooling/mcp_tool_phpunit.bats +++ b/plugin-tests/dev-tooling/mcp_tool_phpunit.bats @@ -23,12 +23,21 @@ teardown() { assert_output --partial "vendor/bin/phpunit" } +@test "phpunit: a string top-level config section refuses the call" { + printf '%s\n' '{"environment":"native","phpunit":"invalid"}' > "${LINT_CONFIG_FILE}" + run tool_phpunit_run '{}' + assert_failure + assert_output --partial 'Config error: jq could not evaluate .phpunit.testsuite' + refute_output --partial 'vendor/bin/phpunit' +} + @test "phpunit: testsuite flag added when testsuite provided" { run tool_phpunit_run '{"testsuite":"unit"}' assert_success assert_output --partial '--testsuite="unit"' } + @test "phpunit: paths override testsuite" { run tool_phpunit_run '{"testsuite":"unit","paths":["tests/Unit/FooTest.php"]}' assert_success diff --git a/plugin-tests/dev-tooling/mcp_tool_phpunit_coverage.bats b/plugin-tests/dev-tooling/mcp_tool_phpunit_coverage.bats index acc5a68f..a9a68686 100644 --- a/plugin-tests/dev-tooling/mcp_tool_phpunit_coverage.bats +++ b/plugin-tests/dev-tooling/mcp_tool_phpunit_coverage.bats @@ -143,6 +143,18 @@ teardown() { assert_output --partial "Uncovered methods: doStuff" } +@test "coverage_gaps: each file's detail lines are separate lines" { + exec_command() { echo "${SAMPLE_TWO_FILES}"; } + run tool_phpunit_coverage_gaps '{}' + assert_success + assert_line --regexp '^ *20\.0% \( 4 uncovered\) /app/src/Foo/Bar\.php$' + assert_line " Uncovered methods: doStuff" + assert_line " Lines: 15-17, 25" + assert_line --regexp '^ *50\.0% \( 1 uncovered\) /app/src/Baz/Qux\.php$' + assert_line " Lines: 8" + assert_output --partial $' Lines: 8\n\nSummary: ' +} + @test "coverage_gaps: covered method names do not appear" { exec_command() { echo "${SAMPLE_TWO_FILES}"; } run tool_phpunit_coverage_gaps '{}' diff --git a/plugin-tests/dev-tooling/mcp_tool_rector.bats b/plugin-tests/dev-tooling/mcp_tool_rector.bats index 043d4aeb..223164ca 100644 --- a/plugin-tests/dev-tooling/mcp_tool_rector.bats +++ b/plugin-tests/dev-tooling/mcp_tool_rector.bats @@ -8,6 +8,13 @@ PLUGIN_DIR="${REPO_ROOT}/plugins/dev-tooling" setup() { setup_php_mcp_env "${PLUGIN_DIR}" "${PLUGIN_DIR}/mcp-server-php/lib/rector.sh" + # The shape of shopware/shopware's composer.json: "rector" is the dry run, + # "rector-fix" applies the changes. + _write_composer_json '{"scripts":{"rector":["@php bootstrap.php","rector process --dry-run"],"rector-fix":["@php bootstrap.php","rector process"]}}' +} + +_write_composer_json() { + printf '%s\n' "$1" > "${BATS_TEST_TMPDIR}/composer.json" } teardown() { @@ -17,15 +24,46 @@ teardown() { # --- rector_fix (preferred tool) --- -@test "rector_fix: defaults — composer rector, json, no-progress-bar, no dry-run" { +@test "rector_fix: defaults — composer rector-fix, json, no-progress-bar, no dry-run" { run tool_rector_fix '{}' assert_success - assert_output --partial "composer rector" + assert_output --partial "composer rector-fix -- " assert_output --partial '--output-format="json"' assert_output --partial "--no-progress-bar" refute_output --partial "--dry-run" } +@test "rector_fix: a composer.json with only a non-dry-run rector script runs composer rector" { + _write_composer_json '{"scripts":{"rector":"rector process"}}' + run tool_rector_fix '{}' + assert_success + assert_output --partial "composer rector -- " + refute_output --partial "rector-fix" +} + +@test "rector_fix: a dry-run rector script without a rector-fix script is refused" { + _write_composer_json '{"scripts":{"rector":["@php bootstrap.php","rector process --dry-run"]}}' + run tool_rector_fix '{}' + assert_failure + assert_output --partial "${BATS_TEST_TMPDIR}/composer.json" + assert_output --partial 'its "rector" script runs with --dry-run and there is no "rector-fix" script' + refute_output --partial "--no-progress-bar" +} + +@test "rector_fix: a dry-run rector script in string form is refused" { + _write_composer_json '{"scripts":{"rector":"rector process --dry-run"}}' + run tool_rector_fix '{}' + assert_failure + assert_output --partial 'its "rector" script runs with --dry-run' +} + +@test "rector_check: stays on composer rector without reading composer.json" { + rm "${BATS_TEST_TMPDIR}/composer.json" + run tool_rector_check '{}' + assert_success + assert_output --partial "composer rector -- --dry-run" +} + @test "rector_fix: console output format" { run tool_rector_fix '{"output_format":"console"}' assert_success diff --git a/plugin-tests/dev-tooling/php_tools.bats b/plugin-tests/dev-tooling/php_tools.bats index 4d571a38..b6718c50 100644 --- a/plugin-tests/dev-tooling/php_tools.bats +++ b/plugin-tests/dev-tooling/php_tools.bats @@ -6,29 +6,69 @@ load 'test_helper/common_setup' CONFIG_PREFIX="php-tooling" -php_hook_blocks() { assert_hook_blocks "check-php-tools.sh" "$1" "$2"; } +# The block message names the tool and its server; neither host's mcp__ form. +php_hook_blocks() { + assert_hook_blocks "check-php-tools.sh" "$1" "$2" + assert_output --partial "on the \`php-tooling\` MCP server" + refute_output --partial "mcp__" +} # bats test_tags=blocking bats_test_function --description "blocks vendor/bin/phpstan → suggests phpstan_analyze" \ -- php_hook_blocks "vendor/bin/phpstan analyze src/" "phpstan_analyze" bats_test_function --description "blocks vendor/bin/ecs → suggests ecs_check/ecs_fix" \ - -- php_hook_blocks "vendor/bin/ecs check src/" "ecs_check or ecs_fix" + -- php_hook_blocks "vendor/bin/ecs check src/" "\`ecs_check\` or \`ecs_fix\`" bats_test_function --description "blocks vendor/bin/phpunit → suggests phpunit_run" \ -- php_hook_blocks "vendor/bin/phpunit tests/" "phpunit_run" bats_test_function --description "blocks bin/console → suggests console_run/console_list" \ - -- php_hook_blocks "bin/console cache:clear" "console_run or console_list" + -- php_hook_blocks "bin/console cache:clear" "\`console_run\` or \`console_list\`" bats_test_function --description "blocks && compound command → suggests phpstan_analyze" \ -- php_hook_blocks "git pull && vendor/bin/phpstan analyze" "phpstan_analyze" bats_test_function --description "blocks composer phpstan → suggests phpstan_analyze" \ -- php_hook_blocks "composer phpstan -- src/" "phpstan_analyze" bats_test_function --description "blocks composer ecs → suggests ecs_check/ecs_fix" \ - -- php_hook_blocks "composer ecs -- src/" "ecs_check or ecs_fix" + -- php_hook_blocks "composer ecs -- src/" "\`ecs_check\` or \`ecs_fix\`" bats_test_function --description "blocks vendor/bin/rector → suggests rector_fix/rector_check" \ - -- php_hook_blocks "vendor/bin/rector process src/" "rector_fix or rector_check" + -- php_hook_blocks "vendor/bin/rector process src/" "\`rector_fix\` or \`rector_check\`" bats_test_function --description "blocks composer rector → suggests rector_fix/rector_check" \ - -- php_hook_blocks "composer rector -- --dry-run" "rector_fix or rector_check" + -- php_hook_blocks "composer rector -- --dry-run" "\`rector_fix\` or \`rector_check\`" +bats_test_function --description "blocks composer rector-fix → suggests rector_fix/rector_check" \ + -- php_hook_blocks "composer rector-fix -- src/" "\`rector_fix\` or \`rector_check\`" +@test "blocks composer rector-fix without arguments" { + php_hook_blocks "composer rector-fix" "\`rector_fix\` or \`rector_check\`" +} bats_test_function --description "blocks php bin/console → suggests console_run/console_list" \ - -- php_hook_blocks "php bin/console cache:clear" "console_run or console_list" + -- php_hook_blocks "php bin/console cache:clear" "\`console_run\` or \`console_list\`" + +# bats test_tags=cwd +@test "reads the config from the hook input cwd when CURSOR_PROJECT_DIR is unset" { + unset CURSOR_PROJECT_DIR + local project + project=$(make_cwd_project "php-tooling" "ddev") + run_hook_with_cwd "check-php-tools.sh" "vendor/bin/phpstan analyze" "$project" + assert_failure 2 + assert_output --partial "'ddev' environment" +} + +# bats test_tags=cwd +@test "an empty CURSOR_PROJECT_DIR falls through to the hook input cwd" { + export CURSOR_PROJECT_DIR="" + local project + project=$(make_cwd_project "php-tooling" "ddev") + run_hook_with_cwd "check-php-tools.sh" "vendor/bin/phpstan analyze" "$project" + assert_failure 2 + assert_output --partial "'ddev' environment" +} + +# bats test_tags=cwd +@test "CURSOR_PROJECT_DIR wins over the hook input cwd when both are set" { + local project + project=$(make_cwd_project "php-tooling" "ddev") + run_hook_with_cwd "check-php-tools.sh" "vendor/bin/phpstan analyze" "$project" + assert_failure 2 + assert_output --partial "'native' environment" + refute_output --partial "'ddev' environment" +} # bats test_tags=allow @test "allows unrelated commands" { diff --git a/plugin-tests/dev-tooling/phpstan_baseline.bats b/plugin-tests/dev-tooling/phpstan_baseline.bats index 30d00467..71cc181c 100644 --- a/plugin-tests/dev-tooling/phpstan_baseline.bats +++ b/plugin-tests/dev-tooling/phpstan_baseline.bats @@ -191,3 +191,44 @@ create_neon_baseline() { assert_success echo "$output" | jq -e '.additional_context | contains("src/Foo.php")' } + +# bats test_tags=cwd +@test "CURSOR_PROJECT_DIR wins over cwd from input when both are set" { + create_php_baseline "src/Foo.php" + local other="${BATS_TEST_TMPDIR}/other-project" + mkdir -p "$other" + local input + input=$(printf '{"tool_input": {"paths": ["src/Foo.php"]}, "cwd": "%s"}' "$other") + run_baseline_hook "$input" + assert_success + echo "$output" | jq -e '.additional_context | contains("src/Foo.php")' +} + +# bats test_tags=cwd +@test "silent when CURSOR_PROJECT_DIR is unset and input carries no cwd" { + create_php_baseline "src/Foo.php" + unset CURSOR_PROJECT_DIR + run bash -c 'printf "%s" "$1" | bash "$2"' _ '{"tool_input": {"paths": ["src/Foo.php"]}}' "$BASELINE_SCRIPT" + assert_success + assert_output "" +} + +# bats test_tags=output +@test "warning names no mcp__ tool form" { + create_php_baseline "src/Foo.php" + run_baseline_hook "$(make_post_input '["src/Foo.php"]')" + assert_success + refute_output --partial "mcp__" +} + +# ============================================================================ +# postToolUse matcher +# ============================================================================ + +# bats test_tags=config +@test "hooks.json phpstan matcher is the short tool name" { + local matcher + matcher=$(jq -r '.hooks.postToolUse[] | select(.command | contains("check-phpstan-baseline.sh")) | .matcher' \ + "${REPO_ROOT}/plugins/dev-tooling/hooks/hooks.json") + [[ "$matcher" == "phpstan_analyze" ]] +} diff --git a/plugin-tests/dev-tooling/scope_js_tools.bats b/plugin-tests/dev-tooling/scope_js_tools.bats index 1fbd84ed..4d10e717 100644 --- a/plugin-tests/dev-tooling/scope_js_tools.bats +++ b/plugin-tests/dev-tooling/scope_js_tools.bats @@ -6,31 +6,6 @@ load 'test_helper/common_setup' PLUGIN_DIR="${REPO_ROOT}/plugins/dev-tooling" -# Answers the `npm pkg get "scripts."` probe with the body the Shopware -# Administration package.json declares. -_fake_admin_script_body() { - local name="$1" - - case "${name}" in - lint) - printf '%s\n' '"eslint src test build.ts --cache"' ;; - lint:fix) - printf '%s\n' '"npm run lint -- --fix"' ;; - lint:debugging) - printf '%s\n' '"eslint"' ;; - lint:scss) - printf '%s\n' '"npm run stylelint:base -- **/*.scss"' ;; - lint:scss-fix) - printf '%s\n' '"npm run lint:scss -- --fix"' ;; - jest:base) - printf '%s\n' '"jest --config jest.config.js"' ;; - build) - printf '%s\n' '"vite build"' ;; - *) - printf '%s\n' '{}' ;; - esac -} - setup() { LINT_CONFIG_FILE="${BATS_TEST_TMPDIR}/.mcp-js-tooling.json" JS_CONTEXT="admin" @@ -53,6 +28,7 @@ JSON log() { :; } CALLS_FILE="${BATS_TEST_TMPDIR}/calls.log" source "${PLUGIN_DIR}/shared/environment.sh" + source "${PLUGIN_DIR}/shared/js_paths.sh" source "${PLUGIN_DIR}/shared/scope.sh" PROJECT_ROOT="${BATS_TEST_TMPDIR}" export PROJECT_ROOT @@ -70,7 +46,7 @@ JSON case "${cmd}" in 'npm pkg get "scripts.'*) local name="${cmd#npm pkg get \"scripts.}" - _fake_admin_script_body "${name%\"}" + shopware_trunk_script_body administration "${name%\"}" ;; *) printf '%s\n' "${cmd}" @@ -78,6 +54,9 @@ JSON esac } source "${PLUGIN_DIR}/mcp-server-js-admin/lib/eslint.sh" + source "${PLUGIN_DIR}/mcp-server-js-admin/lib/stylelint.sh" + source "${PLUGIN_DIR}/mcp-server-js-admin/lib/prettier.sh" + source "${PLUGIN_DIR}/mcp-server-js-admin/lib/tsc.sh" source "${PLUGIN_DIR}/mcp-server-js-admin/lib/jest.sh" source "${PLUGIN_DIR}/mcp-server-js-admin/lib/lint-all.sh" source "${PLUGIN_DIR}/mcp-server-js-admin/lib/build.sh" @@ -90,6 +69,57 @@ teardown() { PROJECT_ROOT DEV_TOOLING_STATE_FILE } +js_tool_refuses_string_section() { + local function_name="$1" section="$2" + jq --arg section "${section}" '.scopes["plugin-x"][$section] = "invalid"' "${LINT_CONFIG_FILE}" > "${LINT_CONFIG_FILE}.new" + mv "${LINT_CONFIG_FILE}.new" "${LINT_CONFIG_FILE}" + run "${function_name}" '{"scope":"plugin-x"}' + assert_failure + assert_output --partial 'Config error: jq could not evaluate' + assert_output --partial 'Cannot index string' + [ ! -e "${CALLS_FILE}" ] +} + +bats_test_function --description "admin eslint_check: string section refuses without executing" -- js_tool_refuses_string_section tool_eslint_check eslint +bats_test_function --description "admin eslint_fix: string section refuses without executing" -- js_tool_refuses_string_section tool_eslint_fix eslint +bats_test_function --description "admin stylelint_check: string section refuses without executing" -- js_tool_refuses_string_section tool_stylelint_check stylelint +bats_test_function --description "admin stylelint_fix: string section refuses without executing" -- js_tool_refuses_string_section tool_stylelint_fix stylelint +bats_test_function --description "admin prettier_check: string section refuses without executing" -- js_tool_refuses_string_section tool_prettier_check prettier +bats_test_function --description "admin prettier_fix: string section refuses without executing" -- js_tool_refuses_string_section tool_prettier_fix prettier +bats_test_function --description "admin tsc_check: string section refuses without executing" -- js_tool_refuses_string_section tool_tsc_check tsc +bats_test_function --description "admin jest_run: string section refuses without executing" -- js_tool_refuses_string_section tool_jest_run jest + +# The read of the "unit" script body is the one command that precedes the +# install flag check. +@test "jest: an invalid install flag refuses before running any command but the script read" { + jq '.scopes["plugin-x"].jest.install_if_missing = "true"' "${LINT_CONFIG_FILE}" > "${LINT_CONFIG_FILE}.new" + mv "${LINT_CONFIG_FILE}.new" "${LINT_CONFIG_FILE}" + run tool_jest_run '{"scope":"plugin-x"}' + assert_failure + assert_output --partial 'jest.install_if_missing must be a boolean (found string)' + run grep -v -F 'npm pkg get "scripts.unit"' "${CALLS_FILE}" + assert_failure 1 +} + +@test "jest: explicit null install flag refuses before running any command but the script read" { + jq '.scopes["plugin-x"].jest.install_if_missing = null' "${LINT_CONFIG_FILE}" > "${LINT_CONFIG_FILE}.new" + mv "${LINT_CONFIG_FILE}.new" "${LINT_CONFIG_FILE}" + run tool_jest_run '{"scope":"plugin-x"}' + assert_failure + assert_output --partial 'jest.install_if_missing must be a boolean (found null)' + run grep -v -F 'npm pkg get "scripts.unit"' "${CALLS_FILE}" + assert_failure 1 +} + +@test "jest: an invalid env map refuses with jq's error" { + jq '.scopes["plugin-x"].jest.env = "invalid" | .scopes["plugin-x"].jest.install_if_missing = false' "${LINT_CONFIG_FILE}" > "${LINT_CONFIG_FILE}.new" + mv "${LINT_CONFIG_FILE}.new" "${LINT_CONFIG_FILE}" + run tool_jest_run '{"scope":"plugin-x"}' + assert_failure + assert_output --partial 'string ("invalid") has no keys' + [ ! -e "${CALLS_FILE}" ] +} + @test "eslint scoped: runs under scope cwd" { run tool_eslint_check '{"scope":"plugin-x"}' assert_success @@ -116,6 +146,25 @@ teardown() { assert_output --partial 'Scope "ghost" is not declared' } +# The scope runs in the plugin root, so a plugin's own administration tree is a +# path below that root and gets no rebase onto the core package directory. +@test "eslint scoped: a repo-root path under the scope cwd keeps its path below the plugin root" { + mkdir -p "${BATS_TEST_TMPDIR}/custom/plugins/X/src/Resources/app/administration/src" + touch "${BATS_TEST_TMPDIR}/custom/plugins/X/src/Resources/app/administration/src/x.ts" + run tool_eslint_check '{"scope":"plugin-x","paths":["custom/plugins/X/src/Resources/app/administration/src/x.ts"]}' + assert_success + run cat "${CALLS_FILE}" + assert_line --regexp '^\[scope=custom/plugins/X\|sub=\] npm exec --no -- eslint .* "src/Resources/app/administration/src/x\.ts"$' +} + +@test "stylelint scoped with paths: probes for and runs the local binary under the scope cwd" { + run tool_stylelint_check '{"scope":"plugin-x","paths":["src/scss/base.scss"]}' + assert_success + run cat "${CALLS_FILE}" + assert_line --partial '[scope=custom/plugins/X|sub=] npm exec --no -c "test -x node_modules/.bin/stylelint' + assert_line '[scope=custom/plugins/X|sub=] npm exec --no -- stylelint --cache -f string "src/scss/base.scss"' +} + @test "jest scoped: runs in scope cwd + jest.cwd" { mkdir -p "${BATS_TEST_TMPDIR}/custom/plugins/X/tests/jest/administration/node_modules" run tool_jest_run '{"scope":"plugin-x"}' @@ -143,7 +192,7 @@ _set_jest_env() { _set_jest_env '{"NODE_OPTIONS":"--require ./bootstrap.js"}' run tool_jest_run '{"scope":"plugin-x"}' assert_success - assert_output --partial 'NODE_OPTIONS="--require ./bootstrap.js" npm run jest:base' + assert_output --partial 'NODE_OPTIONS="--require ./bootstrap.js" npm run unit' } @test "jest scoped: an env value containing a line break is refused" { @@ -153,13 +202,25 @@ _set_jest_env() { assert_output --partial 'declares a jest.env entry containing a line break' } +@test "jest scoped: a refused test path pattern installs nothing" { + # node_modules deliberately missing, so install_if_missing would run npm ci + mkdir -p "${BATS_TEST_TMPDIR}/custom/plugins/X/tests/jest/administration" + touch "${CALLS_FILE}" + run tool_jest_run '{"scope":"plugin-x","testPathPatterns":"a\nb"}' + assert_failure + assert_output --partial "contains a line break" + run cat "${CALLS_FILE}" + refute_output --partial "npm ci" +} + @test "jest scoped: install_if_missing runs npm ci when node_modules absent" { # node_modules deliberately missing mkdir -p "${BATS_TEST_TMPDIR}/custom/plugins/X/tests/jest/administration" run tool_jest_run '{"scope":"plugin-x"}' assert_success run cat "${CALLS_FILE}" - assert_line --index 0 --partial "npm ci" + assert_line --index 0 --partial 'npm pkg get "scripts.unit"' + assert_line --index 1 --partial "npm ci" } @test "jest scoped: install_if_missing skipped when node_modules present" { @@ -196,14 +257,6 @@ _set_jest_env() { refute_line --partial "npm ci" } -@test "jest scoped: routes at jest:base, not the fallback aggregate" { - mkdir -p "${BATS_TEST_TMPDIR}/custom/plugins/X/tests/jest/administration/node_modules" - run tool_jest_run '{"scope":"plugin-x"}' - assert_success - assert_output --partial "npm run jest:base" - refute_output --partial "npm run unit" -} - @test "lint_all scoped: runs under scope cwd" { run tool_lint_all '{"scope":"plugin-x"}' assert_success @@ -238,3 +291,27 @@ _set_jest_env() { run cat "${CALLS_FILE}" assert_line --partial "[scope=custom/plugins/X|sub=]" } + +# The core-only tools run scripts a plugin package does not define, so a +# default_scope pinned to a plugin must not move them into it. +_assert_core_tool_ignores_default_scope() { + local pinned + pinned=$(jq '.default_scope = "plugin-x"' "${LINT_CONFIG_FILE}") + printf '%s\n' "${pinned}" > "${LINT_CONFIG_FILE}" + run "tool_$1" '{}' + assert_success + run cat "${CALLS_FILE}" + refute_line --partial "[scope=custom/plugins/X" + assert_line --partial "[scope=|sub=]" +} + +bats_test_function --description "lint_all: a default_scope pinned to a plugin still runs in the core package" \ + -- _assert_core_tool_ignores_default_scope lint_all +bats_test_function --description "lint_twig: a default_scope pinned to a plugin still runs in the core package" \ + -- _assert_core_tool_ignores_default_scope lint_twig +bats_test_function --description "unit_setup: a default_scope pinned to a plugin still runs in the core package" \ + -- _assert_core_tool_ignores_default_scope unit_setup +bats_test_function --description "vite_build: a default_scope pinned to a plugin still runs in the core package" \ + -- _assert_core_tool_ignores_default_scope vite_build +bats_test_function --description "webpack_build: a default_scope pinned to a plugin still runs in the core package" \ + -- _assert_core_tool_ignores_default_scope webpack_build diff --git a/plugin-tests/dev-tooling/scope_php_tools.bats b/plugin-tests/dev-tooling/scope_php_tools.bats index 004a0eba..33a3b107 100644 --- a/plugin-tests/dev-tooling/scope_php_tools.bats +++ b/plugin-tests/dev-tooling/scope_php_tools.bats @@ -52,6 +52,49 @@ teardown() { PROJECT_ROOT DEV_TOOLING_STATE_FILE } +_declare_string_bootstrap() { + jq '.scopes["plugin-x"].phpstan.bootstrap = "composer install" | .scopes["plugin-x"].rector.bootstrap = "composer install"' \ + "${LINT_CONFIG_FILE}" > "${LINT_CONFIG_FILE}.new" + mv "${LINT_CONFIG_FILE}.new" "${LINT_CONFIG_FILE}" +} + +# The capturing exec_command stub creates CALLS_FILE on its first call, so the +# file's absence means no command ran at all, bootstrap included. +assert_calls_file_absent() { + if [[ -e "${CALLS_FILE}" ]]; then + echo "a command ran:" >&2 + cat "${CALLS_FILE}" >&2 + return 1 + fi +} + +php_tool_refuses_string_section() { + local function_name="$1" section="$2" + jq --arg section "${section}" '.scopes["plugin-x"][$section] = "invalid"' "${LINT_CONFIG_FILE}" > "${LINT_CONFIG_FILE}.new" + mv "${LINT_CONFIG_FILE}.new" "${LINT_CONFIG_FILE}" + run "${function_name}" '{"scope":"plugin-x"}' + assert_failure + assert_output --partial 'Config error: jq could not evaluate' + assert_output --partial 'Cannot index string' + assert_calls_file_absent +} + +bats_test_function --description "phpstan: a string scope tool section refuses without executing" -- php_tool_refuses_string_section tool_phpstan_analyze phpstan +bats_test_function --description "rector_check: a string scope tool section refuses without executing" -- php_tool_refuses_string_section tool_rector_check rector +bats_test_function --description "rector_fix: a string scope tool section refuses without executing" -- php_tool_refuses_string_section tool_rector_fix rector +bats_test_function --description "ecs_check: a string scope tool section refuses without executing" -- php_tool_refuses_string_section tool_ecs_check style +bats_test_function --description "ecs_fix: a string scope tool section refuses without executing" -- php_tool_refuses_string_section tool_ecs_fix style +bats_test_function --description "phpunit: a string scope tool section refuses without executing" -- php_tool_refuses_string_section tool_phpunit_run phpunit + +@test "style: an unknown backend refuses before running a command" { + jq '.scopes["plugin-x"].style.tool = "other"' "${LINT_CONFIG_FILE}" > "${LINT_CONFIG_FILE}.new" + mv "${LINT_CONFIG_FILE}.new" "${LINT_CONFIG_FILE}" + run tool_ecs_check '{"scope":"plugin-x"}' + assert_failure + assert_output --partial "style.tool 'other' must be ecs or php-cs-fixer" + assert_calls_file_absent +} + @test "phpstan scoped: runs bootstrap before phpstan" { run tool_phpstan_analyze '{"scope":"plugin-x"}' assert_success @@ -99,6 +142,23 @@ teardown() { assert_output --partial "bootstrap failed" } +@test "phpstan scoped: a string bootstrap is refused and nothing runs" { + _declare_string_bootstrap + run tool_phpstan_analyze '{"scope":"plugin-x"}' + assert_failure + assert_output --partial "scopes.plugin-x.phpstan.bootstrap" + assert_output --partial "an array of commands" + refute_output --partial "composer phpstan" + assert_calls_file_absent +} + +@test "phpstan scoped: a refused argument runs no bootstrap" { + run tool_phpstan_analyze '{"scope":"plugin-x","config":"a'"'"'b"}' + assert_failure + assert_output --partial "single quote" + assert_calls_file_absent +} + @test "rector scoped: runs bootstrap before rector" { run tool_rector_check '{"scope":"plugin-x"}' assert_success @@ -119,6 +179,41 @@ teardown() { refute_line --partial "php tests/phpstan/bootstrap.php" } +@test "rector_fix scoped: the scope's own rector-fix script is the one run" { + mkdir -p "${BATS_TEST_TMPDIR}/custom/plugins/X" + printf '%s\n' '{"scripts":{"rector-fix":"rector process"}}' > "${BATS_TEST_TMPDIR}/custom/plugins/X/composer.json" + run tool_rector_fix '{"scope":"plugin-x"}' + assert_success + run cat "${CALLS_FILE}" + assert_line --partial "[scope=custom/plugins/X] composer rector-fix -- " +} + +# The bootstrap runner lives once in shared/scope.sh, which setup sources; this +# exercises it through rector's call site. +@test "rector scoped: a string bootstrap is refused and nothing runs" { + mkdir -p "${BATS_TEST_TMPDIR}/custom/plugins/X" + printf '%s\n' '{"scripts":{"rector-fix":"rector process"}}' > "${BATS_TEST_TMPDIR}/custom/plugins/X/composer.json" + _declare_string_bootstrap + run tool_rector_fix '{"scope":"plugin-x"}' + assert_failure + assert_output --partial "scopes.plugin-x.rector.bootstrap" + assert_calls_file_absent +} + +@test "rector_check scoped: a refused argument runs no bootstrap" { + run tool_rector_check '{"scope":"plugin-x","only":"a'"'"'b"}' + assert_failure + assert_output --partial "single quote" + assert_calls_file_absent +} + +@test "rector_fix scoped: a refused argument runs no bootstrap" { + run tool_rector_fix '{"scope":"plugin-x","only":"a'"'"'b"}' + assert_failure + assert_output --partial "single quote" + assert_calls_file_absent +} + @test "ecs_check scoped: routes to php-cs-fixer with scope style config" { run tool_ecs_check '{"scope":"plugin-x"}' assert_success diff --git a/plugin-tests/dev-tooling/scope_resolution.bats b/plugin-tests/dev-tooling/scope_resolution.bats index 4830bf53..6b0c356f 100644 --- a/plugin-tests/dev-tooling/scope_resolution.bats +++ b/plugin-tests/dev-tooling/scope_resolution.bats @@ -97,6 +97,31 @@ _assert_scope_refused() { _assert_scope_refused 'plugin-"x' } +# A config edited into non-JSON mid-session made a call run unscoped as shopware. +@test "resolve_scope: config that is not valid JSON -> refused naming the file" { + _write_config '{bad' + run _scope_sh 'resolve_scope ""' + assert_failure + assert_output --partial "${LINT_CONFIG_FILE}" + assert_output --partial 'does not parse as a JSON object' +} + +@test "resolve_scope: missing config file -> refused naming it as missing" { + rm -f "${LINT_CONFIG_FILE}" + run _scope_sh 'resolve_scope ""' + assert_failure + assert_output --partial "${LINT_CONFIG_FILE}" + assert_output --partial 'does not exist' +} + +@test "scope_validate: a string scopes section refuses with jq's error" { + _write_config '{"environment":"native","scopes":"nope"}' + run _scope_sh 'scope_validate' + assert_failure + assert_output --partial 'Config error: jq could not evaluate' + assert_output --partial 'Cannot index string' +} + @test "scope_validate: reserved name shopware in scopes -> error" { _write_config '{"environment":"native","scopes":{"shopware":{"cwd":"x"}}}' run _scope_sh 'scope_validate' @@ -137,6 +162,14 @@ _assert_scope_refused() { assert_output "" } +@test "scope_get_tool_field: a string-typed per-tool value -> refused naming the file and jq's error" { + _write_config '{"environment":"native","scopes":{"plugin-x":{"cwd":"p","phpstan":"phpstan.neon"}}}' + run _scope_sh 'SCOPE_NAME=plugin-x; scope_get_tool_field phpstan config' + assert_failure + assert_output --partial "${LINT_CONFIG_FILE}" + assert_output --partial 'Cannot index string' +} + @test "scope_get_bootstrap: returns newline-separated commands" { _write_config '{"environment":"native","scopes":{"plugin-x":{"cwd":"p","phpstan":{"bootstrap":["a b","c d"]}}}}' run _scope_sh 'SCOPE_NAME=plugin-x; scope_get_bootstrap phpstan' @@ -151,3 +184,19 @@ _assert_scope_refused() { assert_success assert_output "" } + +@test "scope_get_bootstrap: a string bootstrap -> refused naming the key" { + _write_config '{"environment":"native","scopes":{"plugin-x":{"cwd":"p","phpstan":{"bootstrap":"composer install"}}}}' + run _scope_sh 'SCOPE_NAME=plugin-x; scope_get_bootstrap phpstan' + assert_failure + assert_output --partial 'scopes.plugin-x.phpstan.bootstrap' + assert_output --partial 'an array of commands' +} + +@test "scope_get_bootstrap: a non-string element -> refused rather than run as a literal" { + _write_config '{"environment":"native","scopes":{"plugin-x":{"cwd":"p","phpstan":{"bootstrap":["composer install",null]}}}}' + run _scope_sh 'SCOPE_NAME=plugin-x; scope_get_bootstrap phpstan' + assert_failure + assert_output --partial 'scopes.plugin-x.phpstan.bootstrap' + assert_output --partial 'not a non-empty string' +} diff --git a/plugin-tests/dev-tooling/session_start.bats b/plugin-tests/dev-tooling/session_start.bats index 342db3f8..a5b0600f 100644 --- a/plugin-tests/dev-tooling/session_start.bats +++ b/plugin-tests/dev-tooling/session_start.bats @@ -60,3 +60,67 @@ run_session_start() { assert_success echo "$output" | jq -e '.additional_context | length > 0' } + +# ============================================================================ +# Project directory: CURSOR_PROJECT_DIR, else workspace_roots / cwd +# ============================================================================ + +# Run the hook with the given JSON on stdin. +run_session_start_with_input() { + run bash -c 'printf "%s" "$1" | bash "$2"' _ "$1" "$SESSION_SCRIPT" +} + +# bats test_tags=output +@test "directives name no mcp__ tool form" { + run_session_start + assert_success + refute_output --partial "mcp__" +} + +# bats test_tags=cwd +@test "reads enforcement from the hook input cwd when CURSOR_PROJECT_DIR is unset" { + unset CURSOR_PROJECT_DIR + local project="${BATS_TEST_TMPDIR}/cwd-project" + mkdir -p "$project" + echo '{"enforce_mcp_tools": false}' > "${project}/.mcp-php-tooling.json" + echo '{"enforce_mcp_tools": false}' > "${project}/.mcp-js-tooling.json" + run_session_start_with_input "$(jq -cn --arg cwd "$project" '{cwd: $cwd}')" + assert_success + assert_output "" +} + +# bats test_tags=cwd +@test "renders scopes from the hook input cwd when CURSOR_PROJECT_DIR is unset" { + unset CURSOR_PROJECT_DIR + local project="${BATS_TEST_TMPDIR}/cwd-project" + mkdir -p "$project" + echo '{"scopes": {"plugin-z": {"cwd": "custom/plugins/Z"}}}' > "${project}/.mcp-php-tooling.json" + run_session_start_with_input "$(jq -cn --arg cwd "$project" '{cwd: $cwd}')" + assert_success + assert_output --partial "php-tooling scopes" + assert_output --partial "plugin-z" +} + +# bats test_tags=cwd +@test "CURSOR_PROJECT_DIR wins over the hook input cwd when both are set" { + local project="${BATS_TEST_TMPDIR}/cwd-project" + mkdir -p "$project" + echo '{"scopes": {"plugin-x": {"cwd": "custom/plugins/X"}}}' > "${BATS_TEST_TMPDIR}/.mcp-php-tooling.json" + echo '{"scopes": {"plugin-z": {"cwd": "custom/plugins/Z"}}}' > "${project}/.mcp-php-tooling.json" + run_session_start_with_input "$(jq -cn --arg cwd "$project" '{cwd: $cwd}')" + assert_success + assert_output --partial "plugin-x" + refute_output --partial "plugin-z" +} + +# bats test_tags=cwd +@test "js scopes note that some tools ignore the default scope" { + unset CURSOR_PROJECT_DIR + local project="${BATS_TEST_TMPDIR}/cwd-project" + mkdir -p "$project" + echo '{"scopes": {"plugin-z": {"cwd": "custom/plugins/Z"}}}' > "${project}/.mcp-js-tooling.json" + run_session_start_with_input "$(jq -cn --arg cwd "$project" '{cwd: $cwd}')" + assert_success + assert_output --partial "ignore the default scope" + assert_output --partial "ludtwig_check" +} diff --git a/plugin-tests/dev-tooling/test_helper/common_setup.bash b/plugin-tests/dev-tooling/test_helper/common_setup.bash index dbd0f008..c27d99ed 100644 --- a/plugin-tests/dev-tooling/test_helper/common_setup.bash +++ b/plugin-tests/dev-tooling/test_helper/common_setup.bash @@ -24,6 +24,26 @@ teardown() { unset CURSOR_PROJECT_DIR } +# Run a hook script with the hook input's cwd set. When CURSOR_PROJECT_DIR is +# unset, the cwd is how the hook names the project. +# Args: $1 = script name, $2 = bash command, $3 = cwd +run_hook_with_cwd() { + local payload + payload=$(jq -cn --arg cmd "$2" --arg cwd "$3" '{tool_input: {command: $cmd}, cwd: $cwd}') + run bash -c 'printf "%s" "$1" | bash "$2"' _ "$payload" "${SCRIPTS_DIR}/$1" +} + +# Create a project directory holding an MCP config of the given environment, +# distinct from the one setup_config writes at BATS_TEST_TMPDIR. +# Args: $1 = config prefix, $2 = environment +# Stdout: the project directory +make_cwd_project() { + local dir="${BATS_TEST_TMPDIR}/cwd-project" + mkdir -p "$dir" + jq -n --arg env "$2" '{environment: $env}' > "${dir}/.mcp-${1}.json" + printf '%s\n' "$dir" +} + # The path $2 relative to the directory $1. Both must be absolute and # canonical. No external tool computes this portably — BSD realpath has no # --relative-to — and the fixtures below have both sides already. @@ -187,3 +207,210 @@ setup_php_mcp_env() { # shellcheck source=/dev/null # lib_path is caller-supplied at runtime; each test passes a different tool library source "${lib_path}" } + +# Answer an `npm pkg get "scripts."` probe the way npm answers it against +# the Shopware package.json whose "scripts" block the fixture copies verbatim +# from shopware/shopware trunk (c59a7d3484c): the body as a JSON string, or +# `{}` for a script the package does not define. +# Args: $1 = package, "administration" or "storefront", $2 = script name +# Stdout: the probe answer +shopware_trunk_script_body() { + jq --arg name "$2" 'if has($name) then .[$name] else {} end' \ + "${BATS_TEST_DIRNAME}/fixtures/shopware-trunk/$1-package-scripts.json" +} + +# The status js_fake_npm_probe returns for a command that is neither probe. +JS_FAKE_NPM_PROBE_UNHANDLED=125 + +# The fake exec_npm_command of mcp_tool_js_admin.bats and +# mcp_tool_js_storefront.bats answers from these variables, set in their setup(): +# FAKE_ABSENT_SCRIPTS scripts answered `{}`, as if the package lacked them +# FAKE_BODY_NAME, FAKE_BODY one script answered with a different body +# FAKE_PROBE_OUTPUT the answer of the path probe; FAKE_PROBE_FILE records its command +# FAKE_CALL_LOG every wrapped command, in order +# FAKE_REPORT_OUTPUT what a Jest run writes into FAKE_REPORT_STORE, a real file, so +# a report an earlier run left differs from one this run wrote; +# FAKE_RUN_WRITES_REPORT=0 makes the run write none, the clear +# deletes the file and the read returns whatever is there +# FAKE_REPORT_READ_FILE the command that read the report +# FAKE_CLEAR_EXIT, FAKE_CLEAR_OUTPUT, FAKE_RUN_EXIT status and output of the clear and the run +# The probe variables are listed at js_fake_npm_probe. + +# Answer the two probes a path-scoped JS lint runs through `npm exec --no -c`, +# for an exec_npm_command fake. The directory test runs for real, as sh in the +# package directory, so it answers about the files a test created. The +# local-binary probe reports a binary named in FAKE_MISSING_BINARIES missing in +# the given directory. FAKE_DIRECTORY_PROBE_ERROR and FAKE_BINARY_PROBE_ERROR +# make the probe fail before it can test anything, such as on a stopped +# container. +# Globals: reads FAKE_DIRECTORY_PROBE_ERROR, FAKE_BINARY_PROBE_ERROR, +# FAKE_MISSING_BINARIES, BATS_TEST_TMPDIR +# Args: $1 = the command, $2 = the package directory the binary probe reports, +# which under a container is not a host path +# Returns: the probe's status, or JS_FAKE_NPM_PROBE_UNHANDLED for any other +# command +js_fake_npm_probe() { + local cmd="$1" + local package_dir="$2" + + case "${cmd}" in + 'npm exec --no -c "[ -d '*) + if [[ -n "${FAKE_DIRECTORY_PROBE_ERROR}" ]]; then + printf '%s\n' "${FAKE_DIRECTORY_PROBE_ERROR}" + return 1 + fi + # LINT_WORKDIR is empty here: environment.sh resets it when + # sourced, and setup() sets it before that. + (LINT_WORKDIR="${BATS_TEST_TMPDIR}"; cd "$(get_js_workdir)" 2>/dev/null || true; eval "sh -c ${cmd#npm exec --no -c }") + ;; + 'npm exec --no -c "test -x node_modules/.bin/'*) + if [[ -n "${FAKE_BINARY_PROBE_ERROR}" ]]; then + printf '%s\n' "${FAKE_BINARY_PROBE_ERROR}" + return 1 + fi + local binary="${cmd#npm exec --no -c \"test -x node_modules/.bin/}" + case " ${FAKE_MISSING_BINARIES} " in + *" ${binary%% *} "*) + printf '%s\n%s\n' "LOCAL_BINARY_MISSING_IN" "${package_dir}" + return 3 + ;; + esac + ;; + *) + return "${JS_FAKE_NPM_PROBE_UNHANDLED}" + ;; + esac +} + +# Installs the fake npm in the directory $1. It implements the two `npm exec` +# forms as npm 11 runs them: `-c` hands the string to sh with the package's +# node_modules/.bin first on PATH, `--` runs that directory's binary. +_js_install_fake_npm() { + local bin_dir="$1" + mkdir -p "${bin_dir}" + cat > "${bin_dir}/npm" <<'NPM' +#!/usr/bin/env bash +[[ "$1 $2" == "exec --no" ]] || exit 90 +case "$3" in + -c) PATH="${PWD}/node_modules/.bin:${PATH}" exec sh -c "$4" ;; + --) shift 3; bin="$1"; shift; exec "${PWD}/node_modules/.bin/${bin}" "$@" ;; +esac +exit 91 +NPM + chmod +x "${bin_dir}/npm" +} + +# Installs each binary named in JS_FAKE_BINARIES (default: eslint, stylelint and +# prettier) in the package directory $1's node_modules/.bin. A fake prints its +# working directory, one bracketed line per argument and, for an argument +# holding `*`, one `match:` line per file the pattern names, as bash expands it +# with globstar from that directory. +_js_install_fake_linters() { + local package_dir="$1" binary + mkdir -p "${package_dir}/node_modules/.bin" + for binary in ${JS_FAKE_BINARIES-eslint stylelint prettier}; do + cat > "${package_dir}/node_modules/.bin/${binary}" <<'LINTER' +#!/usr/bin/env bash +shopt -s globstar nullglob +printf 'cwd=%s\n' "$(pwd)" +for arg in "$@"; do printf '[%s]\n' "${arg}"; done +for arg in "$@"; do + [[ "${arg}" == *"*"* ]] || continue + eval "matches=( ${arg} )" + for match in "${matches[@]}"; do printf 'match:%s\n' "${match}"; done +done +LINTER + chmod +x "${package_dir}/node_modules/.bin/${binary}" + done +} + +# Defines docker, vagrant and ddev as functions doing what each does with its +# argv. docker and vagrant hand their string to a shell. The ddev shim models +# ddev/ddev main 94c92c96415f: `ddev npm` is the command file +# pkg/ddevapp/global_dotddev_assets/commands/web/npm (`## ExecRaw: true`), and +# cmd/ddev/cmd/commands.go:528 (`opts.RawCmd = append([]string{fullPath}, +# osArgs...)`) hands it argv unchanged; `ddev exec -d` joins argv, +# double-quoting an argument holding a space, tab, line break, `"` or `#` +# (quoteArgs), and parses the result with `bash -c` again. +_js_define_env_shims() { + docker() { bash -c "${!#}"; } + vagrant() { bash -c "$3"; } + ddev() { + if [[ "$1" == "npm" ]]; then + shift + npm "$@" + return + fi + [[ "$1 $2" == "exec -d" ]] || return 92 + local dir="$3" joined="" arg + shift 3 + for arg in "$@"; do + if [[ "${arg}" == *[\"\ $'\t'$'\r'$'\n'\#]* ]]; then + arg="\"${arg//\"/\\\"}\"" + fi + joined="${joined:+${joined} }${arg}" + done + bash -c "cd \"${dir}\" && ( ${joined} )" + } +} + +# Runs a command a JS tool built, through the real environment wrapper, with +# fakes that reproduce each argv-parsing step, so a quoting bug surfaces as it +# would on the real tool. The docker-compose path builds its wrapper with the +# real compose module but stubs `_compose_resolve_workdir`, so the real workdir +# join is not exercised. +# Globals: reads JS_CONTEXT, PLUGIN_DIR, JS_FAKE_BINARIES +# Args: $1 = native, docker, docker-compose, vagrant, ddev or ddev-worktree, +# $2 = the command +js_execute_in_env() { + local env="$1" cmd="$2" + + # environment.sh resets LINT_WORKDIR when sourced; a tool call rebinds it + # through worktree_enter, and this helper calls no tool. + LINT_WORKDIR="${BATS_TEST_TMPDIR}" + local package_dir bin_dir="${BATS_TEST_TMPDIR}/fake-bin" + package_dir=$(get_js_workdir) + _js_install_fake_npm "${bin_dir}" + _js_install_fake_linters "${package_dir}" + _js_define_env_shims + + LINT_ENV="${env}" + if [[ "${env}" == "docker-compose" ]]; then + # PLUGIN_DIR is set by the test file that loads this helper. + # shellcheck source=/dev/null disable=SC2153 + source "${PLUGIN_DIR}/shared/docker-compose.sh" + _compose_check_prerequisites() { return 0; } + _compose_resolve_container() { printf '%s\n' "shopware-web-1"; } + _compose_resolve_workdir() { printf '%s\n' "${BATS_TEST_TMPDIR}"; } + fi + if [[ "${env}" == "ddev-worktree" ]]; then + LINT_ENV="ddev" + WORKTREE_EFFECTIVE_ROOT="${BATS_TEST_TMPDIR}/linked-worktree" + fi + DOCKER_CONTAINER="web" + local wrapped + wrapped=$(wrap_npm_command "${cmd}") + PATH="${bin_dir}:${PATH}" + cd "${package_dir}" || return 93 + eval "${wrapped}" +} + +# Overrides _env_targets_worktree and LINT_ENV for the rest of the test. +_as_ddev_worktree_call() { + LINT_ENV="ddev" + _env_targets_worktree() { return 0; } +} + +# Writes LINT_CONFIG_FILE with scope "plugin-x" carrying a Stylelint config. +_use_stylelint_scope_config() { + cat > "${LINT_CONFIG_FILE}" <<'JSON' +{"environment":"native","scopes":{"plugin-x":{"cwd":"custom/plugins/X","stylelint":{"config":".stylelintrc.plugin"}}}} +JSON +} + +# The forms a linter binary takes in a command; BIN stands for its name. The hook +# suites check every binary in every form: a form missing for one binary fails. +JS_HOOK_BINARY_FORMS=("npm exec BIN" "npm exec -- BIN" "npm exec --no -- BIN" + "npx BIN" "npx --no-install BIN" "npx -y BIN" + "npx BIN@9.1.0" "npm exec BIN@9.1.0" + "node_modules/.bin/BIN" "./node_modules/.bin/BIN") diff --git a/plugin-tests/dev-tooling/tool_schema.bats b/plugin-tests/dev-tooling/tool_schema.bats index 95fe84e3..ebea0dd7 100644 --- a/plugin-tests/dev-tooling/tool_schema.bats +++ b/plugin-tests/dev-tooling/tool_schema.bats @@ -37,3 +37,18 @@ _validate_tool_call() { assert_failure assert_output --partial "Unknown parameter(s): testNamePatternn" } + +@test "php-tooling schema: phpunit_run accepts the core redis suite" { + run _validate_tool_call "${PLUGIN_DIR}/mcp-server-php/tools.json" "phpunit_run" '{"testsuite":"redis"}' + assert_success +} + +@test "php-tooling schema: phpunit_run accepts a suite name a plugin defines" { + run _validate_tool_call "${PLUGIN_DIR}/mcp-server-php/tools.json" "phpunit_run" '{"testsuite":"SwagExample_Unit-Tests"}' + assert_success +} + +@test "php-tooling schema: phpunit_run refuses a suite name carrying a shell metacharacter" { + run _validate_tool_call "${PLUGIN_DIR}/mcp-server-php/tools.json" "phpunit_run" '{"testsuite":"unit;id"}' + assert_failure +} diff --git a/plugin-tests/dev-tooling/worktree_conformance.bats b/plugin-tests/dev-tooling/worktree_conformance.bats index b5d5c5ea..98c24d1b 100644 --- a/plugin-tests/dev-tooling/worktree_conformance.bats +++ b/plugin-tests/dev-tooling/worktree_conformance.bats @@ -83,6 +83,7 @@ TOOLS_JSON="\${PLUGIN_DIR}/${server_dir}/tools.json" log() { :; } source "\${PLUGIN_DIR}/shared/config.sh" source "\${PLUGIN_DIR}/shared/environment.sh" +source "\${PLUGIN_DIR}/shared/js_paths.sh" source "\${PLUGIN_DIR}/shared/scope.sh" PROJECT_ROOT=$(printf '%q' "${LAUNCH_ROOT}") export PROJECT_ROOT @@ -91,6 +92,7 @@ LINT_ENV="native" LINT_WORKDIR="\${PROJECT_ROOT}" source "\${PLUGIN_DIR}/shared/worktree.sh" worktree_state_init +worktree_launch_common_init trap worktree_state_cleanup EXIT # A lib that fails to source would otherwise drop its tools from the # enumeration below and leave every remaining tool reporting OK, so the scan diff --git a/plugin-tests/dev-tooling/worktree_hook.bats b/plugin-tests/dev-tooling/worktree_hook.bats index fa3830fc..ebbd6cab 100644 --- a/plugin-tests/dev-tooling/worktree_hook.bats +++ b/plugin-tests/dev-tooling/worktree_hook.bats @@ -78,6 +78,18 @@ _enter_input() { assert_output --partial "git -c worktree.useRelativePaths=true worktree repair \"${wt}\"" } +# The servers accept an absolute gitdir under native; only the container +# environments refuse it. +@test "EnterWorktree on an absolute-linkage worktree limits the refusal to container environments" { + local wt="${BATS_TEST_TMPDIR}/wt-abs" + mkdir -p "${wt}" + printf 'gitdir: /somewhere/.git/worktrees/wt-abs\n' > "${wt}/.git" + _run_hook_and_decode_context "$(_enter_input "${wt}" "${wt}")" + assert_success + assert_output --partial "refuse under the docker, docker-compose, vagrant and ddev environments" + refute_output --partial "in every environment" +} + @test "EnterWorktree names the repair command when the .git file has no trailing newline" { # `read` populates the variable and still returns 1 at EOF on a final line # without a newline; a guard that clears the variable on that status drops diff --git a/plugin-tests/dev-tooling/worktree_js_tools.bats b/plugin-tests/dev-tooling/worktree_js_tools.bats index c7ceaa5c..ac7cfb91 100644 --- a/plugin-tests/dev-tooling/worktree_js_tools.bats +++ b/plugin-tests/dev-tooling/worktree_js_tools.bats @@ -20,8 +20,14 @@ _make_git_worktree_fixture() { WORKTREE_ROOT="${BATS_TEST_TMPDIR}/wt" git -C "${LAUNCH_ROOT}" worktree add -q "${WORKTREE_ROOT}" -b wt-branch worktree_gitdir_relative "${WORKTREE_ROOT}" - mkdir -p "${WORKTREE_ROOT}/src/Administration/Resources/app/administration/node_modules" - mkdir -p "${WORKTREE_ROOT}/src/Storefront/Resources/app/storefront/node_modules" + local package binary + for package in src/Administration/Resources/app/administration src/Storefront/Resources/app/storefront; do + mkdir -p "${WORKTREE_ROOT}/${package}/node_modules/.bin" + for binary in eslint stylelint prettier; do + printf '#!/bin/sh\n' > "${WORKTREE_ROOT}/${package}/node_modules/.bin/${binary}" + chmod +x "${WORKTREE_ROOT}/${package}/node_modules/.bin/${binary}" + done + done } setup() { @@ -59,6 +65,7 @@ CALLS_FILE=$(printf '%q' "${calls_file}") log() { :; } source "\${PLUGIN_DIR}/shared/config.sh" source "\${PLUGIN_DIR}/shared/environment.sh" +source "\${PLUGIN_DIR}/shared/js_paths.sh" source "\${PLUGIN_DIR}/shared/scope.sh" PROJECT_ROOT=$(printf '%q' "${LAUNCH_ROOT}") export PROJECT_ROOT @@ -67,6 +74,7 @@ LINT_ENV="native" LINT_WORKDIR="\${PROJECT_ROOT}" source "\${PLUGIN_DIR}/shared/worktree.sh" worktree_state_init +worktree_launch_common_init trap worktree_state_cleanup EXIT HEADER @@ -86,6 +94,10 @@ exec_npm_command() { printf '[cwd=%s][workdir=%s][jsworkdir=%s] %s\n' "$(pwd)" "${LINT_WORKDIR}" "${jswd}" "$1" >> "${CALLS_FILE}" case "$1" in 'npm pkg get "scripts.'*) printf '"a-script"\n' ;; + # The local-binary probe and the directory test run for real, as sh in + # the directory the command would run in, so they answer about that + # directory's files. + 'npm exec --no -c "test -x '*|'npm exec --no -c "[ -d '*) (cd "${jswd}" && eval "sh -c ${1#npm exec --no -c }") ;; *) printf '%s\n' "$1" ;; esac } @@ -96,9 +108,15 @@ BODY for lib in "$@"; do printf 'source "%s/%s/lib/%s"\n' "${PLUGIN_DIR}" "${server_dir}" "${lib}" >> "${script}" done - printf '%s %q > /dev/null\n' "${tool_fn}" "${json_args}" >> "${script}" - # shellcheck disable=SC2016 # ${CALLS_FILE} must expand in the generated script when it runs, not here - printf 'cat -- "${CALLS_FILE}"\n' >> "${script}" + # The tool's own output and exit status follow the calls log, after a + # separator line. + { + printf 'tool_code=0\n%s %q > %q || tool_code=$?\n' "${tool_fn}" "${json_args}" "${calls_file}.out" + # shellcheck disable=SC2016 # ${CALLS_FILE} must expand in the generated script when it runs, not here + printf 'cat -- "${CALLS_FILE}"\n' + # shellcheck disable=SC2016 # ${tool_code} must expand in the generated script when it runs, not here + printf 'printf -- "--- tool output, exit %%s\\n" "${tool_code}"\ncat -- %q\n' "${calls_file}.out" + } >> "${script}" run bash "${script}" } @@ -122,9 +140,6 @@ BODY "{\"project_root\":\"${WORKTREE_ROOT}\"}" prepare.sh assert_success assert_output --partial "[cwd=${WORKTREE_ROOT}][workdir=${WORKTREE_ROOT}][jsworkdir=${WORKTREE_ROOT}/src/Administration/Resources/app/administration] npm ci" - # The success summary is not assertable here: _run_js_tool discards the - # tool's stdout and prints only the calls log. worktree_php_tools.bats pins - # the summary-on-success / full-output-on-failure contract. } @test "storefront worktree_prepare: runs npm ci in the package directory of a worktree with no node_modules" { @@ -133,9 +148,6 @@ BODY "{\"project_root\":\"${WORKTREE_ROOT}\"}" prepare.sh assert_success assert_output --partial "[cwd=${WORKTREE_ROOT}][workdir=${WORKTREE_ROOT}][jsworkdir=${WORKTREE_ROOT}/src/Storefront/Resources/app/storefront] npm ci" - # The success summary is not assertable here: _run_js_tool discards the - # tool's stdout and prints only the calls log. worktree_php_tools.bats pins - # the summary-on-success / full-output-on-failure contract. } @test "admin lint_all: a project_root argument reaches the resolved working directory" { @@ -190,3 +202,47 @@ BODY assert_success assert_output --partial "[cwd=${WORKTREE_ROOT}][workdir=${WORKTREE_ROOT}][jsworkdir=${WORKTREE_ROOT}/src/Storefront/Resources/app/storefront]" } + +# --- path-scoped runs of the package's own binary, one per route --- + +# The path-scoped routes run `npm exec` with no npm script in between, so the +# package directory the binary is resolved from is the JS working directory +# itself. Each case pins the run, not only the probe, to the worktree's package. + +@test "admin stylelint_check with paths: runs the local binary in the worktree's package directory" { + _run_js_tool admin mcp-server-js-admin tool_stylelint_check \ + "{\"project_root\":\"${WORKTREE_ROOT}\",\"paths\":[\"src/app/base.scss\"]}" stylelint.sh + assert_success + assert_output --partial "[jsworkdir=${WORKTREE_ROOT}/src/Administration/Resources/app/administration] npm exec --no -- stylelint --cache" +} + +@test "admin prettier_check with paths: runs the local binary in the worktree's package directory" { + _run_js_tool admin mcp-server-js-admin tool_prettier_check \ + "{\"project_root\":\"${WORKTREE_ROOT}\",\"paths\":[\"src/app/main.ts\"]}" prettier.sh + assert_success + assert_output --partial "[jsworkdir=${WORKTREE_ROOT}/src/Administration/Resources/app/administration] npm exec --no -- prettier --check" +} + +@test "storefront stylelint_check with paths: runs the local binary in the worktree's package directory" { + _run_js_tool storefront mcp-server-js-storefront tool_stylelint_check \ + "{\"project_root\":\"${WORKTREE_ROOT}\",\"paths\":[\"src/scss/base.scss\"]}" stylelint.sh + assert_success + assert_output --partial "[jsworkdir=${WORKTREE_ROOT}/src/Storefront/Resources/app/storefront] npm exec --no -- stylelint --config stylelint.config.js" +} + +@test "storefront eslint_check with components paths: starts in the worktree's package directory" { + _run_js_tool storefront mcp-server-js-storefront tool_eslint_check \ + "{\"project_root\":\"${WORKTREE_ROOT}\",\"paths\":[\"views/components/checkout/cart.js\"]}" eslint.sh + assert_success + assert_output --partial "[jsworkdir=${WORKTREE_ROOT}/src/Storefront/Resources/app/storefront] npm exec --no -c \"cd ../.. && eslint" +} + +@test "admin stylelint_check with paths: refuses when the worktree's package has no stylelint" { + rm "${WORKTREE_ROOT}/src/Administration/Resources/app/administration/node_modules/.bin/stylelint" + _run_js_tool admin mcp-server-js-admin tool_stylelint_check \ + "{\"project_root\":\"${WORKTREE_ROOT}\",\"paths\":[\"src/app/base.scss\"]}" stylelint.sh + assert_success + assert_output --partial "--- tool output, exit 1" + assert_output --partial "\"node_modules/.bin/stylelint\" is not installed in the package directory \"${WORKTREE_ROOT}/src/Administration/Resources/app/administration\"" + refute_output --partial "npm exec --no -- stylelint" +} diff --git a/plugin-tests/dev-tooling/worktree_php_tools.bats b/plugin-tests/dev-tooling/worktree_php_tools.bats index 27f8e580..a50940e9 100644 --- a/plugin-tests/dev-tooling/worktree_php_tools.bats +++ b/plugin-tests/dev-tooling/worktree_php_tools.bats @@ -48,6 +48,7 @@ setup() { # shellcheck source=/dev/null source "${PLUGIN_DIR}/shared/worktree.sh" worktree_state_init + worktree_launch_common_init # Captures both the shell's cwd (proves the resolver's cd reached this # call) and LINT_WORKDIR (proves the resolver also rebound the variable # every real command-wrapping path reads). A regression that keeps the cd diff --git a/plugin-tests/dev-tooling/worktree_resolution.bats b/plugin-tests/dev-tooling/worktree_resolution.bats index 58367ae9..240cc217 100644 --- a/plugin-tests/dev-tooling/worktree_resolution.bats +++ b/plugin-tests/dev-tooling/worktree_resolution.bats @@ -9,6 +9,9 @@ PLUGIN_DIR="${REPO_ROOT}/plugins/dev-tooling" # A launch checkout plus real linked worktrees created with `git worktree add`, # so validation against git's own registry (`_worktree_is_registered`) passes. _make_git_worktree_fixture() { + # The fixture's git, and the module's git calls under test, read no user or + # system configuration. + export GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 LAUNCH_ROOT="${BATS_TEST_TMPDIR}/launch" mkdir -p "${LAUNCH_ROOT}" git -C "${LAUNCH_ROOT}" init -q @@ -62,6 +65,7 @@ setup() { # shellcheck source=/dev/null source "${PLUGIN_DIR}/shared/worktree.sh" worktree_state_init + worktree_launch_common_init # Before any test body runs: the real exec_command reaches a container CLI # under a container environment. A test that means to exercise the probe # calls stub_worktree_probe to replace this. @@ -178,6 +182,22 @@ _resolve_and_report_binding() { assert_output "${LAUNCH_ROOT}|launch" } +# A call naming the launch root by another spelling means the launch root. Held +# to the worktree rules instead, it is refused as the main checkout. +@test "a call naming the launch root with a trailing slash resolves to the launch root" { + run _resolve_and_report "{\"project_root\":\"${LAUNCH_ROOT}/\"}" + assert_success + assert_output "${LAUNCH_ROOT}|call" +} + +@test "a call naming the launch root through a symlink resolves to the launch root" { + ln -s "${LAUNCH_ROOT}" "${BATS_TEST_TMPDIR}/launch-link" + + run _resolve_and_report "{\"project_root\":\"${BATS_TEST_TMPDIR}/launch-link\"}" + assert_success + assert_output "${LAUNCH_ROOT}|call" +} + # --- Successful match against a real worktree --- @test "a real linked worktree of the launch root resolves successfully" { @@ -246,6 +266,24 @@ FAKE assert_output --partial "${WORKTREE_B}" } +@test "a hand-made per-worktree directory outside the registry is refused as unlisted" { + # Every identity test ahead of the registry passes this: ".git" is a file + # with a relative pointer, the git dir differs from the common dir, the + # back-pointer names the candidate, and commondir names the launch + # repository. Only `git worktree list` does not know it. + local forged="${BATS_TEST_TMPDIR}/forged-rel" + local admin="${BATS_TEST_TMPDIR}/hand-made-admin" + mkdir -p "${forged}" "${admin}" + git -C "${LAUNCH_ROOT}" rev-parse HEAD > "${admin}/HEAD" + git -C "${LAUNCH_ROOT}" rev-parse --path-format=absolute --git-common-dir > "${admin}/commondir" + printf '%s/.git\n' "${forged}" > "${admin}/gitdir" + printf 'gitdir: ../hand-made-admin\n' > "${forged}/.git" + + run _resolve_and_report "{\"project_root\":\"${forged}\"}" + assert_failure + assert_output --partial "\`git worktree list\` in \"${LAUNCH_ROOT}\" does not list it" +} + @test "a back-pointer written relative resolves against the per-worktree directory" { # `git worktree add --relative-paths` writes BOTH links relative: the # ".git" pointer and the back-pointer, the latter relative to the @@ -471,9 +509,8 @@ _assert_worktree_config_refused() { run _resolve_and_report "{\"project_root\":\"${WORKTREE_A}\"}" assert_failure - assert_output --partial "${WORKTREE_A}/.mcp-php-tooling.json" - assert_output --partial "the configuration file in force" - assert_output --partial "does not parse as a JSON object" + assert_output --partial "Refusing to run against \"${WORKTREE_A}\": its configuration could not be loaded" + assert_output --partial "${WORKTREE_A}/.mcp-php-tooling.json does not hold a JSON object" } @test "a worktree config that does not parse as JSON is refused, naming the file" { @@ -492,6 +529,34 @@ _assert_worktree_config_refused() { _assert_worktree_config_refused 'null' } +# Two files are merged, and the merge refuses one that does not parse. That +# refusal must not read as "the worktree has no config of its own", which would +# run the call under the launch configuration. +@test "a worktree whose second config does not parse as JSON is refused, naming that file" { + mkdir -p "${WORKTREE_A}/.claude" + printf '{"environment":"native"}\n' > "${WORKTREE_A}/.mcp-php-tooling.json" + printf '{bad\n' > "${WORKTREE_A}/.claude/.mcp-php-tooling.json" + + run _resolve_and_report "{\"project_root\":\"${WORKTREE_A}\"}" + assert_failure + assert_output --partial "Refusing to run against \"${WORKTREE_A}\": its configuration could not be loaded" + assert_output --partial "${WORKTREE_A}/.claude/.mcp-php-tooling.json does not hold a JSON object" +} + +# The override is read on every call, so a file it names that is removed while +# the session runs refuses the call. The refusal names the variable, not the +# worktree's own files, which may not exist at all. +@test "a worktree call whose config override names a missing file is refused, naming the variable" { + local override="${BATS_TEST_TMPDIR}/override.json" + export MCP_PHP_TOOLING_CONFIG="${override}" + + run _resolve_and_report "{\"project_root\":\"${WORKTREE_A}\"}" + unset MCP_PHP_TOOLING_CONFIG + assert_failure + assert_output --partial "Refusing to run against \"${WORKTREE_A}\": MCP_PHP_TOOLING_CONFIG names the configuration file ${override}, which does not exist." + refute_output --partial "Fix that file, or remove it" +} + # The launch configuration parses at server start, so this state needs someone # to edit the file while the session runs — which is ordinary. Before the check # covered the inherited config, the call went through and ran with the @@ -571,6 +636,7 @@ LINT_ENV="native" LINT_WORKDIR="${PROJECT_ROOT}" source "${PLUGIN_DIR}/shared/worktree.sh" worktree_state_init +worktree_launch_common_init ( worktree_resolve_root "{\"project_root\":\"${WORKTREE_A}\"}" >/dev/null 2>&1 ) @@ -631,6 +697,7 @@ LINT_ENV="native" LINT_WORKDIR="${PROJECT_ROOT}" source "${PLUGIN_DIR}/shared/worktree.sh" worktree_state_init +worktree_launch_common_init _exists() { ls -1d "$1" 2>/dev/null | wc -l | tr -d ' '; } @@ -706,6 +773,7 @@ LINT_ENV="native" LINT_WORKDIR="${PROJECT_ROOT}" source "${PLUGIN_DIR}/shared/worktree.sh" worktree_state_init +worktree_launch_common_init _exists() { ls -1d "$1" 2>/dev/null | wc -l | tr -d ' '; } REPORT_FILE="${TMPDIR}/setter-report" @@ -953,12 +1021,7 @@ _assert_gitdir_classified() { _assert_gitdir_classified $'gitdir: /a\nb' invalid } -# --- An absolutely linked worktree is refused everywhere --- -# -# Enumerated at runtime, because the verdict does not vary with the -# environment: which environment a call runs under is a property of a -# configuration file, not of the pointer, so a root accepted natively today is -# reached through a container the moment one is configured. +# --- An absolutely linked worktree: accepted natively, refused in a container --- _ALL_ENVS=(native docker docker-compose vagrant ddev) @@ -973,22 +1036,27 @@ _worktree_gitdir_absolute() { printf 'gitdir: %s\n' "${target}" > "${wt}/.git" } -@test "an absolutely linked worktree is refused under every environment, naming the remediation" { +@test "an absolutely linked worktree is accepted under native" { _worktree_gitdir_absolute "${WORKTREE_A}" + run _resolve_and_report "{\"project_root\":\"${WORKTREE_A}\"}" + assert_success + assert_output "${WORKTREE_A}|call" +} + +@test "an absolutely linked worktree is refused under every container environment, naming the remediation" { + _worktree_gitdir_absolute "${WORKTREE_IN_ROOT}" + local environment - for environment in "${_ALL_ENVS[@]}"; do + for environment in "${_CONTAINER_ENVS[@]}"; do _write_launch_environment "${environment}" LINT_ENV="${environment}" - run _resolve_and_report "{\"project_root\":\"${WORKTREE_A}\"}" + run _resolve_and_report "{\"project_root\":\"${WORKTREE_IN_ROOT}\"}" assert_failure - assert_output --partial "carries an absolute gitdir pointer" - assert_output --partial "git -c worktree.useRelativePaths=true worktree repair \"${WORKTREE_A}\"" + assert_output --partial "carries an absolute gitdir pointer, which names a host path that does not exist inside a container" + assert_output --partial "git -c worktree.useRelativePaths=true worktree repair \"${WORKTREE_IN_ROOT}\"" done - - # Restore the fixture for any later test in this file. - worktree_gitdir_relative "${WORKTREE_A}" } # --- Charset refusals --- diff --git a/plugin-tests/dev-tooling/worktree_state.bats b/plugin-tests/dev-tooling/worktree_state.bats index 67367d27..1c838da4 100644 --- a/plugin-tests/dev-tooling/worktree_state.bats +++ b/plugin-tests/dev-tooling/worktree_state.bats @@ -56,6 +56,7 @@ setup() { # shellcheck source=/dev/null source "${PLUGIN_DIR}/shared/worktree.sh" worktree_state_init + worktree_launch_common_init # Before any test body runs: the real exec_command reaches a container CLI # under a container environment. A test that means to exercise the probe # calls stub_worktree_probe to replace this. diff --git a/plugin-tests/mcp-shared/config.bats b/plugin-tests/mcp-shared/config.bats index 35a18b57..89b56855 100644 --- a/plugin-tests/mcp-shared/config.bats +++ b/plugin-tests/mcp-shared/config.bats @@ -1,8 +1,9 @@ #!/usr/bin/env bats # bats file_tags=mcp-core,config -# Tests for the shared config module's filename and environment-variable prefix -# parameterization: the MCP path (.mcp-.json, MCP_*_CONFIG), the LSP path -# (.lsp-.json, LSP_*_CONFIG), and the two required-input refusals. +# Tests for the shared config module's filename and environment-variable +# derivation from CONFIG_PREFIX (.mcp-.json, MCP_*_CONFIG), its +# required-input refusal, the merge of more than one discovered file, and the +# refusal of a config file that does not hold a JSON object. # Sources the template source of truth (templates/mcp-shared/config.sh); every # plugin copy is kept byte-identical to it by the template-sync CI check, so this # one suite covers the module in all consuming plugins. @@ -14,13 +15,12 @@ setup() { CONFIG_SH="${REPO_ROOT}/templates/mcp-shared/config.sh" } -@test "MCP path: CONFIG_FILE_NAME is .mcp-php-tooling.json when CONFIG_FILE_PREFIX unset" { +@test "CONFIG_FILE_NAME is .mcp-php-tooling.json and CONFIG_ENV_VAR is MCP_PHP_TOOLING_CONFIG" { run bash -c " set -euo pipefail log() { :; } export -f log CONFIG_PREFIX='php-tooling' - unset CONFIG_FILE_PREFIX CONFIG_ENV_VAR_PREFIX source '${CONFIG_SH}' printf '%s|%s\n' \"\${CONFIG_FILE_NAME}\" \"\${CONFIG_ENV_VAR}\" " @@ -28,43 +28,104 @@ setup() { assert_line --index -1 ".mcp-php-tooling.json|MCP_PHP_TOOLING_CONFIG" } -@test "LSP path: CONFIG_FILE_NAME is .lsp-php-tooling.json when CONFIG_FILE_PREFIX=.lsp-" { +@test "Missing CONFIG_PREFIX fails" { run bash -c " set -euo pipefail log() { :; } export -f log + unset CONFIG_PREFIX + source '${CONFIG_SH}' + " + assert_failure + assert_output --partial "CONFIG_PREFIX must be set" +} + +# The merge runs whenever two discovery locations hold a file, and its temp file +# is the server's for the rest of the process. The EXIT trap config.sh installs +# is what removes it, so the observation is made after the process has exited. +@test "the merged config of two discovered files is removed when the process exits" { + local project="${BATS_TEST_TMPDIR}/project" + mkdir -p "${project}/.claude" "${BATS_TEST_TMPDIR}/tmp" + printf '{"environment":"native"}\n' > "${project}/.mcp-php-tooling.json" + printf '{"default_scope":"x"}\n' > "${project}/.claude/.mcp-php-tooling.json" + + run bash -c " + set -euo pipefail + log() { :; } + # Places the merge's temp file where the test can list it; macOS mktemp + # ignores TMPDIR when it is called without a template. + mktemp() { command mktemp '${BATS_TEST_TMPDIR}/tmp/merged.XXXXXX'; } CONFIG_PREFIX='php-tooling' - CONFIG_FILE_PREFIX='.lsp-' - CONFIG_ENV_VAR_PREFIX='LSP' source '${CONFIG_SH}' - printf '%s|%s\n' \"\${CONFIG_FILE_NAME}\" \"\${CONFIG_ENV_VAR}\" + load_config '${project}' + jq -c . \"\${LINT_CONFIG_FILE}\" + printf '%s\n' \"\${LINT_CONFIG_FILE}\" " assert_success - assert_line --index -1 ".lsp-php-tooling.json|LSP_PHP_TOOLING_CONFIG" + assert_line --index 0 '{"environment":"native","default_scope":"x"}' + assert_line --index 1 --regexp "^${BATS_TEST_TMPDIR}/tmp/" + run find "${BATS_TEST_TMPDIR}/tmp" -type f + assert_output "" } -@test "LSP path fails when CONFIG_FILE_PREFIX set but CONFIG_ENV_VAR_PREFIX unset" { +# Runs load_config against a project, logging to stdout. +# Args: $1 = project directory +_run_load_config() { run bash -c " set -euo pipefail - log() { :; } - export -f log + log() { printf '%s: %s\n' \"\$1\" \"\$2\"; } CONFIG_PREFIX='php-tooling' - CONFIG_FILE_PREFIX='.lsp-' - unset CONFIG_ENV_VAR_PREFIX source '${CONFIG_SH}' + if load_config '$1'; then + printf 'loaded: %s\n' \"\${LINT_CONFIG_FILE:-}\" + else + printf 'load_config failed\n' + fi " - assert_failure - assert_output --partial "CONFIG_ENV_VAR_PREFIX required" } -@test "Missing CONFIG_PREFIX fails on the MCP path" { +# Valid JSON that is not an object merges into nothing usable, so the refusal +# states the requirement rather than calling the file invalid JSON. +@test "a discovered config holding a JSON value that is not an object fails the merge, naming the file" { + local project="${BATS_TEST_TMPDIR}/project" + mkdir -p "${project}/.claude" + printf '{"environment":"native"}\n' > "${project}/.mcp-php-tooling.json" + printf '[]\n' > "${project}/.claude/.mcp-php-tooling.json" + + _run_load_config "${project}" + assert_success + assert_line "ERROR: ${project}/.claude/.mcp-php-tooling.json does not hold a JSON object: a config file must be valid JSON whose top-level value is an object" + assert_line --index -1 "load_config failed" +} + +@test "a config override holding a JSON value that is not an object fails, naming the file" { + local override="${BATS_TEST_TMPDIR}/override.json" + printf '[]\n' > "${override}" + run bash -c " set -euo pipefail - log() { :; } - export -f log - unset CONFIG_PREFIX CONFIG_FILE_PREFIX CONFIG_ENV_VAR_PREFIX + log() { printf '%s: %s\n' \"\$1\" \"\$2\"; } + CONFIG_PREFIX='php-tooling' + MCP_PHP_TOOLING_CONFIG='${override}' source '${CONFIG_SH}' + if load_config '${BATS_TEST_TMPDIR}'; then + printf 'loaded: %s\n' \"\${LINT_CONFIG_FILE:-}\" + else + printf 'load_config failed\n' + fi " - assert_failure - assert_output --partial "CONFIG_PREFIX must be set" + assert_success + assert_line "ERROR: ${override} does not hold a JSON object: a config file must be valid JSON whose top-level value is an object" + assert_line --index -1 "load_config failed" +} + +@test "a single discovered config that is not valid JSON fails, naming the file" { + local project="${BATS_TEST_TMPDIR}/project" + mkdir -p "${project}" + printf '{bad\n' > "${project}/.mcp-php-tooling.json" + + _run_load_config "${project}" + assert_success + assert_line "ERROR: ${project}/.mcp-php-tooling.json does not hold a JSON object: a config file must be valid JSON whose top-level value is an object" + assert_line --index -1 "load_config failed" } diff --git a/plugin-tests/mcp-shared/docker_compose.bats b/plugin-tests/mcp-shared/docker_compose.bats index 978c5c25..03dc81ef 100644 --- a/plugin-tests/mcp-shared/docker_compose.bats +++ b/plugin-tests/mcp-shared/docker_compose.bats @@ -207,46 +207,78 @@ _compose_recorded_dirs() { assert_output --partial "Service 'web' is not running" } +# The compose CLI writes its own warnings to stderr (an unset variable, an +# obsolete `version` key) ahead of valid JSON on stdout. The text jq parses +# must be stdout alone; stderr is for the failure messages. @test "_compose_resolve_container: fails when service not defined in compose" { docker() { if [[ "$1" == "compose" && "$2" == "ps" ]]; then return 0 fi if [[ "$1" == "compose" && "$2" == "config" ]]; then + printf '%s\n' 'WARN[0000] the attribute version is obsolete' >&2 echo '{"services":{"database":{},"adminer":{}}}' return 0 fi command docker "$@" } - export -f docker COMPOSE_SERVICE="web" COMPOSE_FILE_OVERRIDE="" run _compose_resolve_container assert_failure - assert_output --partial "Service 'web' not found in compose config" - assert_output --partial "Available services:" + assert_output --partial "Service 'web' not found in compose config. Available services: adminer, database" +} + +@test "_compose_resolve_container: a compose warning on stderr does not break the parse of the running service" { + docker() { + if [[ "$1" == "compose" && "$2" == "ps" ]]; then + printf '%s\n' 'WARN[0000] The "FOO" variable is not set. Defaulting to a blank string.' >&2 + echo '{"Service":"web","Name":"shopware-web-1","State":"running"}' + return 0 + fi + command docker "$@" + } + run _compose_resolve_container + assert_success + assert_output "shopware-web-1" +} + +@test "_compose_resolve_container: a failing ps query carries the CLI's stderr in the message" { + docker() { + if [[ "$1" == "compose" && "$2" == "ps" ]]; then + printf '%s\n' 'Cannot connect to the Docker daemon' >&2 + return 1 + fi + command docker "$@" + } + run _compose_resolve_container + assert_failure + # One line: a probe that printed nothing to stdout adds no blank line. + assert_output "Failed to query running containers: Cannot connect to the Docker daemon" } # --- _compose_resolve_workdir --- -# The resolver answers for the root the call targets, not for the launch tree: -# answering for the launch tree is what makes a worktree call cd into the launch -# tree's container path and run there under the worktree's name. -@test "_compose_resolve_workdir: resolves the targeted root rather than the launch root" { +# Answers `docker compose config` with one bind mount of the test directory at +# /var/www/html, preceded by a warning on stderr the way the compose CLI writes +# one: the bind-mount parse has to read stdout alone. +_stub_compose_bind_mount() { docker() { if [[ "$1" == "compose" && "$2" == "config" ]]; then - cat <&2 + printf '{"services":{"web":{"volumes":[{"type":"bind","source":"%s","target":"/var/www/html"}]}}}\n' \ + "${BATS_TEST_TMPDIR}" return 0 fi command docker "$@" } - export -f docker - COMPOSE_WORKDIR_OVERRIDE="" - COMPOSE_SERVICE="web" - COMPOSE_FILE_OVERRIDE="" - PROJECT_ROOT="${BATS_TEST_TMPDIR}" +} + +# The resolver answers for the root the call targets, not for the launch tree: +# answering for the launch tree is what makes a worktree call cd into the launch +# tree's container path and run there under the worktree's name. +@test "_compose_resolve_workdir: resolves the targeted root rather than the launch root" { + _stub_compose_bind_mount WORKTREE_EFFECTIVE_ROOT="${BATS_TEST_TMPDIR}/.claude/worktrees/x" run _compose_resolve_workdir @@ -262,20 +294,7 @@ JSONEOF } @test "_compose_resolve_workdir: detects bind mount target matching project root" { - docker() { - if [[ "$1" == "compose" && "$2" == "config" ]]; then - cat < "${LINT_CONFIG_FILE}" + run _get_config_value '.phpunit.testsuite' 'default-suite' + assert_failure + assert_output --partial "Config error: jq could not evaluate .phpunit.testsuite against ${LINT_CONFIG_FILE}" + assert_output --partial 'Cannot index string' + refute_output --partial 'default-suite' +} + +@test "config lookup: missing key uses the optional default" { + LINT_CONFIG_FILE="${BATS_TEST_TMPDIR}/config.json" + printf '%s\n' '{"phpunit":{}}' > "${LINT_CONFIG_FILE}" + run _get_config_value '.phpunit.testsuite' 'default-suite' + assert_success + assert_output 'default-suite' } # --- Native environment --- @@ -92,23 +111,9 @@ teardown() { # --- DDEV environment --- -@test "wrap_command ddev: non-composer command uses ddev exec" { - LINT_ENV="ddev" - run wrap_command "vendor/bin/phpunit" - assert_success - assert_output --partial "ddev exec vendor/bin/phpunit" -} - -@test "wrap_command ddev: composer command uses ddev without exec" { - LINT_ENV="ddev" - run wrap_command "composer phpstan" - assert_success - assert_output "ddev composer phpstan" - refute_output --partial "ddev exec" -} - @test "wrap_command ddev: preserves XDEBUG_MODE prefix in ddev exec" { LINT_ENV="ddev" + LINT_WORKDIR="/var/www/html" run wrap_command "XDEBUG_MODE=coverage vendor/bin/phpunit --coverage-text" assert_success assert_output --partial "ddev exec XDEBUG_MODE=coverage vendor/bin/phpunit" @@ -203,6 +208,43 @@ teardown() { assert_output 'probed:npm pkg get "scripts.unit:components"' } +# A warning on stderr must not reach the parsed probe answer. Every environment +# shares exec_npm_command's redirect, so the native one stands for all of them. +_npm_probe_native_env() { + LINT_ENV="native" + LINT_WORKDIR="${BATS_TEST_TMPDIR}" + JS_CONTEXT="" + SCOPE_CWD="" + SCOPE_JS_SUBDIR="" +} + +@test "npm_script_body: a warning npm writes to stderr does not reach the parsed answer" { + _npm_probe_native_env + npm() { + printf '%s\n' 'npm warn config production Use --omit=dev instead.' >&2 + printf '%s\n' '"eslint"' + } + run npm_script_body "lint" + assert_success + assert_output "eslint" +} + +@test "npm_script_body: a failing probe is unusable and its message carries the stderr" { + _npm_probe_native_env + local log_file="${BATS_TEST_TMPDIR}/log" + log() { printf '%s: %s\n' "$1" "$2" >> "${log_file}"; } + npm() { + printf '%s\n' 'boom' >&2 + return 1 + } + run npm_script_body "lint" + assert_failure 2 + assert_output "" + run cat "${log_file}" + assert_output --partial 'npm_script_body: probe for "lint" failed:' + assert_output --partial "boom" +} + @test "npm_script_body: refuses a script name that cannot be embedded, before probing" { exec_npm_command() { printf '%s\n' '"probe-ran"'; } run npm_script_body "lint'; id; :" @@ -811,12 +853,83 @@ _assert_configured_mapping_refuses() { assert_equal "${rc}" 1 } +# The name selects how every later command is wrapped, and a name no wrapper +# knows runs them on the host as though it were native. "dockr" is the typo that +# does exactly that. +@test "detect_environment: refuses an environment name no wrapper knows, naming it" { + LINT_CONFIG_FILE="${BATS_TEST_TMPDIR}/launch.json" + printf '%s\n' '{"environment":"dockr"}' > "${LINT_CONFIG_FILE}" + log() { printf '%s: %s\n' "$1" "$2"; } + + run detect_environment "/project" + assert_failure 1 + assert_output --partial "${LINT_CONFIG_FILE} declares environment \"dockr\", which this server does not recognize." + assert_output --partial "native, docker, docker-compose, vagrant, ddev" +} + +@test "detect_environment: accepts each environment name the wrappers know" { + LINT_CONFIG_FILE="${BATS_TEST_TMPDIR}/launch.json" + local name + for name in native docker docker-compose vagrant ddev; do + jq -n --arg env "${name}" \ + '{environment: $env, docker: {container: "web"}, "docker-compose": {service: "web"}}' \ + > "${LINT_CONFIG_FILE}" + run detect_environment "/project" + assert_success + done +} + @test "detect_environment: refuses a docker config with no container" { LINT_CONFIG_FILE="${BATS_TEST_TMPDIR}/launch.json" printf '%s\n' '{"environment":"docker"}' > "${LINT_CONFIG_FILE}" run detect_environment "/project" assert_failure 1 + assert_output --partial '".docker.container" is missing or empty' +} + +# Merges a base file holding $1 with a second file, then runs detect_environment. +# Args: $1 = the base file's JSON +# Globals: sets MERGED_SOURCES to the two source paths as the refusal names them, +# MERGED_TEMP_FILE to the merged temp file, which no refusal may name +_detect_merged_environment() { + local project="${BATS_TEST_TMPDIR}/project" + mkdir -p "${project}/.claude" + printf '%s\n' "$1" > "${project}/.mcp-php-tooling.json" + printf '{"default_scope":"x"}\n' > "${project}/.claude/.mcp-php-tooling.json" + MERGED_SOURCES="${project}/.mcp-php-tooling.json ${project}/.claude/.mcp-php-tooling.json" + local temp_record="${BATS_TEST_TMPDIR}/merged-temp-path" + + run bash -c " + set -euo pipefail + log() { printf '%s: %s\n' \"\$1\" \"\$2\"; } + CONFIG_PREFIX='php-tooling' + source '${REPO_ROOT}/templates/mcp-shared/config.sh' + source '${REPO_ROOT}/templates/mcp-shared/environment.sh' + load_config '${project}' >/dev/null + printf '%s' \"\${_CONFIG_TEMP_FILE}\" > '${temp_record}' + detect_environment '${project}' + " + MERGED_TEMP_FILE=$(< "${temp_record}") +} + +# A merged configuration lives in a temp file the server removes on exit, so +# every refusal names the files the user can open. +@test "detect_environment: each refusal of a merged configuration names its source files" { + _detect_merged_environment '{"environment":"dockr"}' + assert_failure 1 + assert_output --partial "ERROR: the configuration merged from ${MERGED_SOURCES} declares environment \"dockr\"" + + _detect_merged_environment '{"docker":{"container":"web"}}' + assert_failure 1 + assert_output --partial "ERROR: Missing 'environment' field in the configuration merged from ${MERGED_SOURCES}" + + _detect_merged_environment '{"environment":"docker"}' + assert_failure 1 + assert_output --partial "Refusing to run: the \"docker\" environment requires a container name in the configuration merged from ${MERGED_SOURCES}," + assert_output --partial "ERROR: Could not derive the environment from the configuration merged from ${MERGED_SOURCES}:" + assert [ -n "${MERGED_TEMP_FILE}" ] + refute_output --partial "${MERGED_TEMP_FILE}" } # A workdir of "/" is the container root. The join is where the doubled @@ -840,6 +953,18 @@ _assert_configured_mapping_refuses() { assert_output --partial "${absent}" } +# The name selects how every later command is wrapped; one no wrapper knows +# would otherwise be derived as native and run every command on the host. +@test "_set_workdir_from_config: refuses an environment name no wrapper knows, naming it" { + local config="${BATS_TEST_TMPDIR}/typo.json" + printf '%s\n' '{"environment":"dockr"}' > "${config}" + + run _set_workdir_from_config "/worktree" "${config}" "dockr" + assert_failure 1 + assert_output --partial "${config} declares environment \"dockr\", which this server does not recognize." + assert_output --partial "Known environments: native, docker, docker-compose, vagrant, ddev." +} + @test "_set_workdir_from_config: refuses an empty environment, naming the field" { local config="${BATS_TEST_TMPDIR}/worktree.json" printf '%s\n' '{"docker":{"container":"worktree-container"}}' > "${config}" @@ -935,3 +1060,42 @@ _assert_configured_mapping_refuses() { assert_success assert_output "ddev composer install" } + +# ddev's own default directory is /var/www/html, so a configured ddev.workdir +# other than that reaches the container only when it is named. Bound through +# _set_workdir_from_config, the way the server binds it at startup. +_bind_ddev_workdir() { + LINT_CONFIG_FILE="${BATS_TEST_TMPDIR}/.mcp-php-tooling.json" + printf '{"environment":"ddev","ddev":{"workdir":"%s"}}\n' "$1" > "${LINT_CONFIG_FILE}" + LINT_ENV="ddev" + PROJECT_ROOT="${BATS_TEST_TMPDIR}/project" + WORKTREE_EFFECTIVE_ROOT="${PROJECT_ROOT}" + _set_workdir_from_config "${PROJECT_ROOT}" "${LINT_CONFIG_FILE}" ddev +} + +@test "wrap_command ddev: an unscoped command at the launch root names a non-default ddev.workdir" { + _bind_ddev_workdir "/var/www/html/shopware" + run wrap_command "vendor/bin/phpunit" + assert_success + assert_output 'ddev exec -d "/var/www/html/shopware" vendor/bin/phpunit' +} + +@test "wrap_command ddev: an unscoped composer call at the launch root names a non-default ddev.workdir" { + _bind_ddev_workdir "/var/www/html/shopware" + run wrap_command "composer install" + assert_success + assert_output 'ddev exec -d "/var/www/html/shopware" composer install' +} + +# A server with the worktree module answers a launch-root call from the workdir +# it bound at startup; an edit of the launch configuration mid-session is inert. +@test "wrap_command ddev: a launch-root call names the bound non-default ddev.workdir after the file changed" { + _bind_ddev_workdir "/var/www/html/shopware" + WORKTREE_LAUNCH_CONFIG_FILE="${LINT_CONFIG_FILE}" + WORKTREE_SELECTED_CONFIG_FILE="${LINT_CONFIG_FILE}" + printf '%s\n' '{"environment":"ddev"}' > "${LINT_CONFIG_FILE}" + + run wrap_command "composer install" + assert_success + assert_output 'ddev exec -d "/var/www/html/shopware" composer install' +} diff --git a/plugin-tests/mcp-shared/scope_wrap.bats b/plugin-tests/mcp-shared/scope_wrap.bats index a6a4af97..449d80ef 100644 --- a/plugin-tests/mcp-shared/scope_wrap.bats +++ b/plugin-tests/mcp-shared/scope_wrap.bats @@ -74,15 +74,6 @@ _make_hostile_dir() { assert_output --partial "cd /vagrant/custom/plugins/X && vendor/bin/phpstan" } -@test "wrap_command ddev: no scope -> ddev exec unchanged" { - LINT_ENV="ddev" - LINT_WORKDIR="/var/www/html" - SCOPE_CWD="" - run wrap_command "vendor/bin/phpstan" - assert_success - assert_output "ddev exec vendor/bin/phpstan" -} - @test "wrap_command ddev: scope adds -d flag" { LINT_ENV="ddev" LINT_WORKDIR="/var/www/html" @@ -101,15 +92,6 @@ _make_hostile_dir() { assert_output 'ddev exec -d "/var/www/html/custom/plugins/X" composer install' } -@test "wrap_command ddev: no-scope composer still uses ddev composer shortcut" { - LINT_ENV="ddev" - LINT_WORKDIR="/var/www/html" - SCOPE_CWD="" - run wrap_command "composer install" - assert_success - assert_output "ddev composer install" -} - @test "get_js_workdir: no scope, admin context -> core admin path" { LINT_WORKDIR="/project" JS_CONTEXT="admin" @@ -181,8 +163,8 @@ _make_hostile_dir() { assert_output "${LINT_WORKDIR}" } -# detect_environment assigns whatever ".environment" holds into LINT_ENV with no -# allowlist, so a typo reaches the wrappers' unknown-environment branch and the +# detect_environment refuses an unknown name, but a caller that sets LINT_ENV +# itself can still reach the wrappers' unknown-environment branch, and the # command it emits runs locally. The working directory has to be entered there # too: leaving it to a `cd` inside the emitted string would put a "$" or a # backtick from the project root into text that exec_npm_command evals. @@ -218,7 +200,7 @@ _make_hostile_dir() { assert_output --partial "${BATS_TEST_TMPDIR}/absent" } -@test "wrap_npm_command ddev: scoped path uses cd && ddev npm" { +@test "wrap_npm_command ddev: a scoped launch-root call names the container workdir with ddev exec -d" { LINT_ENV="ddev" LINT_WORKDIR="/var/www/html" JS_CONTEXT="storefront" @@ -226,39 +208,12 @@ _make_hostile_dir() { SCOPE_JS_SUBDIR="" run wrap_npm_command "npm run lint" assert_success - assert_output "cd /var/www/html/custom/plugins/X && ddev npm run lint" -} - -# A call that targets a worktree runs against a directory ddev does not know as -# its project root, so the JS working directory has to reach the container; -d -# is how ddev's exec takes one. -@test "wrap_npm_command ddev: a call against a worktree names the JS working directory" { - LINT_ENV="ddev" - LINT_WORKDIR="/var/www/html/.claude/worktrees/x" - JS_CONTEXT="storefront" - SCOPE_CWD="" - SCOPE_JS_SUBDIR="" - PROJECT_ROOT="${BATS_TEST_TMPDIR}/project" - WORKTREE_EFFECTIVE_ROOT="${PROJECT_ROOT}/.claude/worktrees/x" - run wrap_npm_command "npm run lint" - assert_success - assert_output 'ddev exec -d "/var/www/html/.claude/worktrees/x/src/Storefront/Resources/app/storefront" npm run lint' -} - -@test "wrap_npm_command ddev: a worktree call carries the scope suffix in the named workdir" { - LINT_ENV="ddev" - LINT_WORKDIR="/var/www/html/.claude/worktrees/x" - JS_CONTEXT="storefront" - SCOPE_CWD="custom/plugins/X" - SCOPE_JS_SUBDIR="tests/jest/storefront" - PROJECT_ROOT="${BATS_TEST_TMPDIR}/project" - WORKTREE_EFFECTIVE_ROOT="${PROJECT_ROOT}/.claude/worktrees/x" - run wrap_npm_command "npm run lint" - assert_success - assert_output 'ddev exec -d "/var/www/html/.claude/worktrees/x/custom/plugins/X/tests/jest/storefront" npm run lint' + assert_output 'ddev exec -d "/var/www/html/custom/plugins/X" npm run lint' } -@test "wrap_npm_command ddev: a launch-root call keeps the ddev npm shortcut" { +# The JS working directory is a container path, so a host-side `cd` into it +# would fail. A worktree call takes the same branch with its mapped workdir. +@test "wrap_npm_command ddev: a launch-root call names the JS working directory and emits no host cd" { LINT_ENV="ddev" LINT_WORKDIR="/var/www/html" JS_CONTEXT="storefront" @@ -268,5 +223,5 @@ _make_hostile_dir() { WORKTREE_EFFECTIVE_ROOT="${PROJECT_ROOT}" run wrap_npm_command "npm run lint" assert_success - assert_output "cd /var/www/html/src/Storefront/Resources/app/storefront && ddev npm run lint" + assert_output 'ddev exec -d "/var/www/html/src/Storefront/Resources/app/storefront" npm run lint' } diff --git a/plugin-tests/shopware-env/config_fallback.bats b/plugin-tests/shopware-env/config_fallback.bats index dae54c03..fae9026e 100644 --- a/plugin-tests/shopware-env/config_fallback.bats +++ b/plugin-tests/shopware-env/config_fallback.bats @@ -27,6 +27,40 @@ load 'test_helper/common_setup' assert_equal "$DOCKER_CONTAINER" "shopware-app" } +@test "resolve_lifecycle_env: refuses docker args without docker_service" { + setup_lifecycle_mcp_env "${PLUGIN_DIR}/mcp-server-lifecycle/lib/dependencies.sh" + LIFECYCLE_HAS_CONFIG="false" + run resolve_lifecycle_env '{"environment": "docker"}' + assert_failure 1 + assert_output --partial "the docker environment requires a 'docker_service' argument" +} + +# Without a configuration nothing names the container's workdir, so it is the +# default dev-tooling binds; the host project root does not exist in there. +@test "resolve_lifecycle_env: docker and vagrant args run in the container default workdir, not the host root" { + setup_lifecycle_mcp_env "${PLUGIN_DIR}/mcp-server-lifecycle/lib/dependencies.sh" + LIFECYCLE_HAS_CONFIG="false" + unset LINT_CONFIG_FILE + + resolve_lifecycle_env '{"environment": "docker", "docker_service": "web"}' + run wrap_command "composer install" + assert_output "docker exec -i \"web\" bash -c 'cd /var/www/html && composer install'" + + resolve_lifecycle_env '{"environment": "vagrant"}' + run wrap_command "composer install" + assert_output "vagrant ssh -c 'cd /vagrant && composer install'" +} + +@test "resolve_lifecycle_env: ddev args keep ddev's own argv at the default workdir" { + setup_lifecycle_mcp_env "${PLUGIN_DIR}/mcp-server-lifecycle/lib/dependencies.sh" + LIFECYCLE_HAS_CONFIG="false" + unset LINT_CONFIG_FILE + + resolve_lifecycle_env '{"environment": "ddev"}' + run wrap_command "composer install" + assert_output "ddev composer install" +} + @test "resolve_lifecycle_env: fails when no config and no arg" { setup_lifecycle_mcp_env "${PLUGIN_DIR}/mcp-server-lifecycle/lib/dependencies.sh" LIFECYCLE_HAS_CONFIG="false" @@ -34,3 +68,57 @@ load 'test_helper/common_setup' assert_failure assert_output --partial "no .mcp-php-tooling.json config found" } + +# Argument-path setup for docker-compose: restores the real exec_command that +# setup_lifecycle_mcp_env stubs out, and puts a docker stub on PATH that logs +# every argv to DOCKER_LOG and answers the compose queries issued before the exec. +setup_docker_compose_args_env() { + setup_lifecycle_mcp_env "${PLUGIN_DIR}/mcp-server-lifecycle/lib/dependencies.sh" + source "${PLUGIN_DIR}/shared/environment.sh" + LIFECYCLE_HAS_CONFIG="false" + LINT_ENV="" + PROJECT_ROOT="$(cd "${BATS_TEST_TMPDIR}" && pwd -P)" + LINT_WORKDIR="${PROJECT_ROOT}" + DOCKER_LOG="${BATS_TEST_TMPDIR}/docker.log" + : > "${DOCKER_LOG}" + mkdir -p "${BATS_TEST_TMPDIR}/bin" + cat > "${BATS_TEST_TMPDIR}/bin/docker" <> "${DOCKER_LOG}" +case "\$*" in + *"compose version"*) echo "Docker Compose version v2.20.0" ;; + *"ps --format json"*) echo '{"Service":"web","Name":"proj-web-1"}' ;; + *"config --format json"*) echo '{"services":{"web":{"volumes":[{"type":"bind","source":"${PROJECT_ROOT}","target":"/var/www/html"}]}}}' ;; +esac +STUB + chmod +x "${BATS_TEST_TMPDIR}/bin/docker" + PATH="${BATS_TEST_TMPDIR}/bin:${PATH}" +} + +@test "resolve_lifecycle_env: docker-compose args with compose_file reach docker with -f" { + setup_docker_compose_args_env + run tool_install_dependencies '{"environment": "docker-compose", "docker_service": "web", "compose_file": "docker-compose.test.yml", "composer": true}' + assert_success + run cat "${DOCKER_LOG}" + assert_output --partial "compose -f ${PROJECT_ROOT}/docker-compose.test.yml" + assert_output --partial "exec -i proj-web-1" + assert_output --partial "composer install" +} + +@test "resolve_lifecycle_env: docker-compose args without compose_file reach docker without -f" { + setup_docker_compose_args_env + run tool_install_dependencies '{"environment": "docker-compose", "docker_service": "web", "composer": true}' + assert_success + run cat "${DOCKER_LOG}" + assert_output --partial "composer install" + refute_output --partial "compose -f" +} + +@test "resolve_lifecycle_env: refuses docker-compose args without docker_service before calling docker" { + setup_docker_compose_args_env + run tool_install_dependencies '{"environment": "docker-compose", "composer": true}' + assert_failure + assert_output --partial "docker_service" + assert_output --partial "docker-compose" + assert_equal "$(< "${DOCKER_LOG}")" "" +} diff --git a/plugin-tests/shopware-env/hook_enforcement.bats b/plugin-tests/shopware-env/hook_enforcement.bats index 3904c022..e93602ab 100644 --- a/plugin-tests/shopware-env/hook_enforcement.bats +++ b/plugin-tests/shopware-env/hook_enforcement.bats @@ -36,11 +36,11 @@ bats_test_function --description "blocks bin/console plugin:activate → suggest # frontend build chain commands bats_test_function --description "blocks bin/console bundle:dump → suggests frontend_build_*" \ - -- lifecycle_hook_blocks "bin/console bundle:dump" "frontend_build_admin or frontend_build_storefront" + -- lifecycle_hook_blocks "bin/console bundle:dump" "\`frontend_build_admin\` or \`frontend_build_storefront\`" bats_test_function --description "blocks bin/console theme:compile → suggests frontend_build_storefront" \ -- lifecycle_hook_blocks "bin/console theme:compile" "frontend_build_storefront" bats_test_function --description "blocks bin/console assets:install → suggests frontend_build_*" \ - -- lifecycle_hook_blocks "bin/console assets:install" "frontend_build_admin or frontend_build_storefront" + -- lifecycle_hook_blocks "bin/console assets:install" "\`frontend_build_admin\` or \`frontend_build_storefront\`" @test "allows unrelated commands without block message" { run_hook "check-lifecycle-tools.sh" "git status" @@ -62,4 +62,22 @@ bats_test_function --description "blocks bin/console assets:install → suggests run_hook_cursor "check-lifecycle-tools.sh" "composer install" assert_failure 2 assert_output --partial "install_dependencies" + assert_output --partial "on the \`lifecycle-tooling\` MCP server" +} + +@test "block message names the tool and server without a host mcp__ prefix" { + run_hook "check-lifecycle-tools.sh" "composer install" + assert_failure 2 + assert_output --partial "Use \`install_dependencies\` on the \`lifecycle-tooling\` MCP server instead!" + refute_output --partial "mcp__" +} + +# bats test_tags=cwd +@test "reads the config from the hook input cwd when CURSOR_PROJECT_DIR is unset" { + unset CURSOR_PROJECT_DIR + local project + project=$(make_cwd_project "php-tooling" "ddev") + run_hook_with_cwd "check-lifecycle-tools.sh" "composer install" "$project" + assert_failure 2 + assert_output --partial "'ddev' environment" } diff --git a/plugin-tests/shopware-env/lifecycle_startup.bats b/plugin-tests/shopware-env/lifecycle_startup.bats new file mode 100644 index 00000000..ea3048be --- /dev/null +++ b/plugin-tests/shopware-env/lifecycle_startup.bats @@ -0,0 +1,79 @@ +#!/usr/bin/env bats +# bats file_tags=shopware-env,config +bats_require_minimum_version 1.11.0 + +# Starts the real lifecycle server against a project directory. Its config is +# optional: a project with none starts and its tools take the environment from +# their arguments. A config that is present but cannot be loaded is not "none". + +load 'test_helper/common_setup' + +INITIALIZE='{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"bats","version":"1"}}}' + +setup() { + # A copy, so the server's log lands outside the checkout. + SERVER_COPY="${BATS_TEST_TMPDIR}/plugin" + mkdir -p "${SERVER_COPY}" + cp -R "${PLUGIN_DIR}/shared" "${PLUGIN_DIR}/mcp-server-lifecycle" "${SERVER_COPY}/" + rm -f "${SERVER_COPY}/mcp-server-lifecycle/server.log" + + PROJECT="${BATS_TEST_TMPDIR}/project" + mkdir -p "${PROJECT}" +} + +# Runs the server in PROJECT over one initialize request. +_start_server() { + # shellcheck disable=SC2016 # the inner bash expands its own positional parameters + run --separate-stderr bash -c 'cd "$1" && PROJECT_ROOT="$1" "$2" <<< "$3"' _ \ + "${PROJECT}" "${SERVER_COPY}/mcp-server-lifecycle/server.sh" "${INITIALIZE}" +} + +@test "a project holding no config starts the server" { + _start_server + + assert_success + run jq -r 'select(.id == 0) | .result.serverInfo.name' <<< "${output}" + assert_output "lifecycle-tooling" +} + +# The refusal's wording is pinned where load_config is tested; here only that +# the server stops with a message. +@test "a second config file that is not valid JSON stops the server" { + mkdir -p "${PROJECT}/.claude" + printf '{"environment":"native"}\n' > "${PROJECT}/.mcp-php-tooling.json" + printf '{bad\n' > "${PROJECT}/.claude/.mcp-php-tooling.json" + + _start_server + + assert_failure 1 + assert_output "" + # This bats-assert has no assert_stderr; asserted through output for its diff. + output="${stderr}" + refute_output "" +} + +# The host names the project in PROJECT_ROOT and starts the server elsewhere, so +# the override is read against the project root, not the process's directory. +@test "a relative config override is read against PROJECT_ROOT, not the process directory" { + mkdir -p "${PROJECT}/cfg" "${BATS_TEST_TMPDIR}/elsewhere" + printf '{"environment":"native"}\n' > "${PROJECT}/cfg/php.json" + + # shellcheck disable=SC2016 # the inner bash expands its own positional parameters + run --separate-stderr bash -c 'cd "$1" && PROJECT_ROOT="$2" MCP_PHP_TOOLING_CONFIG=cfg/php.json "$3" <<< "$4"' _ \ + "${BATS_TEST_TMPDIR}/elsewhere" "${PROJECT}" "${SERVER_COPY}/mcp-server-lifecycle/server.sh" "${INITIALIZE}" + + assert_success + run jq -r 'select(.id == 0) | .result.serverInfo.name' <<< "${output}" + assert_output "lifecycle-tooling" +} + +@test "a config override naming a missing file stops the server, naming the file" { + export MCP_PHP_TOOLING_CONFIG="${BATS_TEST_TMPDIR}/missing.json" + + _start_server + + assert_failure 1 + assert_output "" + output="${stderr}" + assert_output --partial "${MCP_PHP_TOOLING_CONFIG}" +} diff --git a/plugin-tests/shopware-env/test_helper/common_setup.bash b/plugin-tests/shopware-env/test_helper/common_setup.bash index 589d63bb..96734304 100644 --- a/plugin-tests/shopware-env/test_helper/common_setup.bash +++ b/plugin-tests/shopware-env/test_helper/common_setup.bash @@ -13,6 +13,26 @@ setup_config() { printf '%s\n' "$content" > "${BATS_TEST_TMPDIR}/.mcp-${prefix}.json" } +# Run a hook script with the hook input's cwd set. When CURSOR_PROJECT_DIR is +# unset, the cwd is how the hook names the project. +# Args: $1 = script name, $2 = bash command, $3 = cwd +run_hook_with_cwd() { + local payload + payload=$(jq -cn --arg cmd "$2" --arg cwd "$3" '{tool_input: {command: $cmd}, cwd: $cwd}') + run bash -c 'printf "%s" "$1" | bash "$2"' _ "$payload" "${SCRIPTS_DIR}/$1" +} + +# Create a project directory holding an MCP config of the given environment, +# distinct from the one setup_config writes at BATS_TEST_TMPDIR. +# Args: $1 = config prefix, $2 = environment +# Stdout: the project directory +make_cwd_project() { + local dir="${BATS_TEST_TMPDIR}/cwd-project" + mkdir -p "$dir" + jq -n --arg env "$2" '{environment: $env}' > "${dir}/.mcp-${1}.json" + printf '%s\n' "$dir" +} + # Setup for MCP lifecycle tool tests. # Stubs log/exec_command, sources environment.sh + resolve_env.sh, then # sources the given tool library. diff --git a/plugins/dev-tooling/.cursor-plugin/plugin.json b/plugins/dev-tooling/.cursor-plugin/plugin.json index 21e6d8d7..dc4f6bd8 100644 --- a/plugins/dev-tooling/.cursor-plugin/plugin.json +++ b/plugins/dev-tooling/.cursor-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "dev-tooling", - "version": "5.0.0", + "version": "5.0.1", "description": "Three MCP servers for PHP and JavaScript operations. PHP (php-tooling): PHPStan, ECS, Rector, PHPUnit, PHPUnit coverage gap analysis, Symfony Console. Administration (js-admin-tooling): ESLint, Stylelint, Prettier, Jest, TypeScript, Vite builds. Storefront (js-storefront-tooling): ESLint, Stylelint, Jest, Webpack builds. Includes a sessionStart hook that injects MCP tool directives and beforeShellExecution hooks that enforce MCP tool usage by blocking bash commands. Supports native, Docker, Docker Compose, Vagrant and DDEV environments.", "author": { "name": "Shopware Labs" diff --git a/plugins/dev-tooling/AGENTS.md b/plugins/dev-tooling/AGENTS.md index dfca0cc1..c5603082 100644 --- a/plugins/dev-tooling/AGENTS.md +++ b/plugins/dev-tooling/AGENTS.md @@ -30,14 +30,17 @@ plugins/dev-tooling/ │ ├── check-phpstan-baseline.sh # postToolUse hook: warns when analyzed paths appear in phpstan-baseline.neon │ ├── worktree-directives.sh # beforeShellExecution hook on git worktree add/remove: set_project_root reminder; on enter also the repair command for an absolute gitdir pointer when the path already exists │ └── lib/ -│ └── common.sh # Shared: parse_hook_input(), load_mcp_config(), block_tool() +│ ├── common.sh # Shared (template-synced from templates/hooks-shared/common.sh): parse_hook_input(), load_mcp_config(), resolve_project_dir(), block_tool() +│ └── js_binary.sh # Shared binary-run matcher of the two JS hooks (dev-tooling-owned, not templated) │ ├── shared/ # SHARED FRAMEWORK (language-agnostic) │ ├── mcpserver_core.sh # JSON-RPC 2.0 protocol handler + validate_tool_arguments() │ ├── config.sh # Config discovery & merging (parameterized via CONFIG_PREFIX) +│ ├── launch.sh # Launch mode: bound, or unbound when the host started the server in this plugin's own directory (dev-tooling-owned, not templated) │ ├── environment.sh # Environment detection, PHP & JS command wrapping, argument quoting, path guards, environment-side path mapping, noise filtering │ ├── worktree.sh # Per-call root resolution and worktree validation: worktree_enter(), set_project_root, cwd (dev-tooling-owned, not templated) │ ├── server_run.sh # Shared server tail: run_mcp_server() call and why it is not isolated in a subshell (dev-tooling-owned, not templated) +│ ├── js_paths.sh # JS path-scoped runs: local-binary probe, second-config check, package-path rebase, directory patterns, ddev glob/directory refusal (dev-tooling-owned, not templated) │ ├── scope.sh # Scope resolution: resolve_scope(), scope_get_tool_field() │ ├── docker-compose.sh # Docker Compose environment: call-time resolution of container/workdir │ └── mcp-js-tooling.schema.json # JSON Schema for .mcp-js-tooling.json (shared by JS servers) @@ -75,7 +78,7 @@ plugins/dev-tooling/ ├── config.json # Server metadata (name="js-storefront-tooling") ├── tools.json # ESLint, Stylelint, Jest, Vitest, ludtwig, Webpack tools └── lib/ - ├── eslint.sh # tool_eslint_check(), tool_eslint_fix() — routes paths to eslint:app / eslint:components + ├── eslint.sh # tool_eslint_check(), tool_eslint_fix() — routes paths to the app tree / the components tree ├── stylelint.sh # tool_stylelint_check(), tool_stylelint_fix() ├── jest.sh # tool_jest_run() — app/storefront package suite only ├── vitest.sh # tool_vitest_run() — views/components component suite @@ -132,6 +135,7 @@ All MCP servers source shared framework files: ```bash source "${SHARED_DIR}/mcpserver_core.sh" # JSON-RPC protocol source "${SHARED_DIR}/config.sh" # Config discovery +source "${SHARED_DIR}/launch.sh" # Launch mode: bound, or unbound in the plugin directory source "${SHARED_DIR}/environment.sh" # Command execution ``` @@ -178,15 +182,14 @@ Tools in `tools.json` map to bash functions with `tool_` prefix: # Admin/Storefront servers - hardcoded npm script names from Shopware package.json. # Two routes per tool, selected by whether the caller supplied paths: appending # to the aggregate script only ever widens it (npm appends `--` args to the end -# of the whole script body), so a path-scoped call is routed at a separate -# target-less base script instead, and refuses when that script is unusable. +# of the whole script body), so a path-scoped call runs without it. tool_eslint_check() { local args="$1" # No paths: aggregate script's own targets stay authoritative. local cmd="npm run lint -- ..." # Admin uses "lint", Storefront uses "lint:js" - # Paths supplied: routed at a target-less base script instead, so the - # given paths are the ONLY targets (Admin: "lint:debugging"; Storefront: - # "eslint:app" / "eslint:components", picked per path). + # Paths supplied: the given paths are the ONLY targets. Both ESLint tools + # run the package's own binary through `npm exec --no`. + # docs/reference.md lists each tool's route and refusals. exec_npm_command "${cmd}" } ``` @@ -210,7 +213,7 @@ Both handle environment-specific execution (native/docker/docker-compose/vagrant | Add blocked PHP command | `hooks/scripts/check-php-tools.sh` | - | `block_tool()`, grep pattern | | Add blocked Admin JS command | `hooks/scripts/check-js-admin-tools.sh` | - | `block_tool()`, `is_admin_context()` | | Add blocked Storefront JS command | `hooks/scripts/check-js-storefront-tools.sh` | - | `block_tool()`, `is_storefront_context()` | -| Modify shared hook logic | `hooks/scripts/lib/common.sh` | - | `parse_hook_input()`, `load_mcp_config()`, `block_tool()` | +| Modify shared hook logic | `templates/hooks-shared/common.sh` (edit template, sync per `.cursor/rules/template-sync.mdc`) | - | `parse_hook_input()`, `load_mcp_config()`, `resolve_project_dir()`, `block_tool(server, description, tool...)` | | Disable hook enforcement | `.mcp-*-tooling.json` | - | `enforce_mcp_tools: false` | | Adjust hook timeout | `hooks/hooks.json` | - | `timeout` field (default: 5s) | | Add config location | `templates/mcp-shared/config.sh` (edit template, sync per `.cursor/rules/template-sync.mdc`) | - | `CONFIG_LOCATIONS` array | @@ -220,6 +223,8 @@ Both handle environment-specific execution (native/docker/docker-compose/vagrant | Modify protocol | upstream `shopwareLabs/bash-mcp-sdk` (release pinned in `.mcp-sdk.lock`; never edit `shared/mcpserver_core.sh` in place) | - | `process_request()`, `handle_*()` | | Update tool schemas | `mcp-server-*/tools.json` | - | JSON Schema Draft 7 | | Register new server | `mcp.json` | - | `mcpServers` object | +| Change launch or bind behavior | `shared/launch.sh` | `shared/worktree.sh` (`worktree_launch_hydrate`, `_worktree_launch_bind`) | `LAUNCH_MODE`, the `launch` record in the state file | +| Change JS path rebasing | `shared/js_paths.sh` | `mcp-server-js-*/lib/` | path-scoped runs through the package binary | ## ✏️ When to Modify What @@ -285,8 +290,8 @@ This plugin's own suites are in `plugin-tests/dev-tooling/`: | `mcp_tool_console.bats` | Console tool command construction | | `mcp_tool_ecs.bats` | ECS tool command construction | | `mcp_tool_rector.bats` | Rector tool command construction | -| `mcp_tool_js_admin.bats` | Admin JS MCP tool command construction | -| `mcp_tool_js_storefront.bats` | Storefront JS MCP tool command construction (ESLint routing, Jest, Vitest, ludtwig) | +| `mcp_tool_js_admin.bats` | Admin JS tool commands; Stylelint and Prettier executed through the env wrappers | +| `mcp_tool_js_storefront.bats` | Storefront JS tool commands; ESLint and Stylelint executed through the env wrappers | | `mcp_tool_phpstan.bats` | PHPStan tool command construction | | `mcp_tool_phpunit.bats` | PHPUnit tool command construction (coverage, config, drivers) | | `mcp_tool_phpunit_coverage.bats` | PHPUnit coverage gap parsing (clover XML, filtering, ranges) | @@ -301,10 +306,20 @@ This plugin's own suites are in `plugin-tests/dev-tooling/`: | `worktree_php_tools.bats` | `phpunit_coverage_gaps`: clover paths relative to the mapped workdir, refused read | | `worktree_js_tools.bats` | `project_root` reaching the JS package directory, which the conformance scan does not capture | | `worktree_conformance.bats` | Every enumerated `tool_*` function runs in the named worktree and runs nothing against a refused one, with the enumeration reconciled against `tools.json` | - +Three non-suite entries sit alongside them: + +- `test_helper/common_setup.bash`: shared helpers. + - `setup_config()` and `setup()`. + - `setup_php_mcp_env()`, which stubs `log()` and `exec_command()` before sourcing a tool library. + - The worktree git fixtures `worktree_gitdir_relative()` and `_absolute_path_relative_to()`. + - The probe stubs `stub_worktree_probe()` and `worktree_test_guard_probe()`. + - `shopware_trunk_script_body()`, which answers an `npm pkg get "scripts."` probe from the trunk fixtures. + - `js_execute_in_env()`, which runs a command a JS tool built through `wrap_npm_command` for one environment against fake `npm`, `docker`, `vagrant` and `ddev` and fake linter binaries. +- `fixtures/coverage/`: Clover XML samples for `mcp_tool_phpunit_coverage.bats`. +- `fixtures/shopware-trunk/`: the `scripts` blocks of the Administration and Storefront `package.json` files, copied verbatim from shopware/shopware trunk. The JS tool suites answer script probes from them. The modules this plugin consumes from `templates/mcp-shared/` are covered once, for every consuming plugin, in `plugin-tests/mcp-shared/`: -| Test File | Coverage | +| Test File | Coverage | |-------------------------------|---------------------------------------------------------------------------| | `environment.bats` | Environment wrapping, argument quoting, `parse_paths_json`, path guards | | `docker_compose.bats` | Docker Compose call-time container/workdir resolution | diff --git a/plugins/dev-tooling/CHANGELOG.md b/plugins/dev-tooling/CHANGELOG.md index 52b1c552..cdc94ce5 100644 --- a/plugins/dev-tooling/CHANGELOG.md +++ b/plugins/dev-tooling/CHANGELOG.md @@ -5,6 +5,23 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [5.0.1] - 2026-10-27 + +### Changed +- **`set_project_root` with the launch root clears the sticky root.** Naming the root the server started in was refused as a checkout that is not a linked worktree. It now clears the sticky root, the same as omitting `project_root`. +- **A server started in the plugin directory stays unbound until `set_project_root` binds a project.** `initialize` and `tools/list` still answer. Every other tool refuses until that bind. Cursor starts the servers in the session project, so they stay bound at launch. Export `PROJECT_ROOT` to bind at startup. +- **Block messages name the tool and its server.** `beforeShellExecution` now says ``Use `phpstan_analyze` on the `php-tooling` MCP server instead!`` and the same shape for the JS servers. The JS hooks also block `npm exec` / `npm x`, a `node_modules/.bin/` path, an `@version` suffix, and a `-c` / `--call` string that runs the binary. +- **`jest_run` always runs the package `unit` script.** The `jest:base` route is gone. `ci: true` appends `--ci`. The tool checks its arguments and the `unit` script before it installs dependencies. +- **`vite_build`, `webpack_build`, `lint_all`, `lint_twig`, `unit_setup`, and `vitest_run` ignore `default_scope`.** They run against the core package. `vitest_run` refuses a plugin scope. `tsc_check` still honors `default_scope` and refuses a plugin scope whose package defines no `lint:types` script. The sessionStart scopes note says so for `js-tooling`. +- **An absolute `.git` gitdir pointer is accepted under `native`.** The container environments (`docker`, `docker-compose`, `vagrant`, `ddev`) still refuse it, and the worktree reminder names that split. The repair command is unchanged. + +### Fixed +- **Path-scoped Stylelint, Prettier, and ESLint run the package binary.** Calls with `paths` no longer route to `stylelint:base`, `prettier:base`, `eslint:app`, or `eslint:components`, which Shopware's `package.json` files do not define. They run `npm exec --no -- ` with the aggregate script's flags, and refuse when `node_modules/.bin/` is missing so a global binary cannot run instead. Administration ESLint with `paths` uses the local `eslint` binary the same way. Under a scope, an ESLint path is rebased so a plugin's own `app/administration` or `app/storefront` segment stays. +- **A config that is present but broken is refused.** `load_config` refuses a file that is not a JSON object, and a `jq` expression that cannot be evaluated returns the `jq` error instead of a default. An environment name outside `native`, `docker`, `docker-compose`, `vagrant`, and `ddev` is refused at startup and at bind. A worktree whose own config cannot be loaded is refused instead of running under the launch root's configuration. +- **A relative `MCP_PHP_TOOLING_CONFIG` or `MCP_JS_TOOLING_CONFIG` survives a worktree call.** The override is made absolute against the directory the server started in. +- **PHP tools no longer drop caller values.** `console_run` honors an explicit `false` for `no_debug` and `no_interaction`, passes empty positional arguments through, and refuses an option value that is not a boolean, a string, or an array of strings and numbers. `console_list` returns a failing `bin/console list` with its output. `phpunit_run` accepts any `testsuite` matching `^[A-Za-z0-9_.-]{1,64}$`. `rector_fix` runs `composer rector-fix` when that script exists, and refuses when the only `rector` script carries `--dry-run`. +- **Hooks find the project from `CURSOR_PROJECT_DIR`, then `workspace_roots` or `cwd`.** Config lookup, the sessionStart scopes section, and the PHPStan baseline warning share that resolution. Config files stay `.cursor/.mcp-*.json` then `.mcp-*.json`. + ## [5.0.0] - 2026-09-19 ### Added diff --git a/plugins/dev-tooling/README.md b/plugins/dev-tooling/README.md index 34d76552..b6743e99 100644 --- a/plugins/dev-tooling/README.md +++ b/plugins/dev-tooling/README.md @@ -82,13 +82,15 @@ The [full reference](./docs/reference.md) has parameter tables and examples for ## 🌳 Worktree Support -Every tool except `cwd`, on all three servers, takes an optional `project_root` to run one call against a linked git worktree of the root the server was launched in. `set_project_root` and `cwd` manage that state rather than targeting one call with it — `set_project_root` takes a `project_root` and sticks it for every later call on that server process (each server is a separate process holding its own sticky value), and omitting the argument clears it; `cwd` takes no parameters and reports what a server currently resolves to. +Every tool except `cwd`, on all three servers, takes an optional `project_root` to run one call against a linked git worktree of the server's project root. `set_project_root` and `cwd` manage that state rather than targeting one call with it — `set_project_root` takes a `project_root` and sticks it for every later call on that server process (each server is a separate process holding its own sticky value), and omitting the argument, or naming the launch root itself, clears it; `cwd` takes no parameters and reports what a server currently resolves to. + +A server started in its own plugin directory has no project root yet, so it has no launch root to fall back on and every tool but `set_project_root` and `cwd` refuses until one is bound. There the first `set_project_root` call with a path binds the server: it discovers the configuration, derives the environment, and records the root every later call enters, so from then on the server behaves as one started in that root — and later calls may stick a linked git worktree of it. Omitting the argument while unbound is refused rather than clearing anything. Export `PROJECT_ROOT` with the project path before starting the server to bind at startup. > [!NOTE] > Worktree targeting works in every environment. Under `docker`, `docker-compose`, `vagrant`, and `ddev` the worktree has to sit inside the launch project root — that root is the only tree the container or VM mounts — so a worktree created elsewhere on the host is refused. An in-root worktree is reached at its own position below the environment's working directory: `docker.workdir`, `vagrant.workdir`, or `ddev.workdir`, and for `docker-compose` a configured `docker-compose.workdir`, or else the destination of the longest matching bind mount. > [!IMPORTANT] -> A worktree's `.git` file has to carry a relative `gitdir` pointer. `git worktree add` writes an absolute one unless the repository sets `worktree.useRelativePaths`, and an absolute pointer names a host path that does not exist inside a container — so it is refused in every environment, `native` included. Relink an existing worktree with `git -c worktree.useRelativePaths=true worktree repair ` (needs git 2.48 or newer), or create one with `git worktree add --relative-paths`. Setting `git config worktree.useRelativePaths true` once in the repository makes every later worktree carry relative linkage from the start. +> A worktree's `.git` file has to carry a relative `gitdir` pointer under `docker`, `docker-compose`, `vagrant`, and `ddev`. `git worktree add` writes an absolute one unless the repository sets `worktree.useRelativePaths`, and an absolute pointer names a host path that does not exist inside a container, so those environments refuse it. `native` accepts an absolute pointer, because the command runs on the host where the pointer resolves. Relink an existing worktree with `git -c worktree.useRelativePaths=true worktree repair ` (needs git 2.48 or newer), or create one with `git worktree add --relative-paths`. Setting `git config worktree.useRelativePaths true` once in the repository makes every later worktree carry relative linkage from the start. A fresh worktree holds tracked files only, so the launch tree's `vendor/` and `node_modules` are not in it and every composer- or npm-backed tool refuses until they exist. Each server's `worktree_prepare` installs its own toolchain's dependencies in the target root — `composer install` on `php-tooling`, `npm ci` in the package directory on the JS servers — through the configured environment, which under a container runs the install inside the container at the mapped path. Re-run it after the worktree's `composer.json`/`composer.lock` or `package-lock.json` changes; the dependency check only tests that the install directory exists. @@ -134,8 +136,9 @@ Use scopes when developing a Shopware plugin inside `custom/plugins//`. A ### Calling tools -- Omit `scope` → uses `default_scope` (or project-root behavior). -- Pass `scope: "swag-commercial"` → overrides the default for one call. +- Omit `scope` → uses `default_scope` (or project-root behavior) for scope-aware PHP tools, JS lint/format tools, `tsc_check`, `jest_run`, and JS `worktree_prepare`. +- Omit `scope` on `lint_all`, `lint_twig`, `unit_setup`, `vite_build`, `webpack_build`, or `vitest_run` → ignores `default_scope` and uses the core package. `ludtwig_check` and `ludtwig_fix` take no `scope` at all and always use the core package. +- Pass `scope: "swag-commercial"` → selects that plugin for tools that support plugin scopes; `vitest_run` refuses plugin scopes. - Pass `scope: "shopware"` → forces project-root behavior. Run the `setting-up` skill to let the agent probe the plugin and write the scope for you. diff --git a/plugins/dev-tooling/SETUP.md b/plugins/dev-tooling/SETUP.md index 6feab051..c2bc1b98 100644 --- a/plugins/dev-tooling/SETUP.md +++ b/plugins/dev-tooling/SETUP.md @@ -20,7 +20,6 @@ - **Install**: https://jqlang.github.io/jq/download/ - **Required by**: All three MCP servers (php-tooling, js-admin-tooling, js-storefront-tooling) - ## Configuration Files ### Scope of this setup @@ -47,7 +46,7 @@ This skill configures MCP wiring only. It does not run `composer install`, initi 4. **Compose service name** (only if environment = docker-compose): Which service in your `docker-compose.yml` runs PHP? Default: `web` -5. **Compose working directory** (only if environment = docker-compose, optional): Working directory inside the compose service. Leave blank to use the service's default `WORKDIR`. +5. **Compose working directory** (only if environment = docker-compose, optional): The project root's path inside the compose service. Leave blank to detect it from the service's bind mounts: the longest bind mount whose host source contains the project root decides, and the project root's path below that source is appended to the mount's destination. Set it when no bind mount of the service covers the project root. 6. **Compose file** (only if environment = docker-compose, optional): Path to a specific compose file. Leave blank to let `docker compose` auto-discover `docker-compose.yml` / `compose.yml` from the project root. @@ -121,7 +120,7 @@ Symfony Console defaults (`console.env`, `console.verbosity`, `console.no_debug` 4. **Compose service name** (only if environment = docker-compose): Which service in your `docker-compose.yml` runs Node.js? Default: `web` -5. **Compose working directory** (only if environment = docker-compose, optional): Working directory inside the compose service. Leave blank to use the service's default `WORKDIR`. +5. **Compose working directory** (only if environment = docker-compose, optional): The project root's path inside the compose service. Leave blank to detect it from the service's bind mounts: the longest bind mount whose host source contains the project root decides, and the project root's path below that source is appended to the mount's destination. Set it when no bind mount of the service covers the project root. 6. **Compose file** (only if environment = docker-compose, optional): Path to a specific compose file. Leave blank to let `docker compose` auto-discover `docker-compose.yml` / `compose.yml` from the project root. @@ -156,7 +155,6 @@ Stored as `enforce_mcp_tools` in the config. } ``` - ## Plugin Scope Setup Optional phase. Writes one or more scopes into `.mcp-php-tooling.json` and/or `.mcp-js-tooling.json` and optionally pins one as `default_scope` when the user develops against a Shopware plugin in `custom/plugins//`. diff --git a/plugins/dev-tooling/docs/configuration.md b/plugins/dev-tooling/docs/configuration.md index 65c0b576..6f13fa16 100644 --- a/plugins/dev-tooling/docs/configuration.md +++ b/plugins/dev-tooling/docs/configuration.md @@ -80,6 +80,8 @@ Config is resolved in two stages. The environment variable wins if it's set, oth A common pattern is to check a shared `.mcp-php-tooling.json` into git and keep a personal `.cursor/.mcp-php-tooling.json` with your own overrides. +A server that starts bound to a project, `shopware-env`'s lifecycle server included, refuses to start when the override variable names a file that does not exist, and when the override file or a discovered file does not hold a JSON object; the error names the file. A server started unbound applies the same checks when `set_project_root` binds it. A bound server also refuses to start when `environment` is not `native`, `docker`, `docker-compose`, `vagrant` or `ddev`; with several files merged, the error names each file the configuration was merged from. + ## Environment Options | Field | Type | Default | Description | @@ -94,16 +96,18 @@ A common pattern is to check a shared `.mcp-php-tooling.json` into git and keep | `ddev.workdir` | string | `/var/www/html` | Working directory inside DDEV | | `log_file` | string | - | Additional log file; relative paths resolve against project root | +Under `ddev`, a `ddev.workdir` other than `/var/www/html` is passed to every PHP and composer call as `ddev exec -d ""`, and the JS tools always pass their package directory the same way. + ## 🌳 Worktree Configuration -A tool call may target a linked git worktree of the launch root by passing `project_root`, or by sticking one first with `set_project_root`. Targeting works in every environment: `native`, `docker`, `docker-compose`, `vagrant`, and `ddev`. +A tool call may target a linked git worktree of the launch root by passing `project_root`, or by sticking one first with `set_project_root`. Targeting works in every environment: `native`, `docker`, `docker-compose`, `vagrant`, and `ddev`. A server started in the plugin's own directory has no launch root until `set_project_root` binds one, which discovers that root's configuration at bind time; see [reference.md](./reference.md#-worktree-support). Under the four container environments the worktree has to sit inside the launch project root, because that root is the only tree the container or VM mounts and a worktree outside it has no path inside. The worktree is reached at its own position below the environment's working directory (`docker.workdir`, `vagrant.workdir`, `ddev.workdir`), and under `docker-compose` below a configured `docker-compose.workdir`, or below the destination of the longest matching bind mount when none is set. Once the mapping exists, `cwd` and the messages raised after it name both the host path and the environment-side path; the refusals that precede the mapping name the host path alone, since none exists yet. -Validation is the same in every environment: the root has to be one `git worktree add` created, its per-worktree git directory has to point back at that root, and its `.git` file has to carry a **relative** `gitdir` pointer. `git worktree add` writes an absolute one unless the repository sets `worktree.useRelativePaths`, and an absolute pointer names a host path that does not exist inside a container — so it is refused under `native` as well. Relink it with `git -c worktree.useRelativePaths=true worktree repair `, which needs git 2.48 or newer, or create the worktree with `git worktree add --relative-paths`. +Under every environment the root has to be one `git worktree add` created, and its per-worktree git directory has to point back at that root. Under `docker`, `docker-compose`, `vagrant`, and `ddev` the `.git` file also has to carry a **relative** `gitdir` pointer. `git worktree add` writes an absolute one unless the repository sets `worktree.useRelativePaths`, and an absolute pointer names a host path that does not exist inside a container, so those environments refuse it. `native` accepts an absolute pointer, because the command runs on the host where the pointer resolves. Relink a refused worktree with `git -c worktree.useRelativePaths=true worktree repair `, which needs git 2.48 or newer, or create the worktree with `git worktree add --relative-paths`. > [!TIP] -> One repository setting removes the recurring worktree friction. `git config worktree.useRelativePaths true` (git 2.48 or newer) makes every later worktree carry relative linkage from the start — `git worktree add` otherwise writes an absolute pointer that needs the repair command before the first tool call. Pass an explicit starting point (`HEAD`, a branch, or a commit) so the worktree carries the code you mean to test; without one, `git worktree add` branches from the repository's default branch. +> One repository setting removes the recurring worktree friction. `git config worktree.useRelativePaths true` (git 2.48 or newer) makes every later worktree carry relative linkage from the start — `git worktree add` otherwise writes an absolute pointer that the container environments (`docker`, `docker-compose`, `vagrant`, `ddev`) refuse before the first tool call. `native` accepts an absolute pointer, because the command runs on the host where it resolves. Pass an explicit starting point (`HEAD`, a branch, or a commit) so the worktree carries the code you mean to test; without one, `git worktree add` branches from the repository's default branch. A root carrying a single quote or a control character is refused in every environment: a single quote would terminate the single-quoted string the `docker`, `docker-compose` and `vagrant` wrappers embed the command in, and a line break would split the probe's command. Under `docker`, `docker-compose`, `vagrant`, and `ddev` the root charset check refuses whitespace and the set `$`, backtick, backslash, `"`, `;`, `&`, `|`, `<`, `>`, `(`, `)`, `{`, `}`. For the first three the reason is that the wrapper embeds the working directory unquoted inside a single-quoted `bash -c` string, so a space ends the directory name; `ddev` quotes that directory but parses it a second time inside the container. Glob characters (`*`, `?`, bracket patterns) are admitted deliberately in every environment. `native` emits no `cd` and admits all of these. @@ -111,14 +115,14 @@ After validation the tool probes that the environment reaches the mapped path, t **Configuration read timing** differs between the launch root and a worktree target: -- The launch root's configuration is discovered and bound once, when the server starts, and its environment scalars — the environment, the container name, and the environment-side working directory — are derived then. Individual values are still read out of that file on each use, but a mid-session edit to any of those three does not reach a worktree-targeted call until the server restarts: validation, the mapping and the existence probe all answer from the startup binding, so a running server keeps running against the environment it started with. +- The launch root's configuration is discovered and bound once — when the server starts, or when `set_project_root` binds a server that started without a project root — and its environment scalars — the environment, the container name, and the environment-side working directory — are derived then. Individual values are still read out of that file on each use, but a mid-session edit to any of those three does not reach a worktree-targeted call until the server restarts: validation, the mapping and the existence probe all answer from the startup binding, so a running server keeps running against the environment it started with. - A worktree's own configuration is discovered fresh on every call that targets it. A call targeting the launch root never picks up a worktree's file. -**Configuration selection for a worktree**: a freshly linked worktree holds tracked files only, and the tooling config files (`.mcp-php-tooling.json`, `.mcp-js-tooling.json`) are user-local and untracked — so a worktree ordinarily carries no configuration of its own. When it has none, the launch root's configuration applies unchanged: a worktree of the same checkout runs the same toolchain. When it has one, that configuration is discovered and applied for calls targeting that worktree, following the same discovery priority as the launch root — including the `environment` field it declares, so a worktree with its own configuration runs under that configuration's environment for that call, while a later call against the launch root still runs under the environment the server started with. +**Configuration selection for a worktree**: a freshly linked worktree holds tracked files only, and the tooling config files (`.mcp-php-tooling.json`, `.mcp-js-tooling.json`) are user-local and untracked — so a worktree ordinarily carries no configuration of its own. When it has none, the launch root's configuration applies unchanged: a worktree of the same checkout runs the same toolchain. When it has one, that configuration is discovered and applied for calls targeting that worktree, following the same discovery priority as the launch root — including the `environment` field it declares, so a worktree with its own configuration runs under that configuration's environment for that call, while a later call against the launch root still runs under the environment the server started with. A worktree configuration that cannot be loaded, or that declares an `environment` outside the five names, refuses the call. ## 📌 Dependencies -You need `bash` 4.1+, `jq` 1.7+, and Node.js 20+ for the JS tools. The vendored protocol handler checks both floors at startup and refuses to run below either. Worktree targeting — the optional `project_root` parameter — effectively needs `git` 2.48+: resolution itself needs 2.31 (`git rev-parse --path-format`), but the mandatory relative `gitdir` linkage and its repair command are 2.48 features, so on 2.31–2.47 every stock worktree is refused with a remedy that git cannot run. Below either floor a worktree-targeted call is refused with a message naming the version, and every other tool is unaffected. The MCP servers don't bundle any of the actual linters or test runners. They shell out to whatever is already installed in the target project, so PHPStan, ECS, PHPUnit, Rector, ESLint, Stylelint, Prettier, Jest, and TypeScript all need to be available there (usually via `composer.json` or `package.json` in the Shopware checkout). +You need `bash` 4.1+, `jq` 1.7+, and Node.js 20+ for the JS tools. The vendored protocol handler checks both floors at startup and refuses to run below either. Worktree targeting — the optional `project_root` parameter — effectively needs `git` 2.48+: resolution itself needs 2.31 (`git rev-parse --path-format`), but the relative `gitdir` linkage that the container environments require, and its repair command, are 2.48 features, so on 2.31–2.47 every stock worktree is refused under a container environment with a remedy that git cannot run. Below either floor a worktree-targeted call is refused with a message naming the version, and every other tool is unaffected. The MCP servers don't bundle any of the actual linters or test runners. They shell out to whatever is already installed in the target project, so PHPStan, ECS, PHPUnit, Rector, ESLint, Stylelint, Prettier, Jest, and TypeScript all need to be available there (usually via `composer.json` or `package.json` in the Shopware checkout). ## 🩺 Troubleshooting diff --git a/plugins/dev-tooling/docs/mcp-enforcement.md b/plugins/dev-tooling/docs/mcp-enforcement.md index cd8a0bec..f42503bb 100644 --- a/plugins/dev-tooling/docs/mcp-enforcement.md +++ b/plugins/dev-tooling/docs/mcp-enforcement.md @@ -8,7 +8,7 @@ MCP is a synchronous request-response protocol. A long-running watcher like `npm ## 🛡️ Enforcement Hooks -Three hooks work together. A **sessionStart** hook injects a directive at the top of every conversation that lists the available MCP tools and tells the agent to prefer them over bash; the prompt lives in `hooks/prompts/mcp-tool-directives.md` if you want to read or tweak it. A **beforeShellExecution** hook is the safety net: it intercepts bash commands that map to a known MCP tool and points the agent at the replacement, so even if the sessionStart directive got ignored or compacted away, the bad call gets caught before it runs. The same event also runs `worktree-directives.sh` on `git worktree add` and `git worktree remove`, reminding the session to call `set_project_root` on all three servers, since each holds its own sticky root. A **postToolUse** hook watches `phpstan_analyze`. When it runs against specific files, it cross-references `phpstan-baseline.neon` (or `.php`) and surfaces a warning if any of the analyzed paths appear in the baseline, which usually means a baseline entry has gone stale. Full-project PHPStan runs skip the check because PHPStan validates the baseline natively there. +Three hooks work together. A **sessionStart** hook injects a directive at the top of every conversation that lists the available MCP tools and tells the agent to prefer them over bash; the prompt lives in `hooks/prompts/mcp-tool-directives.md` if you want to read or tweak it. A **beforeShellExecution** hook is the safety net: it intercepts bash commands that map to a known MCP tool and points the agent at the replacement, so even if the sessionStart directive got ignored or compacted away, the bad call gets caught before it runs. The block message names the tool and its server (`Use \`phpstan_analyze\` on the \`php-tooling\` MCP server instead!`). The same event also runs `worktree-directives.sh` on `git worktree add` and `git worktree remove`, reminding the session to call `set_project_root` on all three servers, since each holds its own sticky root. A **postToolUse** hook watches `phpstan_analyze`. When it runs against specific files, it cross-references `phpstan-baseline.neon` (or `.php`) and surfaces a warning if any of the analyzed paths appear in the baseline, which usually means a baseline entry has gone stale. Full-project PHPStan runs skip the check because PHPStan validates the baseline natively there. The sessionStart directive and the MCP-enforcement beforeShellExecution hooks honor `enforce_mcp_tools` and turn off when it's `false`. The worktree-directives reminder and the postToolUse baseline check ignore the flag and always run. @@ -22,61 +22,69 @@ Flip the switch per config file (`.mcp-php-tooling.json` or `.mcp-js-tooling.jso ### Blocked PHP Commands -| Bash Command | MCP Tool | -|-------------------------------------------------------------|--------------------------------------------------| -| `vendor/bin/phpstan`, `composer phpstan` | `mcp__php-tooling__phpstan_analyze` | -| `vendor/bin/ecs`, `vendor/bin/php-cs-fixer`, `composer ecs` | `mcp__php-tooling__ecs_check` / `ecs_fix` | -| `vendor/bin/phpunit`, `composer phpunit` | `mcp__php-tooling__phpunit_run` | -| `bin/console`, `php bin/console` | `mcp__php-tooling__console_run` / `console_list` | -| `vendor/bin/rector`, `composer rector` | `mcp__php-tooling__rector_fix` / `rector_check` | +| Bash Command | MCP Tool on `php-tooling` | +|--------------------------------------------------------------------|--------------------------------| +| `vendor/bin/phpstan`, `composer phpstan` | `phpstan_analyze` | +| `vendor/bin/ecs`, `vendor/bin/php-cs-fixer`, `composer ecs` | `ecs_check` / `ecs_fix` | +| `vendor/bin/phpunit`, `composer phpunit` | `phpunit_run` | +| `bin/console`, `php bin/console` | `console_run` / `console_list` | +| `vendor/bin/rector`, `composer rector`, `composer rector-fix` | `rector_fix` / `rector_check` | ### Blocked JavaScript Commands -The JS hook picks Admin vs Storefront from the command itself and redirects to the matching server. Detection is by path pattern first, then by scripts that only exist on one side — `lint:js`, `production`, `development`, `unit:components`, `eslint:app`, `eslint:components` and `stylelint:app` for Storefront, plus a bare `ludtwig`, which lints Storefront Twig templates and nothing else. `jest:base` is declared by both `package.json` files and carries no side-specific marker, so it cannot be classified this way: a command that also names the Storefront tree (path pattern or another Storefront-only script) is claimed by the Storefront hook, and every other `jest:base` invocation — including a bare one — falls to the Admin hook's unknown-context default. +The JS hook picks Admin vs Storefront from the command itself and redirects to the matching server. Detection is by path pattern first, then by script names that belong to one side — `lint:js`, `production`, `development`, `unit:components`, `eslint:app`, `eslint:components` and `stylelint:app` for Storefront, plus a bare `ludtwig`, which lints Storefront Twig templates and nothing else. `jest:base` carries no side-specific marker, so it cannot be classified this way: a command that also names the Storefront tree (path pattern or another Storefront-only script) is claimed by the Storefront hook, and every other `jest:base` invocation — including a bare one — falls to the Admin hook's unknown-context default. > [!NOTE] > Detection reads the whole command string, so a compound command that names both trees — `git diff -- src/Administration src/Storefront && npm run jest:base` — satisfies both detectors and is blocked twice, once per server. This applies to any command mentioning both trees, not only the base scripts. -`lint:debugging`, `stylelint:base`, `prettier:base` and `jest:base` (Admin) and `eslint:app`, `eslint:components`, `stylelint:app` and `jest:base` (Storefront) are the target-less base npm scripts the corresponding MCP tools route path-scoped runs at directly — see [reference.md](./reference.md) for the routing rules. They are blocked the same as every other script below. - -| Bash Command | Admin MCP Tool | Storefront MCP Tool | -|-------------------------------------------------------------------------------------------------------------|-------------------|---------------------| -| `npm run lint`, `npx eslint` | `eslint_check` | `eslint_check` | -| `npm run lint:js` | N/A | `eslint_check` | -| `npm run lint:debugging` | `eslint_check` | N/A | -| `npm run eslint:app`, `npm run eslint:components` | N/A | `eslint_check` | -| `npm run lint:fix` | `eslint_fix` | `eslint_fix` | -| `npm run lint:js:fix` | N/A | `eslint_fix` | -| `npm run lint:scss`, `npx stylelint` | `stylelint_check` | `stylelint_check` | -| `npm run stylelint:base` | `stylelint_check` | N/A | -| `npm run stylelint:app` | N/A | `stylelint_check` | -| `npm run lint:scss-fix` | `stylelint_fix` | `stylelint_fix` | -| `npm run format`, `npx prettier` | `prettier_check` | N/A (Admin only) | -| `npm run prettier:base` | `prettier_check` | N/A (Admin only) | -| `npm run format:fix` | `prettier_fix` | N/A (Admin only) | -| `npm run unit`, `npx jest` | `jest_run` | `jest_run` | -| `npm run jest:base` | `jest_run` | `jest_run` | -| `npm run lint:types`, `npx tsc` | `tsc_check` | N/A (Admin only) | -| `npm run lint:all` | `lint_all` | N/A (Admin only) | -| `npm run lint:twig` | `lint_twig` | N/A (Admin only) | -| `npm run build` | `vite_build` | N/A | -| `npm run unit:components` (and `:watch` / `:coverage`), `npx vitest`, `composer storefront:components:unit` | N/A | `vitest_run` | -| `composer ludtwig:storefront`, bare `ludtwig` | N/A | `ludtwig_check` | -| `composer ludtwig:storefront:fix` | N/A | `ludtwig_fix` | -| `npm run production/development` | N/A | `webpack_build` | +Tool binaries are blocked when run directly at a command position, in three forms: + +- `npx `, `npm exec ` or its alias `npm x `, with an optional version suffix (`npx eslint@9`). +- `/node_modules/.bin/`. +- The command-string form, `npx -c ''`, `npm exec -c ""` or `--call`, when the string runs the binary at its start or after `;`, `&&` or `|` (`npm exec --no -c "cd ../.. && eslint views/components"`). + +The binaries are `eslint`, `stylelint` and `jest` on both servers, `prettier` and `tsc` on Administration only, and `vitest` on Storefront only. Between the runner and the binary the hooks look past `-y`, `--yes`, `--no`, `--no-install`, `-q`, `--quiet`, `--silent` and `--`. Before `-c` they look past the same flags except `--`, plus `--package`, `-p`, `--workspace` and `-w` with their value. + +Not blocked: + +- A flag that takes a value before the binary (`npx --package=eslint eslint`, `npm exec --workspace foo -- eslint`). Reading its value as the binary would also block `npm exec --package eslint some-other-tool`. +- A bare binary name (`eslint`, `jest`). A command-position match would block a commit message containing `; eslint config`. +- A binary name in an argument. + +[reference.md](./reference.md) describes how each MCP tool routes its own path-scoped runs. The table still lists `stylelint:base`, `prettier:base`, `jest:base`, `eslint:app`, `eslint:components` and `stylelint:app`, which Shopware's `package.json` files do not define, because a project can define them. + +| Bash Command | Admin MCP Tool | Storefront MCP Tool | +|------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------|---------------------| +| `npm run lint`, `npx eslint`, `npm exec eslint`, `node_modules/.bin/eslint` | `eslint_check` | `eslint_check` | +| `npm run lint:js` | N/A | `eslint_check` | +| `npm run lint:debugging` | `eslint_check` | N/A | +| `npm run eslint:app`, `npm run eslint:components` | N/A | `eslint_check` | +| `npm run lint:fix` | `eslint_fix` | `eslint_fix` | +| `npm run lint:js:fix` | N/A | `eslint_fix` | +| `npm run lint:scss`, `npx stylelint`, `npm exec stylelint`, `node_modules/.bin/stylelint` | `stylelint_check` | `stylelint_check` | +| `npm run stylelint:base` | `stylelint_check` | N/A | +| `npm run stylelint:app` | N/A | `stylelint_check` | +| `npm run lint:scss-fix` | `stylelint_fix` | `stylelint_fix` | +| `npm run format`, `npx prettier`, `npm exec prettier`, `node_modules/.bin/prettier` | `prettier_check` | N/A (Admin only) | +| `npm run prettier:base` | `prettier_check` | N/A (Admin only) | +| `npm run format:fix` | `prettier_fix` | N/A (Admin only) | +| `npm run unit`, `npx jest`, `npm exec jest`, `node_modules/.bin/jest` | `jest_run` | `jest_run` | +| `npm run jest:base` | `jest_run` | `jest_run` | +| `npm run lint:types`, `npx tsc`, `npm exec tsc`, `node_modules/.bin/tsc` | `tsc_check` | N/A (Admin only) | +| `npm run lint:all` | `lint_all` | N/A (Admin only) | +| `npm run lint:twig` | `lint_twig` | N/A (Admin only) | +| `npm run build` | `vite_build` | N/A | +| `npm run unit:components` (and `:watch` / `:coverage`), `npx vitest`, `npm exec vitest`, `node_modules/.bin/vitest`, `composer storefront:components:unit` | N/A | `vitest_run` | +| `composer ludtwig:storefront`, bare `ludtwig` | N/A | `ludtwig_check` | +| `composer ludtwig:storefront:fix` | N/A | `ludtwig_fix` | +| `npm run production/development` | N/A | `webpack_build` | `npm run unit` and `npm run unit:components` are matched by separate patterns, so the component suite is redirected to `vitest_run` and never to `jest_run`. The `:fix` ludtwig pattern is tested before the plain one, so `composer ludtwig:storefront:fix` resolves to `ludtwig_fix` rather than being shadowed by `ludtwig_check`. -Commands that aren't blocked: `npm install`, `composer install`, watch-mode scripts other than `npm run unit:components:watch`, and any npm script that doesn't match one of the patterns above. +Commands that aren't blocked: `npm install`, `composer install`, watch-mode scripts other than `npm run unit:components:watch`, any npm script that doesn't match one of the patterns above, the bare binary names described above, and `npx`, `npm exec` or `npm x` running a tool not named in the table. ## 🔗 Plugin Integration -Other plugins can pull these tools into their own skills or agents by referencing them in frontmatter. The MCP tool name is `mcp____`: - -```markdown ---- -tools: mcp__php-tooling__phpstan_analyze, mcp__php-tooling__ecs_check, mcp__js-admin-tooling__eslint_check ---- -``` +Other plugins can pull these tools into their own skills or agents by naming the short tool on its server. Cursor agents list those names in the agent body rather than a host-prefixed `mcp__` form. The `test-writing` plugin in this marketplace is a working example. diff --git a/plugins/dev-tooling/docs/reference.md b/plugins/dev-tooling/docs/reference.md index e274fe67..b79918f1 100644 --- a/plugins/dev-tooling/docs/reference.md +++ b/plugins/dev-tooling/docs/reference.md @@ -109,7 +109,7 @@ Use console_list with namespace "cache" | `scope` | string | Scope name from `.mcp-php-tooling.json`; `shopware` forces project-root behavior | | `project_root` | string | Absolute path to a linked git worktree of the launch root. See [🌳 Worktree Support](#-worktree-support). | -With `output_file` set, stdout goes to the file and the response carries only the resolved path, the byte count and the exit status — stderr still comes back in the response. A relative path resolves against the project root, parent directories are created, and the file is replaced only after the command exits zero. A failed command leaves the target as it was and returns its stdout in the response instead. The value is refused when it is longer than 4096 bytes, or when the target already exists as a symlink or as anything other than a regular file. Omit it (or pass an empty string) to get the output in the response as before. +With `output_file` set, stdout goes to the file and the response carries only the resolved path, the byte count and the exit status — stderr still comes back in the response. A relative path resolves against the project root, parent directories are created, and the file is replaced only after the command exits zero. A failed command leaves the target as it was and returns its stdout in the response instead. The value is refused when it is longer than 4096 bytes or its final path component is `.git`. An existing symlink or non-regular target is also refused. Omit it (or pass an empty string) to get the output in the response as before. `feature_all` sets `FEATURE_ALL=` in the command's process environment inside the target environment. `feature_all "major"` with `command "cache:clear"` is the deprecation gate `FEATURE_ALL=major bin/console cache:clear`. @@ -119,6 +119,8 @@ With `output_file` set, stdout goes to the file and the response carries only th Rector refactoring. `rector_fix` detects and applies transformations (preferred); `rector_check` is a dry-run preview. +`rector_fix` reads `composer.json` at the effective root, or under the scope's `cwd` when one is set. It runs `composer rector-fix` when that file defines a `rector-fix` script; otherwise it runs `composer rector`. If only a `rector` script with `--dry-run` is available, the call is refused because the run would apply nothing. + ``` Use rector_fix with paths ["src/Core/Content/"] Use rector_fix with only "CountArrayToEmptyArrayComparisonRector" @@ -138,20 +140,24 @@ Use rector_fix with only_suffix "Controller" ### `set_project_root` -Sets or clears the sticky project root for this server process. With a `project_root`, validates it as a linked git worktree of the launch root and sticks it — every later call on this server targets it until `set_project_root` is called again with no argument. Without one, clears the sticky root unconditionally (no validation of the value discarded) and returns the server to its launch root. +Sets or clears the sticky project root for this server process, and binds a server that started without one. + +- A server started in its own plugin directory has no project root, and the first call carrying a `project_root` binds it instead of sticking it. The root has to be a directory outside the plugin directory that holds this server's `.mcp-php-tooling.json`, at its top or in one of the supported tool directories, unless `MCP_PHP_TOOLING_CONFIG` names the configuration file (a relative value is read against the root being bound); on success the server loads that configuration, derives the environment, and records that root with symlinks resolved, which every later call enters before it runs. After the bind, a tool call may target the launch root itself, in any spelling that resolves to the same directory, or a linked git worktree of it; any other directory is refused. The bind is refused when the configuration cannot be loaded or declares an `environment` other than `native`, `docker`, `docker-compose`, `vagrant` or `ddev`. A call with no `project_root` while unbound is refused: there is no project root to return to. +- A server that has a project root — started in one, or bound as above — validates a `project_root` as a linked git worktree of that root and sticks it; every later call on this server targets it until `set_project_root` is called again with no argument. Without one, clears the sticky root unconditionally (no validation of the value discarded) and returns the server to its project root; naming the launch root itself, in any spelling that resolves to the same directory, does the same. ``` +Use php-tooling set_project_root with project_root "/path/to/project" Use php-tooling set_project_root with project_root "/path/to/worktree" Use php-tooling set_project_root ``` -| Parameter | Type | Description | -|----------------|--------|-------------------------------------------------------------------------------------------| -| `project_root` | string | Absolute path to a linked git worktree of the launch root. Omit to clear the sticky root. | +| Parameter | Type | Description | +|----------------|--------|--------------------------------------------------------------------------------------------| +| `project_root` | string | Absolute path to bind, or a linked worktree of the launch root. Once bound, omit to clear. | ### `cwd` -Reports this server's resolution state: the effective project root, its source (`launch` or `sticky` — `cwd` takes no `project_root`, so it never reports the `call` source the other tools' banners can show), whether it currently resolves, the resolved working directory, the environment, and the configuration file(s) in use. No parameters, validates nothing, never fails — including when a sticky root names a directory that no longer exists. +Reports this server's resolution state: the effective project root, its source (`launch` or `sticky` — `cwd` takes no `project_root`, so it never reports the `call` source the other tools' banners can show), whether it currently resolves, the resolved working directory, the environment, and the configuration file(s) in use. A server with no project root yet reports the root as `none (unbound)`, names the plugin directory it started in and the `set_project_root` call that binds it, and reports the configuration as pending until a bind loads one. No parameters, validates nothing, never fails — including when a sticky root names a directory that no longer exists. "Resolves" reports resolution and mapping, not reachability: the existence probe runs on tool calls, not here, so a root `cwd` reports as resolving can still be refused by the next tool call's probe. @@ -161,11 +167,13 @@ Use php-tooling cwd ## 🖥️ Administration Tools (`js-admin-tooling`) -Runs inside `src/Administration/Resources/app/administration`. No context parameter. +Runs inside `src/Administration/Resources/app/administration`. No context parameter. ESLint, Stylelint, Prettier, and `tsc_check` reject shell-hostile scoped config paths and quote accepted paths before passing them to the command wrapper. ### `eslint_check` / `eslint_fix` -ESLint linting / auto-fix for Administration. Two routes, selected by whether `paths` is supplied: with paths, the run goes to the target-less npm script `lint:debugging` so the given paths are the only targets; without paths, the aggregate `lint` / `lint:fix` script runs and its own baked-in targets stay authoritative. The aggregate is never a fallback for a path-scoped run — npm appends `--` arguments to the end of the whole script body, so appending a path to a body that already names its own targets would widen the run rather than narrow it to the path. A path-scoped run refuses outright when `lint:debugging` is unavailable or cannot take appended arguments. +ESLint linting / auto-fix for Administration. With `paths`, the package's own ESLint binary runs through `npm exec --no -- eslint`; the supplied paths are its only targets. Without `paths`, the aggregate `lint` / `lint:fix` script runs with its own targets. + +The aggregate cannot replace a path-scoped run because npm appends arguments after the script body's targets, widening the run. A path-scoped run refuses when the package's `node_modules/.bin/eslint` is missing because `npm exec --no` would otherwise run a global binary. ``` Use js-admin-tooling eslint_fix with paths ["src/app/component/"] @@ -178,13 +186,24 @@ Use js-admin-tooling eslint_fix with paths ["src/app/component/"] | `scope` | string | both | Scope name from `.mcp-js-tooling.json`; `shopware` forces project-root behavior | | `project_root` | string | both | Absolute path to a linked git worktree of the launch root. See [🌳 Worktree Support](#-worktree-support). | -When `paths` is supplied, these are the ONLY targets the run covers; a path containing `app/administration/` is rebased onto the package directory by stripping everything up to and including that prefix. Omit `paths` to run the targets the aggregate `lint` / `lint:fix` script configures for itself. +When `paths` is supplied, these are the ONLY targets the run covers. Without a scope, a path containing `app/administration/` loses everything through that prefix. Under a scope the path is rebased onto the scope cwd: a leading `./` and then a leading `/` come off, an absolute path is cut through its first `//`, a path naming the scope cwd itself becomes `.`, and any other path passes through. The plugin's own `app/administration/` segment stays. Omit `paths` to run the targets the aggregate `lint` / `lint:fix` script configures for itself. Every path is validated before ESLint runs: it must exist and resolve to at least one file carrying an extension the Administration ESLint config reads (`js`, `ts`, `tsx`, `vue`, `json`, `twig`). A path that fails either check is refused with a message naming it, rather than linting nothing and reporting success. ### `stylelint_check` / `stylelint_fix` -Stylelint SCSS linting / auto-fix. Two routes, selected by whether `paths` is supplied: with paths, the run goes to the target-less npm script `stylelint:base` so the given paths are the only targets; without paths, the aggregate `lint:scss` / `lint:scss-fix` script runs (bare when there is nothing else to append) and its own `**/*.scss` target stays authoritative. The aggregate is never a fallback for a path-scoped run — appending a path to a body that already names `**/*.scss` would widen the run to every SCSS file plus the path, never narrow it. That matters most for `stylelint_fix`, which writes: a widened fix would modify files nobody named. A path-scoped run refuses outright when `stylelint:base` is unavailable. +Stylelint SCSS linting / auto-fix. Two routes, selected by whether `paths` is supplied: + +- With `paths`, the package's own Stylelint binary runs through `npm exec --no -- stylelint --cache`, the flags of the `lint:scss` script without its target. The given paths are the only targets. +- Without `paths`, the aggregate `lint:scss` / `lint:scss-fix` script runs, bare when there is nothing else to append. Its own `**/*.scss` target stays authoritative. + +The aggregate is never a fallback for a path-scoped run. Appending a path to a body that already names `**/*.scss` would widen the run to every SCSS file plus the path. That matters most for `stylelint_fix`, which writes: a widened fix would modify files nobody named. + +The run is refused when: + +- A path-scoped run finds no `node_modules/.bin/stylelint` in the package directory. `npm exec --no` installs nothing but would run a globally installed `stylelint`, so the tool checks for the package's own binary first. +- A scoped config contains shell-hostile characters. The tool checks and quotes the config path before appending `--config`. +- A run without `paths` has a scoped config, and the aggregate script's own `stylelint` command already passes `--config`, `--config=`, `-c` or `-c=`. Stylelint takes its config option only once. The tool reads only that script's own body, not the body of a script it calls through `npm run`. ``` Use js-admin-tooling stylelint_fix with paths ["src/**/*.scss"] @@ -200,11 +219,23 @@ Use js-admin-tooling stylelint_fix with paths ["src/**/*.scss"] When `paths` is supplied, these are the ONLY targets the run covers. Omit `paths` to run the targets the aggregate SCSS script configures for itself. > [!NOTE] -> A literal path is validated before Stylelint runs: it must exist and resolve to at least one `.scss` or `.css` file, or it is refused with a message naming it rather than linting nothing and reporting success. A glob pattern (containing `*`, `?`, or `[`) skips that check — the existence probe cannot resolve a glob — and reaches Stylelint unchecked for expansion there. +> A literal path is validated before Stylelint runs. A file must carry the `.scss` extension `lint:scss` lints, and a directory must hold at least one `.scss` file. Otherwise the path is refused with a message naming it, rather than linting nothing and reporting success. +> +> A directory, including one whose name ends in `.scss`, reaches Stylelint as the quoted pattern `/**/*.scss`. Stylelint expands it, so only `.scss` files are linted or fixed. Stylelint given a bare directory would read every file in it. +> +> A glob pattern (containing `*`, `?`, or `[`) skips the validation, because the existence probe cannot resolve a glob. It reaches Stylelint unchecked for expansion there. + +> [!NOTE] +> Under `ddev`, directory and glob paths are refused. `ddev exec` re-parses the command in the container's shell, which would expand the pattern itself before Stylelint sees it. Pass file paths there. A directory or glob path holding a space, a tab or `#` is accepted because `ddev exec` quotes that argument again, so it reaches Stylelint intact. ### `prettier_check` / `prettier_fix` -Prettier format check / auto-format for Administration. Two routes, selected by whether `paths` is supplied: with paths, the run goes to the target-less npm script `prettier:base`, with the `--check` / `--write` mode flag supplied by the tool, so the given paths are the only targets; without paths, the aggregate `format` / `format:fix` script runs bare (plus a `--config` override when a scope selects one) and its own glob targets stay authoritative. The aggregate is never a fallback for a path-scoped run, for the same reason as ESLint and Stylelint above — appending would widen, not narrow. That matters most for `prettier_fix`, which writes. A path-scoped run refuses outright when `prettier:base` is unavailable. +Prettier format check / auto-format for Administration. Two routes, selected by whether `paths` is supplied: + +- With `paths`, the package's own Prettier binary runs through `npm exec --no -- prettier` with `--check` (`prettier_check`) or `--write --cache` (`prettier_fix`), the flags of the `format` / `format:fix` scripts without their globs. The given paths are the only targets. +- Without `paths`, the aggregate `format` / `format:fix` script runs bare, plus a `--config` override when a scope selects one. Its own glob targets stay authoritative. + +The aggregate is never a fallback for a path-scoped run, for the reason given for [Stylelint](#stylelint_check--stylelint_fix). That matters most for `prettier_fix`, which writes. A path-scoped run is refused when `node_modules/.bin/prettier` is missing from the package directory. ``` Use js-admin-tooling prettier_check with paths ["src/app/component/"] @@ -219,13 +250,19 @@ Use js-admin-tooling prettier_check with paths ["src/app/component/"] When `paths` is supplied, these are the ONLY targets the run covers. Omit `paths` to check/format the targets the aggregate `format` / `format:fix` script configures for itself. > [!NOTE] -> A literal path is validated before Prettier runs: it must exist and resolve to at least one `.js` or `.ts` file, or it is refused with a message naming it. A glob pattern (containing `*`, `?`, or `[`) skips that check and reaches Prettier unchecked for expansion there. +> A literal path is validated before Prettier runs. A file must carry one of the extensions the `format` globs name (`.js`, `.ts`, `.mjs`), and a directory must hold at least one such file. Otherwise the path is refused with a message naming it. +> +> A directory, including one whose name ends in one of those extensions, reaches Prettier as the quoted pattern `/**/*.{js,ts,mjs}`. Prettier expands it, so only those files are checked or rewritten. Prettier given a bare directory would format every file type it supports. +> +> A glob pattern (containing `*`, `?`, or `[`) skips the validation and reaches Prettier unchecked for expansion there. +> +> Under `ddev`, directory and glob paths are refused, as for [Stylelint](#stylelint_check--stylelint_fix). ### `jest_run` Jest unit tests. Single run only. Watch mode isn't supported (see [mcp-enforcement.md](./mcp-enforcement.md)). -Runs at the target-less npm script `jest:base`. When that script is unavailable, the tool falls back to the aggregate `unit` script instead of refusing — `jest_run` covers the same suite either way, so nothing is silently widened — but `unit`'s body hardcodes `--ci`, and the tool prints a notice naming the consequences (see the `ci` row below). +Every run uses the package's npm script `unit`. The core Administration `unit` script passes `--ci`. The tool checks scope and test-pattern arguments before attempting dependency installation, so those argument refusals install nothing. **The result comes from Jest's own JSON report, not the process exit code.** Every run appends `--json --outputFile=`; the tool clears that path before starting, reads it afterwards, and decides from the counts it carries: @@ -237,7 +274,7 @@ Runs at the target-less npm script `jest:base`. When that script is unavailable, | all passed, process exited non-zero | success, stating the exit code prominently and keeping the output | | report missing or unparseable | falls back to the exit code, and says the status came from there | -The last two rows are the point. A coverage-threshold breach or a post-run writer erroring makes Jest exit non-zero after every test passed, and that was previously reported as a failed run. The report also carries the counts when `ci` is true, where Jest's own summary line is suppressed. +The last two rows are the point. A coverage-threshold breach or a post-run writer erroring makes Jest exit non-zero after every test passed, and that was previously reported as a failed run. The report also carries the counts under `unit`'s CI mode, where Jest's own summary line is suppressed. > [!NOTE] > The report path is cleared before each run rather than after. A report present afterwards therefore always belongs to the run that just finished — otherwise a run that crashed before writing one would be judged by the previous run's results, and a failing suite could be reported as a pass. One report file per server process may sit in the environment's `/tmp` between runs. @@ -251,17 +288,17 @@ Use js-admin-tooling jest_run with coverage true |--------------------|---------|----------------------------------------------------------------------------------------------------------| | `testPathPatterns` | string | Regex on test file paths | | `testNamePattern` | string | Regex on test names | -| `coverage` | boolean | Generate coverage report | -| `updateSnapshots` | boolean | Update snapshots | -| `ci` | boolean | Run Jest in CI mode (`--ci`, default `false`); see below. | +| `coverage` | boolean | Append `--coverage`; core Administration already collects coverage on every run. | +| `updateSnapshots` | boolean | Append `--updateSnapshot` to update snapshots | +| `ci` | boolean | Append `--ci`. The core `unit` script already passes it, but a plugin scope's `unit` script may not. | | `scope` | string | Scope name from `.mcp-js-tooling.json`; `shopware` forces project-root behavior | | `project_root` | string | Absolute path to a linked git worktree of the launch root. See [🌳 Worktree Support](#-worktree-support). | -`ci` runs Jest in CI mode (`--ci`). `jest.config.ts` derives `isCi` from an exact `--ci` match in `process.argv` and uses it for both `collectCoverage` and the reporter choice: turning `ci` on collects coverage regardless of `coverage` and swaps the reporters to `jest-silent-reporter` plus `jest-junit`, suppressing the per-test lines and the summary. `ci` is forced on, without recourse, whenever the `unit` fallback above is in effect. Leave it off unless CI-identical output is needed. +The Administration `unit` script always passes `--ci`. Its Jest configuration derives `isCi` from that argument, collects coverage, and selects `jest-silent-reporter` plus `jest-junit`. Passing `coverage` adds `--coverage` but does not change core Administration coverage collection. `jest-silent-reporter` suppresses Jest's `Tests:` line, so the tool reads the counts from its JSON report. ### `tsc_check` -`npm run lint:types` against the project tsconfig. +`npm run lint:types` against the project tsconfig. An explicit scope can supply a TypeScript project config; the tool rejects shell-hostile config paths and quotes accepted ones. Without `scope`, the tool uses `default_scope`, or the core Administration package when no default is set. | Parameter | Type | Description | |----------------|--------|----------------------------------------------------------------------------------------------------------| @@ -270,7 +307,7 @@ Use js-admin-tooling jest_run with coverage true ### `lint_all` -Runs TypeScript, ESLint, Stylelint, and Prettier in one shot. Intended for pre-commit validation. +Runs TypeScript, ESLint, Stylelint, and Prettier in one shot. Intended for pre-commit validation. Without `scope`, `lint_all` ignores `default_scope` and runs the core script. | Parameter | Type | Description | |----------------|--------|----------------------------------------------------------------------------------------------------------| @@ -279,7 +316,7 @@ Runs TypeScript, ESLint, Stylelint, and Prettier in one shot. Intended for pre-c ### `lint_twig` -ESLint against `.html.twig` files. Validates Admin Vue component templates. +ESLint against `.html.twig` files. Validates Admin Vue component templates. Without `scope`, `lint_twig` ignores `default_scope` and runs the core script. | Parameter | Type | Description | |----------------|--------|----------------------------------------------------------------------------------------------------------| @@ -288,7 +325,7 @@ ESLint against `.html.twig` files. Validates Admin Vue component templates. ### `unit_setup` -Regenerates the component import resolver map. Run it when Jest fails with import/module resolution errors. +Regenerates the component import resolver map. Run it when Jest fails with import/module resolution errors. Without `scope`, `unit_setup` ignores `default_scope` and runs the core script. | Parameter | Type | Description | |----------------|--------|----------------------------------------------------------------------------------------------------------| @@ -297,7 +334,7 @@ Regenerates the component import resolver map. Run it when Jest fails with impor ### `vite_build` -Vite build for Administration (Vue 3). +Vite build for Administration (Vue 3). Without `scope`, `vite_build` ignores `default_scope` and runs the core build. | Parameter | Type | Description | |----------------|--------|----------------------------------------------------------------------------------------------------------| @@ -307,11 +344,11 @@ Vite build for Administration (Vue 3). ### `set_project_root` -Sets or clears the sticky project root for this server process. Same behavior as the PHP server's `set_project_root` above — a separate process, a separate sticky value. +Sets or clears the sticky project root for this server process, and binds a server that started without one. Same behavior as the PHP server's `set_project_root` above — a separate process, a separate sticky value. A bind requires a directory holding this server's own `.mcp-js-tooling.json`, at its top or in one of the supported tool directories, unless `MCP_JS_TOOLING_CONFIG` names the configuration file; after the bind, a call may target that root itself or stick a linked git worktree of it. -| Parameter | Type | Description | -|----------------|--------|-------------------------------------------------------------------------------------------| -| `project_root` | string | Absolute path to a linked git worktree of the launch root. Omit to clear the sticky root. | +| Parameter | Type | Description | +|----------------|--------|--------------------------------------------------------------------------------------------| +| `project_root` | string | Absolute path to bind, or a linked worktree of the launch root. Once bound, omit to clear. | ### `cwd` @@ -319,14 +356,21 @@ Reports this server's resolution state. No parameters. Same shape as the PHP ser ## 🛒 Storefront Tools (`js-storefront-tooling`) -Runs inside `src/Storefront/Resources/app/storefront`. No context parameter. +Runs inside `src/Storefront/Resources/app/storefront`. No context parameter. ESLint and Stylelint reject shell-hostile scoped config paths and quote accepted paths before passing them to the command wrapper. > [!NOTE] > Prettier and TypeScript aren't exposed for Storefront. The Shopware 6 Storefront `package.json` has no corresponding npm scripts. ### `eslint_check` / `eslint_fix` -ESLint linting / auto-fix for Storefront. The Storefront splits ESLint across two npm scripts — `eslint:app` for the `app/storefront` package and `eslint:components` for the component tree under `src/Storefront/Resources/views/components` — so each supplied path is routed to the tree that owns it and both scripts run when both trees are targeted. A path containing `views/components` goes to the components tree; everything else goes to the app tree. +ESLint linting / auto-fix for Storefront. The Storefront's `lint:js` script runs ESLint twice: once in the `app/storefront` package, and once from `src/Storefront/Resources` with `--config ./app/storefront/eslint.config.js` for the component tree under `views/components`. Each supplied path is routed to the tree that owns it, and both trees run when both are targeted. A path containing `views/components` goes to the components tree; everything else goes to the app tree. + +With paths, each tree runs the package's own ESLint binary through `npm exec --no`, with the flags of its `lint:js` call (`--no-error-on-unmatched-pattern --report-unused-disable-directives`, plus the components config). The given paths are the only targets. The components call starts with `npm exec --no -c` in the package directory and changes to `../..` before ESLint runs. App-tree paths under a scope run with the scope's ESLint config. + +A path-scoped run is refused when: + +- `node_modules/.bin/eslint` is missing from the package directory. +- A scope other than `shopware` is active and a path routes to the components tree. That tree and `./app/storefront/eslint.config.js` belong to the core Storefront package, not to the scope's package. The refusal comes before anything runs. ``` Use js-storefront-tooling eslint_fix with paths ["src/plugin/"] @@ -344,38 +388,61 @@ Three path forms are accepted, per path: - repo-root-relative — `src/Storefront/Resources/views/components/…` or `src/Storefront/Resources/app/storefront/…` - tree-relative — `views/components/…` for the components tree, `src/…` or `build/…` for the app tree -- a path already carrying the package prefix +- a path already carrying the package prefix — `app/storefront/…`, unscoped runs only: under a scope that prefix stays as written and the path is refused as missing + +Under a scope, app-tree paths are rebased onto the scope cwd: a leading `./` and then a leading `/` come off, an absolute path is cut through its first `//`, a path naming the scope cwd itself becomes `.`, and any other path passes through. The plugin's own `app/storefront/` segment stays. Every path is validated before ESLint runs. A path that does not exist, or that resolves to no file carrying an extension the Storefront ESLint config reads (`js`, `ts`, `mjs`, `cjs`, `jsx`, `tsx`, `vue`, `json`), is refused with a message naming it — so `paths: ["src/scss"]` fails loudly instead of linting nothing and reporting success. A path containing a single quote, a newline, or a carriage return is refused as well; those characters cannot be quoted safely through the container command wrappers. Omitting `paths` runs the aggregate `lint:js` / `lint:js:fix` script bare across both trees. > [!WARNING] -> `output_format` is ignored on a no-paths `eslint_check`. The no-paths branch runs `npm run lint:js` bare, and that script chains bare `npm run` calls, so an appended reporter flag would never reach ESLint. Pass `paths` when you need `json` output. +> `output_format` is ignored on a no-paths `eslint_check`. The no-paths branch runs `npm run lint:js` bare, because that script chains two ESLint calls and ends in a subshell, so an appended reporter flag would land after the subshell instead of reaching either call. Pass `paths` when you need `json` output. > [!NOTE] > A no-paths run under an active scope that selects its own ESLint config is refused rather than run, because the bare script would silently apply the package's own config instead. Pass `paths`, or call with `scope: "shopware"`. ### `stylelint_check` / `stylelint_fix` -Stylelint SCSS linting / auto-fix. Same routing as the Administration versions: with `paths` supplied, the run goes to the target-less npm script `stylelint:app` so the given paths are the only targets; without `paths`, the aggregate `lint:scss` / `lint:scss-fix` script runs and its own `./src/scss` target stays authoritative. The aggregate is never a fallback for a path-scoped run, and a path-scoped run refuses outright when `stylelint:app` is unavailable. Parameters: `paths` (file paths or glob patterns, relative to the `app/storefront` package directory), `output_format` on the check tool (`string` default, `json`, `compact`), `scope`, and `project_root` (see [🌳 Worktree Support](#-worktree-support)). +Stylelint SCSS linting / auto-fix. Same routing as the [Administration versions](#stylelint_check--stylelint_fix), selected by whether `paths` is supplied: + +- With `paths`, the package's own Stylelint binary runs through `npm exec --no -- stylelint --config stylelint.config.js --cache`, the flags of the `lint:scss` script without its target. The given paths are the only targets. +- Without `paths`, the aggregate `lint:scss` / `lint:scss-fix` script runs, and its own `./src/scss` target stays authoritative. + +The aggregate is never a fallback for a path-scoped run. + +On the path route under a scope, `--config stylelint.config.js` is left out, because that file belongs to the core Storefront package. A scope's own Stylelint config is then the only `--config`. Without one, Stylelint finds the scope package's own config. Without `paths`, a scope's Stylelint config is appended to the aggregate script. + +The run is refused when: + +- A path-scoped run finds no `node_modules/.bin/stylelint` in the package directory. +- A scoped config path contains shell-hostile characters. +- A run without `paths` has a scoped config, and the aggregate script's own `stylelint` command already passes `--config`, `--config=`, `-c` or `-c=`, as the core `lint:scss` does. The tool reads only that script's own body, so `lint:scss-fix`, which calls `lint:scss` through `npm run`, is not refused by this check. + +Parameters: `paths` (file paths or glob patterns, relative to the `app/storefront` package directory), `output_format` on the check tool (`string` default, `json`, `compact`), `scope`, and `project_root` (see [🌳 Worktree Support](#-worktree-support)). ``` Use js-storefront-tooling stylelint_fix with paths ["src/**/*.scss"] ``` > [!NOTE] -> A literal path is validated before Stylelint runs: it must exist and resolve to at least one `.scss` or `.css` file, or it is refused with a message naming it. A glob pattern (containing `*`, `?`, or `[`) skips that check and reaches Stylelint unchecked for expansion there. +> A literal path is validated before Stylelint runs. A file must carry the `.scss` or `.css` extension, and a directory must hold at least one such file. Otherwise the path is refused with a message naming it. +> +> A directory, including one whose name ends in `.scss` or `.css`, reaches Stylelint as the quoted pattern `/**/*.{scss,css}`, so only those files are linted or fixed. +> +> A glob pattern (containing `*`, `?`, or `[`) skips the validation and reaches Stylelint unchecked for expansion there. +> +> Under `ddev`, directory and glob paths are refused unless they hold a space, a tab or `#`, as for [Administration Stylelint](#stylelint_check--stylelint_fix). ### `jest_run` -Jest unit tests for the Storefront **`app/storefront` package suite only**. Jest's `rootDir` is that package and its `testMatch` collects `**/test/**/*.test.js`, so the component tests under `src/Storefront/Resources/views/components/` are never collected — run those with [`vitest_run`](#vitest_run). A `testPathPatterns` value naming `views/components` is rejected with a message pointing at `vitest_run`. +Jest unit tests for the Storefront **`app/storefront` package suite only**. Jest's `rootDir` is that package and its `testMatch` collects `**/test/**/*.test.js`, so the component tests under `src/Storefront/Resources/views/components/` are never collected — run those with [`vitest_run`](#vitest_run). A `testPathPatterns` value naming `views/components` is rejected. Under scope `shopware` the message points at `vitest_run`; under a plugin scope it states that `vitest_run` refuses every plugin scope. -Runs at the target-less npm script `jest:base`. When that script is unavailable, the tool falls back to the aggregate `unit` script instead of refusing — `jest_run` covers the same suite either way — but `unit`'s body hardcodes `--ci`, and the tool prints a notice naming the consequence: the `ci` argument is ignored and CI mode is forced. +Every run uses the package's npm script `unit`. The core Storefront `unit` script passes `--ci`. The `ci` argument appends `--ci` for a plugin scope's `unit` script that does not pass it. The tool checks scope and test-pattern arguments before attempting dependency installation, so those argument refusals install nothing. The result comes from Jest's JSON report rather than the process exit code, exactly as described for [the Admin version](#jest_run) — including the cleared-before-each-run report path. This matters more here than on Administration: the Storefront config collects coverage unconditionally and enforces global thresholds, so a path-scoped run of a few files exits non-zero on the threshold while every test passes. Those runs previously reported as errors. -Same parameters as the Admin version — `testPathPatterns`, `testNamePattern`, `coverage`, `updateSnapshots`, `ci`, plus `scope` and `project_root` (see [🌳 Worktree Support](#-worktree-support)) — except `ci`'s consequence differs here: the Storefront `jest.config.js` sets `collectCoverage: true` unconditionally, so `coverage` is unaffected either way and `ci` changes only Jest's own CI-mode behavior. Under CI mode Jest declines to write *new* snapshots — but an explicit `updateSnapshots` still wins, because Jest resolves `--ci` without `--updateSnapshot` to snapshot mode `none` and an explicit `--updateSnapshot` to `all` regardless of `--ci`. +Same parameters as the Admin version: `testPathPatterns`, `testNamePattern`, `coverage`, `updateSnapshots`, `ci`, `scope`, and `project_root` (see [🌳 Worktree Support](#-worktree-support)). Storefront's Jest configuration always collects coverage, so the `coverage` flag adds `--coverage` without changing coverage collection. CI mode writes no missing snapshots; explicit `updateSnapshots` adds `--updateSnapshot` and permits snapshot updates. ### `vitest_run` @@ -392,9 +459,11 @@ Use js-storefront-tooling vitest_run with testNamePattern "renders the slider" | `testNamePattern` | string | Regex on test names (`-t`) | | `coverage` | boolean | Run `unit:components:coverage` instead | | `updateSnapshots` | boolean | Update Vitest snapshots (`-u`) | -| `scope` | string | Scope name from `.mcp-js-tooling.json` | +| `scope` | string | Only `shopware` is accepted; omitting it also selects core behavior. Plugin scopes are refused. | | `project_root` | string | Absolute path to a linked git worktree of the launch root. See [🌳 Worktree Support](#-worktree-support). | +`vitest_run` ignores `default_scope` when `scope` is omitted. + `paths` accepts the same three forms as the Storefront ESLint tools (repo-root-relative, tree-relative `views/components/…`, or a path already carrying the package prefix) and each one is checked for existence before Vitest runs. A path containing a single quote or a line break is refused. ### `ludtwig_check` / `ludtwig_fix` @@ -416,7 +485,7 @@ Neither tool takes `paths` and neither takes `scope`: the composer script body i ### `webpack_build` -Webpack build for Storefront (vanilla JS). +Webpack build for Storefront (vanilla JS). Without `scope`, `webpack_build` ignores `default_scope` and runs the core build. `mode` accepts `development` and `production`; omitting it selects `production`. | Parameter | Type | Description | |----------------|--------|----------------------------------------------------------------------------------------------------------| @@ -426,11 +495,11 @@ Webpack build for Storefront (vanilla JS). ### `set_project_root` -Sets or clears the sticky project root for this server process. Same behavior as the PHP server's `set_project_root` above — a separate process, a separate sticky value. +Sets or clears the sticky project root for this server process, and binds a server that started without one. Same behavior as the PHP server's `set_project_root` above — a separate process, a separate sticky value. A bind requires a directory holding this server's own `.mcp-js-tooling.json`, at its top or in one of the supported tool directories, unless `MCP_JS_TOOLING_CONFIG` names the configuration file; after the bind, a call may target that root itself or stick a linked git worktree of it. -| Parameter | Type | Description | -|----------------|--------|-------------------------------------------------------------------------------------------| -| `project_root` | string | Absolute path to a linked git worktree of the launch root. Omit to clear the sticky root. | +| Parameter | Type | Description | +|----------------|--------|--------------------------------------------------------------------------------------------| +| `project_root` | string | Absolute path to bind, or a linked worktree of the launch root. Once bound, omit to clear. | ### `cwd` @@ -438,12 +507,14 @@ Reports this server's resolution state. No parameters. Same shape as the PHP ser ## 🌳 Worktree Support -Every tool except `cwd`, on all three servers, accepts `project_root`. Pass it to run one call against a linked git worktree of the root the server was launched in, instead of the launch root itself. Targeting works in every environment: `native`, `docker`, `docker-compose`, `vagrant`, and `ddev`. +Every tool except `cwd`, on all three servers, accepts `project_root`. Pass it to run one call against a linked git worktree of the server's project root, instead of that root itself. Targeting works in every environment: `native`, `docker`, `docker-compose`, `vagrant`, and `ddev`. + +**Binding a server that has no project root.** Cursor starts a server in the session's project directory, so it is bound at launch. A server started in the plugin's own directory comes up unbound and refuses every tool except `set_project_root` and `cwd`. On such a server the first `set_project_root` call carrying a path binds it — the configuration, the environment and the working directory are derived from that root, and it stays the server's root for the rest of the process, so a later call may target that root itself or stick a linked git worktree of it. Exporting `PROJECT_ROOT` with the project path before starting the server binds at startup instead. Throughout this section, "launch root" means the root the server is bound to, by either route. What the environment adds: - **In-root under containers.** `docker`, `docker-compose`, `vagrant`, and `ddev` refuse a worktree outside the launch project root, which is the only tree the container or VM mounts. An in-root worktree is reached at its own position below the environment's working directory; under `docker-compose` a configured `docker-compose.workdir` decides, or else the longest matching bind mount. -- **Relative linkage, in every environment.** The worktree's `.git` file has to carry a relative `gitdir` pointer. `git worktree add` writes an absolute one unless the repository sets `worktree.useRelativePaths`, and an absolute pointer names a host path that does not exist inside a container — so the call is refused under `native` too. Relink the worktree with `git -c worktree.useRelativePaths=true worktree repair ` (git 2.48 or newer), or create it with `git worktree add --relative-paths`. Setting `git config worktree.useRelativePaths true` once makes every later worktree carry relative linkage from the start. +- **Relative linkage, under containers.** Under `docker`, `docker-compose`, `vagrant`, and `ddev` the worktree's `.git` file has to carry a relative `gitdir` pointer. `git worktree add` writes an absolute one unless the repository sets `worktree.useRelativePaths`, and an absolute pointer names a host path that does not exist inside a container, so the call is refused. `native` accepts an absolute pointer, because the command runs on the host where the pointer resolves. Relink the worktree with `git -c worktree.useRelativePaths=true worktree repair ` (git 2.48 or newer), or create it with `git worktree add --relative-paths`. Setting `git config worktree.useRelativePaths true` once makes every later worktree carry relative linkage from the start. - **Dependency provisioning.** A fresh worktree holds tracked files only, so `vendor/` and `node_modules` are missing and the composer- and npm-backed tools refuse until they exist. Each server's `worktree_prepare` installs its own toolchain's dependencies in the target root through the configured environment: `composer install --no-interaction` on `php-tooling`, `npm ci` in the package directory on `js-admin-tooling` and `js-storefront-tooling`. It takes `project_root` like every other tool and skips the dependency check the other tools run. The JS variants also take `scope` — their install and dependency gate both derive the same package directory through `get_js_workdir`; the PHP variant deliberately does not, because the gate checks `vendor/autoload.php` at the effective root and a scoped install would land where the gate never looks. A successful install returns a short completion summary — the per-package installer output is suppressed — while a failed one returns the full output. Re-run it after the worktree's `composer.json`/`composer.lock` or `package-lock.json` changes — the dependency check only tests that the install directory exists. Admin Jest additionally needs `unit_setup` after the install plus the gitignored `test/_mocks_/entity-schema.json`, which `unit_setup` does not regenerate — dump it with `console_run` on `php-tooling` (env `prod`): `framework:schema -s entity-schema src/Administration/Resources/app/administration/test/_mocks_/entity-schema.json` (the flag is `-s`/`--schema-format`; `--schema` does not exist). `ludtwig` needs `worktree_prepare` on `php-tooling`, not on its own server, because it runs composer. Never symlink `vendor/` from the launch tree instead: composer's autoloaders resolve through the symlink and load the launch tree's classes. - **Charset.** A root carrying a single quote or a control character is refused in every environment. Under `docker`, `docker-compose`, `vagrant`, and `ddev`, whitespace and the metacharacter set `$`, backtick, backslash, `"`, `;`, `&`, `|`, `<`, `>`, `(`, `)`, `{`, `}` are refused too — the first three embed the working directory unquoted, and `ddev` parses it a second time inside the container. Glob characters stay admitted. - **Existence probe.** After validation the tool checks that the environment reaches the mapped path, through the same wrapper the call uses. A missing directory refuses the call and names the path; a passing result is cached for that server process per environment, root and mapped path, so an edited workdir in a worktree's own configuration probes again. diff --git a/plugins/dev-tooling/hooks/prompts/mcp-tool-directives.md b/plugins/dev-tooling/hooks/prompts/mcp-tool-directives.md index 7fef3afb..59dbb530 100644 --- a/plugins/dev-tooling/hooks/prompts/mcp-tool-directives.md +++ b/plugins/dev-tooling/hooks/prompts/mcp-tool-directives.md @@ -2,14 +2,14 @@ ALWAYS use MCP dev tools for PHP and JavaScript operations — NEVER run these v MCP tools auto-detect the development environment (native/docker/vagrant/ddev) and apply project configuration. -php-tooling: phpstan_analyze, ecs_check, ecs_fix, phpunit_run, phpunit_coverage_gaps, console_run, console_list, rector_fix, rector_check, worktree_prepare, set_project_root, cwd -js-admin-tooling: eslint_check/fix, stylelint_check/fix, prettier_check/fix, jest_run, tsc_check, lint_all, lint_twig, unit_setup, vite_build, worktree_prepare, set_project_root, cwd -js-storefront-tooling: eslint_check/fix, stylelint_check/fix, jest_run, vitest_run, ludtwig_check/fix, webpack_build, worktree_prepare, set_project_root, cwd +On the `php-tooling` MCP server: `phpstan_analyze`, `ecs_check`, `ecs_fix`, `phpunit_run`, `phpunit_coverage_gaps`, `console_run`, `console_list`, `rector_fix`, `rector_check`, `worktree_prepare`, `set_project_root`, `cwd` +On the `js-admin-tooling` MCP server: `eslint_check`/`eslint_fix`, `stylelint_check`/`stylelint_fix`, `prettier_check`/`prettier_fix`, `jest_run`, `tsc_check`, `lint_all`, `lint_twig`, `unit_setup`, `vite_build`, `worktree_prepare`, `set_project_root`, `cwd` +On the `js-storefront-tooling` MCP server: `eslint_check`/`eslint_fix`, `stylelint_check`/`stylelint_fix`, `jest_run`, `vitest_run`, `ludtwig_check`/`ludtwig_fix`, `webpack_build`, `worktree_prepare`, `set_project_root`, `cwd` -Every tool except cwd takes an optional project_root to target a linked git worktree of the launch root, in every environment; refusals name what to fix and how. After `git worktree add` or `git worktree remove`, call set_project_root (with the worktree path, or with none to clear) on all three servers — each is a separate process with its own sticky value; cwd reports a server's current state. A fresh worktree lacks vendor/ and node_modules — call worktree_prepare on the refusing server instead of provisioning by hand, and NEVER symlink vendor/ from the launch tree (composer's autoloaders resolve through the symlink to the launch tree's classes). +Every tool except `cwd` on each dev-tooling MCP server takes an optional project_root to target a linked git worktree of the launch root, in every environment; refusals name what to fix and how. After `git worktree add` or `git worktree remove`, call `set_project_root` on each dev-tooling MCP server (with the worktree path, or with none to clear) — each is a separate process with its own sticky value; `cwd` on each dev-tooling MCP server reports that server's current state. A fresh worktree lacks vendor/ and node_modules — call `worktree_prepare` on the dev-tooling MCP server the refusal names (a ludtwig refusal on a missing vendor/ names `php-tooling`) instead of provisioning by hand, and NEVER symlink vendor/ from the launch tree (composer's autoloaders resolve through the symlink to the launch tree's classes). -Storefront tests are split across two runners: jest_run covers the app/storefront package suite, vitest_run covers the component suite under src/Storefront/Resources/views/components/. jest_run rejects views/components patterns. +Storefront tests are split across two runners: `jest_run` on the `js-storefront-tooling` MCP server covers the app/storefront package suite, `vitest_run` on the `js-storefront-tooling` MCP server covers the component suite under src/Storefront/Resources/views/components/. `jest_run` on the `js-storefront-tooling` MCP server rejects views/components patterns. -Call tools on the SAME server sequentially — never in parallel. Tools on DIFFERENT servers CAN run in parallel (e.g. phpunit_run + js-storefront jest_run). +Call tools on the SAME server sequentially — never in parallel. Tools on DIFFERENT servers CAN run in parallel (e.g. `phpunit_run` on the `php-tooling` MCP server + `jest_run` on the `js-storefront-tooling` MCP server). -When a dev-tooling run (PHPStan, ECS, PHPUnit, Rector, ESLint, Stylelint, Prettier, TypeScript, Jest, Vitest, ludtwig, or a Vite/Webpack build) would produce more than a trivial single check — especially during a large implementation task — delegate it to the `dev-tooling-runner` subagent so the verbose output stays out of this conversation. You decide what to check: hand it the explicit paths and any affected tests, plus the kinds of checks to run and any mechanical fixes (e.g. ecs_fix) to apply. It executes and returns a condensed pass/fail report. For a quick single-file check you may still call the MCP tool inline. +When a dev-tooling run (PHPStan, ECS, PHPUnit, Rector, ESLint, Stylelint, Prettier, TypeScript, Jest, Vitest, ludtwig, or a Vite/Webpack build) would produce more than a trivial single check — especially during a large implementation task — delegate it to the `dev-tooling-runner` subagent so the verbose output stays out of this conversation. You decide what to check: hand it the explicit paths and any affected tests, plus the kinds of checks to run and any mechanical fixes (e.g. `ecs_fix` on the `php-tooling` MCP server) to apply. It executes and returns a condensed pass/fail report. For a quick single-file check you may still call the MCP tool inline. diff --git a/plugins/dev-tooling/hooks/scripts/check-js-admin-tools.sh b/plugins/dev-tooling/hooks/scripts/check-js-admin-tools.sh index 0b06d3eb..f09d43ce 100755 --- a/plugins/dev-tooling/hooks/scripts/check-js-admin-tools.sh +++ b/plugins/dev-tooling/hooks/scripts/check-js-admin-tools.sh @@ -11,6 +11,7 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" source "${SCRIPT_DIR}/lib/common.sh" +source "${SCRIPT_DIR}/lib/js_binary.sh" parse_hook_input load_mcp_config "js-tooling" @@ -33,9 +34,9 @@ is_admin_context() { return 1 fi # Unknown context - Admin hook handles generic commands. - # This is what claims a bare `npm run jest:base`, a script name both - # packages declare. The Storefront hook declines an unknown context, so - # exactly one of the two hooks blocks it. + # This is what claims a bare `npm run jest:base`, a script name that carries + # no side-specific marker. The Storefront hook declines an unknown context, + # so exactly one of the two hooks blocks it. return 0 } @@ -49,23 +50,23 @@ fi # ============================================================================ if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+lint(\s|--|$)'; then - block_tool "mcp__js-admin-tooling__eslint_check" \ - "Use eslint_check for linting or eslint_fix to auto-fix." + block_tool "js-admin-tooling" \ + "Use eslint_check for linting or eslint_fix to auto-fix." "eslint_check" fi if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+lint:fix(\s|$)'; then - block_tool "mcp__js-admin-tooling__eslint_fix" \ - "Use eslint_fix to auto-fix ESLint violations." + block_tool "js-admin-tooling" \ + "Use eslint_fix to auto-fix ESLint violations." "eslint_fix" fi if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+lint:debugging(\s|--|$)'; then - block_tool "mcp__js-admin-tooling__eslint_check" \ - "Use eslint_check with paths for linting, or eslint_fix with paths to auto-fix." + block_tool "js-admin-tooling" \ + "Use eslint_check with paths for linting, or eslint_fix with paths to auto-fix." "eslint_check" fi -if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npx\s+eslint(\s|$)'; then - block_tool "mcp__js-admin-tooling__eslint_check" \ - "Use eslint_check for linting or eslint_fix to auto-fix." +if runs_binary eslint; then + block_tool "js-admin-tooling" \ + "Use eslint_check for linting or eslint_fix to auto-fix." "eslint_check" fi # ============================================================================ @@ -73,23 +74,23 @@ fi # ============================================================================ if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+lint:scss(\s|--|$)'; then - block_tool "mcp__js-admin-tooling__stylelint_check" \ - "Use stylelint_check for SCSS/CSS linting." + block_tool "js-admin-tooling" \ + "Use stylelint_check for SCSS/CSS linting." "stylelint_check" fi if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+lint:scss-fix(\s|$)'; then - block_tool "mcp__js-admin-tooling__stylelint_fix" \ - "Use stylelint_fix to auto-fix Stylelint violations." + block_tool "js-admin-tooling" \ + "Use stylelint_fix to auto-fix Stylelint violations." "stylelint_fix" fi if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+stylelint:base(\s|--|$)'; then - block_tool "mcp__js-admin-tooling__stylelint_check" \ - "Use stylelint_check with paths for SCSS/CSS linting, or stylelint_fix with paths to auto-fix." + block_tool "js-admin-tooling" \ + "Use stylelint_check with paths for SCSS/CSS linting, or stylelint_fix with paths to auto-fix." "stylelint_check" fi -if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npx\s+stylelint(\s|$)'; then - block_tool "mcp__js-admin-tooling__stylelint_check" \ - "Use stylelint_check for SCSS/CSS linting or stylelint_fix to auto-fix." +if runs_binary stylelint; then + block_tool "js-admin-tooling" \ + "Use stylelint_check for SCSS/CSS linting or stylelint_fix to auto-fix." "stylelint_check" fi # ============================================================================ @@ -97,23 +98,23 @@ fi # ============================================================================ if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+format(\s|$)'; then - block_tool "mcp__js-admin-tooling__prettier_check" \ - "Use prettier_check to verify formatting." + block_tool "js-admin-tooling" \ + "Use prettier_check to verify formatting." "prettier_check" fi if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+format:fix(\s|$)'; then - block_tool "mcp__js-admin-tooling__prettier_fix" \ - "Use prettier_fix to auto-format files." + block_tool "js-admin-tooling" \ + "Use prettier_fix to auto-format files." "prettier_fix" fi if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+prettier:base(\s|--|$)'; then - block_tool "mcp__js-admin-tooling__prettier_check" \ - "Use prettier_check with paths to verify formatting, or prettier_fix with paths to auto-format." + block_tool "js-admin-tooling" \ + "Use prettier_check with paths to verify formatting, or prettier_fix with paths to auto-format." "prettier_check" fi -if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npx\s+prettier(\s|$)'; then - block_tool "mcp__js-admin-tooling__prettier_check" \ - "Use prettier_check to verify formatting or prettier_fix to auto-format." +if runs_binary prettier; then + block_tool "js-admin-tooling" \ + "Use prettier_check to verify formatting or prettier_fix to auto-format." "prettier_check" fi # ============================================================================ @@ -121,18 +122,18 @@ fi # ============================================================================ if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+unit(\s|--|$)'; then - block_tool "mcp__js-admin-tooling__jest_run" \ - "Use jest_run with testPathPattern, testNamePattern, coverage options." + block_tool "js-admin-tooling" \ + "Use jest_run with testPathPattern, testNamePattern, coverage options." "jest_run" fi if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+jest:base(\s|--|$)'; then - block_tool "mcp__js-admin-tooling__jest_run" \ - "Use jest_run with testPathPatterns, testNamePattern, coverage, ci options." + block_tool "js-admin-tooling" \ + "Use jest_run with testPathPatterns, testNamePattern, coverage, ci options." "jest_run" fi -if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npx\s+jest(\s|$)'; then - block_tool "mcp__js-admin-tooling__jest_run" \ - "Use jest_run with testPathPattern, testNamePattern, coverage options." +if runs_binary jest; then + block_tool "js-admin-tooling" \ + "Use jest_run with testPathPattern, testNamePattern, coverage options." "jest_run" fi # ============================================================================ @@ -140,13 +141,13 @@ fi # ============================================================================ if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+lint:types(\s|$)'; then - block_tool "mcp__js-admin-tooling__tsc_check" \ - "Use tsc_check for TypeScript type checking." + block_tool "js-admin-tooling" \ + "Use tsc_check for TypeScript type checking." "tsc_check" fi -if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npx\s+tsc(\s|$)'; then - block_tool "mcp__js-admin-tooling__tsc_check" \ - "Use tsc_check for TypeScript type checking." +if runs_binary tsc; then + block_tool "js-admin-tooling" \ + "Use tsc_check for TypeScript type checking." "tsc_check" fi # ============================================================================ @@ -154,13 +155,13 @@ fi # ============================================================================ if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+lint:all(\s|$)'; then - block_tool "mcp__js-admin-tooling__lint_all" \ - "Use lint_all to run all lint checks (TypeScript, ESLint, Stylelint, Prettier)." + block_tool "js-admin-tooling" \ + "Use lint_all to run all lint checks (TypeScript, ESLint, Stylelint, Prettier)." "lint_all" fi if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+lint:twig(\s|$)'; then - block_tool "mcp__js-admin-tooling__lint_twig" \ - "Use lint_twig for Twig template linting." + block_tool "js-admin-tooling" \ + "Use lint_twig for Twig template linting." "lint_twig" fi # ============================================================================ @@ -168,8 +169,8 @@ fi # ============================================================================ if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+build(\s|--|$)'; then - block_tool "mcp__js-admin-tooling__vite_build" \ - "Use vite_build with mode (development/production) option." + block_tool "js-admin-tooling" \ + "Use vite_build with mode (development/production) option." "vite_build" fi exit 0 diff --git a/plugins/dev-tooling/hooks/scripts/check-js-storefront-tools.sh b/plugins/dev-tooling/hooks/scripts/check-js-storefront-tools.sh index d6acaa5f..aaf11edc 100755 --- a/plugins/dev-tooling/hooks/scripts/check-js-storefront-tools.sh +++ b/plugins/dev-tooling/hooks/scripts/check-js-storefront-tools.sh @@ -11,6 +11,7 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" source "${SCRIPT_DIR}/lib/common.sh" +source "${SCRIPT_DIR}/lib/js_binary.sh" parse_hook_input load_mcp_config "js-tooling" @@ -22,9 +23,9 @@ is_storefront_context() { return 0 fi # Storefront-specific npm scripts. eslint:app, eslint:components and - # stylelint:app are declared only by the Storefront package.json; without - # them here the Admin hook's unknown-context fallback would claim them and - # name the wrong server's tool. + # stylelint:app are Storefront names; without them here the Admin hook's + # unknown-context fallback would claim them and name the wrong server's + # tool. # `:` is absent from the trailing `(\s|$)` alternation, so a bare `lint:js` # alternative never covers the longer colon-suffixed names — lint:js:fix and # the lint:js:app / lint:js:components pairs need the explicit suffix group @@ -56,62 +57,63 @@ fi # Storefront-specific ESLint (lint:js) if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+lint:js(\s|--|$)'; then - block_tool "mcp__js-storefront-tooling__eslint_check" \ - "Use eslint_check for linting." + block_tool "js-storefront-tooling" \ + "Use eslint_check for linting." "eslint_check" fi if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+lint:js:fix(\s|$)'; then - block_tool "mcp__js-storefront-tooling__eslint_fix" \ - "Use eslint_fix to auto-fix ESLint violations." + block_tool "js-storefront-tooling" \ + "Use eslint_fix to auto-fix ESLint violations." "eslint_fix" fi # lint:js and lint:js:fix each chain the two per-tree scripts below, which are # reachable on their own too. if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+lint:js:app(\s|--|$)'; then - block_tool "mcp__js-storefront-tooling__eslint_check" \ - "Use eslint_check with paths for linting, or eslint_fix with paths to auto-fix." + block_tool "js-storefront-tooling" \ + "Use eslint_check with paths for linting, or eslint_fix with paths to auto-fix." "eslint_check" fi if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+lint:js:components(\s|--|$)'; then - block_tool "mcp__js-storefront-tooling__eslint_check" \ - "Use eslint_check with paths under views/components/ for linting, or eslint_fix to auto-fix." + block_tool "js-storefront-tooling" \ + "Use eslint_check with paths under views/components/ for linting, or eslint_fix to auto-fix." "eslint_check" fi if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+lint:js:app:fix(\s|$)'; then - block_tool "mcp__js-storefront-tooling__eslint_fix" \ - "Use eslint_fix with paths to auto-fix ESLint violations." + block_tool "js-storefront-tooling" \ + "Use eslint_fix with paths to auto-fix ESLint violations." "eslint_fix" fi if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+lint:js:components:fix(\s|$)'; then - block_tool "mcp__js-storefront-tooling__eslint_fix" \ - "Use eslint_fix with paths under views/components/ to auto-fix ESLint violations." + block_tool "js-storefront-tooling" \ + "Use eslint_fix with paths under views/components/ to auto-fix ESLint violations." "eslint_fix" fi # Generic lint in Storefront context if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+lint(\s|--|$)'; then - block_tool "mcp__js-storefront-tooling__eslint_check" \ - "Use eslint_check for linting or eslint_fix to auto-fix." + block_tool "js-storefront-tooling" \ + "Use eslint_check for linting or eslint_fix to auto-fix." "eslint_check" fi if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+lint:fix(\s|$)'; then - block_tool "mcp__js-storefront-tooling__eslint_fix" \ - "Use eslint_fix to auto-fix ESLint violations." + block_tool "js-storefront-tooling" \ + "Use eslint_fix to auto-fix ESLint violations." "eslint_fix" fi -# Target-less base scripts the MCP tools route path-scoped runs at +# Target-less base scripts that Shopware's Storefront package.json does not +# define and the MCP tools do not call; the redirects cover a project that does. if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+eslint:app(\s|--|$)'; then - block_tool "mcp__js-storefront-tooling__eslint_check" \ - "Use eslint_check with paths for linting, or eslint_fix with paths to auto-fix." + block_tool "js-storefront-tooling" \ + "Use eslint_check with paths for linting, or eslint_fix with paths to auto-fix." "eslint_check" fi if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+eslint:components(\s|--|$)'; then - block_tool "mcp__js-storefront-tooling__eslint_check" \ - "Use eslint_check with paths under views/components/ for linting, or eslint_fix to auto-fix." + block_tool "js-storefront-tooling" \ + "Use eslint_check with paths under views/components/ for linting, or eslint_fix to auto-fix." "eslint_check" fi -if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npx\s+eslint(\s|$)'; then - block_tool "mcp__js-storefront-tooling__eslint_check" \ - "Use eslint_check for linting or eslint_fix to auto-fix." +if runs_binary eslint; then + block_tool "js-storefront-tooling" \ + "Use eslint_check for linting or eslint_fix to auto-fix." "eslint_check" fi # ============================================================================ @@ -119,23 +121,23 @@ fi # ============================================================================ if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+lint:scss(\s|--|$)'; then - block_tool "mcp__js-storefront-tooling__stylelint_check" \ - "Use stylelint_check for SCSS/CSS linting." + block_tool "js-storefront-tooling" \ + "Use stylelint_check for SCSS/CSS linting." "stylelint_check" fi if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+lint:scss-fix(\s|$)'; then - block_tool "mcp__js-storefront-tooling__stylelint_fix" \ - "Use stylelint_fix to auto-fix Stylelint violations." + block_tool "js-storefront-tooling" \ + "Use stylelint_fix to auto-fix Stylelint violations." "stylelint_fix" fi if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+stylelint:app(\s|--|$)'; then - block_tool "mcp__js-storefront-tooling__stylelint_check" \ - "Use stylelint_check with paths for SCSS/CSS linting, or stylelint_fix with paths to auto-fix." + block_tool "js-storefront-tooling" \ + "Use stylelint_check with paths for SCSS/CSS linting, or stylelint_fix with paths to auto-fix." "stylelint_check" fi -if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npx\s+stylelint(\s|$)'; then - block_tool "mcp__js-storefront-tooling__stylelint_check" \ - "Use stylelint_check for SCSS/CSS linting or stylelint_fix to auto-fix." +if runs_binary stylelint; then + block_tool "js-storefront-tooling" \ + "Use stylelint_check for SCSS/CSS linting or stylelint_fix to auto-fix." "stylelint_check" fi # ============================================================================ @@ -143,21 +145,21 @@ fi # ============================================================================ if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+unit(\s|--|$)'; then - block_tool "mcp__js-storefront-tooling__jest_run" \ - "Use jest_run with testPathPatterns, testNamePattern, coverage options." + block_tool "js-storefront-tooling" \ + "Use jest_run with testPathPatterns, testNamePattern, coverage options." "jest_run" fi -# jest:base is declared by both packages, so it reaches this block only when +# jest:base carries no side-specific marker, so it reaches this block only when # the command names the Storefront tree; a bare invocation stays with the Admin # hook's unknown-context fallback. if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+jest:base(\s|--|$)'; then - block_tool "mcp__js-storefront-tooling__jest_run" \ - "Use jest_run with testPathPatterns, testNamePattern, coverage, ci options." + block_tool "js-storefront-tooling" \ + "Use jest_run with testPathPatterns, testNamePattern, coverage, ci options." "jest_run" fi -if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npx\s+jest(\s|$)'; then - block_tool "mcp__js-storefront-tooling__jest_run" \ - "Use jest_run with testPathPatterns, testNamePattern, coverage options." +if runs_binary jest; then + block_tool "js-storefront-tooling" \ + "Use jest_run with testPathPatterns, testNamePattern, coverage options." "jest_run" fi # ============================================================================ @@ -165,18 +167,18 @@ fi # ============================================================================ if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+unit:components(:watch|:coverage)?(\s|--|$)'; then - block_tool "mcp__js-storefront-tooling__vitest_run" \ - "Use vitest_run with paths, testNamePattern, coverage options." + block_tool "js-storefront-tooling" \ + "Use vitest_run with paths, testNamePattern, coverage options." "vitest_run" fi -if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npx\s+vitest(\s|$)'; then - block_tool "mcp__js-storefront-tooling__vitest_run" \ - "Use vitest_run with paths, testNamePattern, coverage options." +if runs_binary vitest; then + block_tool "js-storefront-tooling" \ + "Use vitest_run with paths, testNamePattern, coverage options." "vitest_run" fi if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*composer\s+storefront:components:unit(\s|$)'; then - block_tool "mcp__js-storefront-tooling__vitest_run" \ - "Use vitest_run with paths, testNamePattern, coverage options." + block_tool "js-storefront-tooling" \ + "Use vitest_run with paths, testNamePattern, coverage options." "vitest_run" fi # ============================================================================ @@ -184,13 +186,13 @@ fi # ============================================================================ if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*composer\s+ludtwig:storefront:fix(\s|$)'; then - block_tool "mcp__js-storefront-tooling__ludtwig_fix" \ - "Use ludtwig_fix to auto-fix Twig template violations." + block_tool "js-storefront-tooling" \ + "Use ludtwig_fix to auto-fix Twig template violations." "ludtwig_fix" fi if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*composer\s+ludtwig:storefront(\s|$)'; then - block_tool "mcp__js-storefront-tooling__ludtwig_check" \ - "Use ludtwig_check for Twig template linting or ludtwig_fix to auto-fix." + block_tool "js-storefront-tooling" \ + "Use ludtwig_check for Twig template linting or ludtwig_fix to auto-fix." "ludtwig_check" fi # A plain-whitespace leading boundary (matching the context detector's) would @@ -202,9 +204,9 @@ fi # optional `--`, because Composer *requires* `composer exec -- ludtwig` as soon # as ludtwig takes its own options — the likeliest real invocation is the one # with the separator, and `npx -y` / `pnpm dlx --` are the same shape. -if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*ludtwig(\s|$)|(^|;|&&|\|)\s*(composer\s+exec|npm\s+exec|npx|pnpm\s+exec|pnpm\s+dlx|bunx|yarn\s+exec|yarn\s+run)(\s+(--?[A-Za-z0-9][-A-Za-z0-9]*|--))*\s+ludtwig(\s|$)'; then - block_tool "mcp__js-storefront-tooling__ludtwig_check" \ - "Use ludtwig_check for Twig template linting or ludtwig_fix to auto-fix." +if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*ludtwig(\s|$)|(^|;|&&|\|)\s*(composer\s+exec|npm\s+(exec|x)|npx|pnpm\s+exec|pnpm\s+dlx|bunx|yarn\s+exec|yarn\s+run)(\s+(--?[A-Za-z0-9][-A-Za-z0-9]*|--))*\s+ludtwig(\s|$)'; then + block_tool "js-storefront-tooling" \ + "Use ludtwig_check for Twig template linting or ludtwig_fix to auto-fix." "ludtwig_check" fi # ============================================================================ @@ -212,8 +214,8 @@ fi # ============================================================================ if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*npm\s+run\s+(production|development)(\s|$)'; then - block_tool "mcp__js-storefront-tooling__webpack_build" \ - "Use webpack_build with mode (development/production) option." + block_tool "js-storefront-tooling" \ + "Use webpack_build with mode (development/production) option." "webpack_build" fi exit 0 diff --git a/plugins/dev-tooling/hooks/scripts/check-php-tools.sh b/plugins/dev-tooling/hooks/scripts/check-php-tools.sh index 9098782e..a1426907 100755 --- a/plugins/dev-tooling/hooks/scripts/check-php-tools.sh +++ b/plugins/dev-tooling/hooks/scripts/check-php-tools.sh @@ -16,68 +16,68 @@ parse_hook_input load_mcp_config "php-tooling" # ============================================================================ -# PHPStan - Use mcp__php-tooling__phpstan_analyze +# PHPStan - Use phpstan_analyze # ============================================================================ if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*(php\s+)?\.?/?vendor/bin/phpstan(\s|$)'; then - block_tool "mcp__php-tooling__phpstan_analyze" \ - "Use phpstan_analyze for static analysis with configurable level (0-9) and paths." + block_tool "php-tooling" \ + "Use phpstan_analyze for static analysis with configurable level (0-9) and paths." "phpstan_analyze" fi if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*composer\s+phpstan(\s|$)'; then - block_tool "mcp__php-tooling__phpstan_analyze" \ - "Use phpstan_analyze for static analysis with configurable level (0-9) and paths." + block_tool "php-tooling" \ + "Use phpstan_analyze for static analysis with configurable level (0-9) and paths." "phpstan_analyze" fi # ============================================================================ -# ECS / PHP-CS-Fixer - Use mcp__php-tooling__ecs_check or ecs_fix +# ECS / PHP-CS-Fixer - Use ecs_check or ecs_fix # ============================================================================ if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*(php\s+)?\.?/?vendor/bin/(ecs|php-cs-fixer)(\s|$)'; then - block_tool "mcp__php-tooling__ecs_check or ecs_fix" \ - "Use ecs_check for dry-run validation or ecs_fix to apply fixes." + block_tool "php-tooling" \ + "Use ecs_check for dry-run validation or ecs_fix to apply fixes." "ecs_check" "ecs_fix" fi if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*composer\s+ecs(-fix)?(\s|$)'; then - block_tool "mcp__php-tooling__ecs_check or ecs_fix" \ - "Use ecs_check for dry-run validation or ecs_fix to apply fixes." + block_tool "php-tooling" \ + "Use ecs_check for dry-run validation or ecs_fix to apply fixes." "ecs_check" "ecs_fix" fi # ============================================================================ -# PHPUnit - Use mcp__php-tooling__phpunit_run +# PHPUnit - Use phpunit_run # ============================================================================ if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*(php\s+)?\.?/?vendor/bin/phpunit(\s|$)'; then - block_tool "mcp__php-tooling__phpunit_run" \ - "Use phpunit_run with testsuite, paths, filter, coverage, stop_on_failure options." + block_tool "php-tooling" \ + "Use phpunit_run with testsuite, paths, filter, coverage, stop_on_failure options." "phpunit_run" fi if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*composer\s+phpunit(\s|$)'; then - block_tool "mcp__php-tooling__phpunit_run" \ - "Use phpunit_run with testsuite, paths, filter, coverage, stop_on_failure options." + block_tool "php-tooling" \ + "Use phpunit_run with testsuite, paths, filter, coverage, stop_on_failure options." "phpunit_run" fi # ============================================================================ -# Symfony Console - Use mcp__php-tooling__console_run or console_list +# Symfony Console - Use console_run or console_list # ============================================================================ if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*(php\s+)?\.?/?bin/console(\s|$)'; then - block_tool "mcp__php-tooling__console_run or console_list" \ - "Use console_run to execute commands or console_list to list available commands." + block_tool "php-tooling" \ + "Use console_run to execute commands or console_list to list available commands." "console_run" "console_list" fi # ============================================================================ -# Rector - Use mcp__php-tooling__rector_fix or rector_check +# Rector - Use rector_fix or rector_check # ============================================================================ if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*(php\s+)?\.?/?vendor/bin/rector(\s|$)'; then - block_tool "mcp__php-tooling__rector_fix or rector_check" \ - "Use rector_fix to apply refactorings or rector_check for dry-run preview." + block_tool "php-tooling" \ + "Use rector_fix to apply refactorings or rector_check for dry-run preview." "rector_fix" "rector_check" fi -if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*composer\s+rector(\s|$)'; then - block_tool "mcp__php-tooling__rector_fix or rector_check" \ - "Use rector_fix to apply refactorings or rector_check for dry-run preview." +if echo "$COMMAND" | grep -qE '(^|;|&&|\|)\s*composer\s+rector(-fix)?(\s|$)'; then + block_tool "php-tooling" \ + "Use rector_fix to apply refactorings or rector_check for dry-run preview." "rector_fix" "rector_check" fi exit 0 diff --git a/plugins/dev-tooling/hooks/scripts/check-phpstan-baseline.sh b/plugins/dev-tooling/hooks/scripts/check-phpstan-baseline.sh index 1431a271..8ce20054 100755 --- a/plugins/dev-tooling/hooks/scripts/check-phpstan-baseline.sh +++ b/plugins/dev-tooling/hooks/scripts/check-phpstan-baseline.sh @@ -11,6 +11,9 @@ set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +source "${SCRIPT_DIR}/lib/common.sh" + INPUT=$(cat) # Extract paths array from tool_input (single jq call) diff --git a/plugins/dev-tooling/hooks/scripts/lib/common.sh b/plugins/dev-tooling/hooks/scripts/lib/common.sh index 57100fba..4a2467e1 100755 --- a/plugins/dev-tooling/hooks/scripts/lib/common.sh +++ b/plugins/dev-tooling/hooks/scripts/lib/common.sh @@ -9,7 +9,7 @@ # parse_hook_input # load_mcp_config "php-tooling" # or "js-tooling" # # ... pattern matching ... -# block_tool "phpstan_analyze" "Description" +# block_tool "php-tooling" "Description" "phpstan_analyze" # Global variables set by this library: # COMMAND - The shell command being checked @@ -103,23 +103,26 @@ load_mcp_config() { fi } -# Block a tool with formatted message -# Args: $1 = MCP tool name (e.g., "phpstan_analyze") +# Block a tool with formatted message. +# Tool names carry no host prefix. The message names the tool and its server. +# Args: $1 = MCP server name (e.g., "php-tooling") # $2 = description of what to use instead +# $3... = tool names, one or more (e.g., "ecs_check" "ecs_fix") # Outputs Cursor deny JSON on stdout, a human message on stderr, exits 2 block_tool() { - local tool="$1" + local server="$1" local description="$2" - local message - - message="$(cat </dev/null || echo "") - if ! resolve_scope "${scope_arg}"; then - echo "Scope resolution error" - return 1 - fi + resolve_core_scope "${args}" || return 1 - worktree_assert_dependencies || return 1 + scope_assert_dependencies || return 1 local mode mode=$(echo "${args}" | jq -r '.mode // "production"') diff --git a/plugins/dev-tooling/mcp-server-js-admin/lib/eslint.sh b/plugins/dev-tooling/mcp-server-js-admin/lib/eslint.sh index 05fb0587..7f167ff8 100644 --- a/plugins/dev-tooling/mcp-server-js-admin/lib/eslint.sh +++ b/plugins/dev-tooling/mcp-server-js-admin/lib/eslint.sh @@ -3,36 +3,25 @@ # Provides eslint_check and eslint_fix MCP tools # # Two routes, selected by whether the caller supplied paths: -# paths supplied -> npm script "lint:debugging", whose body is a bare -# `eslint`, so the caller's paths are the ONLY targets. +# paths supplied -> the package's own ESLint binary through +# `npm exec --no -- eslint`, so the caller's paths are the +# ONLY targets. # paths omitted -> the aggregate script ("lint" / "lint:fix"), whose body # carries its own targets, which stay authoritative. # The aggregate is never a fallback for a path-scoped run. npm appends `--` -# arguments to the END of the whole script body, so appending a path to a body -# that already names `src test build.ts` widens the run to those targets PLUS -# the path — it can never narrow it to the path. A path-scoped run that cannot -# reach the target-less base script fails hard instead. +# arguments to the end of the whole script body, so a path appended to a body +# that already names its own targets widens the run to those targets plus the +# path. It can never narrow the run to the path. -ADMIN_ESLINT_BASE_SCRIPT="lint:debugging" +ADMIN_ESLINT_BINARY="eslint" # Extensions the Administration ESLint flat config can match, read off the # `files:` globs in eslint.config.ts: **/*.js, **/*.ts, **/*.tsx, **/*.vue, # **/*.html.twig and src/**/snippet/*.json. A path that resolves to no file # with one of them lints nothing and still exits 0. ADMIN_ESLINT_EXTENSIONS="js ts tsx vue json twig" - -# Rebase a path onto the app/administration package directory, so a -# repo-root-relative path the caller pasted from a diff resolves in the npm -# working directory. A path that carries no package prefix is passed through. -# Args: $1 = caller-supplied path -if ! declare -F _eslint_rebase_admin_path >/dev/null; then - _eslint_rebase_admin_path() { - local path="$1" - if [[ "${path}" == *"app/administration/"* ]]; then - path="${path#*app/administration/}" - fi - printf '%s\n' "${path}" - } -fi +# The package directory a repo-root-relative path is rebased onto when no scope +# is active; under a scope it is the scope cwd instead. +ADMIN_ESLINT_PACKAGE_MARKER="app/administration/" # Run one ESLint invocation for this tool. # Args: $1 = aggregate npm script used when no paths are supplied, @@ -79,15 +68,10 @@ _eslint_dispatch_admin() { local p while IFS= read -r p; do [[ -z "${p}" ]] && continue - rebased+=("$(_eslint_rebase_admin_path "${p}")") + rebased+=("$(js_rebase_package_path "${ADMIN_ESLINT_PACKAGE_MARKER}" "${p}")") done < <(printf '%s\n' "${paths_json}" | jq -r '.[]') - body=$(npm_script_append_gate "${ADMIN_ESLINT_BASE_SCRIPT}") || gate_code=$? - if [[ "${gate_code}" -ne 0 ]]; then - printf '%s\n' "${body}" - printf '%s\n' "Refusing to run ${tool_name} with paths: a path-scoped run needs the target-less npm script \"${ADMIN_ESLINT_BASE_SCRIPT}\", which is unusable here. The aggregate \"${aggregate}\" script is not a substitute — its body names its own targets and npm appends arguments after them, so it would lint that whole target set on top of the requested paths rather than only the requested paths." - return 1 - fi + js_assert_local_binary "${tool_name}" "${ADMIN_ESLINT_BINARY}" "${aggregate}" || return 1 local missing_report if ! missing_report=$(assert_paths_lintable "." "${ADMIN_ESLINT_EXTENSIONS}" "${rebased[@]}"); then @@ -100,13 +84,13 @@ _eslint_dispatch_admin() { quoted+=("$(shell_quote_arg "${p}")") done - local cmd="npm run ${ADMIN_ESLINT_BASE_SCRIPT} --" + local cmd="npm exec --no -- ${ADMIN_ESLINT_BINARY}" if [[ -n "${flag_string}" ]]; then cmd="${cmd} ${flag_string}" fi cmd="${cmd} ${quoted[*]}" - log "INFO" "Running ESLint (admin, ${ADMIN_ESLINT_BASE_SCRIPT}): ${cmd}" + log "INFO" "Running ESLint (admin, npm exec): ${cmd}" exec_npm_command "${cmd}" } @@ -128,7 +112,7 @@ tool_eslint_check() { worktree_assert_dependencies || return 1 local scoped_config - scoped_config=$(scope_get_tool_field eslint config) + scope_tool_field_or_refuse scoped_config eslint config || return 1 local output_format output_format=$(echo "${args}" | jq -r '.output_format // "stylish"') @@ -140,7 +124,9 @@ tool_eslint_check() { stylish|*) flags+=("-f" "stylish") ;; esac - [[ -n "${scoped_config}" ]] && flags+=("--config" "${scoped_config}") + local config_flag + scope_config_flag_or_refuse config_flag "ESLint configuration" "${scoped_config}" || return 1 + [[ -n "${config_flag}" ]] && flags+=("${config_flag}") _eslint_dispatch_admin "lint" "eslint_check" "${flags[*]}" "${args}" } @@ -162,10 +148,12 @@ tool_eslint_fix() { worktree_assert_dependencies || return 1 local scoped_config - scoped_config=$(scope_get_tool_field eslint config) + scope_tool_field_or_refuse scoped_config eslint config || return 1 local -a flags=("--fix") - [[ -n "${scoped_config}" ]] && flags+=("--config" "${scoped_config}") + local config_flag + scope_config_flag_or_refuse config_flag "ESLint configuration" "${scoped_config}" || return 1 + [[ -n "${config_flag}" ]] && flags+=("${config_flag}") _eslint_dispatch_admin "lint:fix" "eslint_fix" "${flags[*]}" "${args}" } diff --git a/plugins/dev-tooling/mcp-server-js-admin/lib/jest.sh b/plugins/dev-tooling/mcp-server-js-admin/lib/jest.sh index 88480200..1a08870d 100644 --- a/plugins/dev-tooling/mcp-server-js-admin/lib/jest.sh +++ b/plugins/dev-tooling/mcp-server-js-admin/lib/jest.sh @@ -3,14 +3,12 @@ # Provides jest_run MCP tool # Note: watch mode is not supported - long-running processes hang MCP servers # -# Runs route at the target-less npm script "jest:base". The aggregate "unit" -# script is `npm run jest:base -- --ci`, and jest.config.ts derives -# `isCi` from an exact `--ci` match in process.argv: it then sets -# `collectCoverage: isCi` and swaps the reporters for jest-silent-reporter plus -# jest-junit. Routing at "unit" therefore forces coverage on every run and -# suppresses the per-test and summary output the caller asked for, and -# appending `--ci=false` does not undo it because the literal `--ci` is still -# in argv. The `ci` argument puts that mode back under the caller's control. +# Every run is the npm script "unit", `jest --config jest.config.js --ci`, with +# the caller's arguments appended. jest.config.ts, which jest.config.js loads, +# derives `isCi` from an exact `--ci` match in process.argv and then sets +# `collectCoverage: isCi`, so coverage is collected on every run. The `ci` +# argument appends `--ci`, which core's "unit" already passes, so neither it +# nor `coverage` changes a run of the core Administration. # # The tool's result comes from Jest's own JSON report, not from the process # exit code. The exit code answers "did the jest process end cleanly", which is @@ -34,8 +32,7 @@ # /tmp between runs. That is deliberate and costs a round-trip less than a # post-run delete would. -ADMIN_JEST_BASE_SCRIPT="jest:base" -ADMIN_JEST_AGGREGATE_SCRIPT="unit" +ADMIN_JEST_SCRIPT="unit" # Per-server, per-process report path. Requests into one stdio MCP server are # handled sequentially, so a single server never has two runs in flight; the @@ -59,18 +56,26 @@ if ! declare -F _jest_scope_env_prefix >/dev/null; then [[ "${SCOPE_NAME:-shopware}" == "shopware" ]] && return 0 [[ -f "${LINT_CONFIG_FILE:-}" ]] || return 0 - if jq -e --arg name "${SCOPE_NAME}" \ + local has_linebreak + if ! has_linebreak=$(jq -r --arg name "${SCOPE_NAME}" \ '(.scopes[$name].jest.env // {}) | to_entries | any(.[]; (.key + "=" + (.value | tostring)) | (index("\n") != null) or (index("\r") != null))' \ - "${LINT_CONFIG_FILE}" >/dev/null 2>&1; then + "${LINT_CONFIG_FILE}" 2>&1); then + printf '%s\n' "${has_linebreak}" + return 1 + fi + if [[ "${has_linebreak}" == "true" ]]; then printf '%s\n' "Refusing to run: scope \"${SCOPE_NAME}\" declares a jest.env entry containing a line break, which cannot be embedded in a single command." return 1 fi local raw - raw=$(jq -r --arg name "${SCOPE_NAME}" \ + if ! raw=$(jq -r --arg name "${SCOPE_NAME}" \ '(.scopes[$name].jest.env // {}) | to_entries[] | "\(.key)=\(.value)"' \ - "${LINT_CONFIG_FILE}" 2>/dev/null) || return 0 + "${LINT_CONFIG_FILE}" 2>&1); then + printf '%s\n' "${raw}" + return 1 + fi local prefix="" entry while IFS= read -r entry; do @@ -88,7 +93,12 @@ if ! declare -F _jest_install_if_missing >/dev/null; then _jest_install_if_missing() { [[ "${SCOPE_NAME:-shopware}" == "shopware" ]] && return 0 local flag - flag=$(jq -r --arg name "${SCOPE_NAME}" '.scopes[$name].jest.install_if_missing // false' "${LINT_CONFIG_FILE}" 2>/dev/null || echo "false") + if ! flag=$(jq -r --arg name "${SCOPE_NAME}" \ + '(.scopes[$name].jest // {}) | if has("install_if_missing") then .install_if_missing | if type == "boolean" then tostring else error("scopes." + $name + ".jest.install_if_missing must be a boolean (found " + type + ")") end else "false" end' \ + "${LINT_CONFIG_FILE}" 2>&1); then + printf '%s\n' "${flag}" + return 1 + fi [[ "${flag}" != "true" ]] && return 0 # The [[ -d ]] runs on the HOST, so it has to measure a host path: @@ -258,18 +268,12 @@ tool_jest_run() { return 1 fi + # shellcheck disable=SC2034 # read by get_js_workdir in shared/environment.sh SCOPE_JS_SUBDIR="" if [[ "${SCOPE_NAME}" != "shopware" ]]; then - # shellcheck disable=SC2034 # read by get_js_workdir in shared/environment.sh - SCOPE_JS_SUBDIR=$(scope_get_tool_field jest cwd) + scope_tool_field_or_refuse SCOPE_JS_SUBDIR jest cwd || return 1 fi - _jest_install_if_missing || return 1 - - # After the opt-in install, which is what creates the node_modules this - # check would otherwise refuse the run over. - worktree_assert_dependencies || return 1 - local env_prefix env_prefix=$(_jest_scope_env_prefix) || { printf '%s\n' "${env_prefix}"; return 1; } @@ -298,51 +302,36 @@ tool_jest_run() { return 1 fi + # The gate reads only package.json, so it needs no installed dependencies. + local body + if ! body=$(npm_script_append_gate "${ADMIN_JEST_SCRIPT}"); then + printf '%s\n' "${body}" + return 1 + fi + + # After every refusal above, so a refused call installs nothing. + _jest_install_if_missing || return 1 + + # After the opt-in install, which is what creates the node_modules this + # check would otherwise refuse the run over. + worktree_assert_dependencies || return 1 + local -a flags=() [[ -n "${test_path_pattern}" ]] && flags+=("--testPathPatterns=$(shell_quote_arg "${test_path_pattern}")") [[ -n "${test_name_pattern}" ]] && flags+=("--testNamePattern=$(shell_quote_arg "${test_name_pattern}")") [[ "${coverage}" == "true" ]] && flags+=("--coverage") [[ "${update_snapshots}" == "true" ]] && flags+=("--updateSnapshot") + # A plugin package's "unit" may lack the --ci that core's carries; Jest + # accepts the flag twice. + [[ "${ci}" == "true" ]] && flags+=("--ci") - local body - local gate_code=0 - body=$(npm_script_append_gate "${ADMIN_JEST_BASE_SCRIPT}") || gate_code=$? - - local script="${ADMIN_JEST_BASE_SCRIPT}" - - if [[ "${gate_code}" -ne 0 ]]; then - # Degraded route, announced rather than silent. No path widening is at - # stake here — "unit" runs the same suite — so falling back is better - # than refusing, but the caller has to know which arguments the - # fallback overrides. - script="${ADMIN_JEST_AGGREGATE_SCRIPT}" - printf '%s\n' "Notice: the npm script \"${ADMIN_JEST_BASE_SCRIPT}\" is unavailable, so this run falls back to \"${ADMIN_JEST_AGGREGATE_SCRIPT}\", whose body hardcodes --ci. Consequences: the \"ci\" argument is ignored and CI mode is forced; coverage is collected regardless of the \"coverage\" argument, because jest.config.ts sets collectCoverage from that same --ci; and the reporters are swapped to jest-silent-reporter plus jest-junit, so the per-test lines and the summary are suppressed. Reason: ${body}" - elif [[ "${ci}" == "true" ]]; then - # Only the base script needs this appended; the aggregate already - # carries --ci in its body. - flags+=("--ci") - fi - - # Every route asks for the report, the fallback and the CI route included: - # those are the routes where the silent reporter suppresses Jest's own - # "Tests:" line, so the report is the only place the counts exist. + # Under core's "unit" --ci, jest.config.ts swaps the reporters for + # jest-silent-reporter, which suppresses Jest's own "Tests:" line, so the + # report is the only place the counts exist. flags+=("--json" "--outputFile=$(shell_quote_arg "${ADMIN_JEST_REPORT_FILE}")") - local cmd="npm run ${script}" - - # The base script already passed the gate above; only the fallback still - # needs one before anything is appended to it. - if [[ "${script}" == "${ADMIN_JEST_AGGREGATE_SCRIPT}" ]]; then - local aggregate_body - local aggregate_gate=0 - aggregate_body=$(npm_script_append_gate "${script}") || aggregate_gate=$? - if [[ "${aggregate_gate}" -ne 0 ]]; then - printf '%s\n' "${aggregate_body}" - return 1 - fi - fi - cmd="${cmd} -- ${flags[*]}" + local cmd="npm run ${ADMIN_JEST_SCRIPT} -- ${flags[*]}" [[ -n "${env_prefix}" ]] && cmd="${env_prefix} ${cmd}" @@ -356,7 +345,7 @@ tool_jest_run() { return 1 fi - log "INFO" "Running Jest tests (admin, ${script}): ${cmd}" + log "INFO" "Running Jest tests (admin): ${cmd}" local output local run_exit=0 diff --git a/plugins/dev-tooling/mcp-server-js-admin/lib/lint-all.sh b/plugins/dev-tooling/mcp-server-js-admin/lib/lint-all.sh index 2125b03d..1e25674a 100644 --- a/plugins/dev-tooling/mcp-server-js-admin/lib/lint-all.sh +++ b/plugins/dev-tooling/mcp-server-js-admin/lib/lint-all.sh @@ -8,14 +8,9 @@ tool_lint_all() { worktree_enter "${args}" || return 1 - local scope_arg - scope_arg=$(echo "${args}" | jq -r '.scope // empty' 2>/dev/null || echo "") - if ! resolve_scope "${scope_arg}"; then - echo "Scope resolution error" - return 1 - fi + resolve_core_scope "${args}" || return 1 - worktree_assert_dependencies || return 1 + scope_assert_dependencies || return 1 local cmd="npm run lint:all" @@ -30,14 +25,9 @@ tool_lint_twig() { worktree_enter "${args}" || return 1 - local scope_arg - scope_arg=$(echo "${args}" | jq -r '.scope // empty' 2>/dev/null || echo "") - if ! resolve_scope "${scope_arg}"; then - echo "Scope resolution error" - return 1 - fi + resolve_core_scope "${args}" || return 1 - worktree_assert_dependencies || return 1 + scope_assert_dependencies || return 1 local cmd="npm run lint:twig" @@ -53,14 +43,9 @@ tool_unit_setup() { worktree_enter "${args}" || return 1 - local scope_arg - scope_arg=$(echo "${args}" | jq -r '.scope // empty' 2>/dev/null || echo "") - if ! resolve_scope "${scope_arg}"; then - echo "Scope resolution error" - return 1 - fi + resolve_core_scope "${args}" || return 1 - worktree_assert_dependencies || return 1 + scope_assert_dependencies || return 1 local cmd="npm run unit-setup" diff --git a/plugins/dev-tooling/mcp-server-js-admin/lib/prettier.sh b/plugins/dev-tooling/mcp-server-js-admin/lib/prettier.sh index d19e23b7..80bfbfa7 100644 --- a/plugins/dev-tooling/mcp-server-js-admin/lib/prettier.sh +++ b/plugins/dev-tooling/mcp-server-js-admin/lib/prettier.sh @@ -3,52 +3,45 @@ # Provides prettier_check and prettier_fix MCP tools # # Two routes, selected by whether the caller supplied paths: -# paths supplied -> npm script "prettier:base", whose body is a bare -# `prettier`, so the caller's paths are the ONLY targets -# and the mode flag (--check / --write) comes from here. +# paths supplied -> the package's own Prettier binary through +# `npm exec --no -- prettier`, with the flags of the +# aggregate body ("--check", or "--write --cache") but none +# of its globs, so the caller's paths are the ONLY targets. +# A directory path is narrowed to its .js, .ts and .mjs +# files, the extensions those globs name. # paths omitted -> the aggregate script ("format" / "format:fix"), whose # body carries both the mode flag and its own glob # targets, which stay authoritative. -# The aggregate is never a fallback for a path-scoped run. npm appends `--` -# arguments to the END of the whole script body, so appending a path to a body -# that already names `src/**/*.{js,ts}` and friends widens the run to those -# globs PLUS the path — it can never narrow it. That matters most for -# prettier_fix, which writes: a widened fix reformats files nobody named. - -ADMIN_PRETTIER_BASE_SCRIPT="prettier:base" -# Extensions Prettier is pointed at here, read off the globs in the `format` -# script body: src/**/*.{js,ts}, test/**/*.{js,ts}, -# build/vite-plugins/**/*.{js,ts}, build/plugins.vite.ts and build.ts. A path -# that resolves to no file with one of them formats nothing and still exits 0. -ADMIN_PRETTIER_EXTENSIONS="js ts" - -# True when the path is a glob pattern Prettier expands itself rather than a -# literal filesystem path. The existence probe cannot resolve a glob, so glob -# entries skip the guard. -# Args: $1 = caller-supplied path -if ! declare -F _prettier_admin_path_is_glob >/dev/null; then - _prettier_admin_path_is_glob() { - case "$1" in - *"*"*|*"?"*|*"["*) return 0 ;; - esac - return 1 - } -fi +# Why the aggregate never serves a path-scoped run: shared/js_paths.sh. + +ADMIN_PRETTIER_BINARY="prettier" +# The extensions the `format` and `format:fix` globs name: `{js,ts}` and `ts` +# under src, test, scripts and build, `extension-tooling/**/*.mjs`, +# build/plugins.vite.ts and build.ts. A path that resolves to no file with one +# of them formats nothing and still exits 0. +ADMIN_PRETTIER_EXTENSIONS="js ts mjs" +ADMIN_PRETTIER_DIRECTORY_GLOB="**/*.{js,ts,mjs}" # Run one Prettier invocation for this tool. # Args: $1 = aggregate npm script used when no paths are supplied, # $2 = tool name, for the refusal message, -# $3 = mode flag for the path-scoped route (--check or --write), +# $3 = flags for the path-scoped route: the aggregate body's flags +# without its globs ("--check", or "--write --cache"), # $4 = tool arguments JSON # Stdout: Prettier output, or the failure message _prettier_dispatch_admin() { local aggregate="$1" local tool_name="$2" - local mode_flag="$3" + local mode_flags="$3" local args="$4" local scoped_config - scoped_config=$(scope_get_tool_field prettier config) + scope_tool_field_or_refuse scoped_config prettier config || return 1 + + local quoted_config="" + if [[ -n "${scoped_config}" ]]; then + scope_config_arg_or_refuse quoted_config "Prettier configuration" "${scoped_config}" || return 1 + fi local paths_json paths paths_json=$(echo "${args}" | jq -c '.paths // []') @@ -74,7 +67,7 @@ _prettier_dispatch_admin() { printf '%s\n' "${body}" return 1 fi - aggregate_cmd="${aggregate_cmd} -- --config ${scoped_config}" + aggregate_cmd="${aggregate_cmd} -- --config ${quoted_config}" fi log "INFO" "Running Prettier (admin, ${aggregate}): ${aggregate_cmd}" @@ -82,44 +75,20 @@ _prettier_dispatch_admin() { return fi - local -a supplied=() - local -a literals=() - local p - while IFS= read -r p; do - [[ -z "${p}" ]] && continue - supplied+=("${p}") - if ! _prettier_admin_path_is_glob "${p}"; then - literals+=("${p}") - fi - done < <(printf '%s\n' "${paths_json}" | jq -r '.[]') - - body=$(npm_script_append_gate "${ADMIN_PRETTIER_BASE_SCRIPT}") || gate_code=$? - if [[ "${gate_code}" -ne 0 ]]; then - printf '%s\n' "${body}" - printf '%s\n' "Refusing to run ${tool_name} with paths: a path-scoped run needs the target-less npm script \"${ADMIN_PRETTIER_BASE_SCRIPT}\", which is unusable here. The aggregate \"${aggregate}\" script is not a substitute — its body names its own glob targets and npm appends arguments after them, so it would cover that whole target set on top of the requested paths rather than only the requested paths." + local targets + if ! targets=$(js_path_scoped_targets "${tool_name}" "${ADMIN_PRETTIER_BINARY}" "${aggregate}" \ + "${ADMIN_PRETTIER_EXTENSIONS}" "${ADMIN_PRETTIER_DIRECTORY_GLOB}" "Prettier" "${paths_json}"); then + printf '%s\n' "${targets}" return 1 fi - if [[ ${#literals[@]} -gt 0 ]]; then - local missing_report - if ! missing_report=$(assert_paths_lintable "." "${ADMIN_PRETTIER_EXTENSIONS}" "${literals[@]}"); then - printf '%s\n' "${missing_report}" - return 1 - fi - fi - - local -a quoted=() - for p in "${supplied[@]}"; do - quoted+=("$(shell_quote_arg "${p}")") - done - - local cmd="npm run ${ADMIN_PRETTIER_BASE_SCRIPT} -- ${mode_flag}" + local cmd="npm exec --no -- ${ADMIN_PRETTIER_BINARY} ${mode_flags}" if [[ -n "${scoped_config}" ]]; then - cmd="${cmd} --config ${scoped_config}" + cmd="${cmd} --config ${quoted_config}" fi - cmd="${cmd} ${quoted[*]}" + cmd="${cmd} ${targets}" - log "INFO" "Running Prettier (admin, ${ADMIN_PRETTIER_BASE_SCRIPT}): ${cmd}" + log "INFO" "Running Prettier (admin, npm exec): ${cmd}" exec_npm_command "${cmd}" } @@ -159,5 +128,6 @@ tool_prettier_fix() { worktree_assert_dependencies || return 1 - _prettier_dispatch_admin "format:fix" "prettier_fix" "--write" "${args}" + # "--cache" is in the "format:fix" body; the "format" body has none. + _prettier_dispatch_admin "format:fix" "prettier_fix" "--write --cache" "${args}" } diff --git a/plugins/dev-tooling/mcp-server-js-admin/lib/stylelint.sh b/plugins/dev-tooling/mcp-server-js-admin/lib/stylelint.sh index 7772cf7c..4a17c26d 100644 --- a/plugins/dev-tooling/mcp-server-js-admin/lib/stylelint.sh +++ b/plugins/dev-tooling/mcp-server-js-admin/lib/stylelint.sh @@ -3,43 +3,25 @@ # Provides stylelint_check and stylelint_fix MCP tools # # Two routes, selected by whether the caller supplied paths: -# paths supplied -> npm script "stylelint:base", whose body is a target-less -# `stylelint --cache`, so the caller's paths are the ONLY -# targets. +# paths supplied -> the package's own Stylelint binary through +# `npm exec --no -- stylelint --cache`, the flags of the +# "lint:scss" body without its `**/*.scss` target, so the +# caller's paths are the ONLY targets. A directory path is +# narrowed to its .scss files, as that glob is. # paths omitted -> the aggregate script ("lint:scss" / "lint:scss-fix"), # whose body carries its own `**/*.scss` target, which # stays authoritative. -# The aggregate is never a fallback for a path-scoped run. npm appends `--` -# arguments to the END of the whole script body, so appending a path to a body -# that already names `**/*.scss` widens the run to every SCSS file PLUS the -# path — it can never narrow it. That matters most for stylelint_fix, which -# writes: a widened fix modifies files the caller never named. +# Why the aggregate never serves a path-scoped run: shared/js_paths.sh. # # The two routes also differ in where `--fix` comes from. "lint:scss-fix" # carries `--fix` in its own body, so the no-paths route must not add a second -# one; "stylelint:base" carries none, so the path-scoped route must add it or -# stylelint_fix silently runs as a check and writes nothing. - -ADMIN_STYLELINT_BASE_SCRIPT="stylelint:base" -# Extensions Stylelint reads here. Neither .stylelintrc nor the CLI restricts -# the set, so this is the pair the SCSS rulesets actually parse. A path that -# resolves to no file with one of them lints nothing and still exits 0. -ADMIN_STYLELINT_EXTENSIONS="scss css" - -# True when the path is a glob pattern Stylelint expands itself rather than a -# literal filesystem path. The existence probe cannot resolve a glob, so glob -# entries skip the guard. Nothing is lost by skipping it: Stylelint exits 1 on a -# glob that matches no file and names the pattern, so the unmatched-glob case is -# still reported to the caller by the tool itself. -# Args: $1 = caller-supplied path -if ! declare -F _stylelint_admin_path_is_glob >/dev/null; then - _stylelint_admin_path_is_glob() { - case "$1" in - *"*"*|*"?"*|*"["*) return 0 ;; - esac - return 1 - } -fi +# one; the path-scoped command carries none, so the path-scoped route must add +# it or stylelint_fix silently runs as a check and writes nothing. + +ADMIN_STYLELINT_BINARY="stylelint" +# The extension the "lint:scss" glob `**/*.scss` names. +ADMIN_STYLELINT_EXTENSIONS="scss" +ADMIN_STYLELINT_DIRECTORY_GLOB="**/*.scss" # Run one Stylelint invocation for this tool. # Args: $1 = aggregate npm script used when no paths are supplied, @@ -47,7 +29,8 @@ fi # $3 = pre-path flag string used on both routes (may be empty), # $4 = pre-path flag string used ONLY on the path-scoped route, for flags # the aggregate script already carries in its own body (may be empty), -# $5 = tool arguments JSON +# $5 = tool arguments JSON, +# $6 = scope-configured Stylelint config (may be empty) # Stdout: linter output, or the failure message _stylelint_dispatch_admin() { local aggregate="$1" @@ -55,6 +38,7 @@ _stylelint_dispatch_admin() { local flag_string="$3" local path_only_flags="$4" local args="$5" + local scoped_config="$6" local paths_json paths paths_json=$(echo "${args}" | jq -c '.paths // []') @@ -84,61 +68,33 @@ _stylelint_dispatch_admin() { return 1 fi + js_refuse_second_config "${tool_name}" "Stylelint" "${ADMIN_STYLELINT_BINARY}" \ + "${aggregate}" "${body}" "${scoped_config}" || return 1 + local aggregate_cmd="npm run ${aggregate} -- ${flag_string}" log "INFO" "Running Stylelint (admin, ${aggregate}): ${aggregate_cmd}" exec_npm_command "${aggregate_cmd}" return fi - local -a supplied=() - local -a literals=() - local p - while IFS= read -r p; do - [[ -z "${p}" ]] && continue - supplied+=("${p}") - if ! _stylelint_admin_path_is_glob "${p}"; then - literals+=("${p}") - fi - done < <(printf '%s\n' "${paths_json}" | jq -r '.[]') - - body=$(npm_script_append_gate "${ADMIN_STYLELINT_BASE_SCRIPT}") || gate_code=$? - if [[ "${gate_code}" -ne 0 ]]; then - printf '%s\n' "${body}" - printf '%s\n' "Refusing to run ${tool_name} with paths: a path-scoped run needs the target-less npm script \"${ADMIN_STYLELINT_BASE_SCRIPT}\", which is unusable here. The aggregate \"${aggregate}\" script is not a substitute — its body names its own targets and npm appends arguments after them, so it would cover that whole target set on top of the requested paths rather than only the requested paths." + local targets + if ! targets=$(js_path_scoped_targets "${tool_name}" "${ADMIN_STYLELINT_BINARY}" "${aggregate}" \ + "${ADMIN_STYLELINT_EXTENSIONS}" "${ADMIN_STYLELINT_DIRECTORY_GLOB}" "Stylelint" "${paths_json}"); then + printf '%s\n' "${targets}" return 1 fi - if [[ ${#literals[@]} -gt 0 ]]; then - local missing_report - if ! missing_report=$(assert_paths_lintable "." "${ADMIN_STYLELINT_EXTENSIONS}" "${literals[@]}"); then - printf '%s\n' "${missing_report}" - return 1 - fi + # `--cache` is what the "lint:scss" body passes besides its target. + local cmd="npm exec --no -- ${ADMIN_STYLELINT_BINARY} --cache" + if [[ -n "${flag_string}" ]]; then + cmd="${cmd} ${flag_string}" fi - - local -a quoted=() - for p in "${supplied[@]}"; do - quoted+=("$(shell_quote_arg "${p}")") - done - - # The base script's body carries no mode flag of its own, so anything the - # aggregate would have supplied has to be added here instead. - local path_flags="${flag_string}" if [[ -n "${path_only_flags}" ]]; then - if [[ -n "${path_flags}" ]]; then - path_flags="${path_flags} ${path_only_flags}" - else - path_flags="${path_only_flags}" - fi - fi - - local cmd="npm run ${ADMIN_STYLELINT_BASE_SCRIPT} --" - if [[ -n "${path_flags}" ]]; then - cmd="${cmd} ${path_flags}" + cmd="${cmd} ${path_only_flags}" fi - cmd="${cmd} ${quoted[*]}" + cmd="${cmd} ${targets}" - log "INFO" "Running Stylelint (admin, ${ADMIN_STYLELINT_BASE_SCRIPT}): ${cmd}" + log "INFO" "Running Stylelint (admin, npm exec): ${cmd}" exec_npm_command "${cmd}" } @@ -160,7 +116,7 @@ tool_stylelint_check() { worktree_assert_dependencies || return 1 local scoped_config - scoped_config=$(scope_get_tool_field stylelint config) + scope_tool_field_or_refuse scoped_config stylelint config || return 1 local output_format output_format=$(echo "${args}" | jq -r '.output_format // "string"') @@ -174,9 +130,11 @@ tool_stylelint_check() { string|*) flags+=("-f" "string") ;; esac - [[ -n "${scoped_config}" ]] && flags+=("--config" "${scoped_config}") + local config_flag + scope_config_flag_or_refuse config_flag "Stylelint configuration" "${scoped_config}" || return 1 + [[ -n "${config_flag}" ]] && flags+=("${config_flag}") - _stylelint_dispatch_admin "lint:scss" "stylelint_check" "${flags[*]}" "" "${args}" + _stylelint_dispatch_admin "lint:scss" "stylelint_check" "${flags[*]}" "" "${args}" "${scoped_config}" } # Stylelint fix (auto-fix violations) @@ -196,10 +154,12 @@ tool_stylelint_fix() { worktree_assert_dependencies || return 1 local scoped_config - scoped_config=$(scope_get_tool_field stylelint config) + scope_tool_field_or_refuse scoped_config stylelint config || return 1 local -a flags=() - [[ -n "${scoped_config}" ]] && flags+=("--config" "${scoped_config}") + local config_flag + scope_config_flag_or_refuse config_flag "Stylelint configuration" "${scoped_config}" || return 1 + [[ -n "${config_flag}" ]] && flags+=("${config_flag}") # Expanded through a guard: an empty array under `set -u` is not portable # to every bash the servers may run under, and empty is the common case @@ -210,5 +170,5 @@ tool_stylelint_fix() { fi # "--fix" is path-route only: the "lint:scss-fix" body already carries one. - _stylelint_dispatch_admin "lint:scss-fix" "stylelint_fix" "${flag_string}" "--fix" "${args}" + _stylelint_dispatch_admin "lint:scss-fix" "stylelint_fix" "${flag_string}" "--fix" "${args}" "${scoped_config}" } diff --git a/plugins/dev-tooling/mcp-server-js-admin/lib/tsc.sh b/plugins/dev-tooling/mcp-server-js-admin/lib/tsc.sh index 005ec781..4ab297d6 100644 --- a/plugins/dev-tooling/mcp-server-js-admin/lib/tsc.sh +++ b/plugins/dev-tooling/mcp-server-js-admin/lib/tsc.sh @@ -17,14 +17,32 @@ tool_tsc_check() { return 1 fi - worktree_assert_dependencies || return 1 + scope_assert_dependencies || return 1 local scoped_config - scoped_config=$(scope_get_tool_field tsc config) + scope_tool_field_or_refuse scoped_config tsc config || return 1 + + # A plugin package normally defines no "lint:types"; npm fails with "Missing + # script" only after the run started, so the script is probed first. + if [[ "${SCOPE_NAME}" != "shopware" ]]; then + local body_code=0 + npm_script_body "lint:types" >/dev/null || body_code=$? + if [[ "${body_code}" -eq 1 ]]; then + printf '%s\n' "Refusing to run TypeScript check under scope \"${SCOPE_NAME}\": the package defines no \"lint:types\" npm script. Pass scope \"shopware\" to check the core Administration package." + return 1 + fi + if [[ "${body_code}" -ne 0 ]]; then + printf '%s\n' "Could not read npm script \"lint:types\" from package.json under scope \"${SCOPE_NAME}\"; see the server log for the failed probe. Pass scope \"shopware\" to check the core Administration package." + return 1 + fi + fi local cmd="npm run lint:types" if [[ -n "${scoped_config}" ]]; then + local quoted_config + scope_config_arg_or_refuse quoted_config "TypeScript project configuration" "${scoped_config}" || return 1 + local body local gate_code=0 body=$(npm_script_append_gate "lint:types") || gate_code=$? @@ -32,7 +50,7 @@ tool_tsc_check() { printf '%s\n' "${body}" return 1 fi - cmd="${cmd} -- --project ${scoped_config}" + cmd="${cmd} -- --project ${quoted_config}" fi log "INFO" "Running TypeScript check (admin): ${cmd}" diff --git a/plugins/dev-tooling/mcp-server-js-admin/server.sh b/plugins/dev-tooling/mcp-server-js-admin/server.sh index 7c4f44e0..c4ffa873 100755 --- a/plugins/dev-tooling/mcp-server-js-admin/server.sh +++ b/plugins/dev-tooling/mcp-server-js-admin/server.sh @@ -16,7 +16,8 @@ # - jest_run: Run Jest tests # - unit_setup: Fix Jest import resolution # - vite_build: Build with Vite -# - set_project_root: Set or clear the sticky project root +# - set_project_root: Bind the project root of an unbound server, or set or +# clear the sticky project root # - cwd: Report the project root, working directory and config in use # # Supports environments: native, docker, docker-compose, vagrant, ddev @@ -55,20 +56,31 @@ source "${SHARED_DIR}/mcpserver_core.sh" # Source config module and load configuration source "${SHARED_DIR}/config.sh" -if ! load_config "${PROJECT_ROOT}"; then - exit 1 +# A launch in this plugin's own directory starts unbound and skips every +# project-dependent startup step below; set_project_root performs them later. +source "${SHARED_DIR}/launch.sh" +if launch_is_bound; then + if ! load_config "${PROJECT_ROOT}"; then + exit 1 + fi fi # Source remaining modules source "${SHARED_DIR}/environment.sh" +source "${SHARED_DIR}/js_paths.sh" source "${SHARED_DIR}/scope.sh" -if ! scope_validate; then - exit 1 +if launch_is_bound; then + if ! scope_validate; then + exit 1 + fi fi source "${SHARED_DIR}/worktree.sh" if ! worktree_state_init; then exit 1 fi +if launch_is_bound; then + worktree_launch_common_init +fi # One EXIT trap doing both jobs. A second `trap ... EXIT` would replace the one # config.sh installs at source time, leaving the merged-config temp file behind. @@ -85,17 +97,20 @@ source "${SCRIPT_DIR}/lib/prepare.sh" trap 'log "ERROR" "Unexpected error on line ${LINENO}"' ERR -detect_environment "${PROJECT_ROOT}" -_configure_extra_log_file "$(_get_config_value '.log_file' '')" - -log "INFO" "======================================" -log "INFO" "Admin Tooling MCP Server starting" -log "INFO" "Script dir: ${SCRIPT_DIR}" -log "INFO" "Project root: ${PROJECT_ROOT}" -log "INFO" "Config file: ${LINT_CONFIG_FILE}" -log "INFO" "Environment: ${LINT_ENV}" -log "INFO" "Working dir: ${LINT_WORKDIR}" -log "INFO" "Extra log: ${MCP_EXTRA_LOG_FILE:-}" -log "INFO" "======================================" +if launch_is_bound; then + detect_environment "${PROJECT_ROOT}" + log_file=$(_get_config_value '.log_file' '') || exit 1 + _configure_extra_log_file "${log_file}" + + log "INFO" "======================================" + log "INFO" "Admin Tooling MCP Server starting" + log "INFO" "Script dir: ${SCRIPT_DIR}" + log "INFO" "Project root: ${PROJECT_ROOT}" + log "INFO" "Config file: ${LINT_CONFIG_FILE}" + log "INFO" "Environment: ${LINT_ENV}" + log "INFO" "Working dir: ${LINT_WORKDIR}" + log "INFO" "Extra log: ${MCP_EXTRA_LOG_FILE:-}" + log "INFO" "======================================" +fi source "${SHARED_DIR}/server_run.sh" diff --git a/plugins/dev-tooling/mcp-server-js-admin/tools.json b/plugins/dev-tooling/mcp-server-js-admin/tools.json index 397bfca4..bf7e4b53 100644 --- a/plugins/dev-tooling/mcp-server-js-admin/tools.json +++ b/plugins/dev-tooling/mcp-server-js-admin/tools.json @@ -190,7 +190,7 @@ "coverage": { "type": "boolean", "default": false, - "description": "Generate code coverage report" + "description": "Append --coverage. The core Administration collects coverage on every run regardless: \"unit\" passes --ci, and its Jest config turns coverage on under --ci." }, "updateSnapshots": { "type": "boolean", @@ -200,7 +200,7 @@ "ci": { "type": "boolean", "default": false, - "description": "Run Jest in CI mode (--ci). Defaults to false. Turning it on makes the Jest config collect coverage regardless of the \"coverage\" argument and swaps the reporters for jest-silent-reporter plus jest-junit, which suppresses the per-test lines and the summary. Leave it off unless you need CI-identical behavior." + "description": "Append --ci to the run. The core Administration's npm script \"unit\" already passes --ci, so a run under scope \"shopware\" is in CI mode either way. A plugin scope's own \"unit\" script runs in CI mode when it passes --ci itself or when this is set." }, "scope": { "type": "string", @@ -240,7 +240,7 @@ }, "scope": { "type": "string", - "description": "Scope name from .mcp-js-tooling.json. Omit to use the configured default_scope. Pass \"shopware\" to force project-root behavior." + "description": "Scope name from .mcp-js-tooling.json. Omit, or pass \"shopware\", to run in the core Administration package: this tool ignores default_scope." } }, "additionalProperties": false @@ -258,7 +258,7 @@ }, "scope": { "type": "string", - "description": "Scope name from .mcp-js-tooling.json. Omit to use the configured default_scope. Pass \"shopware\" to force project-root behavior." + "description": "Scope name from .mcp-js-tooling.json. Omit, or pass \"shopware\", to run in the core Administration package: this tool ignores default_scope." } }, "additionalProperties": false @@ -276,7 +276,7 @@ }, "scope": { "type": "string", - "description": "Scope name from .mcp-js-tooling.json. Omit to use the configured default_scope. Pass \"shopware\" to force project-root behavior." + "description": "Scope name from .mcp-js-tooling.json. Omit, or pass \"shopware\", to run in the core Administration package: this tool ignores default_scope." } }, "additionalProperties": false @@ -303,7 +303,7 @@ }, "scope": { "type": "string", - "description": "Scope name from .mcp-js-tooling.json. Omit to use the configured default_scope. Pass \"shopware\" to force project-root behavior." + "description": "Scope name from .mcp-js-tooling.json. Omit, or pass \"shopware\", to run in the core Administration package: this tool ignores default_scope." } }, "additionalProperties": false @@ -329,13 +329,13 @@ }, { "name": "set_project_root", - "description": "Set the project root every later call on this server targets, or clear it. Pass a linked git worktree of the root the server was launched in to move the server onto that tree; omit project_root to return it to the launch root. Each of php-tooling, js-admin-tooling and js-storefront-tooling is a separate process and keeps its own setting, so call this on each server you use.", + "description": "Set the project root every later call on this server targets, or clear it. A server started in a project directory is bound to it as its launch root: pass a linked git worktree of that root to move the server onto that tree, and omit project_root, or pass the launch root itself, to return it to the launch root. A server started in its own plugin directory, when the process was started in that directory, has no project root, and every tool except cwd refuses until this is called with the absolute path of the project; that binds the server to it as its launch root for the rest of the process, and calling it again with that path clears any sticky worktree, the same as omitting project_root. Each of php-tooling, js-admin-tooling and js-storefront-tooling is a separate process and keeps its own setting, so call this on each server you use.", "inputSchema": { "type": "object", "properties": { "project_root": { "type": "string", - "description": "Absolute path to a linked git worktree of the root this server was launched in. Omit to clear the setting and return the server to its launch root; the value being discarded is not validated, so this also recovers from a worktree that has been removed. Works in every environment: the call runs against that tree as the server's environment reaches it, and under docker, docker-compose, vagrant and ddev the worktree must sit inside the launch project root, which is the only tree the container or VM mounts." + "description": "Absolute path. On a server with no project root yet: the project to bind, which must hold this server's .mcp-js-tooling.json at its top or in a supported tool directory such as .claude/, unless MCP_JS_TOOLING_CONFIG names the configuration file. Otherwise: a linked git worktree of the root this server was launched in. Omit it, or pass the launch root itself, to clear the setting and return the server to its launch root; the value being discarded is not validated, so this also recovers from a worktree that has been removed. Works in every environment: the call runs against that tree as the server's environment reaches it, and under docker, docker-compose, vagrant and ddev the worktree must sit inside the launch project root, which is the only tree the container or VM mounts." } }, "additionalProperties": false diff --git a/plugins/dev-tooling/mcp-server-js-storefront/lib/build.sh b/plugins/dev-tooling/mcp-server-js-storefront/lib/build.sh index 13d4afaf..c12bd933 100644 --- a/plugins/dev-tooling/mcp-server-js-storefront/lib/build.sh +++ b/plugins/dev-tooling/mcp-server-js-storefront/lib/build.sh @@ -10,37 +10,13 @@ tool_webpack_build() { worktree_enter "${args}" || return 1 - local scope_arg - scope_arg=$(echo "${args}" | jq -r '.scope // empty' 2>/dev/null || echo "") - if ! resolve_scope "${scope_arg}"; then - echo "Scope resolution error" - return 1 - fi + resolve_core_scope "${args}" || return 1 - worktree_assert_dependencies || return 1 + scope_assert_dependencies || return 1 local mode mode=$(echo "${args}" | jq -r '.mode // "production"') - # Reject watch/hot mode - MCP servers cannot handle long-running processes - if [[ "${mode}" == "hot" || "${mode}" == "watch" ]]; then - cat <<'EOF' -Error: Watch mode is not supported via MCP tools. - -MCP servers use a synchronous request-response model that blocks until commands complete. -Watch tasks run indefinitely, which would hang the entire MCP server. - -To run watch mode, open a separate terminal and run: - npm run hot - -Or from the Shopware project root: - cd src/Storefront/Resources/app/storefront && npm run hot - -For one-time builds, use mode "development" or "production" instead. -EOF - return 1 - fi - # Map mode to npm script name local script_name case "${mode}" in diff --git a/plugins/dev-tooling/mcp-server-js-storefront/lib/eslint.sh b/plugins/dev-tooling/mcp-server-js-storefront/lib/eslint.sh index bd55277f..4c551533 100644 --- a/plugins/dev-tooling/mcp-server-js-storefront/lib/eslint.sh +++ b/plugins/dev-tooling/mcp-server-js-storefront/lib/eslint.sh @@ -2,19 +2,44 @@ # ESLint tool implementation for Storefront Tooling MCP Server # Provides eslint_check and eslint_fix MCP tools # -# The Storefront splits ESLint across two trees: -# app tree -> npm script "eslint:app", paths relative to the package -# directory src/Storefront/Resources/app/storefront -# components tree -> npm script "eslint:components", which runs after +# The Storefront's "lint:js" script lints two trees with two ESLint calls: +# app tree -> `eslint --no-error-on-unmatched-pattern +# --report-unused-disable-directives` in the package +# directory src/Storefront/Resources/app/storefront, so +# paths are relative to it +# components tree -> the same flags plus `--config +# ./app/storefront/eslint.config.js`, run after # `cd ../..`, so paths are relative to # src/Storefront/Resources # A run without paths executes the aggregate (lint:js / lint:js:fix), whose own -# targets stay authoritative. A run with paths never reaches the aggregate: on a -# version predating the split, or with either base script otherwise unusable, -# the path-scoped run fails rather than widening to the aggregate's targets. - +# targets stay authoritative. A run with paths never reaches the aggregate: it +# runs those two calls without their targets through the package's own ESLint +# binary (`npm exec --no`), so the caller's paths are the ONLY targets, and it +# fails rather than widening to the aggregate's targets when that binary is not +# installed. +# +# The components call has to start in ../..: ESLint reports a file outside its +# base path as "File ignored because outside of base path" and still exits 0, +# and with an explicit --config the base path is the working directory. It +# still has to start through npm in the package directory: ../.. holds no +# package.json, so `npm exec` started there would resolve its binary from +# another directory, and wrap_npm_command's ddev branch prefixes the command +# with `ddev exec -d ""`, so the host shell splits a bare compound +# command at its first `&&` and only the cd would reach the container. +# `npm exec -c` runs its string through a shell in the package directory with +# the package's node_modules/.bin first on PATH, and the string does the cd. + +STOREFRONT_ESLINT_BINARY="eslint" +# Flags both "lint:js" ESLint calls pass besides their targets. +STOREFRONT_ESLINT_FLAGS="--no-error-on-unmatched-pattern --report-unused-disable-directives" +# The config the components call names, relative to its ../.. working +# directory. +STOREFRONT_ESLINT_COMPONENTS_CONFIG="./app/storefront/eslint.config.js" STOREFRONT_ESLINT_APP_BASE="." STOREFRONT_ESLINT_COMPONENTS_BASE="../.." +# The package directory an app-tree path is rebased onto when no scope is +# active; under a scope it is the scope cwd instead. +STOREFRONT_ESLINT_PACKAGE_MARKER="app/storefront/" # Extensions the Storefront ESLint config can match. A path that resolves to no # file with one of them lints nothing and still exits 0. STOREFRONT_ESLINT_EXTENSIONS="js ts mjs cjs jsx tsx vue json" @@ -35,43 +60,19 @@ _eslint_rebase_components_path() { printf '%s\n' "views/components${path#*views/components}" } -# Rebase an app-tree path onto the app/storefront package directory. -# Args: $1 = caller-supplied path -_eslint_rebase_app_path() { - local path="$1" - if [[ "${path}" == *"app/storefront/"* ]]; then - path="${path#*app/storefront/}" - fi - printf '%s\n' "${path}" -} - # Run one tree's ESLint invocation. Reached only when the caller supplied # paths, so the aggregate is never a fallback here: its body names its own # targets, and npm appends `--` arguments after them, so substituting it would # widen the run instead of narrowing it to the requested paths. -# Args: $1 = target-less npm script for this tree, -# $2 = aggregate npm script, named in the refusal, -# $3 = tree name, for the refusal message, -# $4 = base directory for the existence check, -# $5 = pre-path flag string (may be empty), $6.. = rebased paths +# Args: $1 = tree name, "app" or "components", +# $2 = base directory for the existence check, +# $3 = pre-path flag string (may be empty), $4.. = rebased paths # Stdout: linter output, or the failure message _eslint_invoke_tree() { - local script="$1" - local aggregate="$2" - local tree="$3" - local base_dir="$4" - local flag_string="$5" - shift 5 - - local body - local exit_code=0 - body=$(npm_script_append_gate "${script}") || exit_code=$? - - if [[ "${exit_code}" -ne 0 ]]; then - printf '%s\n' "${body}" - printf '%s\n' "Refusing to lint the ${tree} tree with paths: a path-scoped run needs the target-less npm script \"${script}\", which is unusable here. The aggregate \"${aggregate}\" script is not a substitute — its body names its own targets and npm appends arguments after them, so it would cover that whole target set on top of the requested paths rather than only the requested paths." - return 1 - fi + local tree="$1" + local base_dir="$2" + local flag_string="$3" + shift 3 local missing_report if ! missing_report=$(assert_paths_lintable "${base_dir}" "${STOREFRONT_ESLINT_EXTENSIONS}" "$@"); then @@ -85,26 +86,41 @@ _eslint_invoke_tree() { quoted+=("$(shell_quote_arg "${p}")") done - local cmd="npm run ${script} --" + local eslint_cmd="${STOREFRONT_ESLINT_BINARY} ${STOREFRONT_ESLINT_FLAGS}" + # _eslint_dispatch refuses the components tree under a scope, so no scope + # config reaches this call. + if [[ "${tree}" == "components" ]]; then + eslint_cmd="${eslint_cmd} --config ${STOREFRONT_ESLINT_COMPONENTS_CONFIG}" + fi if [[ -n "${flag_string}" ]]; then - cmd="${cmd} ${flag_string}" + eslint_cmd="${eslint_cmd} ${flag_string}" + fi + eslint_cmd="${eslint_cmd} ${quoted[*]}" + + local cmd + if [[ "${tree}" == "components" ]]; then + # The inner string is quoted once more for the shell that parses this + # command; npm's own shell then parses it, including each path's quotes. + cmd="npm exec --no -c $(shell_quote_arg "cd ${STOREFRONT_ESLINT_COMPONENTS_BASE} && ${eslint_cmd}")" + else + cmd="npm exec --no -- ${eslint_cmd}" fi - cmd="${cmd} ${quoted[*]}" - log "INFO" "Running ESLint (storefront, ${script}): ${cmd}" + log "INFO" "Running ESLint (storefront, ${tree} tree): ${cmd}" exec_npm_command "${cmd}" } # Route the caller's paths onto the two trees and run each one that is used. -# Args: $1 = tool arguments JSON, $2 = fallback npm script, +# Args: $1 = tool arguments JSON, $2 = aggregate npm script, # $3 = pre-path flag string (may be empty), $4 = scope-configured ESLint -# config (may be empty) +# config (may be empty), $5 = tool name, for refusals _eslint_dispatch() { local args="$1" - local fallback="$2" + local aggregate="$2" local flag_string="$3" local scoped_config="$4" + local tool_name="$5" local paths_json paths paths_json=$(echo "${args}" | jq -c '.paths // []') @@ -121,16 +137,17 @@ _eslint_dispatch() { if [[ -z "${paths}" ]]; then # A no-path run executes the aggregate script bare. That script chains - # bare `npm run` calls, so a flags-only append lands past npm's own CLI - # parser and never reaches ESLint — npm_script_append_gate refuses it. + # two ESLint calls and ends in a subshell, so an appended flag would + # land after that subshell, outside both calls — npm_script_append_gate + # refuses it. # Running bare anyway would silently substitute the package script's own # configuration for the scope-selected one. if [[ -n "${scoped_config}" ]]; then - printf '%s\n' "Refusing to run: scope \"${SCOPE_NAME}\" selects the ESLint config \"${scoped_config}\", but a run without paths can only execute \"npm run ${fallback}\" bare, which would apply the package script's own config instead. \"${fallback}\" chains bare run-scripts, so the config cannot be appended to it either. Pass paths so the run is routed to eslint:app / eslint:components, or call with scope \"shopware\"." + printf '%s\n' "Refusing to run: scope \"${SCOPE_NAME}\" selects the ESLint config \"${scoped_config}\", but a run without paths can only execute \"npm run ${aggregate}\" bare, which would apply the package script's own config instead. \"${aggregate}\" chains two ESLint calls, so the config cannot be appended to it either. Pass paths so the run executes ESLint on them directly." return 1 fi - local bare_cmd="npm run ${fallback}" - log "INFO" "Running ESLint (storefront, ${fallback}): ${bare_cmd}" + local bare_cmd="npm run ${aggregate}" + log "INFO" "Running ESLint (storefront, ${aggregate}): ${bare_cmd}" exec_npm_command "${bare_cmd}" return fi @@ -143,18 +160,30 @@ _eslint_dispatch() { if _eslint_is_components_path "${p}"; then component_paths+=("$(_eslint_rebase_components_path "${p}")") else - app_paths+=("$(_eslint_rebase_app_path "${p}")") + app_paths+=("$(js_rebase_package_path "${STOREFRONT_ESLINT_PACKAGE_MARKER}" "${p}")") fi done < <(printf '%s\n' "${paths_json}" | jq -r '.[]') + # The components call is the core Storefront's own: it changes to ../.. and + # names ./app/storefront/eslint.config.js, which exist only relative to + # src/Storefront/Resources/app/storefront. Under a scope the working + # directory is the scope's package instead, where both name something else. + if [[ ${#component_paths[@]} -gt 0 && -n "${SCOPE_CWD:-}" ]]; then + printf '%s\n' "Refusing to run ${tool_name} with paths: scope \"${SCOPE_NAME}\" runs in \"${SCOPE_CWD}\", but these paths route to the core Storefront components tree, which is linted from src/Storefront/Resources with ./app/storefront/eslint.config.js: ${component_paths[*]}. Lint them with scope \"shopware\"." + return 1 + fi + + # Both trees resolve the binary from the package directory. + js_assert_local_binary "${tool_name}" "${STOREFRONT_ESLINT_BINARY}" "${aggregate}" || return 1 + local overall=0 local tree_output local tree_code if [[ ${#app_paths[@]} -gt 0 ]]; then tree_code=0 - tree_output=$(_eslint_invoke_tree "eslint:app" "${fallback}" "app" \ - "${STOREFRONT_ESLINT_APP_BASE}" "${flag_string}" "${app_paths[@]}") || tree_code=$? + tree_output=$(_eslint_invoke_tree "app" "${STOREFRONT_ESLINT_APP_BASE}" \ + "${flag_string}" "${app_paths[@]}") || tree_code=$? printf '%s\n' "${tree_output}" if [[ "${tree_code}" -ne 0 ]]; then overall="${tree_code}" @@ -163,8 +192,8 @@ _eslint_dispatch() { if [[ ${#component_paths[@]} -gt 0 ]]; then tree_code=0 - tree_output=$(_eslint_invoke_tree "eslint:components" "${fallback}" "components" \ - "${STOREFRONT_ESLINT_COMPONENTS_BASE}" "${flag_string}" "${component_paths[@]}") || tree_code=$? + tree_output=$(_eslint_invoke_tree "components" "${STOREFRONT_ESLINT_COMPONENTS_BASE}" \ + "${flag_string}" "${component_paths[@]}") || tree_code=$? printf '%s\n' "${tree_output}" if [[ "${tree_code}" -ne 0 ]]; then overall="${tree_code}" @@ -191,7 +220,7 @@ tool_eslint_check() { worktree_assert_dependencies || return 1 local scoped_config - scoped_config=$(scope_get_tool_field eslint config) + scope_tool_field_or_refuse scoped_config eslint config || return 1 local output_format output_format=$(echo "${args}" | jq -r '.output_format // "stylish"') @@ -203,9 +232,11 @@ tool_eslint_check() { stylish|*) flags+=("-f" "stylish") ;; esac - [[ -n "${scoped_config}" ]] && flags+=("--config" "${scoped_config}") + local config_flag + scope_config_flag_or_refuse config_flag "ESLint configuration" "${scoped_config}" || return 1 + [[ -n "${config_flag}" ]] && flags+=("${config_flag}") - _eslint_dispatch "${args}" "lint:js" "${flags[*]}" "${scoped_config}" + _eslint_dispatch "${args}" "lint:js" "${flags[*]}" "${scoped_config}" "eslint_check" } # ESLint fix (auto-fix violations) @@ -225,10 +256,12 @@ tool_eslint_fix() { worktree_assert_dependencies || return 1 local scoped_config - scoped_config=$(scope_get_tool_field eslint config) + scope_tool_field_or_refuse scoped_config eslint config || return 1 local -a flags=("--fix") - [[ -n "${scoped_config}" ]] && flags+=("--config" "${scoped_config}") + local config_flag + scope_config_flag_or_refuse config_flag "ESLint configuration" "${scoped_config}" || return 1 + [[ -n "${config_flag}" ]] && flags+=("${config_flag}") - _eslint_dispatch "${args}" "lint:js:fix" "${flags[*]}" "${scoped_config}" + _eslint_dispatch "${args}" "lint:js:fix" "${flags[*]}" "${scoped_config}" "eslint_fix" } diff --git a/plugins/dev-tooling/mcp-server-js-storefront/lib/jest.sh b/plugins/dev-tooling/mcp-server-js-storefront/lib/jest.sh index a4899095..2e927832 100644 --- a/plugins/dev-tooling/mcp-server-js-storefront/lib/jest.sh +++ b/plugins/dev-tooling/mcp-server-js-storefront/lib/jest.sh @@ -3,21 +3,14 @@ # Provides jest_run MCP tool # Note: watch mode is not supported - long-running processes hang MCP servers # -# Runs route at the target-less npm script "jest:base". The aggregate "unit" -# script is `npm run jest:base -- --ci`, and appending `--ci=false` does not -# undo that because the literal `--ci` is still in argv. -# What CI mode changes here is snapshot writing. jest-config resolves the -# snapshot mode as `ci && !updateSnapshot ? 'none' : updateSnapshot ? 'all' -# : 'new'`, so `--ci` alone downgrades the default 'new' (write missing -# snapshots) to 'none' (write nothing). An explicit `--updateSnapshot` resolves -# to 'all' whether or not `--ci` is present — it wins, it is not cancelled out. -# Routing every run at "unit" would therefore silently stop new snapshots being -# written on runs that did not ask for CI mode. The `ci` argument puts that mode -# back under the caller's control. -# Coverage is a separate matter here: the Storefront jest.config.js sets -# `collectCoverage: true` unconditionally, so the "coverage" argument only ever -# adds an already-set flag. That is a config-level fact this routing does not -# change. +# Every run is the npm script "unit", `jest --config jest.config.js --ci`, with +# the caller's arguments appended. The `ci` argument appends `--ci`, which +# core's "unit" already passes, so it changes no core Storefront run. CI mode +# writes no missing snapshot: jest-config resolves the snapshot mode as +# `ci && !updateSnapshot ? 'none' : updateSnapshot ? 'all' : 'new'`, so only +# an explicit `--updateSnapshot` writes snapshots. The Storefront +# jest.config.js sets `collectCoverage: true`, so the `coverage` argument +# changes nothing either. # # The tool's result comes from Jest's own JSON report, not from the process # exit code. The exit code answers "did the jest process end cleanly", which is @@ -40,8 +33,7 @@ # /tmp between runs. That is deliberate and costs a round-trip less than a # post-run delete would. -STOREFRONT_JEST_BASE_SCRIPT="jest:base" -STOREFRONT_JEST_AGGREGATE_SCRIPT="unit" +STOREFRONT_JEST_SCRIPT="unit" # Per-server, per-process report path. Requests into one stdio MCP server are # handled sequentially, so a single server never has two runs in flight; the @@ -65,18 +57,26 @@ if ! declare -F _jest_scope_env_prefix >/dev/null; then [[ "${SCOPE_NAME:-shopware}" == "shopware" ]] && return 0 [[ -f "${LINT_CONFIG_FILE:-}" ]] || return 0 - if jq -e --arg name "${SCOPE_NAME}" \ + local has_linebreak + if ! has_linebreak=$(jq -r --arg name "${SCOPE_NAME}" \ '(.scopes[$name].jest.env // {}) | to_entries | any(.[]; (.key + "=" + (.value | tostring)) | (index("\n") != null) or (index("\r") != null))' \ - "${LINT_CONFIG_FILE}" >/dev/null 2>&1; then + "${LINT_CONFIG_FILE}" 2>&1); then + printf '%s\n' "${has_linebreak}" + return 1 + fi + if [[ "${has_linebreak}" == "true" ]]; then printf '%s\n' "Refusing to run: scope \"${SCOPE_NAME}\" declares a jest.env entry containing a line break, which cannot be embedded in a single command." return 1 fi local raw - raw=$(jq -r --arg name "${SCOPE_NAME}" \ + if ! raw=$(jq -r --arg name "${SCOPE_NAME}" \ '(.scopes[$name].jest.env // {}) | to_entries[] | "\(.key)=\(.value)"' \ - "${LINT_CONFIG_FILE}" 2>/dev/null) || return 0 + "${LINT_CONFIG_FILE}" 2>&1); then + printf '%s\n' "${raw}" + return 1 + fi local prefix="" entry while IFS= read -r entry; do @@ -94,7 +94,12 @@ if ! declare -F _jest_install_if_missing >/dev/null; then _jest_install_if_missing() { [[ "${SCOPE_NAME:-shopware}" == "shopware" ]] && return 0 local flag - flag=$(jq -r --arg name "${SCOPE_NAME}" '.scopes[$name].jest.install_if_missing // false' "${LINT_CONFIG_FILE}" 2>/dev/null || echo "false") + if ! flag=$(jq -r --arg name "${SCOPE_NAME}" \ + '(.scopes[$name].jest // {}) | if has("install_if_missing") then .install_if_missing | if type == "boolean" then tostring else error("scopes." + $name + ".jest.install_if_missing must be a boolean (found " + type + ")") end else "false" end' \ + "${LINT_CONFIG_FILE}" 2>&1); then + printf '%s\n' "${flag}" + return 1 + fi [[ "${flag}" != "true" ]] && return 0 # The [[ -d ]] runs on the HOST, so it has to measure a host path: @@ -264,18 +269,12 @@ tool_jest_run() { return 1 fi + # shellcheck disable=SC2034 # read by get_js_workdir in shared/environment.sh SCOPE_JS_SUBDIR="" if [[ "${SCOPE_NAME}" != "shopware" ]]; then - # shellcheck disable=SC2034 # read by get_js_workdir in shared/environment.sh - SCOPE_JS_SUBDIR=$(scope_get_tool_field jest cwd) + scope_tool_field_or_refuse SCOPE_JS_SUBDIR jest cwd || return 1 fi - _jest_install_if_missing || return 1 - - # After the opt-in install, which is what creates the node_modules this - # check would otherwise refuse the run over. - worktree_assert_dependencies || return 1 - local env_prefix env_prefix=$(_jest_scope_env_prefix) || { printf '%s\n' "${env_prefix}"; return 1; } @@ -285,8 +284,15 @@ tool_jest_run() { # Jest's rootDir is the app/storefront package and its testMatch only covers # **/test/**/*.test.js. Storefront component tests live under # views/components/ and are collected by Vitest alone, so a Jest run scoped - # to them would report green without executing a single test. - if [[ "${test_path_pattern}" == *"views/components"* || "${test_path_pattern}" == *"components/"* ]]; then + # to them would report green without executing a single test. The bare + # components/ match holds for the core Storefront only: a plugin scope's own + # Jest tree may keep tests under a components/ directory of its own. + if [[ "${SCOPE_NAME}" != "shopware" && "${test_path_pattern}" == *"views/components"* ]]; then + printf '%s\n' "Refusing to run jest_run under scope \"${SCOPE_NAME}\": a views/components/ pattern names Storefront component tests, which Jest does not collect. vitest_run runs the component suite of the core Storefront only and refuses every plugin scope." + return 1 + fi + if [[ "${SCOPE_NAME}" == "shopware" ]] \ + && [[ "${test_path_pattern}" == *"views/components"* || "${test_path_pattern}" == *"components/"* ]]; then printf '%s\n' "Storefront component tests under views/components/ do not run under Jest: the Jest project's rootDir is the app/storefront package and its testMatch only collects **/test/**/*.test.js. Use vitest_run for them." return 1 fi @@ -313,51 +319,33 @@ tool_jest_run() { return 1 fi + # The gate reads only package.json, so it needs no installed dependencies. + local body + if ! body=$(npm_script_append_gate "${STOREFRONT_JEST_SCRIPT}"); then + printf '%s\n' "${body}" + return 1 + fi + + # After every refusal above, so a refused call installs nothing. + _jest_install_if_missing || return 1 + + # After the opt-in install, which is what creates the node_modules this + # check would otherwise refuse the run over. + worktree_assert_dependencies || return 1 + local -a flags=() [[ -n "${test_path_pattern}" ]] && flags+=("--testPathPatterns=$(shell_quote_arg "${test_path_pattern}")") [[ -n "${test_name_pattern}" ]] && flags+=("--testNamePattern=$(shell_quote_arg "${test_name_pattern}")") [[ "${coverage}" == "true" ]] && flags+=("--coverage") [[ "${update_snapshots}" == "true" ]] && flags+=("--updateSnapshot") + # A plugin package's "unit" may lack the --ci that core's carries; Jest + # accepts the flag twice. + [[ "${ci}" == "true" ]] && flags+=("--ci") - local body - local gate_code=0 - body=$(npm_script_append_gate "${STOREFRONT_JEST_BASE_SCRIPT}") || gate_code=$? - - local script="${STOREFRONT_JEST_BASE_SCRIPT}" - - if [[ "${gate_code}" -ne 0 ]]; then - # Degraded route, announced rather than silent. No path widening is at - # stake here — "unit" runs the same suite — so falling back is better - # than refusing, but the caller has to know which arguments the - # fallback overrides. - script="${STOREFRONT_JEST_AGGREGATE_SCRIPT}" - printf '%s\n' "Notice: the npm script \"${STOREFRONT_JEST_BASE_SCRIPT}\" is unavailable, so this run falls back to \"${STOREFRONT_JEST_AGGREGATE_SCRIPT}\", whose body hardcodes --ci. Consequences: the \"ci\" argument is ignored and CI mode is forced, so a run that did not pass \"updateSnapshots\" writes no new snapshots where it otherwise would have. \"updateSnapshots\" itself still takes effect — an explicit --updateSnapshot resolves the snapshot mode to 'all' regardless of --ci. Coverage is unaffected either way — jest.config.js sets collectCoverage: true unconditionally, so it is collected regardless of the \"coverage\" argument. Reason: ${body}" - elif [[ "${ci}" == "true" ]]; then - # Only the base script needs this appended; the aggregate already - # carries --ci in its body. - flags+=("--ci") - fi - - # Every route asks for the report, the fallback and the CI route included: - # those are the routes where the silent reporter suppresses Jest's own - # "Tests:" line, so the report is the only place the counts exist. flags+=("--json" "--outputFile=$(shell_quote_arg "${STOREFRONT_JEST_REPORT_FILE}")") - local cmd="npm run ${script}" - - # The base script already passed the gate above; only the fallback still - # needs one before anything is appended to it. - if [[ "${script}" == "${STOREFRONT_JEST_AGGREGATE_SCRIPT}" ]]; then - local aggregate_body - local aggregate_gate=0 - aggregate_body=$(npm_script_append_gate "${script}") || aggregate_gate=$? - if [[ "${aggregate_gate}" -ne 0 ]]; then - printf '%s\n' "${aggregate_body}" - return 1 - fi - fi - cmd="${cmd} -- ${flags[*]}" + local cmd="npm run ${STOREFRONT_JEST_SCRIPT} -- ${flags[*]}" [[ -n "${env_prefix}" ]] && cmd="${env_prefix} ${cmd}" @@ -371,7 +359,7 @@ tool_jest_run() { return 1 fi - log "INFO" "Running Jest tests (storefront, ${script}): ${cmd}" + log "INFO" "Running Jest tests (storefront): ${cmd}" local output local run_exit=0 diff --git a/plugins/dev-tooling/mcp-server-js-storefront/lib/stylelint.sh b/plugins/dev-tooling/mcp-server-js-storefront/lib/stylelint.sh index 690ab422..8573ec90 100644 --- a/plugins/dev-tooling/mcp-server-js-storefront/lib/stylelint.sh +++ b/plugins/dev-tooling/mcp-server-js-storefront/lib/stylelint.sh @@ -3,44 +3,33 @@ # Provides stylelint_check and stylelint_fix MCP tools # # Two routes, selected by whether the caller supplied paths: -# paths supplied -> npm script "stylelint:app", whose body is a target-less -# `stylelint --config stylelint.config.js --cache`, so the -# caller's paths are the ONLY targets. +# paths supplied -> the package's own Stylelint binary through +# `npm exec --no -- stylelint --config stylelint.config.js +# --cache`, the flags of the "lint:scss" body without its +# `./src/scss` target, so the caller's paths are the ONLY +# targets. Under a scope that `--config` is left out: a +# scope-configured config takes its place, and without +# one Stylelint finds the scope package's own config. +# A directory path is narrowed to its .scss and .css files. # paths omitted -> the aggregate script ("lint:scss" / "lint:scss-fix"), # whose body carries its own `./src/scss` target, which # stays authoritative. -# The aggregate is never a fallback for a path-scoped run. npm appends `--` -# arguments to the END of the whole script body, so appending a path to a body -# that already names `./src/scss` widens the run to that whole tree PLUS the -# path — it can never narrow it. That matters most for stylelint_fix, which -# writes: a widened fix modifies files the caller never named. +# Why the aggregate never serves a path-scoped run: shared/js_paths.sh. # # The two routes also differ in where `--fix` comes from. "lint:scss-fix" # carries `--fix` in its own body, so the no-paths route must not add a second -# one; "stylelint:app" carries none, so the path-scoped route must add it or -# stylelint_fix silently runs as a check and writes nothing. +# one; the path-scoped command carries none, so the path-scoped route must add +# it or stylelint_fix silently runs as a check and writes nothing. -STOREFRONT_STYLELINT_BASE_SCRIPT="stylelint:app" +STOREFRONT_STYLELINT_BINARY="stylelint" +# The config the "lint:scss" body names, relative to the package directory. +STOREFRONT_STYLELINT_CONFIG="stylelint.config.js" # Extensions Stylelint reads here. Neither stylelint.config.js nor the CLI # restricts the set, so this is the pair the SCSS rulesets actually parse. A # path that resolves to no file with one of them lints nothing and still # exits 0. STOREFRONT_STYLELINT_EXTENSIONS="scss css" - -# True when the path is a glob pattern Stylelint expands itself rather than a -# literal filesystem path. The existence probe cannot resolve a glob, so glob -# entries skip the guard. Nothing is lost by skipping it: Stylelint exits 1 on a -# glob that matches no file and names the pattern, so the unmatched-glob case is -# still reported to the caller by the tool itself. -# Args: $1 = caller-supplied path -if ! declare -F _stylelint_storefront_path_is_glob >/dev/null; then - _stylelint_storefront_path_is_glob() { - case "$1" in - *"*"*|*"?"*|*"["*) return 0 ;; - esac - return 1 - } -fi +STOREFRONT_STYLELINT_DIRECTORY_GLOB="**/*.{scss,css}" # Run one Stylelint invocation for this tool. # Args: $1 = aggregate npm script used when no paths are supplied, @@ -48,7 +37,8 @@ fi # $3 = pre-path flag string used on both routes (may be empty), # $4 = pre-path flag string used ONLY on the path-scoped route, for flags # the aggregate script already carries in its own body (may be empty), -# $5 = tool arguments JSON +# $5 = tool arguments JSON, +# $6 = scope-configured Stylelint config (may be empty) # Stdout: linter output, or the failure message _stylelint_dispatch_storefront() { local aggregate="$1" @@ -56,6 +46,7 @@ _stylelint_dispatch_storefront() { local flag_string="$3" local path_only_flags="$4" local args="$5" + local scoped_config="$6" local paths_json paths paths_json=$(echo "${args}" | jq -c '.paths // []') @@ -85,61 +76,38 @@ _stylelint_dispatch_storefront() { return 1 fi + js_refuse_second_config "${tool_name}" "Stylelint" "${STOREFRONT_STYLELINT_BINARY}" \ + "${aggregate}" "${body}" "${scoped_config}" || return 1 + local aggregate_cmd="npm run ${aggregate} -- ${flag_string}" log "INFO" "Running Stylelint (storefront, ${aggregate}): ${aggregate_cmd}" exec_npm_command "${aggregate_cmd}" return fi - local -a supplied=() - local -a literals=() - local p - while IFS= read -r p; do - [[ -z "${p}" ]] && continue - supplied+=("${p}") - if ! _stylelint_storefront_path_is_glob "${p}"; then - literals+=("${p}") - fi - done < <(printf '%s\n' "${paths_json}" | jq -r '.[]') - - body=$(npm_script_append_gate "${STOREFRONT_STYLELINT_BASE_SCRIPT}") || gate_code=$? - if [[ "${gate_code}" -ne 0 ]]; then - printf '%s\n' "${body}" - printf '%s\n' "Refusing to run ${tool_name} with paths: a path-scoped run needs the target-less npm script \"${STOREFRONT_STYLELINT_BASE_SCRIPT}\", which is unusable here. The aggregate \"${aggregate}\" script is not a substitute — its body names its own targets and npm appends arguments after them, so it would cover that whole target set on top of the requested paths rather than only the requested paths." + local targets + if ! targets=$(js_path_scoped_targets "${tool_name}" "${STOREFRONT_STYLELINT_BINARY}" "${aggregate}" \ + "${STOREFRONT_STYLELINT_EXTENSIONS}" "${STOREFRONT_STYLELINT_DIRECTORY_GLOB}" "Stylelint" "${paths_json}"); then + printf '%s\n' "${targets}" return 1 fi - if [[ ${#literals[@]} -gt 0 ]]; then - local missing_report - if ! missing_report=$(assert_paths_lintable "." "${STOREFRONT_STYLELINT_EXTENSIONS}" "${literals[@]}"); then - printf '%s\n' "${missing_report}" - return 1 - fi + # The "lint:scss" body's flags besides its target. + local cmd="npm exec --no -- ${STOREFRONT_STYLELINT_BINARY}" + # SCOPE_CWD, not the scope's Stylelint config: any scope runs outside the package holding this config. + if [[ -z "${SCOPE_CWD:-}" ]]; then + cmd="${cmd} --config ${STOREFRONT_STYLELINT_CONFIG}" fi - - local -a quoted=() - for p in "${supplied[@]}"; do - quoted+=("$(shell_quote_arg "${p}")") - done - - # The base script's body carries no mode flag of its own, so anything the - # aggregate would have supplied has to be added here instead. - local path_flags="${flag_string}" - if [[ -n "${path_only_flags}" ]]; then - if [[ -n "${path_flags}" ]]; then - path_flags="${path_flags} ${path_only_flags}" - else - path_flags="${path_only_flags}" - fi + cmd="${cmd} --cache" + if [[ -n "${flag_string}" ]]; then + cmd="${cmd} ${flag_string}" fi - - local cmd="npm run ${STOREFRONT_STYLELINT_BASE_SCRIPT} --" - if [[ -n "${path_flags}" ]]; then - cmd="${cmd} ${path_flags}" + if [[ -n "${path_only_flags}" ]]; then + cmd="${cmd} ${path_only_flags}" fi - cmd="${cmd} ${quoted[*]}" + cmd="${cmd} ${targets}" - log "INFO" "Running Stylelint (storefront, ${STOREFRONT_STYLELINT_BASE_SCRIPT}): ${cmd}" + log "INFO" "Running Stylelint (storefront, npm exec): ${cmd}" exec_npm_command "${cmd}" } @@ -161,7 +129,7 @@ tool_stylelint_check() { worktree_assert_dependencies || return 1 local scoped_config - scoped_config=$(scope_get_tool_field stylelint config) + scope_tool_field_or_refuse scoped_config stylelint config || return 1 local output_format output_format=$(echo "${args}" | jq -r '.output_format // "string"') @@ -175,9 +143,11 @@ tool_stylelint_check() { string|*) flags+=("-f" "string") ;; esac - [[ -n "${scoped_config}" ]] && flags+=("--config" "${scoped_config}") + local config_flag + scope_config_flag_or_refuse config_flag "Stylelint configuration" "${scoped_config}" || return 1 + [[ -n "${config_flag}" ]] && flags+=("${config_flag}") - _stylelint_dispatch_storefront "lint:scss" "stylelint_check" "${flags[*]}" "" "${args}" + _stylelint_dispatch_storefront "lint:scss" "stylelint_check" "${flags[*]}" "" "${args}" "${scoped_config}" } # Stylelint fix (auto-fix violations) @@ -197,10 +167,12 @@ tool_stylelint_fix() { worktree_assert_dependencies || return 1 local scoped_config - scoped_config=$(scope_get_tool_field stylelint config) + scope_tool_field_or_refuse scoped_config stylelint config || return 1 local -a flags=() - [[ -n "${scoped_config}" ]] && flags+=("--config" "${scoped_config}") + local config_flag + scope_config_flag_or_refuse config_flag "Stylelint configuration" "${scoped_config}" || return 1 + [[ -n "${config_flag}" ]] && flags+=("${config_flag}") # Expanded through a guard: an empty array under `set -u` is not portable # to every bash the servers may run under, and empty is the common case @@ -211,5 +183,5 @@ tool_stylelint_fix() { fi # "--fix" is path-route only: the "lint:scss-fix" body already carries one. - _stylelint_dispatch_storefront "lint:scss-fix" "stylelint_fix" "${flag_string}" "--fix" "${args}" + _stylelint_dispatch_storefront "lint:scss-fix" "stylelint_fix" "${flag_string}" "--fix" "${args}" "${scoped_config}" } diff --git a/plugins/dev-tooling/mcp-server-js-storefront/lib/vitest.sh b/plugins/dev-tooling/mcp-server-js-storefront/lib/vitest.sh index 17ff9ad0..948b37fa 100644 --- a/plugins/dev-tooling/mcp-server-js-storefront/lib/vitest.sh +++ b/plugins/dev-tooling/mcp-server-js-storefront/lib/vitest.sh @@ -30,20 +30,19 @@ tool_vitest_run() { worktree_enter "${args}" || return 1 + # The component suite is core-only, so default_scope is ignored and a plugin scope refused. local scope_arg scope_arg=$(echo "${args}" | jq -r '.scope // empty' 2>/dev/null || echo "") - if ! resolve_scope "${scope_arg}"; then - echo "Scope resolution error" + if [[ -n "${scope_arg}" && "${scope_arg}" != "shopware" ]]; then + printf '%s\n' "Refusing to run vitest_run under scope \"${scope_arg}\": the Storefront component suite under views/components/ belongs to the core Storefront and runs only from the project root. Omit scope, or pass \"shopware\"." return 1 fi - - SCOPE_JS_SUBDIR="" - if [[ "${SCOPE_NAME}" != "shopware" ]]; then - # shellcheck disable=SC2034 # consumed by shared/environment.sh (get_js_workdir) via dynamic scope - SCOPE_JS_SUBDIR=$(scope_get_tool_field jest cwd) + if ! resolve_scope "shopware"; then + echo "Scope resolution error" + return 1 fi - worktree_assert_dependencies || return 1 + scope_assert_dependencies || return 1 local coverage coverage=$(echo "${args}" | jq -r '.coverage // false') diff --git a/plugins/dev-tooling/mcp-server-js-storefront/server.sh b/plugins/dev-tooling/mcp-server-js-storefront/server.sh index 4fbd565b..4e606924 100755 --- a/plugins/dev-tooling/mcp-server-js-storefront/server.sh +++ b/plugins/dev-tooling/mcp-server-js-storefront/server.sh @@ -16,7 +16,8 @@ # - ludtwig_check: Run ludtwig on Storefront Twig templates # - ludtwig_fix: Auto-fix ludtwig violations # - webpack_build: Build with Webpack -# - set_project_root: Set or clear the sticky project root +# - set_project_root: Bind the project root of an unbound server, or set or +# clear the sticky project root # - cwd: Report the project root, working directory and config in use # # Supports environments: native, docker, docker-compose, vagrant, ddev @@ -55,20 +56,31 @@ source "${SHARED_DIR}/mcpserver_core.sh" # Source config module and load configuration source "${SHARED_DIR}/config.sh" -if ! load_config "${PROJECT_ROOT}"; then - exit 1 +# A launch in this plugin's own directory starts unbound and skips every +# project-dependent startup step below; set_project_root performs them later. +source "${SHARED_DIR}/launch.sh" +if launch_is_bound; then + if ! load_config "${PROJECT_ROOT}"; then + exit 1 + fi fi # Source remaining modules source "${SHARED_DIR}/environment.sh" +source "${SHARED_DIR}/js_paths.sh" source "${SHARED_DIR}/scope.sh" -if ! scope_validate; then - exit 1 +if launch_is_bound; then + if ! scope_validate; then + exit 1 + fi fi source "${SHARED_DIR}/worktree.sh" if ! worktree_state_init; then exit 1 fi +if launch_is_bound; then + worktree_launch_common_init +fi # One EXIT trap doing both jobs. A second `trap ... EXIT` would replace the one # config.sh installs at source time, leaving the merged-config temp file behind. @@ -84,17 +96,20 @@ source "${SCRIPT_DIR}/lib/prepare.sh" trap 'log "ERROR" "Unexpected error on line ${LINENO}"' ERR -detect_environment "${PROJECT_ROOT}" -_configure_extra_log_file "$(_get_config_value '.log_file' '')" - -log "INFO" "======================================" -log "INFO" "Storefront Tooling MCP Server starting" -log "INFO" "Script dir: ${SCRIPT_DIR}" -log "INFO" "Project root: ${PROJECT_ROOT}" -log "INFO" "Config file: ${LINT_CONFIG_FILE}" -log "INFO" "Environment: ${LINT_ENV}" -log "INFO" "Working dir: ${LINT_WORKDIR}" -log "INFO" "Extra log: ${MCP_EXTRA_LOG_FILE:-}" -log "INFO" "======================================" +if launch_is_bound; then + detect_environment "${PROJECT_ROOT}" + log_file=$(_get_config_value '.log_file' '') || exit 1 + _configure_extra_log_file "${log_file}" + + log "INFO" "======================================" + log "INFO" "Storefront Tooling MCP Server starting" + log "INFO" "Script dir: ${SCRIPT_DIR}" + log "INFO" "Project root: ${PROJECT_ROOT}" + log "INFO" "Config file: ${LINT_CONFIG_FILE}" + log "INFO" "Environment: ${LINT_ENV}" + log "INFO" "Working dir: ${LINT_WORKDIR}" + log "INFO" "Extra log: ${MCP_EXTRA_LOG_FILE:-}" + log "INFO" "======================================" +fi source "${SHARED_DIR}/server_run.sh" diff --git a/plugins/dev-tooling/mcp-server-js-storefront/tools.json b/plugins/dev-tooling/mcp-server-js-storefront/tools.json index b259aa9f..8a92e6a3 100644 --- a/plugins/dev-tooling/mcp-server-js-storefront/tools.json +++ b/plugins/dev-tooling/mcp-server-js-storefront/tools.json @@ -2,7 +2,7 @@ "tools": [ { "name": "eslint_check", - "description": "ESLint code quality check (dry-run). Returns violations. Runs in Storefront context. Routes each path to the app tree (eslint:app) or the components tree (eslint:components) and runs both when both are targeted.", + "description": "ESLint code quality check (dry-run). Returns violations. Runs in Storefront context. Routes each path at or below views/components to the components tree and every other path to the app tree, and runs both when both are targeted. Components-tree paths are refused under any scope other than \"shopware\", because that tree belongs to the core Storefront package.", "inputSchema": { "type": "object", "properties": { @@ -15,7 +15,7 @@ "items": { "type": "string" }, - "description": "File paths or directories to lint. Three forms are accepted per path: repo-root-relative (\"src/Storefront/Resources/views/components/...\" or \"src/Storefront/Resources/app/storefront/...\"), tree-relative (\"views/components/...\" for the components tree, \"src/...\" or \"build/...\" for the app tree), and a path already carrying the package prefix. A path containing \"views/components/\" is linted as a component; everything else as app code. Omit to lint both trees via lint:js." + "description": "File paths or directories to lint. Three forms are accepted per path: repo-root-relative (\"src/Storefront/Resources/views/components/...\" or \"src/Storefront/Resources/app/storefront/...\"), tree-relative (\"views/components/...\" for the components tree, \"src/...\" or \"build/...\" for the app tree), and a path already carrying the package prefix (\"app/storefront/...\", unscoped runs only: under a scope only the scope cwd prefix is stripped, so this form stays as written and is refused as missing). A path containing \"views/components/\" is linted as a component; everything else as app code. Omit to lint both trees via lint:js." }, "output_format": { "type": "string", @@ -36,7 +36,7 @@ }, { "name": "eslint_fix", - "description": "ESLint auto-fix. Applies code style fixes in Storefront context. Routes each path to the app tree (eslint:app) or the components tree (eslint:components) and runs both when both are targeted.", + "description": "ESLint auto-fix. Applies code style fixes in Storefront context. Routes each path at or below views/components to the components tree and every other path to the app tree, and runs both when both are targeted. Components-tree paths are refused under any scope other than \"shopware\", because that tree belongs to the core Storefront package.", "inputSchema": { "type": "object", "properties": { @@ -49,7 +49,7 @@ "items": { "type": "string" }, - "description": "File paths or directories to fix. Three forms are accepted per path: repo-root-relative (\"src/Storefront/Resources/views/components/...\" or \"src/Storefront/Resources/app/storefront/...\"), tree-relative (\"views/components/...\" for the components tree, \"src/...\" or \"build/...\" for the app tree), and a path already carrying the package prefix. A path containing \"views/components/\" is fixed as a component; everything else as app code. Omit to fix both trees via lint:js:fix." + "description": "File paths or directories to fix. Three forms are accepted per path: repo-root-relative (\"src/Storefront/Resources/views/components/...\" or \"src/Storefront/Resources/app/storefront/...\"), tree-relative (\"views/components/...\" for the components tree, \"src/...\" or \"build/...\" for the app tree), and a path already carrying the package prefix (\"app/storefront/...\", unscoped runs only: under a scope only the scope cwd prefix is stripped, so this form stays as written and is refused as missing). A path containing \"views/components/\" is fixed as a component; everything else as app code. Omit to fix both trees via lint:js:fix." }, "scope": { "type": "string", @@ -140,7 +140,7 @@ "coverage": { "type": "boolean", "default": false, - "description": "Generate code coverage report" + "description": "Append --coverage. The core Storefront collects coverage on every run regardless: its Jest config sets collectCoverage: true." }, "updateSnapshots": { "type": "boolean", @@ -150,7 +150,7 @@ "ci": { "type": "boolean", "default": false, - "description": "Run Jest in CI mode (--ci). Defaults to false. Turning it on stops Jest writing snapshots that do not exist yet, which it would otherwise do by default. It does not cancel out \"updateSnapshots\": passing that resolves the snapshot mode to \"all\" whether or not CI mode is on, so snapshots are still written. Coverage is unaffected: the Storefront Jest config collects it unconditionally. Leave it off unless you need CI-identical behavior." + "description": "Append --ci to the run. The core Storefront's npm script \"unit\" already passes --ci, so a run under scope \"shopware\" is in CI mode either way. A plugin scope's own \"unit\" script runs in CI mode when it passes --ci itself or when this is set. In CI mode Jest writes no missing snapshot unless \"updateSnapshots\" is set." }, "scope": { "type": "string", @@ -193,7 +193,7 @@ }, "scope": { "type": "string", - "description": "Scope name from .mcp-js-tooling.json. Omit to use the configured default_scope. Pass \"shopware\" to force project-root behavior." + "description": "Only \"shopware\" is accepted. The component suite belongs to the core Storefront and always runs from the project root: omitting scope runs it there regardless of the configured default_scope, and any plugin scope is refused." } }, "additionalProperties": false @@ -248,7 +248,7 @@ }, "scope": { "type": "string", - "description": "Scope name from .mcp-js-tooling.json. Omit to use the configured default_scope. Pass \"shopware\" to force project-root behavior." + "description": "Scope name from .mcp-js-tooling.json. Omit, or pass \"shopware\", to run in the core Storefront package: this tool ignores default_scope." } }, "additionalProperties": false @@ -274,13 +274,13 @@ }, { "name": "set_project_root", - "description": "Set the project root every later call on this server targets, or clear it. Pass a linked git worktree of the root the server was launched in to move the server onto that tree; omit project_root to return it to the launch root. Each of php-tooling, js-admin-tooling and js-storefront-tooling is a separate process and keeps its own setting, so call this on each server you use.", + "description": "Set the project root every later call on this server targets, or clear it. A server started in a project directory is bound to it as its launch root: pass a linked git worktree of that root to move the server onto that tree, and omit project_root, or pass the launch root itself, to return it to the launch root. A server started in its own plugin directory, when the process was started in that directory, has no project root, and every tool except cwd refuses until this is called with the absolute path of the project; that binds the server to it as its launch root for the rest of the process, and calling it again with that path clears any sticky worktree, the same as omitting project_root. Each of php-tooling, js-admin-tooling and js-storefront-tooling is a separate process and keeps its own setting, so call this on each server you use.", "inputSchema": { "type": "object", "properties": { "project_root": { "type": "string", - "description": "Absolute path to a linked git worktree of the root this server was launched in. Omit to clear the setting and return the server to its launch root; the value being discarded is not validated, so this also recovers from a worktree that has been removed. Works in every environment: the call runs against that tree as the server's environment reaches it, and under docker, docker-compose, vagrant and ddev the worktree must sit inside the launch project root, which is the only tree the container or VM mounts." + "description": "Absolute path. On a server with no project root yet: the project to bind, which must hold this server's .mcp-js-tooling.json at its top or in a supported tool directory such as .claude/, unless MCP_JS_TOOLING_CONFIG names the configuration file. Otherwise: a linked git worktree of the root this server was launched in. Omit it, or pass the launch root itself, to clear the setting and return the server to its launch root; the value being discarded is not validated, so this also recovers from a worktree that has been removed. Works in every environment: the call runs against that tree as the server's environment reaches it, and under docker, docker-compose, vagrant and ddev the worktree must sit inside the launch project root, which is the only tree the container or VM mounts." } }, "additionalProperties": false diff --git a/plugins/dev-tooling/mcp-server-php/lib/console.sh b/plugins/dev-tooling/mcp-server-php/lib/console.sh index 4e4fb3d0..c953f25a 100644 --- a/plugins/dev-tooling/mcp-server-php/lib/console.sh +++ b/plugins/dev-tooling/mcp-server-php/lib/console.sh @@ -222,10 +222,10 @@ tool_console_run() { worktree_assert_dependencies || return 1 local default_env default_verbosity default_no_debug default_no_interaction - default_env=$(_get_config_value ".console.env") - default_verbosity=$(_get_config_value ".console.verbosity") - default_no_debug=$(_get_config_value ".console.no_debug") - default_no_interaction=$(_get_config_value ".console.no_interaction") + default_env=$(_get_config_value ".console.env") || return 1 + default_verbosity=$(_get_config_value ".console.verbosity") || return 1 + default_no_debug=$(_get_config_value ".console.no_debug") || return 1 + default_no_interaction=$(_get_config_value ".console.no_interaction") || return 1 local parsed if ! parsed=$(echo "${args}" | jq -c '{ @@ -234,8 +234,8 @@ tool_console_run() { options: (.options // {}), env: (.env // null), verbosity: (.verbosity // null), - no_debug: (.no_debug // null), - no_interaction: (.no_interaction // null), + no_debug: .no_debug, + no_interaction: .no_interaction, output_file: (.output_file // null), feature_all: (.feature_all // null) }' 2>/dev/null); then @@ -249,8 +249,10 @@ tool_console_run() { options_json=$(echo "${parsed}" | jq -c '.options') env=$(echo "${parsed}" | jq -r '.env // empty') verbosity=$(echo "${parsed}" | jq -r '.verbosity // empty') - no_debug=$(echo "${parsed}" | jq -r '.no_debug // empty') - no_interaction=$(echo "${parsed}" | jq -r '.no_interaction // empty') + # "// empty" would read an explicit false as absent and let the configured + # default override it. + no_debug=$(echo "${parsed}" | jq -r '.no_debug | select(. != null)') + no_interaction=$(echo "${parsed}" | jq -r '.no_interaction | select(. != null)') output_file=$(echo "${parsed}" | jq -r '.output_file // empty') feature_all=$(echo "${parsed}" | jq -r '.feature_all // empty') @@ -281,7 +283,7 @@ tool_console_run() { local -a arg_array=() if [[ "${arguments_json}" != "[]" ]]; then while IFS= read -r a; do - [[ -n "${a}" ]] && arg_array+=("${a}") + arg_array+=("${a}") done < <(echo "${arguments_json}" | jq -r '.[]' 2>/dev/null) fi @@ -355,6 +357,12 @@ tool_console_run() { flags+=("--${quoted_key}=$(shell_quote_arg "${value}")") ;; array) + local element_type + element_type=$(echo "${options_json}" | jq -r --arg k "${key}" '[.[$k][] | type | select(. != "string" and . != "number")] | first // empty') + if [[ -n "${element_type}" ]]; then + printf '%s\n' "Refusing to run: console option \"${key}\" holds a ${element_type} element; an array value may hold only strings and numbers." + return 1 + fi local arr_val while IFS= read -r arr_val; do if ! guard=$(assert_no_shell_hostile_chars "console option value" "${arr_val}"); then @@ -364,6 +372,11 @@ tool_console_run() { flags+=("--${quoted_key}=$(shell_quote_arg "${arr_val}")") done < <(echo "${options_json}" | jq -r --arg k "${key}" '.[$k][]' 2>/dev/null) ;; + *) + # The vendored validator does not enforce the oneOf on "options". + printf '%s\n' "Refusing to run: console option \"${key}\" has type ${value_type}; only boolean, string and array values are allowed." + return 1 + ;; esac done < <(echo "${options_json}" | jq -r 'keys[]' 2>/dev/null) fi @@ -457,20 +470,32 @@ tool_console_list() { # The namespace passed the character allowlist above, so it needs no # further guard; it is still quoted so the wrappers see one argument. + local -a flags=("list") + [[ -n "${namespace}" ]] && flags+=("$(shell_quote_arg "${namespace}")") + if [[ "${format}" != "llm" ]]; then - local -a flags=("list") - [[ -n "${namespace}" ]] && flags+=("$(shell_quote_arg "${namespace}")") flags+=("--format=$(shell_quote_arg "${format}")") exec_command "bin/console ${flags[*]}" return fi - local -a flags=("list") - [[ -n "${namespace}" ]] && flags+=("$(shell_quote_arg "${namespace}")") flags+=("--format=json") - local raw_output - raw_output=$(exec_command "bin/console ${flags[*]}") + # A failed command or non-JSON output must reach the caller as it is: the + # formatter would turn either into empty output. + local raw_output rc=0 + raw_output=$(exec_command "bin/console ${flags[*]}") || rc=$? + if [[ "${rc}" -ne 0 ]]; then + printf '%s\n' "${raw_output}" + return "${rc}" + fi + + local formatted + if ! formatted=$(_format_console_list_llm "${raw_output}"); then + printf '%s\n' "The output of bin/console list is not the expected JSON; raw output follows." + printf '%s\n' "${raw_output}" + return 1 + fi - _format_console_list_llm "${raw_output}" + printf '%s\n' "${formatted}" } diff --git a/plugins/dev-tooling/mcp-server-php/lib/ecs.sh b/plugins/dev-tooling/mcp-server-php/lib/ecs.sh index 9ef9992f..5a86cc85 100755 --- a/plugins/dev-tooling/mcp-server-php/lib/ecs.sh +++ b/plugins/dev-tooling/mcp-server-php/lib/ecs.sh @@ -23,18 +23,22 @@ _refuse_linebreak_args() { return 0 } -# _style_backend -> echoes "ecs" or "php-cs-fixer" +# _style_backend -> echoes "ecs" or "php-cs-fixer"; refuses any other configured backend. _style_backend() { local b - b=$(scope_get_tool_field style tool) - [[ -n "${b}" ]] && echo "${b}" || echo "ecs" + scope_tool_field_or_refuse b style tool || return 1 + case "${b}" in + '') printf '%s\n' 'ecs' ;; + ecs|php-cs-fixer) printf '%s\n' "${b}" ;; + *) printf '%s\n' "Refusing to run: style.tool '${b}' must be ecs or php-cs-fixer."; return 1 ;; + esac } -# _style_config_default -> echoes scope.style.config or .ecs.config +# _style_config_default -> echoes scope.style.config or .ecs.config; refuses an unreadable value. _style_config_default() { local c - c=$(scope_get_tool_field style config) - [[ -n "${c}" ]] && { echo "${c}"; return; } + scope_tool_field_or_refuse c style config || return 1 + [[ -n "${c}" ]] && { echo "${c}"; return 0; } _get_config_value ".ecs.config" } @@ -56,8 +60,14 @@ tool_ecs_check() { worktree_assert_dependencies || return 1 local default_config backend - default_config=$(_style_config_default) - backend=$(_style_backend) + if ! default_config=$(_style_config_default); then + printf '%s\n' "${default_config}" + return 1 + fi + if ! backend=$(_style_backend); then + printf '%s\n' "${backend}" + return 1 + fi local parsed if ! parsed=$(echo "${args}" | jq -c '{ @@ -135,8 +145,14 @@ tool_ecs_fix() { worktree_assert_dependencies || return 1 local default_config backend - default_config=$(_style_config_default) - backend=$(_style_backend) + if ! default_config=$(_style_config_default); then + printf '%s\n' "${default_config}" + return 1 + fi + if ! backend=$(_style_backend); then + printf '%s\n' "${backend}" + return 1 + fi local parsed if ! parsed=$(echo "${args}" | jq -c '{ diff --git a/plugins/dev-tooling/mcp-server-php/lib/phpstan.sh b/plugins/dev-tooling/mcp-server-php/lib/phpstan.sh index 7237c7eb..e9b3fc6b 100755 --- a/plugins/dev-tooling/mcp-server-php/lib/phpstan.sh +++ b/plugins/dev-tooling/mcp-server-php/lib/phpstan.sh @@ -4,26 +4,6 @@ set -euo pipefail shopt -s inherit_errexit 2>/dev/null || true -# _run_scope_bootstrap -# Runs scope..bootstrap[] via exec_command in sequence. Any non-zero -# exit aborts with an MCP-facing error message on stdout. -_run_scope_bootstrap() { - local tool="$1" - local cmd - while IFS= read -r cmd; do - [[ -z "${cmd}" ]] && continue - log "INFO" "Scope bootstrap [${tool}]: ${cmd}" - local output rc=0 - output=$(exec_command "${cmd}") || rc=$? - if [[ "${rc}" -ne 0 ]]; then - echo "Scope bootstrap failed for tool '${tool}' (exit ${rc}):" - echo "${output}" - return 1 - fi - done < <(scope_get_bootstrap "${tool}") - return 0 -} - # tool_phpstan_analyze - MCP tool function # Args: $1 = JSON arguments # Returns: Raw PHPStan output (JSON or text based on error_format) @@ -46,14 +26,12 @@ tool_phpstan_analyze() { worktree_assert_dependencies || return 1 - if ! _run_scope_bootstrap phpstan; then - return 1 - fi - local default_config default_memory - default_config=$(scope_get_tool_field phpstan config) - [[ -z "${default_config}" ]] && default_config=$(_get_config_value ".phpstan.config") - default_memory=$(_get_config_value ".phpstan.memory_limit") + scope_tool_field_or_refuse default_config phpstan config || return 1 + if [[ -z "${default_config}" ]]; then + default_config=$(_get_config_value ".phpstan.config") || return 1 + fi + default_memory=$(_get_config_value ".phpstan.memory_limit") || return 1 local parsed if ! parsed=$(echo "${args}" | jq -c '{ @@ -101,6 +79,12 @@ tool_phpstan_analyze() { return 1 fi + # After every argument guard: the bootstrap runs project commands, so a + # refused call must not have run them. + if ! _run_scope_bootstrap phpstan; then + return 1 + fi + log "INFO" "PHPStan analyze: scope='${SCOPE_NAME}' paths='${paths}' level='${level}' format='${error_format}' config='${config}' memory='${memory_limit}'" local -a flags=() diff --git a/plugins/dev-tooling/mcp-server-php/lib/phpunit.sh b/plugins/dev-tooling/mcp-server-php/lib/phpunit.sh index e51dae78..7bcc38ba 100644 --- a/plugins/dev-tooling/mcp-server-php/lib/phpunit.sh +++ b/plugins/dev-tooling/mcp-server-php/lib/phpunit.sh @@ -27,11 +27,11 @@ tool_phpunit_run() { worktree_assert_dependencies || return 1 local scoped_config - scoped_config=$(scope_get_tool_field phpunit config) + scope_tool_field_or_refuse scoped_config phpunit config || return 1 local default_testsuite default_config - default_testsuite=$(_get_config_value ".phpunit.testsuite") - default_config=$(_get_config_value ".phpunit.config") + default_testsuite=$(_get_config_value ".phpunit.testsuite") || return 1 + default_config=$(_get_config_value ".phpunit.config") || return 1 local parsed if ! parsed=$(echo "${args}" | jq -c '{ @@ -65,7 +65,9 @@ tool_phpunit_run() { [[ -z "${testsuite}" ]] && testsuite="${default_testsuite}" [[ -z "${config}" ]] && config="${scoped_config}" [[ -z "${config}" ]] && config="${default_config}" - [[ -z "${coverage_driver}" ]] && coverage_driver=$(_get_config_value ".phpunit.coverage_driver") + if [[ -z "${coverage_driver}" ]]; then + coverage_driver=$(_get_config_value ".phpunit.coverage_driver") || return 1 + fi # Paths are validated and quoted in one step: a malformed "paths" payload # must not fall through to the whole-suite run. diff --git a/plugins/dev-tooling/mcp-server-php/lib/phpunit_coverage.sh b/plugins/dev-tooling/mcp-server-php/lib/phpunit_coverage.sh index 75f7bbe9..6f027078 100644 --- a/plugins/dev-tooling/mcp-server-php/lib/phpunit_coverage.sh +++ b/plugins/dev-tooling/mcp-server-php/lib/phpunit_coverage.sh @@ -190,11 +190,18 @@ END { local file_count=0 local output="" + local entry while IFS='|' read -r pct uncov _ _ filepath ranges methods; do file_count=$((file_count + 1)) - output+=$(printf "\n%6.1f%% (%2d uncovered) %s\n" "${pct}" "${uncov}" "${filepath}") - [[ -n "${methods}" ]] && output+=$(printf " Uncovered methods: %s\n" "${methods}") - output+=$(printf " Lines: %s\n" "${ranges}") + # printf -v keeps the trailing newline that $(printf ...) would strip. + printf -v entry "\n%6.1f%% (%2d uncovered) %s\n" "${pct}" "${uncov}" "${filepath}" + output+="${entry}" + if [[ -n "${methods}" ]]; then + printf -v entry " Uncovered methods: %s\n" "${methods}" + output+="${entry}" + fi + printf -v entry " Lines: %s\n" "${ranges}" + output+="${entry}" done < <(echo "${parsed_lines}" | sort -t'|' -k1,1n) # Header @@ -205,7 +212,7 @@ END { header+=")" echo "${header}" - echo "${output}" + echo "${output%$'\n'}" # Summary local total_pct="0.0" diff --git a/plugins/dev-tooling/mcp-server-php/lib/rector.sh b/plugins/dev-tooling/mcp-server-php/lib/rector.sh index a14db54c..5a3a4f57 100644 --- a/plugins/dev-tooling/mcp-server-php/lib/rector.sh +++ b/plugins/dev-tooling/mcp-server-php/lib/rector.sh @@ -20,30 +20,6 @@ _refuse_linebreak_args() { return 0 } -# _run_scope_bootstrap -# Runs scope..bootstrap[] via exec_command in sequence. Any non-zero -# exit aborts with an MCP-facing error message on stdout. Defined here as a -# local duplicate of the helper in phpstan.sh so rector.sh works when loaded -# standalone (e.g. unit tests that source only this file). -if ! declare -F _run_scope_bootstrap >/dev/null 2>&1; then - _run_scope_bootstrap() { - local tool="$1" - local cmd - while IFS= read -r cmd; do - [[ -z "${cmd}" ]] && continue - log "INFO" "Scope bootstrap [${tool}]: ${cmd}" - local output rc=0 - output=$(exec_command "${cmd}") || rc=$? - if [[ "${rc}" -ne 0 ]]; then - echo "Scope bootstrap failed for tool '${tool}' (exit ${rc}):" - echo "${output}" - return 1 - fi - done < <(scope_get_bootstrap "${tool}") - return 0 - } -fi - # Parse shared Rector arguments from JSON # Args: $1 = JSON arguments # Sets: output_format, config, only, only_suffix, clear_cache, paths_json, paths @@ -53,10 +29,10 @@ _parse_rector_args() { local args="$1" local default_config - default_config=$(_get_config_value ".rector.config") + default_config=$(_get_config_value ".rector.config") || return 1 local scoped_config - scoped_config=$(scope_get_tool_field rector config) + scope_tool_field_or_refuse scoped_config rector config || return 1 local parsed if ! parsed=$(echo "${args}" | jq -c '{ @@ -111,6 +87,34 @@ _parse_rector_args() { return 0 } +# _rector_fix_script +# Shopware core's "rector" script is a dry run; "rector-fix" is the one that writes files. +# Globals: reads WORKTREE_EFFECTIVE_ROOT, SCOPE_CWD +# Stdout: the script name, or a refusal message +# Returns: 1 when only a dry-run "rector" script exists +_rector_fix_script() { + local composer_file="${WORKTREE_EFFECTIVE_ROOT}" + [[ -n "${SCOPE_CWD:-}" ]] && composer_file+="/${SCOPE_CWD}" + composer_file+="/composer.json" + + # An unreadable composer.json falls back to "rector"; composer reports the file itself. + local script + script=$(jq -r ' + .scripts as $scripts + | if ($scripts | type) != "object" then "rector" + elif $scripts | has("rector-fix") then "rector-fix" + elif ($scripts.rector | tostring | contains("--dry-run")) then "dry-run" + else "rector" end + ' "${composer_file}" 2>/dev/null) || script="" + + if [[ "${script}" == "dry-run" ]]; then + printf '%s\n' "Refusing to run rector_fix: in ${composer_file} its \"rector\" script runs with --dry-run and there is no \"rector-fix\" script, so the run would apply nothing." + return 1 + fi + + printf '%s\n' "${script:-rector}" +} + # tool_rector_fix - MCP tool function (apply refactorings) # Args: $1 = JSON arguments # Returns: Rector output (JSON or console) @@ -130,14 +134,22 @@ tool_rector_fix() { worktree_assert_dependencies || return 1 - if ! _run_scope_bootstrap rector; then - return 1 - fi - local paths_json paths output_format config only only_suffix clear_cache _parse_rector_args "${args}" || return 1 + local fix_script + if ! fix_script=$(_rector_fix_script); then + printf '%s\n' "${fix_script}" + return 1 + fi + + # After every argument guard: the bootstrap runs project commands, so a + # refused call must not have run them. + if ! _run_scope_bootstrap rector; then + return 1 + fi + log "INFO" "Rector fix: paths='${paths_json}' format='${output_format}' config='${config}' only='${only}' only_suffix='${only_suffix}' clear_cache='${clear_cache}'" local -a flags=("--no-progress-bar" "--output-format=$(shell_quote_arg "${output_format}")") @@ -147,7 +159,7 @@ tool_rector_fix() { [[ "${clear_cache}" == "true" ]] && flags+=("--clear-cache") [[ -n "${paths}" ]] && flags+=("${paths}") - local cmd="composer rector" + local cmd="composer ${fix_script}" [[ ${#flags[@]} -gt 0 ]] && cmd="${cmd} -- ${flags[*]}" exec_command "${cmd}" @@ -172,14 +184,16 @@ tool_rector_check() { worktree_assert_dependencies || return 1 - if ! _run_scope_bootstrap rector; then - return 1 - fi - local paths_json paths output_format config only only_suffix clear_cache _parse_rector_args "${args}" || return 1 + # After every argument guard: the bootstrap runs project commands, so a + # refused call must not have run them. + if ! _run_scope_bootstrap rector; then + return 1 + fi + log "INFO" "Rector check: paths='${paths_json}' format='${output_format}' config='${config}' only='${only}' only_suffix='${only_suffix}' clear_cache='${clear_cache}'" local -a flags=("--no-progress-bar" "--output-format=$(shell_quote_arg "${output_format}")") diff --git a/plugins/dev-tooling/mcp-server-php/server.sh b/plugins/dev-tooling/mcp-server-php/server.sh index b1e4b905..f30e8b95 100755 --- a/plugins/dev-tooling/mcp-server-php/server.sh +++ b/plugins/dev-tooling/mcp-server-php/server.sh @@ -13,7 +13,8 @@ # - console_list: List available bin/console commands # - rector_check: Preview Rector transformations (dry-run) # - rector_fix: Apply Rector transformations -# - set_project_root: Set or clear the sticky project root +# - set_project_root: Bind the project root of an unbound server, or set or +# clear the sticky project root # - cwd: Report the project root, working directory and config in use # # Supports environments: native, docker, docker-compose, vagrant, ddev @@ -46,19 +47,29 @@ export SCRIPT_DIR SHARED_DIR MCP_CONFIG_FILE MCP_TOOLS_LIST_FILE MCP_LOG_FILE PR source "${SHARED_DIR}/mcpserver_core.sh" source "${SHARED_DIR}/config.sh" -if ! load_config "${PROJECT_ROOT}"; then - exit 1 +# A launch in this plugin's own directory starts unbound and skips every +# project-dependent startup step below; set_project_root performs them later. +source "${SHARED_DIR}/launch.sh" +if launch_is_bound; then + if ! load_config "${PROJECT_ROOT}"; then + exit 1 + fi fi source "${SHARED_DIR}/environment.sh" source "${SHARED_DIR}/scope.sh" -if ! scope_validate; then - exit 1 +if launch_is_bound; then + if ! scope_validate; then + exit 1 + fi fi source "${SHARED_DIR}/worktree.sh" if ! worktree_state_init; then exit 1 fi +if launch_is_bound; then + worktree_launch_common_init +fi # One EXIT trap doing both jobs. A second `trap ... EXIT` would replace the one # config.sh installs at source time, leaving the merged-config temp file behind. @@ -74,17 +85,20 @@ source "${SCRIPT_DIR}/lib/prepare.sh" trap 'log "ERROR" "Unexpected error on line ${LINENO}"' ERR -detect_environment "${PROJECT_ROOT}" -_configure_extra_log_file "$(_get_config_value '.log_file' '')" +if launch_is_bound; then + detect_environment "${PROJECT_ROOT}" + log_file=$(_get_config_value '.log_file' '') || exit 1 + _configure_extra_log_file "${log_file}" -log "INFO" "======================================" -log "INFO" "PHP Linting MCP Server starting" -log "INFO" "Script dir: ${SCRIPT_DIR}" -log "INFO" "Project root: ${PROJECT_ROOT}" -log "INFO" "Config file: ${LINT_CONFIG_FILE}" -log "INFO" "Environment: ${LINT_ENV}" -log "INFO" "Working dir: ${LINT_WORKDIR}" -log "INFO" "Extra log: ${MCP_EXTRA_LOG_FILE:-}" -log "INFO" "======================================" + log "INFO" "======================================" + log "INFO" "PHP Linting MCP Server starting" + log "INFO" "Script dir: ${SCRIPT_DIR}" + log "INFO" "Project root: ${PROJECT_ROOT}" + log "INFO" "Config file: ${LINT_CONFIG_FILE}" + log "INFO" "Environment: ${LINT_ENV}" + log "INFO" "Working dir: ${LINT_WORKDIR}" + log "INFO" "Extra log: ${MCP_EXTRA_LOG_FILE:-}" + log "INFO" "======================================" +fi source "${SHARED_DIR}/server_run.sh" diff --git a/plugins/dev-tooling/mcp-server-php/tools.json b/plugins/dev-tooling/mcp-server-php/tools.json index d242aca8..52be464c 100644 --- a/plugins/dev-tooling/mcp-server-php/tools.json +++ b/plugins/dev-tooling/mcp-server-php/tools.json @@ -76,8 +76,8 @@ }, "testsuite": { "type": "string", - "description": "Test suite to run. Falls back to .lintrc.local.json phpunit.testsuite if not provided.", - "enum": ["unit", "integration", "migration", "devops", "core-framework-batch1", "core-framework-batch2", "core-framework-batch3"] + "pattern": "^[A-Za-z0-9_.-]{1,64}$", + "description": "Name of a test suite defined in the PHPUnit configuration, e.g. unit, integration, migration, redis or a suite a plugin defines. Falls back to phpunit.testsuite from the config file if not provided." }, "paths": { "type": "array", @@ -90,7 +90,7 @@ }, "config": { "type": "string", - "description": "PHPUnit config file path. Falls back to .lintrc.local.json phpunit.config if not provided." + "description": "PHPUnit config file path. Falls back to phpunit.config from the config file if not provided." }, "stop_on_failure": { "type": "boolean", @@ -179,10 +179,10 @@ "oneOf": [ { "type": "boolean" }, { "type": "string" }, - { "type": "array", "items": { "type": "string" } } + { "type": "array", "items": { "type": ["string", "number"] } } ] }, - "description": "Command options as key-value pairs. Boolean true = --flag, string = --key=value, array = multiple --key=value" + "description": "Command options as key-value pairs. Boolean true = --flag, string = --key=value, array of strings or numbers = multiple --key=value" }, "env": { "type": "string", @@ -191,7 +191,7 @@ }, "output_file": { "type": "string", - "description": "Write the command's stdout to this file instead of returning it. A relative path resolves against the project root; parent directories are created. The response then carries the resolved path, the byte count and the exit status, plus stderr. Refused when longer than 4096 bytes, or when the target exists as a symlink or a non-regular file. On a failed command the file is left untouched and stdout comes back in the response." + "description": "Write the command's stdout to this file instead of returning it. A relative path resolves against the project root; an absolute path is accepted and written as given, inside or outside the project root; parent directories are created. The response then carries the resolved path, the byte count and the exit status, plus stderr. Refused when longer than 4096 bytes, when the final path component is .git, or when the target exists as a symlink or a non-regular file. On a failed command the file is left untouched and stdout comes back in the response." }, "feature_all": { "type": "string", @@ -249,7 +249,7 @@ }, { "name": "rector_fix", - "description": "Rector refactoring. Detects and applies code transformations in one step. Preferred over rector_check — shows diffs AND applies them.", + "description": "Rector refactoring. Detects and applies code transformations in one step. Preferred over rector_check — shows diffs AND applies them. Runs composer rector-fix when composer.json defines that script, otherwise composer rector; refuses when there is no rector-fix script and the rector script passes --dry-run, since that run would apply nothing.", "inputSchema": { "type": "object", "properties": { @@ -353,13 +353,13 @@ }, { "name": "set_project_root", - "description": "Set the project root every later call on this server targets, or clear it. Pass a linked git worktree of the root the server was launched in to move the server onto that tree; omit project_root to return it to the launch root. Each of php-tooling, js-admin-tooling and js-storefront-tooling is a separate process and keeps its own setting, so call this on each server you use.", + "description": "Set the project root every later call on this server targets, or clear it. A server started in a project directory is bound to it as its launch root: pass a linked git worktree of that root to move the server onto that tree, and omit project_root, or pass the launch root itself, to return it to the launch root. A server started in its own plugin directory, when the process was started in that directory, has no project root, and every tool except cwd refuses until this is called with the absolute path of the project; that binds the server to it as its launch root for the rest of the process, and calling it again with that path clears any sticky worktree, the same as omitting project_root. Each of php-tooling, js-admin-tooling and js-storefront-tooling is a separate process and keeps its own setting, so call this on each server you use.", "inputSchema": { "type": "object", "properties": { "project_root": { "type": "string", - "description": "Absolute path to a linked git worktree of the root this server was launched in. Omit to clear the setting and return the server to its launch root; the value being discarded is not validated, so this also recovers from a worktree that has been removed. Works in every environment: the call runs against that tree as the server's environment reaches it, and under docker, docker-compose, vagrant and ddev the worktree must sit inside the launch project root, which is the only tree the container or VM mounts." + "description": "Absolute path. On a server with no project root yet: the project to bind, which must hold this server's .mcp-php-tooling.json at its top or in a supported tool directory such as .claude/, unless MCP_PHP_TOOLING_CONFIG names the configuration file. Otherwise: a linked git worktree of the root this server was launched in. Omit it, or pass the launch root itself, to clear the setting and return the server to its launch root; the value being discarded is not validated, so this also recovers from a worktree that has been removed. Works in every environment: the call runs against that tree as the server's environment reaches it, and under docker, docker-compose, vagrant and ddev the worktree must sit inside the launch project root, which is the only tree the container or VM mounts." } }, "additionalProperties": false diff --git a/plugins/dev-tooling/shared/config.sh b/plugins/dev-tooling/shared/config.sh index e3550829..cacc07bc 100644 --- a/plugins/dev-tooling/shared/config.sh +++ b/plugins/dev-tooling/shared/config.sh @@ -15,7 +15,10 @@ # Usage: export CONFIG_PREFIX="php-tooling" # source this file after mcpserver_core.sh (needs log function) # then call: load_config "$PROJECT_ROOT" -# Result: LINT_CONFIG_FILE is set and exported +# Result: LINT_CONFIG_FILE is set and exported. When a config file does +# not hold a JSON object, or the override names a missing file, +# load_config fails and CONFIG_LOAD_ERROR names the cause; it is empty +# after any other outcome. set -euo pipefail shopt -s inherit_errexit 2>/dev/null || true # Bash 4.4+ @@ -25,28 +28,10 @@ if [[ -z "${CONFIG_PREFIX:-}" ]]; then exit 1 fi -# Generate config file name and environment variable from prefix. -# -# MCP path (default, CONFIG_FILE_PREFIX unset): +# Generate config file name and environment variable from prefix: # php-tooling -> .mcp-php-tooling.json, MCP_PHP_TOOLING_CONFIG -# -# LSP path (caller sets CONFIG_FILE_PREFIX=".lsp-", CONFIG_ENV_VAR_PREFIX="LSP"): -# php-tooling -> .lsp-php-tooling.json, LSP_PHP_TOOLING_CONFIG -# -# The LSP path is explicit by design — we don't default CONFIG_FILE_PREFIX to ".mcp-" -# because a silent fallback would mask caller bugs. MCP's .mcp- literal stays hardcoded -# in the else branch below. -if [[ -n "${CONFIG_FILE_PREFIX:-}" ]]; then - if [[ -z "${CONFIG_ENV_VAR_PREFIX:-}" ]]; then - echo "ERROR: CONFIG_ENV_VAR_PREFIX required when CONFIG_FILE_PREFIX is set" >&2 - exit 1 - fi - CONFIG_FILE_NAME="${CONFIG_FILE_PREFIX}${CONFIG_PREFIX}.json" - CONFIG_ENV_VAR="${CONFIG_ENV_VAR_PREFIX}_${CONFIG_PREFIX^^}_CONFIG" -else - CONFIG_FILE_NAME=".mcp-${CONFIG_PREFIX}.json" - CONFIG_ENV_VAR="MCP_${CONFIG_PREFIX^^}_CONFIG" -fi +CONFIG_FILE_NAME=".mcp-${CONFIG_PREFIX}.json" +CONFIG_ENV_VAR="MCP_${CONFIG_PREFIX^^}_CONFIG" CONFIG_ENV_VAR="${CONFIG_ENV_VAR//-/_}" # Configuration locations relative to PROJECT_ROOT @@ -65,6 +50,19 @@ CONFIG_LOCATIONS=( ) _CONFIG_TEMP_FILE="" +CONFIG_LOAD_ERROR="" + +# Refuses a config file that does not hold one JSON object. +# Args: $1 = config file +# Sets: CONFIG_LOAD_ERROR to the logged cause on failure +# Returns: 0 when the file holds a JSON object, 1 otherwise +_config_assert_object() { + if ! jq -e 'type == "object"' "$1" >/dev/null 2>&1; then + CONFIG_LOAD_ERROR="$1 does not hold a JSON object: a config file must be valid JSON whose top-level value is an object" + log "ERROR" "${CONFIG_LOAD_ERROR}" + return 1 + fi +} # Removes the merged-config temp file _merge_configs created, if any. # Installed below as the module's own EXIT trap; a caller whose EXIT trap @@ -77,25 +75,32 @@ config_cleanup() { } trap config_cleanup EXIT +# Called directly, not in a command substitution, so the EXIT trap sees _CONFIG_TEMP_FILE. # Args: config file paths (merge order, later wins) -# Returns: path to temp file with merged JSON +# Sets: LINT_CONFIG_FILE and _CONFIG_TEMP_FILE to the temp file on success; +# CONFIG_LOAD_ERROR to the logged cause on failure +# Returns: 0 on success, 1 otherwise _merge_configs() { - local temp_file - temp_file=$(mktemp) - _CONFIG_TEMP_FILE="${temp_file}" + # Each file is checked on its own so the refusal names the one at fault. + local config_file + for config_file in "$@"; do + _config_assert_object "${config_file}" || return 1 + done - # Start with first file local merged merged=$(cat "$1") shift # Deep merge remaining files (jq -s '.[0] * .[1]' merges recursively) for config_file in "$@"; do - merged=$(echo "${merged}" | jq -s '.[0] * .[1]' - "${config_file}") + merged=$(jq -s '.[0] * .[1]' - "${config_file}" <<< "${merged}") done - echo "${merged}" > "${temp_file}" - echo "${temp_file}" + local temp_file + temp_file=$(mktemp) + _CONFIG_TEMP_FILE="${temp_file}" + printf '%s\n' "${merged}" > "${temp_file}" + LINT_CONFIG_FILE="${temp_file}" } # Sets: _FOUND_CONFIGS array with absolute paths @@ -113,7 +118,9 @@ _discover_configs() { } # Load and merge configuration -# Sets: LINT_CONFIG_FILE (path to config file, possibly merged temp file) +# Sets: LINT_CONFIG_FILE (path to config file, possibly merged temp file); +# CONFIG_LOAD_ERROR (empty unless the override file is missing or a +# config file does not hold a JSON object) # Args: $1 = project root directory # Returns: 0 on success, 1 on error (logs error message) # @@ -124,17 +131,21 @@ _discover_configs() { # Error conditions: # - Environment variable set but file doesn't exist # - No config files found at any location +# - The override file or a discovered file does not hold a JSON object load_config() { local project_root="$1" + CONFIG_LOAD_ERROR="" local env_value="${!CONFIG_ENV_VAR:-}" if [[ -n "${env_value}" ]]; then log "INFO" "Using config from environment variable ${CONFIG_ENV_VAR}: ${env_value}" if [[ ! -f "${env_value}" ]]; then - log "ERROR" "Config file from ${CONFIG_ENV_VAR} not found: ${env_value}" + CONFIG_LOAD_ERROR="Config file from ${CONFIG_ENV_VAR} not found: ${env_value}" + log "ERROR" "${CONFIG_LOAD_ERROR}" return 1 fi + _config_assert_object "${env_value}" || return 1 LINT_CONFIG_FILE="${env_value}" export LINT_CONFIG_FILE @@ -152,11 +163,14 @@ load_config() { fi if [[ ${#_FOUND_CONFIGS[@]} -eq 1 ]]; then + _config_assert_object "${_FOUND_CONFIGS[0]}" || return 1 LINT_CONFIG_FILE="${_FOUND_CONFIGS[0]}" log "INFO" "Using single config: ${LINT_CONFIG_FILE}" else log "INFO" "Merging ${#_FOUND_CONFIGS[@]} config files" - LINT_CONFIG_FILE=$(_merge_configs "${_FOUND_CONFIGS[@]}") + if ! _merge_configs "${_FOUND_CONFIGS[@]}"; then + return 1 + fi log "INFO" "Merged config created: ${LINT_CONFIG_FILE}" fi diff --git a/plugins/dev-tooling/shared/docker-compose.sh b/plugins/dev-tooling/shared/docker-compose.sh index 48731af7..4a409c62 100644 --- a/plugins/dev-tooling/shared/docker-compose.sh +++ b/plugins/dev-tooling/shared/docker-compose.sh @@ -58,6 +58,31 @@ _compose_run() { ( cd "${PROJECT_ROOT}" && eval "${invocation}" ) } +# Keeps compose's stderr warnings off stdout, which the callers parse as JSON. +# Args: $1 = the docker compose invocation to run +# Stdout: its stdout; on failure followed by its stderr +# Returns: the invocation's own status +_compose_run_capture() { + local invocation="$1" + + local stderr_file + stderr_file=$(mktemp) || return 1 + + local stdout_text stderr_text status=0 + stdout_text=$(_compose_run "${invocation}" 2>"${stderr_file}") || status=$? + stderr_text=$(<"${stderr_file}") + rm -f -- "${stderr_file}" + + if [[ "${status}" -ne 0 ]]; then + if [[ -n "${stdout_text}" ]]; then + printf '%s\n' "${stdout_text}" + fi + printf '%s\n' "${stderr_text}" + return "${status}" + fi + printf '%s\n' "${stdout_text}" +} + # Verify docker and docker compose are available. # Returns: 0 on success, 1 with error message on stdout on failure _compose_check_prerequisites() { @@ -87,7 +112,7 @@ _compose_resolve_container() { base_cmd=$(_compose_cmd) local ps_output - ps_output=$(_compose_run "${base_cmd} ps --format json --status running" 2>&1) || { + ps_output=$(_compose_run_capture "${base_cmd} ps --format json --status running") || { echo "Failed to query running containers: ${ps_output}" return 1 } @@ -110,7 +135,7 @@ _compose_resolve_container() { # no longer there, and a call refused by it would otherwise be told the # service is not running while the real reason never reaches the caller. local config_output - config_output=$(_compose_run "${base_cmd} config --format json" 2>&1) || { + config_output=$(_compose_run_capture "${base_cmd} config --format json") || { echo "Service '${COMPOSE_SERVICE}' is not running. Start it with: docker compose up -d ${COMPOSE_SERVICE}${config_output:+ The compose config read said: ${config_output}}" return 1 } @@ -242,7 +267,7 @@ _compose_resolve_workdir_for() { base_cmd=$(_compose_cmd) local config_output - config_output=$(_compose_run "${base_cmd} config --format json" 2>&1) || { + config_output=$(_compose_run_capture "${base_cmd} config --format json") || { echo "Failed to read compose config: ${config_output}" return 1 } diff --git a/plugins/dev-tooling/shared/environment.sh b/plugins/dev-tooling/shared/environment.sh index 3c845116..1d05c086 100644 --- a/plugins/dev-tooling/shared/environment.sh +++ b/plugins/dev-tooling/shared/environment.sh @@ -48,6 +48,7 @@ _get_config_value() { # deriving a second configuration does not have to rebind the global first. # Args: $1 = config file, $2 = jq path, $3 = default # Stdout: the value, or the default +# Returns: 1 when jq cannot evaluate the field _config_value_from() { local config_file="$1" local path="$2" @@ -56,7 +57,10 @@ _config_value_from() { [[ -f "${config_file}" ]] || { echo "${default}"; return 0; } local value - value=$(jq -r "${path} // empty" "${config_file}" 2>/dev/null || echo "") + if ! value=$(jq -r "${path} // empty" "${config_file}" 2>&1); then + printf '%s\n' "Config error: jq could not evaluate ${path} against ${config_file}: ${value}" >&2 + return 1 + fi [[ -n "${value}" ]] && echo "${value}" || echo "${default}" } @@ -72,10 +76,20 @@ detect_environment() { exit 1 fi + local config_label + config_label=$(_config_label "${LINT_CONFIG_FILE}") + local env_value env_value=$(jq -r '.environment // empty' "${LINT_CONFIG_FILE}" 2>/dev/null || echo "") if [[ -z "${env_value}" ]]; then - log "ERROR" "Missing 'environment' field in ${LINT_CONFIG_FILE}" + log "ERROR" "Missing 'environment' field in ${config_label}" + exit 1 + fi + + # _set_workdir_from_config refuses an unknown name too, but only on stderr; + # this refusal goes through log, so the server log names the value as well. + if [[ "${env_value}" != "native" ]] && ! _env_is_container_environment "${env_value}"; then + log "ERROR" "${config_label} declares environment \"${env_value}\", which this server does not recognize. Known environments: native, docker, docker-compose, vagrant, ddev." exit 1 fi @@ -86,7 +100,7 @@ detect_environment() { # not the JSON-RPC stream, so the exit below is what stops the server with a # log line rather than with a malformed protocol frame. if ! _set_workdir_from_config "${project_root}" "${LINT_CONFIG_FILE}" "${LINT_ENV}"; then - log "ERROR" "Could not derive the environment from ${LINT_CONFIG_FILE}: a field it needs is missing or empty. The refusal above names it." + log "ERROR" "Could not derive the environment from ${config_label}: a field it needs is missing or empty. The refusal above names it." exit 1 fi @@ -94,6 +108,21 @@ detect_environment() { return 0 } +# How a refusal names a configuration file. A merged configuration is a temp +# file removed on exit, so it is named by the files it was merged from. +# Args: $1 = config file +# Stdout: the label +_config_label() { + local config_file="$1" + + if [[ -n "${_CONFIG_TEMP_FILE:-}" && "${config_file}" == "${_CONFIG_TEMP_FILE}" ]]; then + printf '%s\n' "the configuration merged from ${_FOUND_CONFIGS[*]:-}" + return 0 + fi + + printf '%s\n' "${config_file}" +} + # The container name the docker environment runs commands in. # A refusal goes to stderr rather than stdout: this is reached from # detect_environment at startup, where stdout is the JSON-RPC stream. @@ -107,7 +136,7 @@ _get_docker_container() { container=$(jq -r '.docker.container // empty' "${config_file}" 2>/dev/null || echo "") if [[ -z "${container}" ]]; then - printf '%s\n' "Refusing to run: the \"docker\" environment requires a container name in \"${config_file}\", and the field \".docker.container\" is missing or empty." >&2 + printf '%s\n' "Refusing to run: the \"docker\" environment requires a container name in $(_config_label "${config_file}"), and the field \".docker.container\" is missing or empty." >&2 return 1 fi @@ -160,7 +189,7 @@ _set_workdir_from_config() { case "${environment}" in docker) - workdir=$(_config_value_from "${config_file}" ".docker.workdir" "/var/www/html") + workdir=$(_config_value_from "${config_file}" ".docker.workdir" "/var/www/html") || return 1 if ! container=$(_get_docker_container "${config_file}"); then return 1 fi @@ -168,20 +197,26 @@ _set_workdir_from_config() { docker-compose) _ensure_compose_module || return 1 # Read config values — no CLI calls at startup - compose_service=$(_config_value_from "${config_file}" '."docker-compose".service' "web") - compose_workdir=$(_config_value_from "${config_file}" '."docker-compose".workdir' "") - compose_file=$(_config_value_from "${config_file}" '."docker-compose".file' "") + compose_service=$(_config_value_from "${config_file}" '."docker-compose".service' "web") || return 1 + compose_workdir=$(_config_value_from "${config_file}" '."docker-compose".workdir' "") || return 1 + compose_file=$(_config_value_from "${config_file}" '."docker-compose".file' "") || return 1 workdir="(resolved at call time)" ;; vagrant) - workdir=$(_config_value_from "${config_file}" ".vagrant.workdir" "/vagrant") + workdir=$(_config_value_from "${config_file}" ".vagrant.workdir" "/vagrant") || return 1 ;; ddev) - workdir=$(_config_value_from "${config_file}" ".ddev.workdir" "/var/www/html") + workdir=$(_config_value_from "${config_file}" ".ddev.workdir" "/var/www/html") || return 1 ;; - native|*) + native) workdir="${project_root}" ;; + *) + # The name selects how every later command is wrapped, and one no + # wrapper knows would run them on the host as though it were native. + printf '%s\n' "Refusing to run: $(_config_label "${config_file}") declares environment \"${environment}\", which this server does not recognize. Known environments: native, docker, docker-compose, vagrant, ddev." >&2 + return 1 + ;; esac LINT_WORKDIR="${workdir}" @@ -445,7 +480,7 @@ resolve_env_workdir() { local base suffix case "${LINT_ENV}" in docker|vagrant|ddev) - base=$(_env_configured_workdir "${LINT_ENV}") + base=$(_env_configured_workdir "${LINT_ENV}") || return 1 if ! suffix=$(_env_relative_suffix "${host_root}" "${launch_base}"); then printf '%s\n' "${suffix}" return 1 @@ -568,19 +603,20 @@ wrap_command() { echo "vagrant ssh -c 'cd ${workdir} && ${cmd}'" ;; ddev) - if [[ -n "${scoped}" ]] || _env_targets_worktree; then - # A call targeting a worktree runs against a directory ddev does - # not know as its project root, so the resolved workdir has to - # be named; -d is how ddev's exec takes one. A launch-root call - # keeps the argv below, which is the ddev default. + if [[ -n "${scoped}" ]] || _env_targets_worktree \ + || [[ "${LINT_WORKDIR}" != "/var/www/html" ]]; then + # A scoped call, a call targeting a worktree, and a ddev.workdir + # other than ddev's default /var/www/html all run in a directory + # ddev would not pick, so the resolved workdir has to be named; + # -d is how ddev's exec takes one. A launch-root call at the + # default keeps the argv below. # - # The composer shortcut stays inside the launch-root branch and - # deliberately does not cover a worktree call: `ddev composer` + # The composer shortcut stays inside the default branch and + # deliberately does not cover these calls: `ddev composer` # re-execs composer at ddev's own project root and takes no -d, - # so routing a worktree call through it would run the command - # against the launch tree and have the result attributed to the - # worktree. A worktree call names the workdir and reaches the - # composer binary directly instead. + # so routing one through it would run the command in the wrong + # directory. Naming the workdir reaches the composer binary + # directly instead. echo "ddev exec -d \"${workdir}\" ${cmd}" elif [[ "${cmd}" == composer* ]]; then echo "ddev ${cmd}" @@ -603,10 +639,10 @@ wrap_command() { # wrap into the command is inside the container or guest, the local process # cannot enter it, and their wrappers still carry their own cd. # -# The gate names those four rather than testing for "native", because -# detect_environment applies no allowlist — it assigns whatever ".environment" -# holds straight into LINT_ENV — so a typo such as "nativ" or an unsupported -# name such as "podman" falls through both wrappers to a command that runs +# The gate names those four rather than testing for "native", because a caller +# that sets LINT_ENV without going through detect_environment — which refuses +# any name outside native and the container environments — can hand it a name +# such as "podman" that falls through both wrappers to a command that runs # locally, against the host path _set_workdir_from_config gave it. Testing for # "native" would leave exactly that case with no directory entered, which is the # one shape that would force a workdir back into a command string. @@ -933,30 +969,19 @@ wrap_npm_command() { echo "vagrant ssh -c 'cd ${workdir} && ${cmd}'" ;; ddev) - # DDEV has native npm/yarn commands that handle workdir automatically - if _env_targets_worktree; then - # The launch-root shortcuts below run ddev against ddev's own - # project root. A worktree is a different directory, so the JS - # working directory is named instead, and -d is how ddev's exec - # takes one. - echo "ddev exec -d \"${workdir}\" ${cmd}" - elif [[ "${cmd}" == npm* ]]; then - local npm_args="${cmd#npm }" - echo "cd ${workdir} && ddev npm ${npm_args}" - elif [[ "${cmd}" == yarn* ]]; then - local yarn_args="${cmd#yarn }" - echo "cd ${workdir} && ddev yarn ${yarn_args}" - else - echo "cd ${workdir} && ddev exec ${cmd}" - fi + # The JS working directory is a container path, so it is named to + # ddev (-d is how ddev's exec takes one) for a launch-root call and + # a worktree call alike. A host-side `cd` into it would enter a + # directory that does not exist on the host. + echo "ddev exec -d \"${workdir}\" ${cmd}" ;; *) log "ERROR" "Unknown environment: ${LINT_ENV}" # Bare, matching wrap_command's own unknown-environment branch and - # the native branch above. detect_environment applies no allowlist, - # so this branch is reachable from a typo in the config, and the - # command it emits runs locally — which makes the workdir - # exec_npm_command enters the right one. Emitting `cd "${workdir}"` + # the native branch above. detect_environment refuses an unknown + # name, so this branch is reachable only from a caller that sets + # LINT_ENV itself, and the command it emits runs locally — which + # makes the workdir exec_npm_command enters the right one. Emitting `cd "${workdir}"` # here instead would not be safe merely by being quoted: a "$" or a # backtick stays live inside double quotes, and the string reaches # an eval. @@ -966,9 +991,12 @@ wrap_npm_command() { } # Execute npm command in detected environment +# With $2 stderr goes to that file, so a caller that parses the output sees stdout alone. # Args: $1 = command +# $2 = optional file that receives the command's stderr exec_npm_command() { local cmd="$1" + local stderr_file="${2:-}" local wrapped_cmd wrapped_cmd=$(wrap_npm_command "${cmd}") || { echo "${wrapped_cmd}" @@ -987,7 +1015,9 @@ exec_npm_command() { # get_js_workdir is re-read here rather than taken from wrap_npm_command, # which no longer emits it. Under a non-native environment the value it # returns is a container path and _enter_command_workdir discards it. - output=$(_enter_command_workdir "$(get_js_workdir)" && eval "${wrapped_cmd}" &1) || exit_code=$? + # + # Without a file, stderr joins stdout: /dev/stdout is the capture pipe here. + output=$(_enter_command_workdir "$(get_js_workdir)" && eval "${wrapped_cmd}" "${stderr_file:-/dev/stdout}") || exit_code=$? output=$(printf '%s' "${output}" | _filter_env_noise) log "INFO" "Command exit code: ${exit_code}" @@ -1017,12 +1047,18 @@ npm_script_body() { return 2 fi - local raw + # stderr is kept apart: an npm or container-client warning would fail the shape check. + local stderr_file + stderr_file=$(mktemp) || return 2 + + local raw stderr_text local exit_code=0 - raw=$(exec_npm_command "npm pkg get $(shell_quote_arg "scripts.${script_name}")") || exit_code=$? + raw=$(exec_npm_command "npm pkg get $(shell_quote_arg "scripts.${script_name}")" "${stderr_file}") || exit_code=$? + stderr_text=$(<"${stderr_file}") + rm -f -- "${stderr_file}" if [[ "${exit_code}" -ne 0 ]]; then - log "ERROR" "npm_script_body: probe for \"${script_name}\" failed: ${raw}" + log "ERROR" "npm_script_body: probe for \"${script_name}\" failed: ${raw}${raw:+${stderr_text:+ }}${stderr_text}" return 2 fi @@ -1034,7 +1070,7 @@ npm_script_body() { fi if [[ "${raw}" != '"'*'"' ]]; then - log "ERROR" "npm_script_body: unexpected npm pkg get output for \"${script_name}\": ${raw}" + log "ERROR" "npm_script_body: unexpected npm pkg get output for \"${script_name}\": ${raw}${raw:+${stderr_text:+ }}${stderr_text}" return 2 fi diff --git a/plugins/dev-tooling/shared/js_paths.sh b/plugins/dev-tooling/shared/js_paths.sh new file mode 100644 index 00000000..0ad62ed2 --- /dev/null +++ b/plugins/dev-tooling/shared/js_paths.sh @@ -0,0 +1,325 @@ +#!/usr/bin/env bash +# Path-scoped runs of a JS package's own linter binary, for the JS MCP servers: +# Admin Prettier and Stylelint, Storefront Stylelint, and the Admin and +# Storefront ESLint binary probe and package-path rebase. Also the Stylelint +# check that refuses a second config on an aggregate script. +# +# Owned by dev-tooling. Not templated — do not add it to the mapping in +# .cursor/rules/template-sync.mdc. +# +# A path-scoped run executes the package's own binary through `npm exec --no`, +# never the aggregate npm script: npm appends `--` arguments after the script +# body's own targets, so a path appended to the aggregate widens the run to +# those targets and cannot narrow it. +# +# Requires: exec_npm_command(), shell_quote_arg() and assert_paths_lintable() +# from environment.sh, LINT_ENV, SCOPE_NAME, SCOPE_CWD, jq. + +# Rebase a caller path onto the package directory the linter runs in. Unscoped, +# the package lies below the marker, so the path is stripped through it. Under a +# scope the package is the scope cwd: a leading "./" comes off the path, then a +# leading "/" is stripped, otherwise the first "//" of an absolute +# path. A path naming the cwd itself — relative, or absolute ending in "/" +# — is the package, and an empty result prints as ".". A path carrying no cwd +# prefix passes through. +# Globals: SCOPE_CWD (read) +# Args: $1 = package marker including its trailing slash, $2 = caller path +# Stdout: the path relative to the package directory, or "." for the package itself +js_rebase_package_path() { + local marker="$1" + local path="$2" + + if [[ -z "${SCOPE_CWD:-}" ]]; then + if [[ "${path}" == *"${marker}"* ]]; then + path="${path#*"${marker}"}" + fi + [[ -z "${path}" ]] && path="." + printf '%s\n' "${path}" + return 0 + fi + + local cwd="${SCOPE_CWD#./}" + while [[ "${cwd}" == */ ]]; do + cwd="${cwd%/}" + done + if [[ -z "${cwd}" ]]; then + printf '%s\n' "${path}" + return 0 + fi + + path="${path#./}" + if [[ "${path}" == "${cwd}/"* ]]; then + path="${path#"${cwd}/"}" + elif [[ "${path}" == "${cwd}" ]]; then + path="" + elif [[ "${path}" == /* && "${path}" == *"/${cwd}" ]]; then + path="" + elif [[ "${path}" == /* && "${path}" == *"/${cwd}/"* ]]; then + path="${path#*"/${cwd}/"}" + fi + [[ -z "${path}" ]] && path="." + printf '%s\n' "${path}" +} + +# Refuse to append a scope config to an aggregate script whose own linter +# command already passes one: the linter accepts its config option only once. +# Args: $1 = tool name, $2 = linter name, $3 = binary, $4 = aggregate npm +# script, $5 = its body, $6 = scope-configured config (may be empty) +# Stdout: the refusal +# Returns: 0 when no scope config is set or the body passes no config, 1 otherwise +js_refuse_second_config() { + local tool_name="$1" + local linter="$2" + local binary="$3" + local aggregate="$4" + local body="$5" + local scoped_config="$6" + + if [[ -z "${scoped_config}" ]]; then + return 0 + fi + + local -a words=() + read -r -a words <<< "${body}" + local word in_command=0 + for word in "${words[@]+"${words[@]}"}"; do + if [[ "${in_command}" -eq 0 ]]; then + if [[ "${word}" == "${binary}" || "${word}" == */"${binary}" ]]; then + in_command=1 + fi + continue + fi + case "${word}" in + "&&") + in_command=0 + ;; + --config|--config=*|-c|-c=*) + printf '%s\n' "Refusing to run ${tool_name}: scope \"${SCOPE_NAME}\" selects the ${linter} config \"${scoped_config}\", but npm script \"${aggregate}\" already passes its own config to ${binary}: \"${body}\". ${linter} accepts its config option only once, so the appended one cannot apply. Pass paths so the run executes ${linter} on them directly." + return 1 + ;; + esac + done + return 0 +} + +# True when the path is a glob pattern the linter expands itself. The existence +# probe cannot resolve a glob, so a glob skips it. +# Args: $1 = caller-supplied path +js_path_is_glob() { + case "$1" in + *"*"*|*"?"*|*"["*) return 0 ;; + esac + return 1 +} + +# Refuse a path-scoped run when the package's own binary is not executable in +# node_modules/.bin where the command runs: `npm exec --no` installs nothing, +# but runs a global binary of the same name when the package has none. Probe +# exit 3 means the binary is missing, and the probe then prints the directory +# it ran in, under a container the container's path; any other non-zero exit +# means the probe itself failed. +# Args: $1 = tool name, $2 = binary, $3 = aggregate npm script, named in the +# refusal +# Stdout: the refusal +# Returns: 0 when the binary is executable, 1 otherwise +js_assert_local_binary() { + local tool_name="$1" + local binary="$2" + local aggregate="$3" + local bin_path="node_modules/.bin/${binary}" + + local probe="test -x ${bin_path} || { echo LOCAL_BINARY_MISSING_IN; pwd; exit 3; }" + local output + local probe_code=0 + output=$(exec_npm_command "npm exec --no -c $(shell_quote_arg "${probe}")") || probe_code=$? + if [[ "${probe_code}" -eq 0 ]]; then + return 0 + fi + + if [[ "${probe_code}" -eq 3 && "${output}" == *LOCAL_BINARY_MISSING_IN$'\n'* ]]; then + local package_dir="${output##*LOCAL_BINARY_MISSING_IN$'\n'}" + package_dir="${package_dir%%$'\n'*}" + printf '%s\n' "Refusing to run ${tool_name} with paths: \"${bin_path}\" is not installed in the package directory \"${package_dir}\". A path-scoped run executes only the package's own ${binary} binary: it installs none and uses no global one, and the aggregate \"${aggregate}\" script is not a substitute, because its own targets would widen the run. Run \`npm ci\` in that directory, or call worktree_prepare on this server for a worktree." + return 1 + fi + + printf '%s\n' "Refusing to run ${tool_name} with paths: could not check whether the package's own ${binary} binary is installed; the probe exited with ${probe_code}.${output:+ Probe output: ${output}}" + return 1 +} + +# Print, one per line, the literal paths that name directories. A path without +# an accepted extension passed the lintable probe only as a directory; one with +# an accepted extension may still be a directory, so those are tested where the +# command runs. +# Args: $1 = tool name, $2 = space-separated accepted extensions, +# $3.. = literal paths that passed the lintable probe +# Stdout: the directories, or the refusal +# Returns: 0 on success, 1 when the test could not run +js_path_directories() { + local tool_name="$1" + local -a extensions=() + read -r -a extensions <<< "$2" + shift 2 + + local -a directories=() + local p ext named script="" + for p in "$@"; do + named=0 + for ext in "${extensions[@]}"; do + if [[ "${p}" == *".${ext}" ]]; then + named=1 + fi + done + if [[ "${named}" -eq 0 ]]; then + directories+=("${p}") + else + script="${script}[ -d $(shell_quote_arg "${p}") ] && echo DIRECTORY:$(shell_quote_arg "${p}"); " + fi + done + + if [[ -n "${script}" ]]; then + local output + local probe_code=0 + output=$(exec_npm_command "npm exec --no -c $(shell_quote_arg "${script}true")") || probe_code=$? + if [[ "${probe_code}" -ne 0 ]]; then + printf '%s\n' "Refusing to run ${tool_name} with paths: could not check which of them are directories; the probe exited with ${probe_code}.${output:+ Probe output: ${output}}" + return 1 + fi + local line + while IFS= read -r line; do + if [[ "${line}" == DIRECTORY:* ]]; then + directories+=("${line#DIRECTORY:}") + fi + done <<< "${output}" + fi + + if [[ ${#directories[@]} -gt 0 ]]; then + printf '%s\n' "${directories[@]}" + fi +} + +# The pattern a directory reaches the linter as: the linter reads every file +# type it supports below a directory, so the directory is narrowed to the +# accepted extensions. The caller's quoting keeps the pattern away from the +# shell, so the linter expands it. +# Args: $1 = directory path, $2 = glob below it, e.g. "**/*.scss" +# Stdout: the pattern +js_directory_pattern() { + local path="$1" + + while [[ "${path}" == */ && "${path}" != "/" ]]; do + path="${path%/}" + done + printf '%s\n' "${path}/$2" +} + +# Refuse glob patterns and directories under ddev: the command +# reaches `ddev exec`, which re-parses it in the container's bash without +# quoting a value that holds no space, tab or "#", so that bash +# would expand the pattern itself, without globstar, before the linter sees it. +# A value holding one of those characters is quoted again and reaches the +# linter intact. A double quote never reaches here: parse_paths_json already +# refuses it under ddev. +# Args: $1 = tool name, $2 = linter name for the refusal, +# $3.. = the caller's glob patterns and directories +# Stdout: the refusal +# Returns: 0 when every such path is re-quoted or the environment is not ddev, +# 1 otherwise +js_assert_no_pattern_under_ddev() { + local tool_name="$1" + local linter="$2" + shift 2 + + if [[ "${LINT_ENV:-}" != "ddev" ]]; then + return 0 + fi + + local -a expanded=() + local p + for p in "$@"; do + if [[ "${p}" != *[\ $'\t'\#]* ]]; then + expanded+=("${p}") + fi + done + if [[ ${#expanded[@]} -eq 0 ]]; then + return 0 + fi + + printf '%s\n' "Refusing to run ${tool_name} with paths: under ddev these paths would reach ${linter} as glob patterns the container shell expands first: ${expanded[*]}. Pass file paths instead." + return 1 +} + +# Check the caller's paths for a path-scoped run and turn them into the +# linter's targets, each shell-quoted, with a directory narrowed to the +# directory glob. +# Args: $1 = tool name, $2 = binary, $3 = aggregate npm script, +# $4 = space-separated accepted extensions, $5 = directory glob, +# $6 = linter name for refusals, $7 = paths JSON array +# Stdout: the targets joined by spaces, or the refusal +# Returns: 0 on success, 1 on a refusal +js_path_scoped_targets() { + local tool_name="$1" + local binary="$2" + local aggregate="$3" + local extension_list="$4" + local directory_glob="$5" + local linter="$6" + local paths_json="$7" + + local -a supplied=() + local -a literals=() + local p + while IFS= read -r p; do + if [[ -z "${p}" ]]; then + continue + fi + supplied+=("${p}") + if ! js_path_is_glob "${p}"; then + literals+=("${p}") + fi + done < <(printf '%s\n' "${paths_json}" | jq -r '.[]') + + js_assert_local_binary "${tool_name}" "${binary}" "${aggregate}" || return 1 + + local -a directories=() + if [[ ${#literals[@]} -gt 0 ]]; then + local report + if ! report=$(assert_paths_lintable "." "${extension_list}" "${literals[@]}"); then + printf '%s\n' "${report}" + return 1 + fi + if ! report=$(js_path_directories "${tool_name}" "${extension_list}" "${literals[@]}"); then + printf '%s\n' "${report}" + return 1 + fi + while IFS= read -r p; do + if [[ -n "${p}" ]]; then + directories+=("${p}") + fi + done <<< "${report}" + fi + + local -a patterns=() + for p in "${supplied[@]}"; do + if js_path_is_glob "${p}"; then + patterns+=("${p}") + fi + done + js_assert_no_pattern_under_ddev "${tool_name}" "${linter}" \ + "${patterns[@]+"${patterns[@]}"}" "${directories[@]+"${directories[@]}"}" || return 1 + + local -a quoted=() + local target directory + for p in "${supplied[@]}"; do + target="${p}" + for directory in "${directories[@]+"${directories[@]}"}"; do + if [[ "${directory}" == "${p}" ]]; then + target=$(js_directory_pattern "${p}" "${directory_glob}") + break + fi + done + quoted+=("$(shell_quote_arg "${target}")") + done + + printf '%s\n' "${quoted[*]}" +} diff --git a/plugins/dev-tooling/shared/launch.sh b/plugins/dev-tooling/shared/launch.sh new file mode 100644 index 00000000..8455ab00 --- /dev/null +++ b/plugins/dev-tooling/shared/launch.sh @@ -0,0 +1,95 @@ +#!/usr/bin/env bash +# Launch mode of a dev-tooling MCP server: bound to the project root it was +# started in, or unbound because the host started it in this plugin's own +# directory. Cursor starts a server in the session's project directory. A +# server whose launch root is this plugin starts unbound: initialize and +# tools/list work, and every tool refuses until set_project_root binds a +# project (worktree.sh). +# +# Owned by dev-tooling. Not templated — do not add it to the mapping in +# .cursor/rules/template-sync.mdc. +# +# Requires: PROJECT_ROOT and MCP_CONFIG_FILE set by server.sh; log() from +# mcpserver_core.sh. Sourced after config.sh and before load_config. +# +# Public: +# launch_is_bound - true unless the server started unbound +# launch_path_in_plugin_root - true when a canonical path is the +# plugin root or inside it +# launch_anchor_config_override - makes a relative MCP__CONFIG +# absolute against a directory +# +# Globals set at source time: +# LAUNCH_MODE - "bound" or "unbound" +# LAUNCH_PLUGIN_ROOT - this plugin's root, canonical +# LAUNCH_SERVER_NAME - the server's name from its config.json; unbound only +# PROJECT_ROOT, LINT_CONFIG_FILE - exported empty when unbound + +set -euo pipefail +shopt -s inherit_errexit 2>/dev/null || true # Bash 4.4+ + +LAUNCH_PLUGIN_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)" +LAUNCH_SERVER_NAME="" +LAUNCH_MODE="bound" + +# launch_path_in_plugin_root +# Args: $1 = a path already resolved with `pwd -P` +# Returns: 0 when it is the plugin root or sits under it, 1 otherwise +launch_path_in_plugin_root() { + local path="$1" + [[ "${path}" == "${LAUNCH_PLUGIN_ROOT}" || "${path}" == "${LAUNCH_PLUGIN_ROOT}/"* ]] +} + +# launch_anchor_config_override +# Makes a relative config-variable override absolute against . A +# relative value only names a file from the directory the server read it in, +# and a call that enters a worktree, or the dispatch subshell of a later call +# that starts from the host's environment again, is somewhere else — the +# project's configuration would be dropped without a word. The caller picks the +# directory the value was meant against and repeats the call wherever the +# environment is rebuilt. +# Args: $1 = the directory, physical form +# Globals: reads and assigns the variable CONFIG_ENV_VAR names +launch_anchor_config_override() { + local name="${CONFIG_ENV_VAR:-}" + if [[ -z "${name}" ]]; then + return 0 + fi + local value="${!name:-}" + if [[ -n "${value}" && "${value}" != /* ]]; then + printf -v "${name}" '%s' "$1/${value}" + fi +} + +# launch_is_bound +# Returns: 0 when the server started bound to a project root, 1 when unbound +launch_is_bound() { + [[ "${LAUNCH_MODE}" == "bound" ]] +} + +# A root that does not resolve stays bound, so startup refuses it exactly as +# before. MCP__CONFIG is deliberately not consulted: it names a +# configuration file, not a project, and honoring it here would make the +# plugin directory the root every tool runs in. The bind honors it instead. +_launch_canonical_root="" +_launch_canonical_root=$(cd "${PROJECT_ROOT}" >/dev/null 2>&1 && pwd -P) || _launch_canonical_root="" +if [[ -n "${_launch_canonical_root}" ]] && launch_path_in_plugin_root "${_launch_canonical_root}"; then + LAUNCH_MODE="unbound" + + # The name the refusal tells the caller to call set_project_root on. + LAUNCH_SERVER_NAME=$(jq -r '.serverInfo.name // empty' "${MCP_CONFIG_FILE}" 2>/dev/null) || LAUNCH_SERVER_NAME="" + if [[ -z "${LAUNCH_SERVER_NAME}" ]]; then + log "ERROR" "Cannot read .serverInfo.name from ${MCP_CONFIG_FILE}" + exit 1 + fi + + PROJECT_ROOT="" + LINT_CONFIG_FILE="" + export PROJECT_ROOT LINT_CONFIG_FILE + + log "INFO" "${LAUNCH_SERVER_NAME} starting without a project root: launched in its plugin directory ${LAUNCH_PLUGIN_ROOT}. Every tool refuses until set_project_root binds one." +else + # Anchored to the project root, which is not the process's directory when a host names it in PROJECT_ROOT. + launch_anchor_config_override "${_launch_canonical_root:-$(pwd -P)}" +fi +unset _launch_canonical_root diff --git a/plugins/dev-tooling/shared/mcp-js-tooling.schema.json b/plugins/dev-tooling/shared/mcp-js-tooling.schema.json index 41282e27..1f178ead 100644 --- a/plugins/dev-tooling/shared/mcp-js-tooling.schema.json +++ b/plugins/dev-tooling/shared/mcp-js-tooling.schema.json @@ -79,7 +79,7 @@ }, "default_scope": { "type": "string", - "description": "Scope name used when a tool is called without an explicit scope argument." + "description": "Scope name used when a scope-aware tool is called without an explicit scope argument. lint_all, lint_twig, unit_setup, vite_build, webpack_build and vitest_run ignore it and run against the core package; ludtwig_check and ludtwig_fix take no scope at all and always run there." }, "scopes": { "type": "object", diff --git a/plugins/dev-tooling/shared/scope.sh b/plugins/dev-tooling/shared/scope.sh index 5c27c6b5..1db65322 100644 --- a/plugins/dev-tooling/shared/scope.sh +++ b/plugins/dev-tooling/shared/scope.sh @@ -6,16 +6,42 @@ # # Requires: LINT_CONFIG_FILE must be set and exported before sourcing. # Requires: log() function (from mcpserver_core.sh). +# Requires: exec_command(), assert_no_shell_hostile_chars() and +# shell_quote_arg() (from environment.sh). +# Requires: worktree_assert_dependencies() (from worktree.sh). # # Public: # scope_validate - called once at server start; fails hard on -# reserved-name or missing-default violations +# reserved-name or missing-default violations, +# and on a configuration jq cannot evaluate # resolve_scope - resolves scope from arg | default_scope | "shopware" # sets globals: SCOPE_NAME, SCOPE_CWD -# returns 1 and prints error on undeclared scope +# returns 1 and prints error on an undeclared scope, +# a config file that does not exist or is not a +# JSON object, and a config jq cannot evaluate # scope_get_tool_field -# - echoes scope.. or empty -# scope_get_bootstrap - echoes scope..bootstrap[] one per line +# - echoes scope.. or empty; returns 1 +# and prints error when jq cannot evaluate the field +# scope_tool_field_or_refuse +# - sets to scope..; returns 1 +# and prints the refusal on stdout +# scope_config_arg_or_refuse