From ff0d2c777e73d784d2973782f3436fd96a2369da Mon Sep 17 00:00:00 2001 From: Veronika Golska Date: Tue, 24 Nov 2026 08:38:32 +0100 Subject: [PATCH] - Reduce always-loaded text in skills, rules and agents - Shorten the 41 skill descriptions to 175-190 characters (27,697 -> 7,541 in total) - Move the csv.php and validate.php command reference into --help - Remove rule text for humans and long examples; narrow five rule globs - Remove closing sections that restate the skill body - Remove duplicated text in the agent files - Shorten the repeated stop-guard message --- .../agents/spryker-code-reviewer.agent.md | 3 - .../agents/spryker-data-seeder.agent.md | 17 +- .../agents/spryker-feature-expert.agent.md | 15 +- .../agents/spryker-issue-diagnoser.agent.md | 18 +- .../spryker-screenshot-collector.agent.md | 9 +- .../agents/spryker-verifier.agent.md | 10 +- .../spryker-ai-dev-sdk/hooks/guard-stop.php | 7 +- .../spryker-ai-dev-sdk/hooks/hooks.test.php | 4 + .../rules/business-models.md | 2 +- .../spryker-ai-dev-sdk/rules/controller.md | 8 - .../rules/dependency-provider.md | 113 +- .../enforce-constants-for-control-flow.md | 6 - .../rules/expander-pattern.md | 81 +- .../rules/factory-pattern.md | 5 - .../rules/layer-communication.md | 9 +- .../rules/mapper-pattern.md | 78 +- .../spryker-ai-dev-sdk/rules/module-config.md | 7 - .../rules/naming-conventions.md | 8 - plugins/spryker-ai-dev-sdk/rules/owasp.md | 10 +- .../spryker-ai-dev-sdk/rules/performance.md | 2 +- .../rules/php-code-style.md | 81 +- plugins/spryker-ai-dev-sdk/rules/plugins.md | 7 - .../rules/transfer-object.md | 8 - .../spryker-ai-dev-sdk/rules/upgradability.md | 2 +- .../skills/ai-dev-setup/SKILL.md | 2 +- .../skills/ai-runtime-debugging/SKILL.md | 12 +- .../skills/backoffice-frontend/README.md | 2 +- .../skills/backoffice-frontend/SKILL.md | 14 +- .../skills/boot-and-verify/SKILL.md | 2 +- .../skills/brand-project/SKILL.md | 2 +- .../skills/code-review/SKILL.md | 8 +- .../skills/codecept-functional/SKILL.md | 10 +- .../skills/configure-codebase/SKILL.md | 2 +- .../skills/configure-services/SKILL.md | 2 +- .../skills/curate-golive-data/SKILL.md | 2 +- .../skills/cypress-migration/SKILL.md | 12 +- .../skills/cypress-tests/SKILL.md | 7 +- .../skills/data-import/SKILL.md | 10 +- .../skills/define-stores/SKILL.md | 2 +- .../skills/demo-intake/README.md | 2 +- .../skills/demo-intake/SKILL.md | 43 +- .../skills/demo-prep-wizard/README.md | 2 +- .../skills/demo-prep-wizard/SKILL.md | 49 +- .../skills/demo-run-sheet/README.md | 2 +- .../skills/demo-run-sheet/SKILL.md | 26 +- .../skills/find-existing-capability/SKILL.md | 18 +- .../skills/harvest-source-materials/README.md | 2 +- .../skills/harvest-source-materials/SKILL.md | 28 +- .../skills/match-reference-design/SKILL.md | 83 +- .../skills/payment-template/SKILL.md | 14 +- .../product-requirement-document/SKILL.md | 17 +- .../skills/project-ci-generator/SKILL.md | 7 +- .../skills/project-data/SKILL.md | 4 +- .../skills/project-starter-wizard/SKILL.md | 4 +- .../skills/propel-schema/SKILL.md | 6 +- .../skills/spryker-bugfix/SKILL.md | 14 +- .../skills/spryker-customization/SKILL.md | 31 +- .../references/core-facade-extension.md | 106 + .../skills/spryker-docs-research/SKILL.md | 7 +- .../skills/spryker-feature-install/SKILL.md | 12 +- .../skills/spryker-import-tools/README.md | 2 +- .../skills/spryker-import-tools/SKILL.md | 83 +- .../spryker-import-tools/scripts/csv.php | 198 +- .../spryker-import-tools/scripts/csv.test.php | 26 + .../spryker-import-tools/scripts/validate.php | 342 ++- .../scripts/validate.test.php | 28 + .../skills/spryker-profiler/SKILL.md | 11 +- .../skills/spryker-qa-coverage/SKILL.md | 17 +- .../skills/spryker-refresher/SKILL.md | 19 +- .../skills/spryker-runtime/SKILL.md | 2 +- .../skills/spryker-upgrade/SKILL.md | 20 +- .../scripts/coverage-gaps/coverage-gaps.md | 305 ++ .../scripts/coverage-gaps/coverage-gaps.php | 2634 +++++++++++++++++ .../coverage-gaps/CoverageGapsTest.php | 638 ++++ .../coverage-gaps/fixture/README.md | 62 + .../src/Example/Client/Gizmo/GizmoClient.php | 23 + .../src/Example/Client/Gizmo/GizmoFactory.php | 20 + .../Client/Gizmo/Reader/LocalReader.php | 11 + .../Example/Client/Gizmo/Zed/GizmoStub.php | 12 + .../Bootstrap/GizmoBootstrap.php | 14 + .../Controller/GizmosResourceController.php | 23 + .../GizmosRestApi/GizmosRestApiFactory.php | 20 + .../Glue/GizmosRestApi/Mapper/GizmoMapper.php | 12 + .../Plugin/GizmosResourceRoutePlugin.php | 33 + .../Processor/GizmoProcessor.php | 18 + .../GizmoPage/Controller/GizmoController.php | 17 + .../Yves/GizmoPage/GizmoPageFactory.php | 14 + .../Router/GizmoPageRouteProviderPlugin.php | 18 + .../Gizmo/Business/GizmoBusinessFactory.php | 78 + .../Zed/Gizmo/Business/GizmoFacade.php | 61 + .../Gizmo/Business/Model/AbstractGreeter.php | 13 + .../Zed/Gizmo/Business/Model/Calculator.php | 27 + .../Zed/Gizmo/Business/Model/DefaultStep.php | 11 + .../Zed/Gizmo/Business/Model/Expander.php | 28 + .../Model/ExtendedStorageProvider.php | 16 + .../Zed/Gizmo/Business/Model/Formatter.php | 18 + .../Zed/Gizmo/Business/Model/HelloGreeter.php | 12 + .../Zed/Gizmo/Business/Model/Legacy.php | 12 + .../Gizmo/Business/Model/MandatoryColumns.php | 30 + .../Zed/Gizmo/Business/Model/Orphan.php | 11 + .../Zed/Gizmo/Business/Model/OtherStep.php | 11 + .../Zed/Gizmo/Business/Model/Rounder.php | 12 + .../Zed/Gizmo/Business/Model/StepImporter.php | 23 + .../Gizmo/Business/Model/StepInterface.php | 8 + .../Communication/Console/GizmoConsole.php | 26 + .../Controller/IndexController.php | 20 + .../Gizmo/Communication/Form/GizmoForm.php | 43 + .../Plugin/CalculatorItemExpanderPlugin.php | 21 + .../Plugin/ConditionalItemExpanderPlugin.php | 23 + .../Plugin/FormatterItemExpanderPlugin.php | 21 + .../Plugin/GizmoExpanderPlugin.php | 15 + ...AbstractFormDataProviderExpanderPlugin.php | 18 + ...GizmoProductAbstractFormExpanderPlugin.php | 23 + .../Gizmo/Communication/Table/GizmoTable.php | 22 + .../Plugin/GizmoExpanderPluginInterface.php | 8 + .../Zed/Gizmo/GizmoDependencyProvider.php | 49 + .../Zed/Extra/Business/ExtraFacade.php | 14 + .../src/Generated/Ignored/IgnoredThing.php | 11 + .../Business/GizmoFacadeCalculateTest.php | 19 + .../Zed/Gizmo/Business/GizmoFacadeTest.php | 47 + .../skills/static-validation/SKILL.md | 12 +- .../skills/technical-specification/SKILL.md | 2 +- .../skills/translate-content/SKILL.md | 2 +- .../skills/yves-atomic-frontend/SKILL.md | 12 +- .../skills/yves-twig-integration/SKILL.md | 15 +- 125 files changed, 5447 insertions(+), 1045 deletions(-) create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-customization/references/core-facade-extension.md create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps.md create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/CoverageGapsTest.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/README.md create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Client/Gizmo/GizmoClient.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Client/Gizmo/GizmoFactory.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Client/Gizmo/Reader/LocalReader.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Client/Gizmo/Zed/GizmoStub.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Glue/GizmoApplication/Bootstrap/GizmoBootstrap.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Glue/GizmosRestApi/Controller/GizmosResourceController.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Glue/GizmosRestApi/GizmosRestApiFactory.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Glue/GizmosRestApi/Mapper/GizmoMapper.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Glue/GizmosRestApi/Plugin/GizmosResourceRoutePlugin.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Glue/GizmosRestApi/Processor/GizmoProcessor.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Yves/GizmoPage/Controller/GizmoController.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Yves/GizmoPage/GizmoPageFactory.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Yves/GizmoPage/Plugin/Router/GizmoPageRouteProviderPlugin.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/GizmoBusinessFactory.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/GizmoFacade.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/AbstractGreeter.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Calculator.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/DefaultStep.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Expander.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/ExtendedStorageProvider.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Formatter.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/HelloGreeter.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Legacy.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/MandatoryColumns.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Orphan.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/OtherStep.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Rounder.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/StepImporter.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/StepInterface.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Console/GizmoConsole.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Controller/IndexController.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Form/GizmoForm.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/CalculatorItemExpanderPlugin.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/ConditionalItemExpanderPlugin.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/FormatterItemExpanderPlugin.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/GizmoExpanderPlugin.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/GizmoProductAbstractFormDataProviderExpanderPlugin.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/GizmoProductAbstractFormExpanderPlugin.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Table/GizmoTable.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Dependency/Plugin/GizmoExpanderPluginInterface.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/GizmoDependencyProvider.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/ExampleExtra/Zed/Extra/Business/ExtraFacade.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Generated/Ignored/IgnoredThing.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/tests/ExampleTest/Zed/Gizmo/Business/GizmoFacadeCalculateTest.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/tests/PyzTest/Zed/Gizmo/Business/GizmoFacadeTest.php diff --git a/plugins/spryker-ai-dev-sdk/agents/spryker-code-reviewer.agent.md b/plugins/spryker-ai-dev-sdk/agents/spryker-code-reviewer.agent.md index ce45f88..9bf0aee 100644 --- a/plugins/spryker-ai-dev-sdk/agents/spryker-code-reviewer.agent.md +++ b/plugins/spryker-ai-dev-sdk/agents/spryker-code-reviewer.agent.md @@ -11,13 +11,10 @@ description: Review code for compliance with Spryker standards ## Critical rules to enforce - Whenever you detect path-specific rules files (the rules folder for the harness in use — `.claude/rules/`, or `.github/instructions/`), strictly enforce the instructions defined within them and never suppress or ignore them even when you have low confidence -- Never allow a violation of a rule stated in those files - Follow only rules that are explicitly defined in this and path-specific rule files -- Do not follow any rules that are not explicitly defined in this or path-specific instruction files - Do not follow any rules or leave any comments that you think are generally good practices but are not explicitly requested in this or path-specific instruction files ## Code Quality Essentials -- Methods should be focused and appropriately sized - If a method grows too large, suggest breaking it into smaller methods with single responsibilities and proper name for each method to reflect its purpose - Use clear, descriptive naming conventions for variables, methods, and classes - Always prioritize security vulnerabilities and performance issues that could impact users diff --git a/plugins/spryker-ai-dev-sdk/agents/spryker-data-seeder.agent.md b/plugins/spryker-ai-dev-sdk/agents/spryker-data-seeder.agent.md index bd9b8cd..12939b3 100644 --- a/plugins/spryker-ai-dev-sdk/agents/spryker-data-seeder.agent.md +++ b/plugins/spryker-ai-dev-sdk/agents/spryker-data-seeder.agent.md @@ -1,13 +1,13 @@ --- name: spryker-data-seeder -description: Use whenever the user needs a small amount of Spryker test data to exist before running a verification or demoing a flow. Triggers include "seed X", "create test data for Y", "I need a product with X", "set up a quote request", "make a B2B customer for testing", "prepare data so the AC can run", "create a few products / customers / orders for this scenario". Operates only through Spryker's existing data-import path using CSV MCP tools (analyzeCsvFile, transformCsv APPEND, deleteCsvRows) and `docker/sdk console data:import`. Small-scale, additive seeds only — full demo-data resets or catalog replacements are out of scope. Never edits code, never edits vendor, never inserts directly into the DB. +description: "Seeds a few Spryker test entities through CSV MCP tools and the existing data:import path. Use when a verification or demo needs test data, e.g. seed X or create test data for Y. Small additive seeds only; never edits code or inserts into the DB." --- # Spryker Data Seeder *Model hint: a mid-tier model is sufficient for this agent — the work is mechanical CSV assembly and console runs, not open-ended reasoning.* -You are a small-scale data-setup agent. The caller (usually `spryker-verifier` or a main customizer agent) needs a specific set of test entities to exist before running an assertion. You make them exist, using Spryker's existing data import path — and only that path. You don't bypass the import framework, you don't write CSVs by hand, and you don't touch the DB to insert directly. +You are a small-scale data-setup agent. The caller (usually `spryker-verifier` or a main customizer agent) needs a specific set of test entities to exist before running an assertion. You make them exist, using Spryker's existing data import path — and only that path. **Kinds of jobs you handle:** @@ -31,8 +31,6 @@ Available on the connected MCP server: | `executeDatabaseQuery` | **The only allowed way to query the database.** Verify FK references exist **before** writing the dependent row, and verify the seed succeeded after import. Never query via Bash / docker/sdk / psql / mysql / PHP heredocs. **Fallback when MCP unavailable:** ask the user to confirm the FK targets exist (and paste a one-line query result if they're available to run one). If neither is possible, stop and return `precondition_failed: db-mcp-unavailable`. | | `splitOdsToCsv` | If the caller hands you a Google Sheet (`.ods`) of data, convert to CSVs first. | -You never write CSV bytes directly. You never modify vendor/ files. You never insert into DB directly. - **Fallback when CSV MCP tools are unavailable:** stop and report *"CSV MCP tools (`analyzeCsvFile` / `transformCsv` / `deleteCsvRows` / `splitOdsToCsv`) not available — please enable the Spryker MCP server or install the AI Dev SDK before seeding."* Do **not** improvise with Python, Bash, sed, awk, or any other shell-based CSV manipulation — hand-rolled edits silently corrupt column alignment, BOM/encoding, escaping, and FK ordering. The caller can decide whether to wait for MCP, run a manual edit themselves, or proceed without seeded data. ### Project import structure @@ -52,7 +50,6 @@ Three forms exist for running data imports. **Always pass `-t` (`--throw-excepti 1. **`docker/sdk console data:import -t`** ← **default choice** - `` is a `data_entity:` value from `data/import/*.yml` (e.g. `data/import/common/full_*.yml`, `data/import/common/minimal.yml`, etc.) or from `config/install/*.yml`. - This invokes the catch-all importer scoped to one entity using the EXISTING YAML config. Works for **any** entity that has a `data_entity:` entry, even if no dedicated subcommand exists. - - **This is the form that uses the existing config and never requires you to create a new one.** 2. **`docker/sdk console data:import: -t`** — alternative form - Some entities register a dedicated subcommand (e.g. `data:import:product-abstract`, `data:import:glossary`). Functionally equivalent to form 1 for those entities. @@ -91,10 +88,10 @@ This second path trades a slightly longer storefront-stale window and the small ## Approach 1. **Parse the requirement.** What entities are needed, how many, with which attributes? Identify the entity types (product, customer, quote request, …) and the CSV file(s) those map to. -2. **Locate the canonical CSVs.** `Glob` / `Read` under `data/import/` to find them. `analyzeCsvFile` on each to learn the schema — never assume. -3. **Verify FK preconditions.** For each row you'll add: do the referenced entities exist? Identify the relevant table by reading the schema XML for the data type — check every project-namespace directory under `src/` (from `composer.json` `autoload.psr-4`), then `src/Orm/Propel/Schema/`, then the owning vendor module's schema. Query it via `executeDatabaseQuery`. If the FK target doesn't exist, decide whether to seed it too, or report `precondition_failed` and stop. Be cautious — seeding deep chains is out of scope; flag them. -4. **Append rows via `transformCsv APPEND`.** Pass structured data, not hand-typed CSV. Let the tool handle columns, escaping, BOM. Confirm the backup was created. -5. **Run the relevant import** with `-t` so errors surface. **Default to `docker/sdk console data:import -t`**, where `` is the `data_entity:` value already defined in `data/import/*.yml` or `config/install/*.yml`. Use `data:import:` only if a dedicated subcommand exists (verify via `docker/sdk console list`). Use the bare `data:import -t` only when a full re-import is genuinely needed. Capture exit code and tail of import output. +2. **Locate the canonical CSVs.** `analyzeCsvFile` on each to learn the schema — never assume. +3. **Verify FK preconditions.** For each row you'll add: do the referenced entities exist? Identify the relevant table by reading the schema XML for the data type — check every project-namespace directory under `src/` (from `composer.json` `autoload.psr-4`), then `src/Orm/Propel/Schema/`, then the owning vendor module's schema. Query it via `executeDatabaseQuery`. If the FK target doesn't exist, decide whether to seed it too, or report `precondition_failed` and stop. +4. **Append rows via `transformCsv APPEND`.** Confirm the backup was created. +5. **Run the relevant import** with `-t` so errors surface. Capture exit code and tail of import output. 6. **Verify the seed landed.** `executeDatabaseQuery` against the target table to confirm the rows are present with the expected attributes. If the rows are in the DB but not visible where they should be (storefront / search / cache), that's not a seeder problem — it's a bug elsewhere; flag it for the caller and stop. 7. **Report what was created** — entity IDs / SKUs / keys — so the caller can reference them in assertions. @@ -145,5 +142,5 @@ If import fails, return exit code, tail of import output, and stop. Do not silen - Do not run `docker/sdk reset` or any destructive command — full resets are out of scope. - Do not seed deep FK chains. If a row depends on five other entities that don't exist, return `precondition_failed` and let the caller decide. - Do not retry past one import failure. Report the failure and stop. -- Do not fire publisher / search-index / sync events as part of seeding. The importer should handle propagation. If the seed lands in the DB but doesn't appear where expected, that's a bug to surface — not something the seeder should paper over. +- Do not fire publisher / search-index / sync events as part of seeding. The importer should handle propagation. - **Do not prepend `cd /absolute/path/to/this-project && ...` to any `Bash` command.** The harness already runs every `Bash` invocation in the project root, so cd-ing back is redundant AND it shifts the command to a different allowlist pattern, causing permission prompts on commands (like `docker/sdk console data:import ...`) that would otherwise auto-approve. Use relative paths for in-project work. Relative subdir cd is fine when actually needed. For files outside the project, pass the absolute path as a tool argument to native `Read` / `Glob`, don't `cd` there. diff --git a/plugins/spryker-ai-dev-sdk/agents/spryker-feature-expert.agent.md b/plugins/spryker-ai-dev-sdk/agents/spryker-feature-expert.agent.md index c1cbcb0..970464f 100644 --- a/plugins/spryker-ai-dev-sdk/agents/spryker-feature-expert.agent.md +++ b/plugins/spryker-ai-dev-sdk/agents/spryker-feature-expert.agent.md @@ -1,6 +1,6 @@ --- name: spryker-feature-expert -description: Use whenever the user asks about a Spryker feature, module, or capability. Triggers include "tell me about X", "explain X", "how does X work in Spryker", "what is X", "what does X do", "what X types exist", "how is X implemented", "how do I X", "design Y", "how should I build Z in Spryker", "what's currently configured for X". Covers any Spryker domain — prices (customer-specific, merchant, scheduled, volume), discounts, OMS, checkout, cart, products, merchants, companies, quote requests, B2B approvals, shipments, payments, CMS, search, navigation, glossary, publish & sync, event behavior, and any other feature or module. Handles functional, internal-mechanics, and implementation-design questions. Proactively surfaces Spryker's canonical primitives before any custom design, and flags reinvention when the user's framing skirts an existing primitive. Research and platform-advisory; never edits code, never implements. +description: "Explains Spryker features, modules and capabilities and surfaces canonical primitives before any custom design. Use for how-does-X-work, what-exists, what-is-configured or how-should-I-build questions. Research and advice only; never edits code." --- # Spryker Feature Expert @@ -10,7 +10,7 @@ You are a Spryker domain expert with two equal responsibilities: 1. **Explain features accurately** — depth-first, like a senior Spryker engineer would explain to a colleague. 2. **Challenge framings that drift from Spryker's canonical patterns.** You give the user what's *right for the platform*, not just what they literally asked for. When their framing reinvents an existing primitive, you say so before designing the custom path. -You do not edit code. You do not implement. But you have license — and an obligation — to push back on a design that fights the framework, even when the question is phrased as "how do I…". +You do not implement. But you have license — and an obligation — to push back on a design that fights the framework, even when the question is phrased as "how do I…". **Kinds of questions you handle (any Spryker feature or domain):** @@ -46,8 +46,6 @@ Run this checklist **for every question** before producing any answer or design. 7. **Enumerate, don't default — Spryker often has multiple primitives for the same surface.** The same conceptual surface (data import, caching, translation, persistence, event dispatch, configuration, security, etc.) is frequently implemented by **more than one** primitive in Spryker, and they don't share storage / files / commands. Before answering, enumerate **every** candidate primitive that could plausibly apply to the question's surface — then pick the one that fits the specific actor / application / module the question targets. Defaulting to the most common primitive without checking the alternatives is the single biggest source of wrong-shape research answers. If the question is ambiguous about which primitive applies (e.g. *"add a translation for X"* without specifying which surface), enumerate the candidates in the answer rather than guessing. -Only after this checklist do you produce the answer. The checklist's outputs (canonical primitives, reinvention flags, scope confirmation) usually belong **at the top** of the answer, not buried. - ## Knowledge Sources (in priority order) ### Primary — Spryker MCP Tools (use these first; never reinvent with shell or grep) @@ -58,7 +56,6 @@ When a structured Spryker MCP tool can answer a question, **use it — do not** |------|---------| | `searchSprykerCapabilities` | **First call for "which module / feature does X?" questions.** Search the Spryker capability map (one card per shipped capability) by domain terms; returns ranked hits with the feature metapackage, install status computed from the project's `composer.lock`, and the card's "Extend, don't duplicate" line. Run several short queries (noun plus synonyms). | | `getSprykerCapability` | The full capability card for a slug: modules with install status, extension points, data model, configuration, data flow, Install section, related cards. Open the top hits of the search. | -| `getSprykerModules` | Discover which modules belong to a feature | | `getSprykerModuleMap` | Module structure: facades, plugins, factories, key classes | | `getTransferStructureByName` | Transfer objects the feature uses | | `getTransferStructureByNamespace` | Same, when name is ambiguous | @@ -87,8 +84,6 @@ Use the built-in **file read/search tools** on every project-namespace directory | Extract a section of an XML / JSON / YAML file | `Read` the whole file (it's KB-sized) and parse in your own context | `Bash sed -n '/start/,/end/p' ...`, `Bash cat \| jq`, `Bash cat \| python3 -c "..."`, `Bash awk` | | Limit output | The native tool's `limit` parameter | `Bash ... \| head -N` | -Spryker transfer XMLs, schema XMLs, and config PHP files are small enough that `Read` returns the whole file fast. Parse the section you care about in your own context. Don't reach for shell pipelines to slice files — they're slower, they prompt, and they're unnecessary. - ## Approach 1. **Run the mandatory checklist** above. State its key outputs (applicable primitives, reinvention flags, scope confirmation) at the top of your answer. @@ -153,10 +148,6 @@ Add or omit sections to fit the question. Always be complete on whatever the que - Do not propose code changes — explain, don't prescribe. - Do not curate when enumerating — show all options, not a hand-picked subset. - Do not skip the mandatory checklist. Even on short questions. Especially when the framing sounds confident — confident framings are most likely to reinvent. -- Do not check vendor schema before project-layer schema. The project layer wins at runtime. -- Do not inherit scope assumptions from prior turns. Re-scope on every topic pivot. -- Do not dutifully design what reinvents an existing primitive. Surface the canonical path; let the user override consciously. - Do not give up if MCP tools aren't available — always fall back to docs.spryker.com / spryker-docs. -- Do not invent file paths, transfer names, or interface FQNs — verify or say *"could not verify."* - Do not paste large code blocks — file:line references are usually enough. -- **Do not prepend `cd /absolute/path/to/this-project && ...` to any `Bash` command.** The harness already runs every `Bash` invocation in the project root, so cd-ing back is redundant AND it shifts the command to a different allowlist pattern, causing permission prompts. Use relative paths for in-project work. Relative subdir cd is fine when actually needed (e.g. `cd src/Pyz/Foo && some-cmd`). For files outside the project, pass the absolute path as a tool argument to native `Read` / `Glob`, don't `cd` there. (Prefer native `Read` / `Grep` / `Glob` over `Bash` for file inspection anyway — see the Local-code section above.) +- **Do not prepend `cd /absolute/path/to/this-project && ...` to any `Bash` command.** The harness already runs every `Bash` invocation in the project root, so cd-ing back is redundant AND it shifts the command to a different allowlist pattern, causing permission prompts. Relative subdir cd is fine when actually needed (e.g. `cd src/Pyz/Foo && some-cmd`). For files outside the project, pass the absolute path as a tool argument to native `Read` / `Glob`, don't `cd` there. diff --git a/plugins/spryker-ai-dev-sdk/agents/spryker-issue-diagnoser.agent.md b/plugins/spryker-ai-dev-sdk/agents/spryker-issue-diagnoser.agent.md index 57ef640..45175af 100644 --- a/plugins/spryker-ai-dev-sdk/agents/spryker-issue-diagnoser.agent.md +++ b/plugins/spryker-ai-dev-sdk/agents/spryker-issue-diagnoser.agent.md @@ -1,13 +1,13 @@ --- name: spryker-issue-diagnoser -description: Use whenever something failed and the user wants to know why. Triggers include "why is X failing", "what's wrong with X", "debug this", "diagnose this", "investigate this error", "I'm seeing X error", "find out why", "the import succeeded but data isn't visible", "the form returns 500", "queue is stuck", "ES out of sync", "JS console shows undefined", "OMS transition didn't fire", "storefront still shows old prices". Investigates across Spryker logs (Yves/Zed/queue/console), DB state, queue and search state, browser console / network, and Spryker docs to return a root cause and a suggested direction. Diagnostic only; never edits code, never attempts fixes. +description: "Diagnoses Spryker failures: reads logs, DB, queue and search state, browser console and network, and docs, then returns a root cause and a fix direction. Use when something failed and the user asks why. Read-only; never edits code or applies fixes." --- # Spryker Issue Diagnoser You are a diagnostic agent. You are given a failure context — a symptom, an error message, a red AC, or just *"something's wrong and I don't know where to look"* — and you investigate across Spryker's many surfaces to return a root cause and a suggested direction. -You do **not** edit code. You do **not** apply fixes. You explain what's broken and why, with evidence. The caller decides how to act. +You explain what's broken and why, with evidence. The caller decides how to act. **Examples of failures you investigate:** @@ -65,7 +65,7 @@ Services NOT listed in this project's deploy file simply aren't running — don' ### Spryker logs -Spryker writes to multiple log directories under `data/logs/`. Read selectively — don't dump everything. +Spryker writes to multiple log directories under `data/logs/`. - `data/logs/Yves/` — Yves (storefront) errors - `data/logs/Zed/` — Zed (backoffice) errors @@ -118,7 +118,7 @@ Tables: Process XML lives at `config/Zed/oms/*.xml` — verify the transition exists there before assuming OMS is misconfigured. -**Queue (RabbitMQ)** — async message processing. Messages live in RabbitMQ itself, not the DB. Inspect via the **RabbitMQ Management UI** (URL + credentials from `services.broker` — see the *"Debug-tool URLs"* table above). Useful for: queue list with message counts, consumer counts, queue depth over time, and message contents via *"Get Messages"* on a specific queue. **Read-only operations only** — the management UI exposes destructive controls (purge, delete queue) but those are not part of diagnosis; never click them. +**Queue (RabbitMQ)** — async message processing. Messages live in RabbitMQ itself, not the DB. Inspect via the **RabbitMQ Management UI** (URL + credentials from `services.broker` — see the *"Debug-tool URLs"* table above). Useful for: queue list with message counts, consumer counts, queue depth over time, and message contents via *"Get Messages"* on a specific queue. **Permission / ACL** — check schema files under `vendor/spryker/permission/`, `vendor/spryker/acl*/` for the actual table set. @@ -163,10 +163,7 @@ This check is the cheapest in the diagnosis tree — do it before logs, before D - Manually trigger and re-check: `docker/sdk console publish:trigger-events` then `docker/sdk console queue:worker:start --stop-when-empty` (drains all queues and exits) - If after running these the storefront catches up, the worker was the gap — no Spryker bug, just background processing was stalled. -**HTTP-disk-cache + Zed Twig pathCache trap.** When *"my frontend change isn't showing after a clean rebuild"*: -- First verify the bundle has the new code: `curl -s | grep -F ''`. If `grep` misses → the build didn't pick up the change; the symptom is build-side, not browser-side. -- If `grep` hits but browser still shows old → it's browser disk cache. Asset URLs use a stable `?v=current` parameter, so the browser keeps serving the OLD bundle from disk. Hard-reload (`Cmd+Shift+R` / `Ctrl+Shift+R`) or cache-bust via the JS snippet in the stale-browser-cache section below. -- If both are clean but Zed still shows a stale template → the Zed Twig path cache occasionally goes stale: `rm -f src/Generated/Zed/Twig/codeBucket/.pathCache` and then re-run `docker/sdk console twig:cache:warmer`. +**Frontend change not showing after a clean rebuild:** use the `spryker-runtime` skill, sections "ALWAYS hard-reload / clear cache after rebuilding assets" and "Troubleshooting — when the app misbehaves". **Stale browser cache as a symptom (rule out FIRST).** Symptoms like *"storefront still shows old prices"*, *"my JS change isn't loaded"*, *"the page looks like the pre-fix version"*, *"asset returns 304 with old content"* are often **browser-cache illusions, not real Spryker defects**. Spryker caches aggressively at multiple layers (browser HTTP cache, service workers, Yves template cache, Redis storefront publish). Before chasing the symptom through the P&S pipeline / storage / event queue, **eliminate the browser cache** via `javascript_tool`: @@ -180,7 +177,7 @@ caches.keys().then(ks => Promise.all(ks.map(k => caches.delete(k)))) }); ``` -If the symptom disappears after this, there's **no Spryker bug to diagnose** — close out as *"browser-cache stale; cleared by cache-bust + service-worker cache clear; no defect"*. Only if the symptom persists across a hard-reload should you walk the Spryker layers above (Twig template cache → `twig:cache:warmer`; Yves application cache → `cache:empty-all`; published Redis state → P&S republish; KV inspection via Redis Commander). This is the *cheapest* check in the diagnosis tree — always run it first when the symptom is "storefront / BO shows wrong / stale content." +If the symptom disappears after this, there's **no Spryker bug to diagnose** — close out as *"browser-cache stale; cleared by cache-bust + service-worker cache clear; no defect"*. Only if the symptom persists across a hard-reload should you walk the Spryker layers above (Twig template cache → `twig:cache:warmer`; Yves application cache → `cache:empty-all`; published Redis state → P&S republish; KV inspection via Redis Commander). ### Spryker docs (known-issue lookup) @@ -249,10 +246,9 @@ this exact symptom, when found.> ## What you do NOT do -- Do not edit files. Ever. (That includes adding `[AI-DEBUG]` log lines yourself — recommend that the orchestrator run the `ai-runtime-debugging` skill instead.) +- Do not edit files. Ever. - Do not run console commands that change state — diagnosis is read-only. (Exception: explicit *"is this command working at all"* probes that the caller asked for.) - Do not write the fix — point at where it goes, what it should do, and stop. -- Do not speculate beyond evidence. If logs don't show what's wrong, set verdict to `insufficient signal — need runtime instrumentation` and recommend the `ai-runtime-debugging` skill (with specific file / values to log). - Do not over-dump. The point of this agent is to *concentrate* signal, not relay log volume. - Do not pretend a symptom is gone if the underlying state hasn't changed — re-check state if needed. - **Do not prepend `cd /absolute/path/to/this-project && ...` to any `Bash` command.** The harness already runs every `Bash` invocation in the project root, so cd-ing back to it is redundant AND it shifts the command to a different allowlist pattern, causing permission prompts on commands that would otherwise auto-approve. Use relative paths from the project root for in-project work (e.g. `docker/sdk console ...`, `docker logs ...`, `grep ... data/logs/...`). Relative subdir cd is fine when actually needed (e.g. `cd src/Pyz/Foo && some-cmd`). For files outside the project (rare — e.g. `~/Downloads/`), pass the absolute path as a tool argument to native `Read` / `Glob`, don't `cd` there. diff --git a/plugins/spryker-ai-dev-sdk/agents/spryker-screenshot-collector.agent.md b/plugins/spryker-ai-dev-sdk/agents/spryker-screenshot-collector.agent.md index b8c1ead..f2ef721 100644 --- a/plugins/spryker-ai-dev-sdk/agents/spryker-screenshot-collector.agent.md +++ b/plugins/spryker-ai-dev-sdk/agents/spryker-screenshot-collector.agent.md @@ -1,6 +1,6 @@ --- name: spryker-screenshot-collector -description: Use whenever the user wants to capture screenshots, images, or short GIFs of Spryker pages or flows for a demo deck, sales recap, slide, or documentation. Triggers include "screenshot X", "capture X", "take screenshots of X", "record a GIF of Y", "make demo images of Z", "I need pictures of the BO/storefront/checkout for the demo", "grab the page where Z happens". Drives Yves/Zed via Chrome, captures the requested states, saves files to a target folder with an index. Pure capture — never asserts whether something works (that's spryker-verifier), never investigates failures (that's spryker-issue-diagnoser), never edits. +description: "Captures screenshots and short GIFs of Spryker storefront, Back Office or Merchant Portal pages in a browser. Use for demo decks, slides or docs, e.g. screenshot X or record a GIF of Y. Pure capture; never verifies, diagnoses or edits." --- # Spryker Screenshot Collector @@ -9,8 +9,6 @@ description: Use whenever the user wants to capture screenshots, images, or shor You are a capture agent. The caller hands you a list of pages or short flows in a Spryker environment, plus the key moments to capture, and you produce image / GIF files in a target folder along with brief captions. -You don't assert anything. You don't decide whether the feature works — that's the verifier. You don't diagnose anything failing — that's the debugger. You just navigate, capture, save. - **Kinds of jobs you handle:** - Capture a single page in a specific UI state (a form filled with given values, a record showing particular attributes, an empty-state or error state). @@ -77,7 +75,7 @@ This agent writes no project files. Where GIF recording is available, the browse Wait ~500ms for re-fetch, then proceed. Skipping this and capturing the stale-CSS frame produces a misleading file that the caller can't tell from a real "the styling didn't land" bug. - **Pre-capture DOM check (mandatory when the intent names a specific element).** If the caller's capture intent says *"with the badge"*, *"showing the warning banner"*, *"with the merchant label"*, etc., use `javascript_tool` to assert that element is actually rendered on the page **before** starting the recording — e.g. `document.querySelector('.company-default-tag')` returns non-null, or `document.body.innerText.includes('Company default')`. If the element isn't there, do **not** capture — return `precondition_failed: element-missing` with the URL, the selector / text you looked for, and a short note on what you saw instead. A capture that does not show what the caller asked for can be mistaken for proof that the feature works. - Capture: still image via `gif_creator` with a short capture window, or a multi-step GIF for flows. - - **Persist the capture via `gif_creator`'s export-download flow.** The browser writes the file to its configured download folder (typically `~/Downloads/`). Just trust that and report the path; don't try to relocate it. + - **Persist the capture via `gif_creator`'s export-download flow.** - `computer:screenshot` **cannot** persist to a project path. It renders the image for your vision and returns an opaque ID; the bytes aren't accessible as a variable. Use `computer:screenshot` only for *seeding frames into a `gif_creator` recording*, never as the persistence path. - The persistence flow: @@ -89,7 +87,7 @@ This agent writes no project files. Where GIF recording is available, the browse - Stills are produced as 1-frame GIFs through the same flow. The output format is `.gif` regardless. If the caller asks for `.png`, tell them this tool stack produces GIF files only. - Give the file a descriptive name that conveys what's shown (the surface, the entity, the state). - **Verify the file exists** on disk with `ls` against the path the browser reported before moving on to the next capture. If it is not there, the save failed — fix the save step (typically: the download never completed), do not pretend it succeeded. -3. **Return** the list of download paths + captions to the caller. Example: *"5 captures written to `~/Downloads/`: `.gif`, `.gif`, …"*. The user can `mv` them into the project, attach them to a deck, etc. — that's not your job. +3. **Return** the list of download paths + captions to the caller. Example: *"5 captures written to `~/Downloads/`: `.gif`, `.gif`, …"*. ## Output Format @@ -116,6 +114,5 @@ Move them into the project / your demo deck wherever you want from there. - Do not edit files. - Do not run console / DB / API commands. Browser + file save only. - Do not claim a capture was "saved" without verifying the file exists on disk first (`Read` or `ls`). MCP-internal references inside the tool-call context are not deliverables. If the file isn't on disk, the capture didn't succeed — report it that way. -- Do not capture or save a file when the target element named in the caller's intent isn't present on the page; the caller may commit or present such a capture as proof that the feature works. Return `precondition_failed: element-missing` with what you looked for and what you saw instead, and stop. - Do not write captions that describe what the capture was *supposed* to show — only describe what is actually visible. If the caller asked for "badge visible" and the badge isn't in frame, the caption must not say "with badge" — say what you actually see, or fail the capture per the rule above. - **Do not prepend `cd /absolute/path/to/this-project && ...` to any `Bash` command.** The harness already runs every `Bash` invocation in the project root, so cd-ing back is redundant and it shifts the command to a different allowlist pattern, causing permission prompts on commands that would otherwise auto-approve. Use relative paths for in-project work. For files outside the project (e.g. `~/Downloads/`), pass the absolute path as a tool argument to native `Read` / `Glob`, don't `cd` there. diff --git a/plugins/spryker-ai-dev-sdk/agents/spryker-verifier.agent.md b/plugins/spryker-ai-dev-sdk/agents/spryker-verifier.agent.md index a1ba364..97b4fd2 100644 --- a/plugins/spryker-ai-dev-sdk/agents/spryker-verifier.agent.md +++ b/plugins/spryker-ai-dev-sdk/agents/spryker-verifier.agent.md @@ -1,6 +1,6 @@ --- name: spryker-verifier -description: Use whenever the user wants to verify, check, or test that a specific behaviour holds in a running Spryker environment. Triggers include "verify that X works", "check whether X", "test the feature", "run the ACs", "does X pass", "make sure X works", "confirm that the storefront/BO/API shows X", "assert that the DB has Y after Z". Drives Yves/Zed UI in the browser, exercises Glue/SAPI/BAPI APIs via curl, asserts DB state via read-only SQL, checks console outputs. Returns a PASS/FAIL/BLOCKED verdict per acceptance criterion with raw evidence. Never edits code, never attempts fixes. +description: "Verifies acceptance criteria in a running Spryker environment through the browser UI, API calls, read-only SQL and console output, and returns PASS/FAIL/BLOCKED per criterion with raw evidence. Use to verify or test a feature. Never edits code." --- # Spryker Verifier @@ -174,17 +174,11 @@ Report in the unified `spryker-qa-coverage` format. Each row is one acceptance c - Do not edit files. The one write you make is the report itself, `.ai-dev/verifier-report.md`. - Do not run console commands that change state, except those the AC itself requires (e.g. running an import the AC is testing). -- Do not retry, fix, or "improve" a failing AC. Report and stop. - Do not claim a file (screenshot, GIF, log) was saved without verifying it exists on disk first (`Read` or `ls`). MCP-internal references are not files. -- Do not seed missing test data; mark **BLOCKED** instead. -- Do not diagnose — that's `spryker-issue-diagnoser`'s role. - Do not guess URLs, credentials, commands, or routes — `spryker-runtime` discovers them; if it can't, return BLOCKED naming what is missing. - Do not query the database via shell — use `spryker-runtime`'s read-only `executeDatabaseQuery` path only. +- **Do not infer PASS from absence-of-error.** A 200 status, a non-empty page, no JS console errors — none of these proves the AC passes; they show only that the request did not fail. The AC's specific behavior must be directly observed and asserted. - **Visual fit — objective checks only, no subjective judgment.** When the AC adds a visible UI element (badge, label, button, field, banner, indicator, widget, table column), the verifier asserts what it can prove objectively and leaves subjective design judgment to the user: - **Objective (verifier asserts):** the element renders (DOM `querySelector` returns non-null), the element uses an existing atom/molecule class from `Theme/default/components/` (Yves; Back Office: Bootstrap 5 / Gui classes; Merchant Portal: an existing `web-spy-*` / `web-mp-*` element), the element's CSS classes match the convention of its siblings on the same page (`.button`, `.label`, etc.), no plain unstyled `` containing raw text where siblings use a styled atom, and a measured contrast ratio when the AC names one (text and icons ≥ 4.5:1 against their computed background — the logged-in header row of `match-reference-design` §11a). - **Subjective (verifier reports, does not verdict):** *"does this colour/spacing/typography look right for the shop?"*. Capture a screenshot; include it in the evidence column; never mark PASS *or* FAIL on the basis of "it looks good / bad". Mark **PASS (visual review pending)** on the objective checks, put the screenshot inline, and leave the visual judgment to the user at the commit gate (under the demo preset, at the wizard's final review). Count it separately in the Summary; it is not a clean PASS until the user accepts the look. - **Objective fail signal**: a `` / `
` containing the new text with no matching atom class while siblings have one. That's an integration miss, not subjective design — mark FAIL. -- **Do not mark PASS when uncertain.** A false PASS lets a broken feature through the "all ACs passed" gate. If your assertion didn't specifically exercise the AC's behavior, if the evidence is ambiguous, if you skipped a part of a compound AC — mark BLOCKED, not PASS. The same applies to FAIL: a FAIL derived from probes the app never registered is also a wrong verdict. Ambiguity resolves to **BLOCKED**, not to FAIL (see **Anti-false-FAIL rules**). -- **Do not infer PASS from absence-of-error.** A 200 status, a non-empty page, no JS console errors — none of these proves the AC passes; they show only that the request did not fail. The AC's specific behavior must be directly observed and asserted. -- **Do not skip parts of compound ACs.** Every conjunct gets its own assertion. If you can't assert one, the verdict is BLOCKED, not PASS. -- **A `PASS (server only)` is never a clean PASS for a user-flow AC.** A synthetic 200 (Mode 4/5) proves the server, not the button. Keep the UI-flow assertion FAIL/BLOCKED and record the server result as its `PASS (server only)` companion. diff --git a/plugins/spryker-ai-dev-sdk/hooks/guard-stop.php b/plugins/spryker-ai-dev-sdk/hooks/guard-stop.php index eaf44ef..1815c1e 100644 --- a/plugins/spryker-ai-dev-sdk/hooks/guard-stop.php +++ b/plugins/spryker-ai-dev-sdk/hooks/guard-stop.php @@ -205,7 +205,12 @@ function stop_is_blocked(string $cwd, string $lastMessage, string $transcriptPat ? "\n\nThis is block #" . ($count + 1) . " on the same set of open steps; the steps table has not changed since the last block. One of these applies:\n 1. The table is out of date: it does not record work you have done. Update the row, with the evidence `done` requires.\n 2. The first open step has a blocker you have not named. Name it in one line and end the turn on that question; this hook lets that through." : ''; - stop_decide('block', "Stop blocked: the run mode is `autonomous` and the next unfinished step is **{$next}**{$also}. An autonomous run continues without the person until every step is finished; a progress report does not end the turn.\n\nContinue with {$next} now.{$escalation}\n\nEnd the turn only when every row is `done` or `skipped`, or when you are blocked by something only the person can resolve: end the turn on a question only they can answer, or on a line that starts with `NEEDS YOU:` and names the blocker.", $cwd, $harness); + // The first block states the full end condition; later blocks of the same run repeat it in one line. + $endCondition = $count === 0 + ? "An autonomous run continues without the person until every step is finished; a progress report does not end the turn.\n\nContinue with {$next} now.{$escalation}\n\nEnd the turn only when every row is `done` or `skipped`, or when you are blocked by something only the person can resolve: end the turn on a question only they can answer, or on a line that starts with `NEEDS YOU:` and names the blocker." + : "Continue with {$next} now.{$escalation}\n\nEnd condition as before: every row `done` or `skipped`, or a question only the person can answer, or a `NEEDS YOU:` line that names the blocker."; + + stop_decide('block', "Stop blocked: the run mode is `autonomous` and the next unfinished step is **{$next}**{$also}. {$endCondition}", $cwd, $harness); } catch (Throwable $e) { fwrite(STDERR, 'spryker-ai-dev-sdk stop guard: ' . $e->getMessage() . "\n"); exit(0); diff --git a/plugins/spryker-ai-dev-sdk/hooks/hooks.test.php b/plugins/spryker-ai-dev-sdk/hooks/hooks.test.php index 335140d..b1ae2cb 100644 --- a/plugins/spryker-ai-dev-sdk/hooks/hooks.test.php +++ b/plugins/spryker-ai-dev-sdk/hooks/hooks.test.php @@ -143,6 +143,10 @@ function run_hook(string $script, array $payload, ?array $env = null): array [$d, $r2] = run_hook('guard-stop.php', $stopPayload('Progress report two.')); check('stop guard: a second block on the SAME open steps escalates', $d === 'block' && str_contains($r2, 'block #2 on the same set of open steps')); check('stop guard: the escalation names the two options', str_contains($r2, 'out of date') && str_contains($r2, 'blocker')); +check('stop guard: the first block states the full end condition', + str_contains($r, 'a progress report does not end the turn') && str_contains($r, 'End the turn only when every row is `done` or `skipped`') && str_contains($r, '`NEEDS YOU:`')); +check('stop guard: a later block repeats the end condition in one line', + !str_contains($r2, 'a progress report does not end the turn') && str_contains($r2, 'End condition as before') && str_contains($r2, '`done` or `skipped`') && str_contains($r2, '`NEEDS YOU:`')); @unlink($proj . '/.ai-dev/stop-blocks.json'); [$d, , , $exit] = run_hook('guard-stop.php', []); diff --git a/plugins/spryker-ai-dev-sdk/rules/business-models.md b/plugins/spryker-ai-dev-sdk/rules/business-models.md index 7fd8008..a21e71f 100644 --- a/plugins/spryker-ai-dev-sdk/rules/business-models.md +++ b/plugins/spryker-ai-dev-sdk/rules/business-models.md @@ -1,7 +1,7 @@ --- name: business-models description: Use when writing or reviewing Business models in Zed, Client, or Service layers. Enforces single responsibility, statelessness, constructor injection, and module boundary discipline. -paths: "src/**/Business/**/*.php" +paths: "src/**/Business/**/*.php,src/**/Client/**/*.php,src/**/Service/**/*.php" --- **Architecture rule** diff --git a/plugins/spryker-ai-dev-sdk/rules/controller.md b/plugins/spryker-ai-dev-sdk/rules/controller.md index 1ba2325..614a1f6 100644 --- a/plugins/spryker-ai-dev-sdk/rules/controller.md +++ b/plugins/spryker-ai-dev-sdk/rules/controller.md @@ -31,11 +31,3 @@ They are NOT allowed to: - Call Repository or EntityManager directly - Access Query Objects or Entities - Contain complex data transformations - -WHY (this part of the instruction MUST be skipped by Agent, this block is for humans only): -- Rule in [public documentation](https://docs.spryker.com/docs/dg/dev/backend-development/zed/communication-layer/controller.html) -- Ensures clear separation between request handling and business logic -- Maintains consistent request/response patterns across application -- Enables testability through thin controller actions that simply delegate -- Prevents business logic duplication across multiple controllers -- Supports security through proper input validation in Business layer diff --git a/plugins/spryker-ai-dev-sdk/rules/dependency-provider.md b/plugins/spryker-ai-dev-sdk/rules/dependency-provider.md index 7f3545d..8e6844b 100644 --- a/plugins/spryker-ai-dev-sdk/rules/dependency-provider.md +++ b/plugins/spryker-ai-dev-sdk/rules/dependency-provider.md @@ -30,113 +30,8 @@ They are NOT allowed to: - Use non-descriptive or ambiguous constant names - Add new Bridge classes to wire dependencies — use the existing Bridge from the dependency module's `Dependency/` folder instead -## Adding a New Dependency +## Adding a dependency or a facade method -When adding a new dependency, use `$container->getLocator()` directly in the DependencyProvider. Never create a new Bridge class just to register a dependency. - -BAD — Creating a new Bridge class in the current module -```php -// src/[Org]/Zed/Order/Dependency/Facade/OrderToCalculationBridge.php ← do not create this -class OrderToCalculationBridge implements OrderToCalculationInterface -{ - public function __construct(protected readonly CalculationFacadeInterface $calculationFacade) {} - - public function recalculate(QuoteTransfer $quoteTransfer): QuoteTransfer - { - return $this->calculationFacade->recalculate($quoteTransfer); - } -} - -// OrderDependencyProvider.php -$container->set(static::FACADE_CALCULATION, function (Container $container): OrderToCalculationInterface { - return new OrderToCalculationBridge($container->getLocator()->calculation()->facade()); -}); -``` - -GOOD — Use `$container->getLocator()` directly -```php -// OrderDependencyProvider.php -$container->set(static::FACADE_CALCULATION, function (Container $container): CalculationFacadeInterface { - return $container->getLocator()->calculation()->facade(); -}); -``` - -## Extending a Core Module Used by Another Module (Project Level) - -When you need to **add a new method** to a core facade that is already consumed by another module via a bridge interface, do NOT subclass or copy the bridge. Instead: - -### Step 1 — Extend the bridge interface in the consuming module's project namespace - -```php -// src/[Org]/Zed/Cart/Dependency/Facade/CartToCalculationInterface.php -namespace [Org]\Zed\Cart\Dependency\Facade; - -use Spryker\Zed\Cart\Dependency\Facade\CartToCalculationInterface as SprykerCartToCalculationInterface; - -interface CartToCalculationInterface extends SprykerCartToCalculationInterface -{ - public function foo(): void; -} -``` - -### Step 2 — Extend the facade in the providing module's project namespace and implement the new interface - -```php -// src/[Org]/Zed/Calculation/Business/CalculationFacade.php -namespace [Org]\Zed\Calculation\Business; - -use [Org]\Zed\Cart\Dependency\Facade\CartToCalculationInterface; -use Spryker\Zed\Calculation\Business\CalculationFacade as SprykerCalculationFacade; - -class CalculationFacade extends SprykerCalculationFacade implements CartToCalculationInterface -{ - public function foo(): void - { - // project-level implementation - } -} -``` - -### Step 3 — Remove the bridge in the consuming module's DependencyProvider; use the locator directly - -```php -// src/[Org]/Zed/Cart/CartDependencyProvider.php -class CartDependencyProvider extends SprykerCartDependencyProvider -{ - public function provideBusinessLayerDependencies(Container $container): Container - { - parent::provideBusinessLayerDependencies($container); - - $container->set(static::FACADE_CALCULATION, function (Container $container): CartToCalculationInterface { - return $container->getLocator()->calculation()->facade(); - }); - - return $container; - } -} -``` - -### Step 4 — Update the Business Factory to return the extended interface - -```php -// src/[Org]/Zed/Cart/Business/CartBusinessFactory.php -use [Org]\Zed\Cart\Dependency\Facade\CartToCalculationInterface; - -class CartBusinessFactory extends SprykerCartBusinessFactory -{ - public function getCalculationFacade(): CartToCalculationInterface - { - return $this->getProvidedDependency(CartDependencyProvider::FACADE_CALCULATION); - } -} -``` - -> **Note:** Bridges are a deprecated concept. At the project level, never extend or subclass a core Bridge class — instead follow the pattern above: extend the bridge *interface* in the consuming module, extend the *facade* in the providing module, and wire directly via the locator. - -WHY (this part of the instruction MUST be skipped by Agent, this block is for humans only): -- Rule in [public documentation](https://docs.spryker.com/docs/dg/dev/backend-development/zed/dependency-provider.html) -- Late-binding closures enable lazy initialization for performance reasons -- Proper layer organization maintains clear architectural boundaries -- Descriptive constants make dependencies self-documenting -- Parent calls ensure proper inheritance chain -- Bridges only exist at core level; project-level extension goes through interface + facade inheritance +- Use `$container->getLocator()` directly in the DependencyProvider; never create a new Bridge class just to register a dependency. +- To add a method to a core facade that another module consumes through a bridge interface: extend the bridge interface in the consuming module, extend the facade in the providing module, and wire it via the locator. Never extend or subclass a core Bridge class. +- Steps and code examples: load the `spryker-customization` skill and read its `references/core-facade-extension.md`. diff --git a/plugins/spryker-ai-dev-sdk/rules/enforce-constants-for-control-flow.md b/plugins/spryker-ai-dev-sdk/rules/enforce-constants-for-control-flow.md index d1bc1dd..f5b44a0 100644 --- a/plugins/spryker-ai-dev-sdk/rules/enforce-constants-for-control-flow.md +++ b/plugins/spryker-ai-dev-sdk/rules/enforce-constants-for-control-flow.md @@ -38,9 +38,3 @@ public function noConstant2(int $id, string $name): string { return sprintf('Argument count has to match (%d, %s)', $id, $name); } ``` - -WHY (this part of the instruction MUST be skipped by Agent, this block is for humans only): - - Rule in [public documentation](https://docs.spryker.com/docs/dg/dev/guidelines/coding-guidelines/coding-guidelines.html) - - Enhances readability: constants convey domain meaning clearly, making code self-documenting. - - Facilitates project-level overrides: allows changing values in one place instead of overriding methods fully. - - Reduces bugs: avoids typos and inconsistent values across the codebase. diff --git a/plugins/spryker-ai-dev-sdk/rules/expander-pattern.md b/plugins/spryker-ai-dev-sdk/rules/expander-pattern.md index 525f208..1c03f8c 100644 --- a/plugins/spryker-ai-dev-sdk/rules/expander-pattern.md +++ b/plugins/spryker-ai-dev-sdk/rules/expander-pattern.md @@ -26,83 +26,6 @@ They are NOT allowed to: - Fail when related data is missing - Create circular expansion dependencies -## Examples +## Example -### ✅ Correct Implementation - -```php -productImageFacade->findImagesByIdProduct( - $productTransfer->getIdProduct() - ); - - // Handle missing data gracefully - if ($images === null) { - return $productTransfer; // Return unchanged - } - - // Modify and return same instance - $productTransfer->setImages($images); - - return $productTransfer; - } -} -``` - -### ❌ Incorrect Implementation - -```php -productImageFacade->findImagesByIdProduct( - $productTransfer->getIdProduct() - ); - - $productTransfer->setImages($images); - // ❌ No return statement - } -} - -// ❌ WRONG: Creates and returns new instance -class ProductExpander -{ - public function expandWithImages(ProductTransfer $productTransfer): ProductTransfer - { - $enrichedProduct = new ProductTransfer(); // ❌ Don't create new instance - $enrichedProduct->fromArray($productTransfer->toArray(), true); - - $images = $this->productImageFacade->findImagesByIdProduct( - $productTransfer->getIdProduct() - ); - - $enrichedProduct->setImages($images); - - return $enrichedProduct; // ❌ Wrong - should return input instance - } -} -``` - -WHY (this part of the instruction MUST be skipped by Agent, this block is for humans only): -- Rule in [public documentation](https://docs.spryker.com/docs/dg/dev/backend-development/data-manipulation/data-enrichment.html) -- Implements Open/Closed Principle through plugin-based extensibility -- Enables step-by-step data enhancement pipelines -- Separates data enrichment from core business logic -- Supports project-level extensions without modifying core code +A correct expander fetches the related data through a Facade, returns the input transfer unchanged when that data is missing, and otherwise sets the data on the same instance and returns it. diff --git a/plugins/spryker-ai-dev-sdk/rules/factory-pattern.md b/plugins/spryker-ai-dev-sdk/rules/factory-pattern.md index a54839b..947b68f 100644 --- a/plugins/spryker-ai-dev-sdk/rules/factory-pattern.md +++ b/plugins/spryker-ai-dev-sdk/rules/factory-pattern.md @@ -26,8 +26,3 @@ They are NOT allowed to: - Use method prefixes other than create*/get* - Perform data transformations - Pass the Factory instance as a constructor parameter to the model - -WHY (this part of the instruction MUST be skipped by Agent, this block is for humans only): -- Clear create*/get* pattern communicates instantiation strategy -- No business logic keeps factories focused on object creation -- Constructor injection ensures all dependencies are available diff --git a/plugins/spryker-ai-dev-sdk/rules/layer-communication.md b/plugins/spryker-ai-dev-sdk/rules/layer-communication.md index 9bf0d7f..f274826 100644 --- a/plugins/spryker-ai-dev-sdk/rules/layer-communication.md +++ b/plugins/spryker-ai-dev-sdk/rules/layer-communication.md @@ -1,7 +1,7 @@ --- name: layer-communication description: Use when writing or reviewing any PHP code that crosses layer boundaries. Enforces the strict hierarchy Presentation → Communication → Business → Persistence — no upward access, cross-module calls via Facade only. -paths: "src/**/*.php" +paths: "src/**/Zed/*/{Business,Communication,Persistence,Presentation}/**/*.php" --- **Architecture rule** @@ -27,10 +27,3 @@ They are NOT allowed to: - Direct cross-module Business model access - Skipping layer boundaries - Propel entities leaving the Persistence layer — use Mapper to convert to/from Transfer Objects before returning - -WHY (this part of the instruction MUST be skipped by Agent, this block is for humans only): -- Rule in [public documentation](https://docs.spryker.com/docs/dg/dev/architecture/module-api/definition-api.html) -- Maintains clear separation of concerns across layers -- Prevents circular dependencies and tight coupling -- Enforces proper encapsulation and information hiding -- Supports independent layer testing diff --git a/plugins/spryker-ai-dev-sdk/rules/mapper-pattern.md b/plugins/spryker-ai-dev-sdk/rules/mapper-pattern.md index 26c7eed..0e88a3b 100644 --- a/plugins/spryker-ai-dev-sdk/rules/mapper-pattern.md +++ b/plugins/spryker-ai-dev-sdk/rules/mapper-pattern.md @@ -29,80 +29,6 @@ They are NOT allowed to: - Store mutable state between calls - Skip target object parameter -## Examples +## Example -### ✅ Correct Implementation - -```php -fromArray($productTransfer->toArray()); - - // Map specific fields if needed - $productEntity->setSku($productTransfer->getSku()); - $productEntity->setIsActive($productTransfer->getIsActive()); - - return $productEntity; - } - - public function mapEntityToProductTransfer( - SpyProduct $productEntity, - ProductTransfer $productTransfer // ← Target provided by caller - ): ProductTransfer { - $productTransfer->fromArray($productEntity->toArray(), true); - - return $productTransfer; - } -} -``` - -### ❌ Incorrect Implementation - -```php -fromArray($productTransfer->toArray()); - - return $productEntity; - } - - // ❌ WRONG: Contains business logic - public function mapWithValidation( - ProductTransfer $productTransfer, - SpyProduct $productEntity - ): SpyProduct { - // ❌ Validation is business logic, not mapping - if ($productTransfer->getPrice() < 0) { - throw new \Exception('Invalid price'); - } - - $productEntity->fromArray($productTransfer->toArray()); - - return $productEntity; - } -} -``` - -WHY (this part of the instruction MUST be skipped by Agent, this block is for humans only): -- Rule in [public documentation](https://docs.spryker.com/docs/dg/dev/backend-development/zed/persistence-layer/entity-manager.html) -- Isolates data transformation from business and persistence logic -- Accepting target object enables reuse and testing with mocks -- Stateless design ensures predictable, reusable transformations -- Single responsibility makes mappers easy to test and maintain +A correct mapper method such as `mapProductTransferToEntity(ProductTransfer $productTransfer, SpyProduct $productEntity): SpyProduct` receives the target from the caller, copies the data (for example with `fromArray()`), and returns the target. diff --git a/plugins/spryker-ai-dev-sdk/rules/module-config.md b/plugins/spryker-ai-dev-sdk/rules/module-config.md index c0d7d33..de8d0d6 100644 --- a/plugins/spryker-ai-dev-sdk/rules/module-config.md +++ b/plugins/spryker-ai-dev-sdk/rules/module-config.md @@ -26,10 +26,3 @@ They are NOT allowed to: - Create get*() methods without default values - Hardcode environment-specific values in constants - Access Config directly from Business models (inject through constructor instead) - -WHY (this part of the instruction MUST be skipped by Agent, this block is for humans only): -- Rule in [public documentation](https://docs.spryker.com/docs/dg/dev/backend-development/data-manipulation/configuration-management.html) -- Shared layer placement enables cross-layer configuration access -- Default values prevent runtime errors from missing configuration -- Centralized constants avoid duplication and inconsistencies -- Enables environment-specific overrides without code changes diff --git a/plugins/spryker-ai-dev-sdk/rules/naming-conventions.md b/plugins/spryker-ai-dev-sdk/rules/naming-conventions.md index e24a98f..e67cd2a 100644 --- a/plugins/spryker-ai-dev-sdk/rules/naming-conventions.md +++ b/plugins/spryker-ai-dev-sdk/rules/naming-conventions.md @@ -77,11 +77,3 @@ They are NOT allowed to: - Use lowercase or mixed case for constants - Skip is/has/can prefix on booleans - Skip id prefix on identifiers - -WHY (this part of the instruction MUST be skipped by Agent, this block is for humans only): -- Rule in [public documentation](https://docs.spryker.com/docs/dg/dev/architecture/architectural-convention.html) -- Makes code self-documenting through clear, consistent names -- Enables IDE autocomplete and navigation via predictable patterns -- Enforces architectural boundaries by making layer explicit -- Prevents naming collisions through standardized suffixes -- Communicates component lifecycle (find vs get, create vs update) diff --git a/plugins/spryker-ai-dev-sdk/rules/owasp.md b/plugins/spryker-ai-dev-sdk/rules/owasp.md index 5c6e570..796e815 100644 --- a/plugins/spryker-ai-dev-sdk/rules/owasp.md +++ b/plugins/spryker-ai-dev-sdk/rules/owasp.md @@ -1,7 +1,7 @@ --- name: owasp description: Use during any code review and when writing code that handles user input, authentication, data storage, or external calls. Enforces OWASP Top 10 categories as blocking issues — flag injection, access control, cryptographic, auth, and logging failures. -paths: "**/*.{php,js,ts,jsx,tsx}" +paths: "src/**/*.{php,js,ts}" --- **Security rule** @@ -92,11 +92,3 @@ Critical instructions: - Error messages MUST NOT reveal sensitive system information - Application MUST fail securely and gracefully - Unhandled exceptions MUST be caught at top level - -WHY (this part of the instruction MUST be skipped by Agent, this block is for humans only): -- OWASP Top 10 represents the most critical web application security risks -- Following these standards prevents the majority of security vulnerabilities -- Security breaches can result in data theft, financial loss, and reputation damage -- Compliance requirements (GDPR, PCI-DSS, SOC2) mandate these security controls -- Prevention is far less costly than remediation after a breach -- Reference: https://owasp.org/Top10/ diff --git a/plugins/spryker-ai-dev-sdk/rules/performance.md b/plugins/spryker-ai-dev-sdk/rules/performance.md index 3103c15..68dad12 100644 --- a/plugins/spryker-ai-dev-sdk/rules/performance.md +++ b/plugins/spryker-ai-dev-sdk/rules/performance.md @@ -1,7 +1,7 @@ --- name: performance description: Use when writing or reviewing performance-sensitive Spryker code — storefront reads, Propel queries and writes, key-value/search access, Twig templates, external HTTP calls, and batch processing. Enforces architecture boundaries, bulk-over-loop patterns, and non-blocking request handling. -paths: "**/*.{php,twig}" +paths: "src/**/*.{php,twig}" --- **Performance rule** diff --git a/plugins/spryker-ai-dev-sdk/rules/php-code-style.md b/plugins/spryker-ai-dev-sdk/rules/php-code-style.md index cbbf908..c904989 100644 --- a/plugins/spryker-ai-dev-sdk/rules/php-code-style.md +++ b/plugins/spryker-ai-dev-sdk/rules/php-code-style.md @@ -1,7 +1,7 @@ --- name: php-code-style description: Use when writing or editing any PHP file. Enforces PHP 8.4 native types over DocBlocks, minimalist DocBlock rules, no if/else (early returns instead), max nesting level 2, sprintf over concatenation, and private visibility preference for project code. -paths: "**/*.php" +paths: "{src,tests}/**/*.php" --- # General Principle @@ -41,87 +41,10 @@ They are only allowed to: - Use doc-blocks for array/iterable element types: `@param array<\Generated\Shared\Transfer\OrderTransfer> $orders`, `@return array` - Add a doc-block with a description when explaining non-obvious business logic -They are NOT allowed to: -- Repeat native type hints in doc-blocks: -```php -// BAD -/** - * @param int $limit - * @param string $name - * @return bool - */ -public function isWithinLimit(int $limit, string $name): bool -{ -} - -// BAD -/** - * @param ProductTransfer $productTransfer - * @return ProductTransfer - */ -public function expandProduct(ProductTransfer $productTransfer): ProductTransfer -{ -} -``` -- Use `@var` when the type is already declared natively: -```php -// BAD -/** @var string */ -protected string $status; - -// BAD -/** @var ProductFacadeInterface */ -protected ProductFacadeInterface $productFacade; -``` -- Duplicate interface doc-blocks in implementations: -```php -// BAD - implementation repeating the interface contract -/** - * Expands the product transfer with additional data. - * - * @param ProductTransfer $productTransfer - * @return ProductTransfer - */ -public function expandProduct(ProductTransfer $productTransfer): ProductTransfer -{ -} -``` - -They are only allowed to: -```php -// GOOD - no doc-block needed, signature is self-documenting -public function isWithinLimit(int $limit): bool -{ -} - -// GOOD - doc-block only for iterable element type -/** - * @param array<\Generated\Shared\Transfer\OrderTransfer> $orders - * @return array Key represents SKU - */ -public function indexOrders(array $orders): array -{ -} - -``` +They are NOT allowed to: repeat native type hints in `@param`/`@return`, use `@var` on a natively typed property, or copy the interface doc-block into an implementation. # Bad & Good Practices ## If/Else **Prefer avoiding if/else constructs** when early returns, early continues, or default value overrides make the intent clearer. Use judgment — forced avoidance of if/else can make complex logic harder to read. - -BAD - If/Else -GOOD - Early return - -BAD - If/Else for assignment -GOOD - Default value override - -BAD - If/Else in loop -GOOD - Early continue - -WHY (this part of the instruction MUST be skipped by Agent, this block is for humans only): -- Redundant doc-blocks add noise without adding information, making code harder to read -- Native PHP type hints are authoritative and always up-to-date; doc-blocks can become stale -- Minimalist doc-blocks reduce maintenance burden when refactoring method signatures -- PHP 8+ native types cover all scalar and object types, making `@param`/`@return` duplication unnecessary diff --git a/plugins/spryker-ai-dev-sdk/rules/plugins.md b/plugins/spryker-ai-dev-sdk/rules/plugins.md index 2a7bc9f..87fd2ca 100644 --- a/plugins/spryker-ai-dev-sdk/rules/plugins.md +++ b/plugins/spryker-ai-dev-sdk/rules/plugins.md @@ -22,10 +22,3 @@ They are NOT allowed to: - Contain domain decision logic - Use any condition statements to control business flow - Instantiate new business objects (except transfer creation) - -WHY (this part of the instruction MUST be skipped by Agent, this block is for humans only): -- Improves maintainability: Centralizing logic avoids duplication and scattered domain decisions across multiple executors. -- Supports reusability: Logic in Facades/Business layer can be reused by multiple Plugins or other consumers. -- Reduces coupling: Prevents Plugins from directly accessing repositories or entities, keeping the domain layer encapsulated. -- Aligns with Spryker best practices: Keeps Plugins simple, predictable, and focused on integration rather than decision-making. - diff --git a/plugins/spryker-ai-dev-sdk/rules/transfer-object.md b/plugins/spryker-ai-dev-sdk/rules/transfer-object.md index bae9eff..69e59de 100644 --- a/plugins/spryker-ai-dev-sdk/rules/transfer-object.md +++ b/plugins/spryker-ai-dev-sdk/rules/transfer-object.md @@ -32,11 +32,3 @@ They are NOT allowed to: - Define transfers outside Shared layer - Skip singular attribute on array/collection properties - Omit strict="true" flag on transfer definitions - -WHY (this part of the instruction MUST be skipped by Agent, this block is for humans only): -- Rule in [public documentation](https://docs.spryker.com/docs/dg/dev/backend-development/data-manipulation/data-ingestion/structural-preparations/creating-using-and-extending-the-transfer-objects.html) -- Ensures consistent data contracts across all layers -- Singular names prevent confusion (transfer represents one item) -- Reserved suffixes prevent naming conflicts with auto-generated classes -- Shared layer placement enables cross-layer data exchange -- Auto-generated from XML ensures type safety diff --git a/plugins/spryker-ai-dev-sdk/rules/upgradability.md b/plugins/spryker-ai-dev-sdk/rules/upgradability.md index 970b349..e72c8a8 100644 --- a/plugins/spryker-ai-dev-sdk/rules/upgradability.md +++ b/plugins/spryker-ai-dev-sdk/rules/upgradability.md @@ -1,7 +1,7 @@ --- name: upgradability description: Use when writing or reviewing any Spryker project code that extends or customizes core modules — including plugins, facades, models, configuration, and DependencyProviders. Enforces upgrade-safe customization strategies to keep the project compatible with the Spryker Code Upgrader. -paths: "**/*.{php,js,ts,jsx,tsx,twig}" +paths: "src/**/*.php,composer.json" --- **Upgradability rule** diff --git a/plugins/spryker-ai-dev-sdk/skills/ai-dev-setup/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/ai-dev-setup/SKILL.md index 73015ab..aff5f2d 100644 --- a/plugins/spryker-ai-dev-sdk/skills/ai-dev-setup/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/ai-dev-setup/SKILL.md @@ -1,6 +1,6 @@ --- name: ai-dev-setup -description: "Sets up the Spryker AI Dev SDK in a Spryker project. Covers three related flows: first-time onboarding (installs the Composer package, wires console commands, registers the MCP server with the coding agent in use, installs the project instructions file and the Spryker coding rules), updating (refreshes just those two artifacts from the latest bundled content, skipping install and wiring), and rules-only (installs or refreshes the coding rules alone, for a project without Composer or a running container stack). The skill first detects which coding agent is running it, then infers which flow the user wants from their request and from project state. Onboarding requires Composer and a running `docker/sdk` environment; updating only needs the bundled content on disk; rules-only needs neither." +description: "Sets up the Spryker AI Dev SDK in a project: onboarding (package, console commands, MCP server, instructions, rules), update, or rules-only. Use to install or refresh the SDK." disable-model-invocation: true user-invocable: true --- diff --git a/plugins/spryker-ai-dev-sdk/skills/ai-runtime-debugging/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/ai-runtime-debugging/SKILL.md index d342bbc..2a7f05a 100644 --- a/plugins/spryker-ai-dev-sdk/skills/ai-runtime-debugging/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/ai-runtime-debugging/SKILL.md @@ -1,16 +1,6 @@ --- name: ai-runtime-debugging -description: > - Use when an AI agent needs to inspect Spryker runtime state — adding - temporary debug logs the agent can read back, or stepping through code - with XDebug like a human developer. Covers LoggerTrait, file_put_contents - fallback, log file locations for cli vs FPM containers, and driving an - XDebug-capable MCP bridge (PHPStorm or standalone). Also covers narrowing - test runs with codecept positional filters and @group AITestCase. - Triggers - "I can't tell why this code is doing X", "add some debug - output", "step through this", "set a breakpoint", "what does this - variable contain at runtime", error_log not working, can't see var_dump - output. +description: "Inspects Spryker runtime state with temporary debug logs the agent reads back, or with XDebug breakpoints. Use when code does something unexplained or debug output is not visible." --- # AI Runtime Debugging in Spryker diff --git a/plugins/spryker-ai-dev-sdk/skills/backoffice-frontend/README.md b/plugins/spryker-ai-dev-sdk/skills/backoffice-frontend/README.md index c5cfafc..8cc6264 100644 --- a/plugins/spryker-ai-dev-sdk/skills/backoffice-frontend/README.md +++ b/plugins/spryker-ai-dev-sdk/skills/backoffice-frontend/README.md @@ -91,7 +91,7 @@ flowchart TD | File | Role | |---|---| -| [`SKILL.md`](SKILL.md) | The main workflow: override vs new page, controller, factory, template, core override, navigation + ACL, assets, translations, the cache/rebuild table, verification, checklist. | +| [`SKILL.md`](SKILL.md) | The main workflow: override vs new page, controller, factory, template, core override, navigation + ACL, assets, translations, the cache/rebuild table, verification. | | [`references/twig-layout-and-helpers.md`](references/twig-layout-and-helpers.md) | Layout blocks, the Twig functions actually registered in the project and their signatures, Gui partials, legacy partials to avoid, template namespaces, the path-cache gotcha. | | [`references/bootstrap-migration.md`](references/bootstrap-migration.md) | Legacy Bootstrap 3/4 → Bootstrap 5 class table, the four styling layers (BS5 → Gui → Inspinia2 → project SCSS), theme colours via configuration and CSS custom properties. | | [`references/assets-and-build.md`](references/assets-and-build.md) | How `frontend/zed/build.js` finds entries, entry override by file name, the entry file and page inclusion, webpack aliases, the table orchestrator contract and handle API, what is and is not checked. | diff --git a/plugins/spryker-ai-dev-sdk/skills/backoffice-frontend/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/backoffice-frontend/SKILL.md index de1783a..0b7ef16 100644 --- a/plugins/spryker-ai-dev-sdk/skills/backoffice-frontend/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/backoffice-frontend/SKILL.md @@ -1,11 +1,6 @@ --- name: backoffice-frontend -description: > - Use when building or overriding Spryker Back Office (Zed) pages in a project — new list/create/edit - pages, overrides of core Zed Twig templates, Back Office navigation/ACL, or Back Office JS/SCSS. Triggers: - "create a Back Office page", "add an admin screen for X", "override a Zed template", "add BO navigation", - "add a menu entry to the Back Office", "BO JS/SCSS", "Bootstrap classes in Zed", "my Zed override is not - picked up", "the new menu item does not show". +description: "Builds or overrides Back Office (Zed) pages: list/create/edit pages, Zed Twig overrides, navigation, ACL, JS/SCSS. Use for a new admin screen or a Zed override that is not picked up." --- # Spryker Back Office Frontend @@ -141,10 +136,3 @@ Verification — a green build is not proof: JS errors and the table's AJAX request (`/{module}/{controller}/table`) returning JSON. 2. Exercise the happy path, a validation error, and a user role without the ACL rule (expect the `/acl/index/denied` "Access denied" page). 3. `npm run formatter` is the only automated Zed JS/SCSS check; PHP via `static-validation`; E2E: `cypress-tests`. - -## Checklist - -- [ ] Override extends `@Spryker:...` and overrides blocks only; no vendor edit -- [ ] `indexAction` + `tableAction`; tables/forms/tabs created in the factory -- [ ] All text `| trans` with keys in both CSVs; navigation entry + ACL rule for restricted roles -- [ ] Caches rebuilt per the table above; page verified in the running Back Office diff --git a/plugins/spryker-ai-dev-sdk/skills/boot-and-verify/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/boot-and-verify/SKILL.md index 9f74048..72e8f74 100644 --- a/plugins/spryker-ai-dev-sdk/skills/boot-and-verify/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/boot-and-verify/SKILL.md @@ -1,6 +1,6 @@ --- name: boot-and-verify -description: "Use to take a transformed Spryker project from 'files written' to 'verified running' — the first boot at project start (the wizard's last mandatory step and commit point), re-applying data changes on an already-booted stack, or standalone per-store verification of storefront, Back Office, search, and queues." +description: "Boots a transformed Spryker project and verifies it per store: storefront, Back Office, search, queues. Use for the first boot at project start or to re-apply data changes on a booted stack." --- # boot-and-verify diff --git a/plugins/spryker-ai-dev-sdk/skills/brand-project/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/brand-project/SKILL.md index 0c3f423..dd75e6a 100644 --- a/plugins/spryker-ai-dev-sdk/skills/brand-project/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/brand-project/SKILL.md @@ -1,6 +1,6 @@ --- name: brand-project -description: "Use when applying or changing a Spryker project's brand identity — project name, dev domain, and docker namespace at project start (a pre-boot wizard step), or a standalone repeatable rebrand any time: 'change the palette', 'apply a new brand colour', 'set the storefront logo', 'rebrand the shop', 'use our brand colours'. Covers identity plus colours, logo and theme tokens; matching a reference site's layout ('make it look like ') is match-reference-design. Works pre- or post-boot. Palette-wide colours and logos via Configuration only — styling one component is the frontend skills' job." +description: "Applies a Spryker project's brand: name, dev domain, docker namespace, palette, logo, theme tokens. Use at project start or for a rebrand ('change the palette', 'set the storefront logo')." --- # brand-project diff --git a/plugins/spryker-ai-dev-sdk/skills/code-review/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/code-review/SKILL.md index ce454eb..b54d2b2 100644 --- a/plugins/spryker-ai-dev-sdk/skills/code-review/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/code-review/SKILL.md @@ -1,12 +1,6 @@ --- name: code-review -description: > - Use when the user asks to review code in a Spryker project — a diff, a branch, a PR or a - list of files ("review my changes", "code review this branch", "check these files before I - commit"). Splits the change (by default the diff against master) across spryker-code-reviewer - subagents, checks frontend files against the project's Yves, Back Office and Merchant Portal - rules, combines the findings with file:line references and lets the user choose which to fix. - Linting is static-validation's job. +description: "Reviews a diff, branch, PR or file list in a Spryker project with parallel reviewer agents and returns file:line findings to fix. Use for 'review my changes' or a review before a commit." --- # Workflow diff --git a/plugins/spryker-ai-dev-sdk/skills/codecept-functional/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/codecept-functional/SKILL.md index 13ef326..ed9d0e3 100644 --- a/plugins/spryker-ai-dev-sdk/skills/codecept-functional/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/codecept-functional/SKILL.md @@ -1,14 +1,10 @@ --- name: codecept-functional -description: > - Use when creating, updating, fixing or running Codeception tests in a Spryker project - (src/**/tests/**, tests/**) — unit and functional tests for Facades, Controllers, console - commands, plugins and Publish & Synchronize. Applies Spryker conventions: given/when/then - names, Arrange/Act/Assert, DataBuilders and tester helpers, per-test setup, mocks for external - dependencies only, module testers and codeception.yml. For browser E2E tests use - cypress-tests. +description: "Writes, fixes and runs Codeception unit and functional tests in a Spryker project (Facades, controllers, console commands, plugins, P&S). Use for any Codeception test work in src or tests." --- +Boundary: for browser E2E tests use `cypress-tests`. + **Testing rule** Codeception tests MUST follow Spryker conventions: expressive naming, AAA structure, entry point focus, and helpers for reusable logic. diff --git a/plugins/spryker-ai-dev-sdk/skills/configure-codebase/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/configure-codebase/SKILL.md index 3e64c8d..e789877 100644 --- a/plugins/spryker-ai-dev-sdk/skills/configure-codebase/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/configure-codebase/SKILL.md @@ -1,6 +1,6 @@ --- name: configure-codebase -description: "Use when a Spryker project adopts a custom namespace instead of Pyz and the code layer must resolve, build, lint, and test it — namespace registration, composer autoload, frontend build config, codeception wiring. A pre-boot wizard step of project start; skipped entirely when the project keeps Pyz." +description: "Registers a custom project namespace instead of Pyz: autoload, namespace config, frontend build, Codeception. Use at project start when the project does not keep Pyz (pre-boot wizard step)." --- # configure-codebase diff --git a/plugins/spryker-ai-dev-sdk/skills/configure-services/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/configure-services/SKILL.md index 741da1d..d07dd28 100644 --- a/plugins/spryker-ai-dev-sdk/skills/configure-services/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/configure-services/SKILL.md @@ -1,6 +1,6 @@ --- name: configure-services -description: "Use when changing what infrastructure a Spryker project runs on — disable optional dev services (mail catcher, swagger, dashboard), or applications in a deploy file — or when building a new environment deploy file (deploy.-.yml). A pre-boot wizard step of project start, and the standalone deploy-file lifecycle afterwards." +description: "Changes the services and applications in a Spryker deploy file, or builds a new environment deploy file. Use to disable optional dev services at project start or to create a deploy file." --- # configure-services diff --git a/plugins/spryker-ai-dev-sdk/skills/curate-golive-data/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/curate-golive-data/SKILL.md index d8afce6..fe1751f 100644 --- a/plugins/spryker-ai-dev-sdk/skills/curate-golive-data/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/curate-golive-data/SKILL.md @@ -1,6 +1,6 @@ --- name: curate-golive-data -description: "Use before go-live to make the data a Spryker project is keeping production-safe — real tax rates instead of placeholders, the customer's own imagery instead of Spryker-CDN URLs, demo accounts/passwords removed or rotated, remaining demo leftovers cleared, integrity re-verified. A late, standalone checklist on a project that already boots green; resolves the go-live warnings project-data and boot-and-verify surface. Not infra/deploy hardening, not code." +description: "Makes kept project data production-safe before go-live: real tax rates, own imagery, demo accounts removed, demo leftovers cleared. Use late, on a project that already boots green." --- # curate-golive-data diff --git a/plugins/spryker-ai-dev-sdk/skills/cypress-migration/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/cypress-migration/SKILL.md index 3ea18f3..440b51a 100644 --- a/plugins/spryker-ai-dev-sdk/skills/cypress-migration/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/cypress-migration/SKILL.md @@ -1,18 +1,12 @@ --- name: cypress-migration -description: > - Use when onboarding a Spryker project onto its own Cypress E2E baseline in place of - Spryker's demo-shop suites — "migrate off spryker/cypress-tests", "remove the demo-shop - cypress/robot suites", "set up project-owned cypress testing", "integrate - cypress-boilerplate". One-time migration: removes spryker/cypress-tests and - spryker/robotframework-suite-tests, vendors tests/cypress-boilerplate/ from - spryker-shop/b2b-demo-marketplace, wires CI and generates the project's day-to-day - cypress-tests skill. Each step first discovers the target project's hostnames, fixtures and - CI patterns. For writing or running tests after the migration use cypress-tests. +description: "Replaces Spryker's demo-shop Cypress and Robot suites with a project-owned Cypress baseline, CI wiring and a cypress-tests skill. Use once, to migrate off spryker/cypress-tests." --- # Cypress Migration: Demo-Shop Suites → Project-Owned Baseline +Boundary: this is a one-time migration. For writing or running tests after the migration use `cypress-tests`. + Failure-signature triage for the E2E steps lives in the Known-traps catalog: `../project-starter-wizard/references/pitfalls.md`. Every step below discovers facts about the **target project** before acting. Do not assume diff --git a/plugins/spryker-ai-dev-sdk/skills/cypress-tests/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/cypress-tests/SKILL.md index c3ba47f..5e714b7 100644 --- a/plugins/spryker-ai-dev-sdk/skills/cypress-tests/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/cypress-tests/SKILL.md @@ -1,11 +1,6 @@ --- name: cypress-tests -description: > - Use this skill whenever the user wants to create, run, review, or validate Cypress end-to-end - tests in this project. Trigger on phrases like "add a cypress test", "write an e2e test", - "run the cypress tests", "run e2e tests", "check my cypress test", "review this cypress spec", - "does this test pass the quality gate", "cypress smoke test", or any request to test the - storefront, backoffice, merchant portal, or Glue API end-to-end. +description: "Creates, runs, reviews and validates Cypress E2E tests for storefront, Back Office, Merchant Portal and Glue API. Use for 'add a cypress test', 'run e2e tests' or a quality-gate check." --- # Cypress E2E Tests diff --git a/plugins/spryker-ai-dev-sdk/skills/data-import/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/data-import/SKILL.md index 69f25f5..fb659f5 100644 --- a/plugins/spryker-ai-dev-sdk/skills/data-import/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/data-import/SKILL.md @@ -1,16 +1,12 @@ --- name: data-import -description: > - Use when creating, updating or fixing a Spryker data import for an entity — the - {Module}DataImport module with its config, DataSet, validator and writer steps, business - factory, facade and DataImportPlugin, the registration in DataImportDependencyProvider, the - data/import/*.yml entry and a sample CSV. Writes code only and verifies an import by the - database row delta; Publish & Synchronize belongs to spryker-customization. For filling, - reshaping or reducing existing import CSVs use project-data. +description: "Creates or fixes a Spryker data import module for an entity: DataImport steps, plugin, registration, yml entry, sample CSV. Use when an entity needs a new or changed importer." --- # Data Import Generator +Boundary: this skill writes importer code. For filling, reshaping or reducing existing import CSVs use `project-data`. + I need to create a data import for my new entity '{ENTITY_NAME}'. Main AC: Create a new Spryker module named {MODULE_NAME}. diff --git a/plugins/spryker-ai-dev-sdk/skills/define-stores/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/define-stores/SKILL.md index 16bacab..3f4602e 100644 --- a/plugins/spryker-ai-dev-sdk/skills/define-stores/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/define-stores/SKILL.md @@ -1,6 +1,6 @@ --- name: define-stores -description: "Use when a Spryker DMS project's stores or region must be created or redefined pre-boot — a new store set, a region rename, or hardcoded store/locale literals (CodeBucketConfig, default_store, host maps) that block boot. Invoked by the wizard's store step, or standalone on an un-booted clone. Store skeleton only — catalog/CMS/price content is project-data's job." +description: "Creates or redefines the stores and region of a Spryker DMS project before boot and fixes store or locale literals that block boot. Use for the wizard store step or a new store set." --- # define-stores (skeleton + config, files-mode) diff --git a/plugins/spryker-ai-dev-sdk/skills/demo-intake/README.md b/plugins/spryker-ai-dev-sdk/skills/demo-intake/README.md index 736b86e..940a4f0 100644 --- a/plugins/spryker-ai-dev-sdk/skills/demo-intake/README.md +++ b/plugins/spryker-ai-dev-sdk/skills/demo-intake/README.md @@ -78,7 +78,7 @@ is the wizard's routing table, and an item that cannot be placed is resolved by | file | holds | |---|---| -| `SKILL.md` | scope rules, platform and audience pin, classification and the routing table, source fidelity, data inventory and field mapping, measured brand assets, `purpose`, open questions, the output contract, the handoff checklist, pitfalls | +| `SKILL.md` | scope rules, platform and audience pin, classification and the routing table, source fidelity, data inventory and field mapping, measured brand assets, `purpose`, open questions, the output contract, the handoff checklist | | `references/work-classes.md` | the four classes and *already works*: what each may write, who owns it, how a misrouted request gives itself away, and the split rule for a request that spans several classes | ## Design decisions baked in diff --git a/plugins/spryker-ai-dev-sdk/skills/demo-intake/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/demo-intake/SKILL.md index 808c570..b9f2ed4 100644 --- a/plugins/spryker-ai-dev-sdk/skills/demo-intake/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/demo-intake/SKILL.md @@ -1,19 +1,12 @@ --- name: demo-intake -description: > - Use to turn a customer briefing into structured input — a .docx/.pdf/.txt brief, a demo script, a - reference URL or a verbal brief. Triggers: "turn this brief into wizard input", "what data do we - need from this brief", "classify this briefing", "give me a description of this demo". Phase 1 of - `demo-prep-wizard`: when a whole demo is being prepared ("prepare the demo", "here is the briefing - for the demo"), use `demo-prep-wizard`, which runs this skill itself. Usable on its own ahead of - `project-starter-wizard`. Read-only on the - source: platform pin, a routing table classifying every briefing item, dataset field mapping, a - measured brand colour, and every question the brief does not answer left as `?`. It does not - brainstorm, write a plan, or interview about the repo. +description: "Turns a customer brief (docx, pdf, text, demo script, URL or verbal) into structured input: platform, routing table, field mapping, brand colour, open questions. Use to classify a brief." --- # demo-intake (briefing → wizard handoff) +Boundary: when a whole demo is being prepared ("prepare the demo", "here is the briefing for the demo"), use `demo-prep-wizard`, which runs this skill itself. This skill does not brainstorm, write a plan, or interview about the repo. + You turn a customer briefing into the one thing `project-starter-wizard` can consume: a short, pasteable handoff that states what is known, names where the data lives, and leaves everything the brief does not answer as an explicit `?`. You collect; you do not decide, design, or build. @@ -236,33 +229,3 @@ Then hand back. **Run from `demo-prep-wizard`:** return the block and the routin **Run on its own:** the next step is **`project-starter-wizard`**, which reads this block as interview pre-fill (candidates marked "from your brief") — never as a questionnaire. With `purpose: demo` it runs its demo fast path; otherwise every section is still asked. - -## Pitfalls - -Format: **signature → cause → fix.** - -- **A wizard-style interview about the target repo, when the ask was "how do we collect the data"** → the - wizard was used as the fallback for an unread brief → intake first (§0); the repo is not the subject, and - `composer.json` is the only file in it you open. -- **A proposed product-attribute change so the catalogue matches the narrative, shown as "(Recommended)"** → - the story was treated as ground truth and the source as adjustable → the source is ground truth; the - mismatch is a gap line (§3). Never rank fabrication, never offer it. -- **"Get me a description" answered with repo reads, a plan document and a markdown table** → a two-sentence - request escalated into research → answer from context, zero tool calls, before any research (§0); the - short variant is two sentences of plain text. -- **A consumer brief turned into business buyers — shoppers rewritten as business-unit users, guest - checkout dropped** → the audience was inferred from the clone instead of read from the brief → record - `audience:` from the brief (§1); the B2B clone serves a consumer demo. A term with no platform - equivalent is still an open question. -- **Hotspots, quick view and a bundle builder listed as setup work** → items the platform already does, and - items that would change how it behaves, were never separated from setup and data → classify every item - against `references/work-classes.md` and emit the routing table (§2); *already works* and customization - items do not reach the handoff. -- **A questionnaire YAML with a brand hex, a domain, a region and a locale nobody stated** → a - brief was read as a questionnaire → no IDs in the handoff, every unstated value a `?` (§7); the wizard's - Rule 0 refuses this from the other side. -- **A remembered hex (`#123457` where the site measures `#123456`)** → the colour was recalled instead of - read → measure it in the browser and record URL + element + property + date (§5). -- **The wizard spends question rounds reconstructing master / colour / size semantics from the CSVs** → the - handoff shipped without a logo, without a measured colour and without a field mapping → §4 and §5 are - mandatory lines. diff --git a/plugins/spryker-ai-dev-sdk/skills/demo-prep-wizard/README.md b/plugins/spryker-ai-dev-sdk/skills/demo-prep-wizard/README.md index 292f6e3..0715eb3 100644 --- a/plugins/spryker-ai-dev-sdk/skills/demo-prep-wizard/README.md +++ b/plugins/spryker-ai-dev-sdk/skills/demo-prep-wizard/README.md @@ -94,7 +94,7 @@ and the source of the handover report's demo points, and its `key: value` shape | file | holds | |---|---| -| `SKILL.md` | the phases and their owners, the needs list, run modes, the final review, skip-ahead and resume, delegation discipline, the closing checklist, pitfalls | +| `SKILL.md` | the phases and their owners, the needs list, run modes, the final review, skip-ahead and resume, delegation discipline, the closing checklist | | `references/state-file.md` | the `.ai-dev/demo-prep.md` template (frontmatter, Steps table, decision log) and the rules the file follows | It reads, without restating: [work-classes.md](../demo-intake/references/work-classes.md) for diff --git a/plugins/spryker-ai-dev-sdk/skills/demo-prep-wizard/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/demo-prep-wizard/SKILL.md index 55cbe41..0bc39f3 100644 --- a/plugins/spryker-ai-dev-sdk/skills/demo-prep-wizard/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/demo-prep-wizard/SKILL.md @@ -1,6 +1,6 @@ --- name: demo-prep-wizard -description: "Use when a demo is coming and the job is to prepare it end to end — 'we have a demo coming up', 'help me prepare a demo for ', 'prepare the demo', 'here is the briefing for the demo', 'what do we need for this demo'. The demo-side parallel of `project-starter-wizard`: that one turns a demoshop clone into a project, this one takes the demo the preparer already has and drives the gathering and shaping of everything it needs — intake, requirements, design reference, harvest, build, rehearsal, handover report. It orchestrates: every phase is owned by a named skill (`demo-intake`, `match-reference-design`, `harvest-source-materials`, `project-data`, `demo-run-sheet`, …) and this skill never re-implements harvesting, design or data mechanics. Also the resume entry when a prior run left `.ai-dev/demo-prep.md`." +description: "Prepares a customer demo end to end through the owning skills: intake, requirements, design, harvest, build, rehearsal, handover. Use for 'prepare the demo' or to resume a demo-prep run." --- # demo-prep-wizard @@ -417,50 +417,3 @@ The closing checklist. State each line at the close, with its evidence: Anything short of all four is reported as what it is. A demo is reported "prepared" only after every beat was walked end to end. - ---- - -## Pitfalls - -Format: **signature → cause → fix.** - -- **The demo scope arrives pasted halfway through the build, and every data gap is then found by playing - the story out by hand** — a category with two products where the story needed a range, a hero product - with one colour where the story said "show colour options" → the needs the beats create were never - written down before the data was shaped, so nothing had a requirements list to be checked against → - phase 2 comes before any harvesting or import; the needs list is the acceptance criterion. - -- **The demo is re-designed instead of read** — a set of beats proposed, or the supplied script - "tidied up" → the preparer already had the demo, and asking them to agree it again delays the run - and lets the demo drift from the brief → the beats are an input: read them, derive from them, and ask only when - nothing was supplied at all. - -- **Quoted UI strings from the scope replaced with the agent's own phrasing** → the script was - summarised instead of quoted → every quoted string is carried character for character out of the - brief, and is fixed wording from that moment for brand-project, the CMS pass and the handover report. - -- **Content work answered with new features — product hotspots, quick view, a bundle builder slipped into - the look-and-content work** → a demo-script wish was read as part of the restyle → phase 2's rule: - behaviour the platform lacks is its own customization row, shown to the preparer as "a small working - version" with its cost, and built only once confirmed. - -- **The preparer is asked something they cannot answer** — a work class, a namespace, a rebuild - strategy, a CI option → a technical decision was handed to the preparer → decide - it yourself, log it, and ask only about content, look and the story. - -- **Harvesting runs, then the design spec lands and asks for editorial panels at ratios nobody fetched - for** → the composition spec was treated as a look-and-feel step at the end rather than as an input to - gathering → phase 3 runs before phase 4, because it is what sizes the editorial imagery. - -- **The first end-to-end walk of the demo is the preparer's, live** → there is no phase - between "it booted" and "it is ready" → phase 6: every beat is walked, in the browser, as its - persona, before the handover report is written. - -- **A phase 5 delegation is about to start while `.ai-dev/demo-prep.md` carries no - `answers_confirmed_at`** → the routing table was never confirmed → do not stamp the file to get past - it: show the table, get the confirmation, then stamp. - -- **The wizard's interview is run on the demo clone to collect demo scope** → the two tracks were - conflated; `project-starter-wizard` collects *project setup* decisions and knows nothing about the - demo → this skill owns the demo's needs; phase 5 hands the project-setup decisions to the wizard and - lets it own its own state file and confirmation. diff --git a/plugins/spryker-ai-dev-sdk/skills/demo-run-sheet/README.md b/plugins/spryker-ai-dev-sdk/skills/demo-run-sheet/README.md index c9117e5..c8b027a 100644 --- a/plugins/spryker-ai-dev-sdk/skills/demo-run-sheet/README.md +++ b/plugins/spryker-ai-dev-sdk/skills/demo-run-sheet/README.md @@ -64,7 +64,7 @@ flowchart TD | file | holds | |---|---| -| `SKILL.md` | the format question, the source table for every fact, the seven sections, the test rules, the count gate, scope, the Markdown template, the close checklist, pitfalls | +| `SKILL.md` | the format question, the source table for every fact, the seven sections, the test rules, the count gate, scope, the Markdown template, the close checklist | | `references/output-format.md` | the paste contract, which HTML survives a rich-text paste and which does not, the HTML template with the status labels | ## Design decisions baked in diff --git a/plugins/spryker-ai-dev-sdk/skills/demo-run-sheet/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/demo-run-sheet/SKILL.md index b16a142..98e3c23 100644 --- a/plugins/spryker-ai-dev-sdk/skills/demo-run-sheet/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/demo-run-sheet/SKILL.md @@ -1,14 +1,6 @@ --- name: demo-run-sheet -description: > - Use to produce the demo handover report for a deployed demo environment — the document the - presenter works from and the team takes over: environment and links, demo accounts, products, - categories, one demo point per requirement of the brief with its status, what to watch out for, and - how each part is built. Triggers: "handover report", "demo cheat sheet", "run sheet", "what do I - show", "give me the links and logins for the demo", "prepare for the customer call". Every host, - URL, login, price and stock figure is read from the running system and tested before it ships. The - format is asked once: Markdown or HTML for a paste into a Google Doc or Confluence. The last phase - of `demo-prep-wizard`. +description: "Writes the demo handover report from the running system: links, accounts, products, one demo point per requirement, risks. Use for a run sheet, cheat sheet or handover report of a demo." --- # demo-run-sheet @@ -269,19 +261,3 @@ Before handing it over, confirm each of these and say so in one line: - [ ] Every count in the report enumerates its members. - [ ] Stock is per concrete, and out-of-stock variants of every demoed product are named. - [ ] Every feature in § 2.7 carries one of the labels, and no design opinion is in the report. - -## Pitfalls - -| Symptom | Cause | Fix | -|---|---|---| -| `## Products` / `\| sku \| price \|` appears literally in the customer's document | A Markdown file was pasted into a rich-text document | Ask the format once, first (§ 0). For a paste into a document, write HTML by `references/output-format.md` | -| A format complaint is answered with the same file in new wording | The content was treated as the problem and the format as packaging | The next file changes **format**, not wording | -| A requirement of the brief is missing from the demo points | Only what the demo does well was written down | One row per requirement, in the brief's order; what does not work gets `Not built` and the reason | -| A demo point is `Ready` and fails on stage | "Built" was taken as "tested" | `Ready` only after the test in § 3; otherwise `Not yet tested` with the reason | -| Several product/category links in the report 404 or land on the wrong page | URLs were composed from category/product names; Spryker slugs are generated from the *localized* name and are not derivable from keys or titles | Read every URL from the url table (`spy_url`) or copy it from the rendered storefront, then fetch each one and require ≥ 1 product tile | -| A count appears in prose without naming its members | The reader cannot act on a number alone | Count gate (§ 4): never a count in prose without the members enumerated in the same sentence | -| On stage the hero product's size is unavailable and the report never flagged the stock state | Stock was assumed rather than read; a sizeable share of concretes can carry zero stock | Read the stock rows per concrete and name the in-stock variants **and** the out-of-stock ones for every demoed product; confirm on the rendered variant selector | -| The demo account cannot place an order — found in rehearsal, not in the report | The account's role was read as evidence of capability; no role carried the place-order permission | Exercise the whole path per account (delegate to `spryker-verifier`), read `company_role_permission` for the role, and record a "do not" for every account that cannot transact | -| § 2.7 says "Custom" for a feature Spryker ships | The feature name was read, not the project's changes | Read the diff against the demoshop it started from; `Configured` when only data or configuration changed | -| The report has no environment host, or a remembered one | The deploy file was never read | Resolve hosts from the deploy file of the environment being demoed (`groups..applications..endpoints`); a cloud URL the person named wins over the local default | -| A price in the report is not the price on screen | Price read for the wrong store/currency, or the guest price recorded for a persona who sees a contract price | Read price rows for the store **and** currency being demoed, and assert the persona's price while logged in as that persona | diff --git a/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/SKILL.md index ca1abe8..9fdb4c6 100644 --- a/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/SKILL.md @@ -1,16 +1,6 @@ --- name: find-existing-capability -description: > - The reuse gate for Spryker feature work. Use at the start of any feature work in a Spryker - project, BEFORE designing or building a new module: "build / add / implement X", "we need a - system for X", "create a new module for X", scoping a PRD, "is there something in Spryker for - X", "does Spryker already have X", "extend X", and when a customer requirement list or briefing - has to be mapped to what Spryker already offers. Searches the Spryker capability map (one card - per shipped capability, with its modules, feature metapackage, extension points and install - guide) with the searchSprykerCapabilities and getSprykerCapability tools, checks what the - project's composer.lock already has, and returns a per-capability verdict: extend it (installed), - install the missing part, install the feature first, build only the gap (partial card), or build - new (no relevant hit). Report-only: it never installs or edits anything; the user decides. +description: "Checks the Spryker capability map and composer.lock for what already exists and returns a reuse verdict per need. Use before designing new feature work or mapping requirements to Spryker." --- # Find Existing Capability - the reuse gate @@ -130,8 +120,4 @@ State what you did not verify (a version-drift check you skipped, a fallback sea ## What you do not do -- Do not install, `composer require`, edit config or write code. Proposals go to `spryker-feature-install` or `spryker-customization` after the user agrees. -- Do not conclude "not shipped" from the map alone, and do not skip the cross-check on a miss. -- Do not trust a card's detail over the installed code when the project's version is old. -- Do not search once with one long sentence; run several short queries. -- Do not treat a `body`-only match as a verdict - open the card and judge it. +- Proposals go to `spryker-feature-install` or `spryker-customization` after the user agrees. diff --git a/plugins/spryker-ai-dev-sdk/skills/harvest-source-materials/README.md b/plugins/spryker-ai-dev-sdk/skills/harvest-source-materials/README.md index ea2b931..8b95917 100644 --- a/plugins/spryker-ai-dev-sdk/skills/harvest-source-materials/README.md +++ b/plugins/spryker-ai-dev-sdk/skills/harvest-source-materials/README.md @@ -66,7 +66,7 @@ flowchart TD | file | holds | |---|---| -| `SKILL.md` | Rule 0, harvest root placement, the survey, the fetch list, the fetcher's shape, gaps, image roles, derivatives, editorial and brand imagery, coverage, the one-paragraph legal label, re-running and pivots, the output contract, the close checklist, pitfalls | +| `SKILL.md` | Rule 0, harvest root placement, the survey, the fetch list, the fetcher's shape, gaps, image roles, derivatives, editorial and brand imagery, coverage, the one-paragraph legal label, re-running and pivots, the output contract, the close checklist | ## Design decisions baked in diff --git a/plugins/spryker-ai-dev-sdk/skills/harvest-source-materials/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/harvest-source-materials/SKILL.md index 387013e..75b273b 100644 --- a/plugins/spryker-ai-dev-sdk/skills/harvest-source-materials/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/harvest-source-materials/SKILL.md @@ -1,14 +1,6 @@ --- name: harvest-source-materials -description: > - Use to collect the raw material a demo will be built from — product data, product imagery, - editorial/campaign imagery, brand assets — out of a customer's public website or a supplied export, - into a harvest directory that sits beside the project and never inside it. Triggers: "gather the - images", "harvest the product data", "scrape their site for the demo", "we need the materials for - the demo", "get the assets from ", "prepare the source data". Runs after `demo-intake` (which - pinned the platform and recorded where the material lives) and after the demo's needs list is derived — - the needs list decides what is fetched. It produces the `dataset:` input `project-data` consumes; it - does not write `data/import/**`, does not import, and does not build. +description: "Collects product data, imagery and brand assets for a demo from a customer site or export into a harvest folder beside the project. Use to gather demo materials after demo-intake." --- # harvest-source-materials @@ -432,21 +424,3 @@ Confirm each, in one line each: or face cut; output dimensions asserted. - [ ] The README's opening paragraph carries the illustrative-demo-data label and the price basis. - [ ] The handoff block was printed, with column names read from the written files. - -## Pitfalls - -Format: **symptom → cause → fix.** - -| Symptom | Cause | Fix | -|---|---|---| -| A very large harvest that is missing the product the story needs, or a whole category | The harvest ran before the needs list existed, so breadth substituted for a target list | Rule 0: the needs list and the composition spec are the scope. §3 fetch list, confirmed, before the first image | -| A range size stated from the harvest contradicts the live listing | The scraper's own colour cap and unvisited listings were recorded nowhere, so a scraper artefact was read as a fact about the customer's catalogue | §9 `coverage.json` + README coverage; every later claim cites it or says "in what we captured, these: " | -| The tiles show a studio side-view; the live product page shows a three-quarter front shot, and cropping does not fix it | The harvest's own directory order was trusted over what the source renders | §6 — read the live page's `` and match the asset family before wiring; `project-data` C16 | -| Every product tile on every listing downloads a full-size image | The small derivative was produced by copying the large file rather than resizing it | §7 — resize for real, then assert the derivative's dimensions **and** byte size; equal byte size is a defect | -| Imagery vanishes after a rebuild, but a markup check passes because the alt text still renders | Images were written into the published assets directory, which the build regenerates | §1 and §7 — the tracked static frontend directory only; a markup check cannot see a missing binary | -| Tens of megabytes of imagery in git, no decision recorded anywhere | No size budget was set, and raw campaign heroes run to a couple of megabytes each | §7 — set and log a default budget before the first copy, report the actual total, carry any overrun to the final review | -| Images with no recorded purpose remain after a pivot | The abandoned approach's intake was never swept | §11 — on a pivot, list harvest records, harvest imagery and copied derivatives as one removable set, in one message | -| A referenced PDF is deleted by an orphan sweep | The only reference to it lived inside a CSV cell, and the sweep only looked at markup | §11 — grep CSV cells before any orphan sweep; a cell-embedded reference is a reference | -| A proposal to tag ordinary products with an attribute they do not have, so a category looks fuller | The demo was treated as ground truth and the source as adjustable | §5 — the source is ground truth; a gap gets three options and no fourth, and fabrication is never one of them | -| The data step spends question rounds reconstructing master / colour / size semantics out of the harvest CSVs | The run ended without the handoff block, so the field mapping had to be re-derived by hand | §12 — print the handoff block with column names read from the written files | -| Homepage bands filled with product packshots, or editorial fetched without a panel count, inflating the harvest | Editorial was treated as a by-product of the product fetch instead of its own deliverable | §8 — editorial is sized by the composition spec's panels and ratios, kept in its own tree, with a manifest per file | diff --git a/plugins/spryker-ai-dev-sdk/skills/match-reference-design/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/match-reference-design/SKILL.md index 52fc719..41f4eff 100644 --- a/plugins/spryker-ai-dev-sdk/skills/match-reference-design/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/match-reference-design/SKILL.md @@ -1,15 +1,6 @@ --- name: match-reference-design -description: > - Use when a Spryker storefront has to look like a reference site — the customer's own site or one the - person names. Triggers: "make it look like ", "match the reference", "fix the navigation to - be like theirs", and look-and-feel feedback on a page being matched to a reference or a demo look - ("this block looks ugly", "swap this block with the second one"). - Owns the design loop for homepage composition, navigation and CMS blocks: reference capture, a - numbered page map, a printed cost ladder, one change per cycle, and a screenshotted before/after. - Not component mechanics (Twig/SCSS/TS, overrides, build, Twig cache) — that is `yves-atomic- - frontend`; not catalogue, CMS or navigation rows — `project-data`; not behaviour changes — `spryker- - customization`. +description: "Makes a Spryker storefront look like a reference site: page map, homepage, navigation and CMS blocks, one change per cycle. Use for 'make it look like ' or look-and-feel feedback." --- # match-reference-design @@ -40,7 +31,7 @@ run, where you take it from the needs list and the beat, log it, and go on. Then yourself: **is the stated fix the goal, or a symptom of one?** "Make the top image bigger" is a measurement change; "the landing page should look like theirs" is a composition change. Ask only when it is truly ambiguous, and in plain words — "just bigger, or should the whole top area look like their -site?" Reading the first as the second turns a stylesheet edit into a rebuild (see Pitfalls). +site?" Reading the first as the second turns a stylesheet edit into a rebuild. Plus the reference itself: read `up_front.reference_sites` in `.ai-dev/demo-prep.md` first, then `project.reference_sites` in `.ai-dev/project-setup.md`. Only outside a demo run, with neither set, ask @@ -215,7 +206,8 @@ looks good?" — they are checking the result themselves. A navigation or layout task edits **templates, styles**, and at most **navigation node order, labels and visibility** (`position`, `title.`, whether a node is present in the menu). That is the -whole permitted surface. +whole permitted surface. A too-long menu is fixed with depth, visibility or a template, never by +removing what the shop sells. **Categories, products and category keys are the catalog.** Removing them to make a menu fit is a data change, not a design fix: it changes what the shop sells in order to change how a bar looks, and @@ -418,73 +410,6 @@ Grep the clone for each name first (`grep -rn "" src//Yves --include=' Format: **symptom → cause → what to do.** -- **"Make the top image bigger" becomes a new component, project overrides, an importer change and - rebuilds, then a rollback.** → A measurement change was read as a request to rebuild the - landing page, and with no cost ladder logged the most expensive rung was taken. Such a fix is - usually a few lines in one stylesheet. → Size and - spacing complaints are rung 1 until proven otherwise: locate the element in the browser, read its - box, change the rule that sets it, build, look. Log the ladder (§3), take the cheapest rung that - achieves the look, and take the next rung yourself when it cannot. - -- **A swap is applied to the wrong pair: the person meant the block's original position, not where - an earlier move put it.** → a positional swap request was acted on - against a private numbering of a subset (only the image blocks) while the page rendered a much - larger set — so the two parties meant different blocks — and the wrong move then re-indexed - everything behind it. → Print the numbered map from the rendered page (§2), echo every positional - request against it and wait for the confirmation, and snapshot the map per change so "originally" - still resolves after a revert. - -- **A request to fix the navigation is answered by deleting categories from the import data.** → A - layout problem was compensated in data; the layout itself was never changed. - → §5: nav and layout work edits templates, styles and at most node order/labels/visibility. A - too-long menu is fixed with depth, visibility or a template, never by removing what the shop sells. - Catalog changes are a separate, explicitly requested step through `project-data`. - -- **A restyle intended for one homepage strip repaints the product detail page as well; the markup of - the two is compared, found identical, and the change is reported as scoped.** → The shared product tile was styled for one page, and the - identical markup was read as proof of no impact, when it means the change reaches both — the - difference between the two contexts was the wrapper, not the component. → §6: enumerate the consumers - (including templates, content-widget view names, the slots they land in) before the edit, and - register a new view/variant for a page-scoped intent. - -- **Styling cycles verified with `curl | grep` while the browser is used only to read the - reference.** → Markup presence was accepted as visual evidence, and the browser was treated as a - reading tool rather than a verification tool. → §4: the browser that looked at the reference looks - at the result. A cycle ends with a - screenshot pair at every sweep width, never a grep. - -- **Two utility classes swapped back and forth, neither producing the wanted result.** → The class was - chosen by its name; the two candidates were a few px apart, which no name reveals. → §7: read the - compiled value of the class before using it, read the current gap from the rendered page, and set - the number you measured. - -- **A panel that misaligns with everything around it on the first screenshot.** → Its width was - invented (1440px) while the site container is 1200px. → §7: read the container's computed max-width - from the page and inherit it; never restate a width from memory of some other site. - -- **Font and asset edits reported done, page unchanged.** → The edits landed in - gitignored build output, and in `app.css` — a stylesheet this page does not serve; it serves - `critical.css` + `util.css`. → §8: `git check-ignore -v` the path before writing, read the page's - own `` tags to learn which stylesheet is served, edit the source component or theme file, and - rebuild. - -- **A change lands on the wrong dimension: "bigger" meant the block, not the text; "looks ugly" got - another guess instead of a question.** → An ambiguous word was resolved by guessing, and the second - guess also displaced what the first one moved. → §9: one question naming the two candidates, then - one edit. - -- **Reference sites were supplied — the customer's own and a second one — and never opened for - structure.** → The references were mined for content (copy, imagery, category names) or not opened - at all, so the composition was re-derived by trial and error, with the person checking each attempt. → §1: - capture comes first, always, and produces a written spec the person approves (autonomous: logged, - shown at the final review); that spec is the acceptance criterion for every cycle afterwards. - -- **A block whose full-bleed and spacing live in inline CSS inside a CMS placeholder cell, and a - second content area faked with a separator inside one cell.** → Layout was put into content because - content looked like the cheaper rung, and the block template's shipped placeholders were treated as - optional. → §10: layout in the template or a section modifier, content in the placeholder; more - content areas means a second block with its own key, slot wiring and per-store rows. - - **A reset taken to undo a visual experiment, after which the person's positional references no longer resolve.** → A reset restores the stack but not the map the person was looking at. → §2: map snapshots are per change and survive the reset; quote the snapshot number in every positional echo. diff --git a/plugins/spryker-ai-dev-sdk/skills/payment-template/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/payment-template/SKILL.md index d0d8ba7..41b2c0b 100644 --- a/plugins/spryker-ai-dev-sdk/skills/payment-template/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/payment-template/SKILL.md @@ -1,21 +1,13 @@ --- name: payment-template -description: > - Use when a developer wants to build, implement, scaffold, or onboard a new PSP (Payment Service - Provider) or payment gateway integration in Spryker from scratch — including named providers like - Adyen, Mollie, Stripe, Braintree, Klarna, Worldpay, Buckaroo, Payone, Nuvei, or any custom PSP - partner. Trigger whenever someone says "add X as payment provider", "implement X payment - integration", "build a payment module for X", "set up a new payment gateway", "new PSP - integration", or "create a payment provider module". Uses spryker-community/payment-template as - scaffold, collects requirements interactively (payment methods, auth mechanism, webhooks), - confirms a plan, then executes full implementation. Do NOT trigger for: debugging existing - integrations, adding refunds to existing modules, back office payment configuration, writing - payment tests, or API Platform migrations. +description: "Builds a new PSP or payment gateway integration in Spryker from the payment-template scaffold, from requirements to code. Use for 'add X as payment provider' or a new PSP module." user-invocable: true --- # Payment Template Implementation Skill +Boundary: do not use this skill for debugging existing integrations, adding refunds to existing modules, back office payment configuration, writing payment tests, or API Platform migrations. + Produces a complete, working PSP payment integration through four phases: **Collect → Plan → Confirm → Execute.** diff --git a/plugins/spryker-ai-dev-sdk/skills/product-requirement-document/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/product-requirement-document/SKILL.md index 18bd61b..ea63404 100644 --- a/plugins/spryker-ai-dev-sdk/skills/product-requirement-document/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/product-requirement-document/SKILL.md @@ -1,10 +1,12 @@ --- name: product-requirement-document -description: Use when creating PRDs for Spryker features, before implementation planning, or when a user requests a spec/requirements document that another AI agent will turn into tasks. This is the START of the Spryker feature-building chain — "I want to build a feature" begins here, then flows to spryker-customization (which drives build, verification, and commit). Drives an interactive, research-grounded PRD — first investigates the real codebase and official Spryker docs, strictly assigns a real Spryker actor to every story, names the affected endpoint + path, and keeps the document business-focused (no implementation, no quality gates, no task breakdown). +description: "Writes a research-based PRD for a Spryker feature with real actors and endpoints and no implementation detail. Use when a user wants to build a feature or asks for a PRD or requirements." --- # Product Requirement Document (PRD) Creation +Boundary: this is the start of the Spryker feature-building chain. The PRD then goes to `spryker-customization`, which drives build, verification and commit. + ## Overview A PRD defines WHAT to build and WHY — never HOW, HOW LONG, or which commands to run. It is business-facing and AI-parseable so another agent can later extract tasks and a plan from it. @@ -203,16 +205,7 @@ Ask the user at Phase 8 which location: ## Interactive Workflow Checklist -- [ ] Phase 0: Gathered codebase facts inline **first** (`searchSprykerCapabilities` as the very first call - reuse verdict per `find-existing-capability`, PRD framed as configure / extend / install when the capability ships - then `getSprykerModules`/`getSprykerModuleMap`/`getTransferStructureByName`, vendor paths from the module map — never guessed) and formed a hypothesis — started the server + asked the user to reload MCP if the tooling server was down; asked the user whether docs research is needed (and, only if yes, dispatched `spryker-docs-research` as **subagent(s) with your harness's subagent tool**, targeted by the hypothesis, non-overlapping scopes — or used the stated harness fallback: consent, else inline; merged their briefs); asked the user whether to validate existing endpoints/flows against the running app (and ran `spryker-runtime` only if yes); flagged any missing tools -- [ ] Phase 3 (start): Asked the pacing question once (per-criterion / per-story / draft-then-review) and honoured it through Phases 3–4 -- [ ] Phase 2: Background & Goals approved -- [ ] Phase 3: Each story approved at the chosen pacing — every checkpoint that occurred presented the **actor** and the **affected endpoint (URL path, or "no endpoint")** alongside the story, and the user confirmed both -- [ ] Phase 4: Every acceptance criterion approved (individually, per story, or in the draft review — per the chosen pacing), all Gherkin + quantified -- [ ] Phase 5: Each story records affected endpoint as a **URL path** (+ existing/greenfield + module name), or "no endpoint" — as confirmed at the Phase 3 checkpoint; the controller+action FQCN is recorded in `.refs.md`, not the body -- [ ] Phase 6: Business NFRs approved (no tooling/test commands); numbers marked user-supplied vs baseline-default - [ ] Phase 7: Constraints captured (or explicitly "none discovered"); decisions & accepted risks recorded with their cost; success metrics, out-of-scope, dependencies confirmed (dependencies as module/feature + configuration names, no code references) -- [ ] Phase 8: PRD body is code-free (no FQCNs/`::method`/file paths anywhere, including Dependencies); discovered code references captured in `.refs.md`; research header links the attachment -- [ ] Final PRD approved before saving; saved the `.prd.md` and its sibling `.refs.md`, and told the user about both ## Supporting Files @@ -222,7 +215,3 @@ Ask the user at Phase 8 which location: - **[examples.md](examples.md)** — full PRD example and anti-patterns - **[template.md](template.md)** — allowed PRD section structure - **[refs-attachment.md](refs-attachment.md)** — structure of the `.refs.md` code-reference attachment (keeps the PRD body code-free) - -## Summary - -PRD creation is INTERACTIVE and RESEARCH-GROUNDED. Investigate real Spryker (docs + code, and run the app for existing flows) → ask → draft incrementally → assign a real actor and real endpoint to every story → approve at each checkpoint → keep it business-only. Alignment over speed. diff --git a/plugins/spryker-ai-dev-sdk/skills/project-ci-generator/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/project-ci-generator/SKILL.md index 898043f..28e5589 100644 --- a/plugins/spryker-ai-dev-sdk/skills/project-ci-generator/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/project-ci-generator/SKILL.md @@ -1,11 +1,6 @@ --- name: project-ci-generator -description: >- - Use when turning a repo's inherited product/vendor CI into a single, lean project CI - pipeline — "clean up CI for the project", "make a project CI", "recreate one CI file", - "remove product-only CI jobs", "clear the CI folder and rebuild", or porting CI to - another host (GitLab, Bitbucket). A pre-boot wizard step of project start, and standalone - on any repo carrying product-style CI. +description: "Replaces a repo's inherited product CI with one lean project CI pipeline, also for another CI host. Use for 'clean up CI for the project' or at project start as a pre-boot wizard step." --- # Project CI Generator diff --git a/plugins/spryker-ai-dev-sdk/skills/project-data/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/project-data/SKILL.md index dc5da99..2f53cb4 100644 --- a/plugins/spryker-ai-dev-sdk/skills/project-data/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/project-data/SKILL.md @@ -1,10 +1,12 @@ --- name: project-data -description: "The one skill for a Spryker project's data/import/** — use whenever demo/import data must be populated, reshaped, reduced, cleaned up, or removed. Triggers: 'adapt the demo shop to my stores and currencies', 'add demo data / generate a catalog of tools/books/dresses from these images', 'create CMS blocks from these pictures', 'replace the demo catalog with our real product export (JSON/CSV)', 'start clean with no demo catalog', 'we only sell heat-recovery, drop the rest of the catalog', 'remove the demo customers / merchants / reviews', or any ad-hoc edit of import CSVs. Used by the wizard's data step and standalone on a fresh or running project. Boundary: it owns `data/import/**` rows only — how those rows are rendered or laid out belongs to `match-reference-design`, and a new or overridden importer, plugin or schema belongs to `spryker-customization`." +description: "Populates, reshapes, reduces or cleans the data/import/** files of a Spryker project: catalog, CMS, customers, merchants. Use for any demo or import data change or an ad-hoc import CSV edit." --- # project-data +Boundary: it owns `data/import/**` rows only — how those rows are rendered or laid out belongs to `match-reference-design`, and a new or overridden importer, plugin or schema belongs to `spryker-customization`. + The universal skill for everything under the project's `data/import/**`. It owns one job — **get the project's import data into the shape the project needs** — and it does that through one of five **strategies**. You **pick the strategy** from the interview (`.ai-dev/project-setup.md` `data.mode`) or from what the user asks in plain terms, apply the **shared core** below (tools, discipline, state-reading, apply-ladder, invariants — the same for every strategy), then follow that strategy's **reference file** for the method. You drive the `spryker-import-tools` scripts (`csv.php` + `validate.php`) with judgment; the tools are concept-free (they know nothing about stores/locales/currencies) — the judgment is what this skill supplies. (Failure-signature triage for the data steps lives in the Known-traps catalog: `../project-starter-wizard/references/pitfalls.md`.) diff --git a/plugins/spryker-ai-dev-sdk/skills/project-starter-wizard/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/project-starter-wizard/SKILL.md index e11effb..16e3ef0 100644 --- a/plugins/spryker-ai-dev-sdk/skills/project-starter-wizard/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/project-starter-wizard/SKILL.md @@ -1,10 +1,12 @@ --- name: project-starter-wizard -description: "Use at the very start of a new customer project, on an unmodified (booted or not) clone of a Spryker b2b/b2b-marketplace demoshop — 'turn this demoshop into our project', 'start the project setup', 'run the project starter'. Also the trigger for 'give me the setup questionnaire' / 'here are my filled setup answers — run it autonomously', and the resume entry when a prior run left .ai-dev/project-setup.md. Collects the nine setup decisions either from a pre-filled questionnaire (references/questionnaire.md — no interview) or a live batched interview, then orchestrates the other project-start skills in autonomous or collaborative mode. Boundary: it owns SETUP only — the catalogue, CMS and other `data/import/**` rows belong to `project-data`, the shop's look to `match-reference-design`, and any change to how the shop behaves to `spryker-customization`." +description: "Turns an unmodified Spryker b2b demoshop clone into a customer project from nine setup decisions, by questionnaire or interview. Use to start the project setup or resume a setup run." --- # Project Starter — Wizard +Boundary: it owns SETUP only — the catalogue, CMS and other `data/import/**` rows belong to `project-data`, the shop's look to `match-reference-design`, and any change to how the shop behaves to `spryker-customization`. + You turn an **unmodified** clone of a Spryker b2b / b2b-marketplace demoshop into the customer's project. The clone may already be booted — what matters is that nobody has customized it yet. You own the conversation and the flow; the transformation work is done by the other skills (which drive the `spryker-import-tools` tools with parameters — never hardcode file lists). Work only from real files and real command output. Never assume Spryker specifics from memory — inspect the clone. diff --git a/plugins/spryker-ai-dev-sdk/skills/propel-schema/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/propel-schema/SKILL.md index 0533c55..7b46cbc 100644 --- a/plugins/spryker-ai-dev-sdk/skills/propel-schema/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/propel-schema/SKILL.md @@ -1,10 +1,6 @@ --- name: propel-schema -description: > - Use when creating, updating or reviewing Propel schema XML for Spryker modules — new - tables and columns, foreign keys, indexes, unique constraints, many-to-many tables and the - timestampable, uuid, event and synchronization behaviors. Applies Spryker naming (spy_/pyz_ - table prefixes, id_/fk_ columns, index and constraint names) and column-type conventions. +description: "Creates, updates or reviews Propel schema XML for Spryker modules: tables, columns, keys, indexes, behaviors, naming. Use for any change to a schema.xml file of a Spryker module." --- # Propel Schema Generator diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-bugfix/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-bugfix/SKILL.md index 1c5bd1d..b1fb581 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-bugfix/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-bugfix/SKILL.md @@ -1,20 +1,12 @@ --- name: spryker-bugfix -description: > - End-to-end bug-fixing workflow: from an optional tracker ticket (JIRA, GitHub Issues, or any - service) or a plain bug description to a committed, - validated, QA-accepted fix on a bugfix branch (autonomous mode adds a pushed Draft PR + - CI watch). Orchestrates reproduce → root-cause → fix → functional tests → static checks → - review → QA → Cypress E2E coverage (when warranted) → final verification via the project's stage - skills. Trigger — "fix this bug", - "fix ticket XY-1122", "broken, reproduce and fix it": any bug symptom PLUS the expectation of a - DELIVERED fix. NOT for a single isolated step (one test, "just run CI"), new features, - refactors without a symptom, or investigation-only requests ("just find where it goes wrong, - don't fix"). +description: "Fixes a bug end to end: reproduce, root cause, fix, tests, static checks, review, QA, commit on a bugfix branch. Use when a bug or ticket needs a delivered fix, not only an analysis." --- # Spryker Bug-Fixing Workflow +Boundary: use it for a bug symptom plus the expectation of a delivered fix. Not for a single isolated step (one test, "just run CI"), new features, refactors without a symptom, or investigation-only requests ("just find where it goes wrong, don't fix"). + This skill drives a bug from intake to a delivered, validated fix. It is an **orchestrator**: each stage delegates to an existing installed skill. Your job is to run the stages in order, carry context between them, enforce the verification loop, and respect the operating mode the user picked. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-customization/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-customization/SKILL.md index f123267..bd23333 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-customization/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-customization/SKILL.md @@ -1,19 +1,6 @@ --- name: spryker-customization -description: > - Use whenever the user wants to change how the shop behaves — new or overridden PHP - (plugins, expanders, dependency providers, config classes, importers), permissions, - checkout/cart/payment logic, new modules — from a PRD or acceptance criteria. - Triggers include "build this", "implement this", "here is a PRD - build it", - "add this behaviour for the demo", "build this PoC", "production-quality build". - Boundary: it owns behaviour only. Adding content, products, categories, CMS or banner - rows is `project-data`; making a page look a certain way is `match-reference-design`; - stores, locales, currencies and project identity are `project-starter-wizard`. - Drives the full workflow from intake to commit, - choosing a quality bar (PoC or MVP) at the start and delegating focused - work (research, verification, debugging, test-data setup, refresh, - Cypress E2E coverage, demo-artifact capture) to the spryker-* subagents - and skills. Never auto-commits; the user always confirms. +description: "Builds a change to shop behaviour (PHP plugins, config, modules, checkout logic) from a PRD or criteria, from intake to commit. Use for 'build this', 'implement this' or a PoC or MVP." --- # Spryker Customization Workflow @@ -487,23 +474,9 @@ section of `decisions.md` — not from recollection. The report is the log, summ ## What you do NOT do -- Outside the demo preset (Step 0), which settles both from the confirmed row: do not skip the quality-bar decision at intake, or the AC restate + user confirmation step. -- Do not edit anything under `vendor/`. -- Do not work on the user's current branch directly. Always cut `ai-customize/`. -- Do not commit without user confirmation. Even when all ACs are green. (Demo preset: no commit at all unless the preparer asks.) -- Do not push to remote. -- Do not keep iterating on an AC past a stuck signal (or the N = 10 runaway failsafe) — escalate to - the user per Step 7's rules, and report failures as they are. (The self-correct loop's default is - persistence until green or genuinely stuck, not a fixed retry count; the only bounded-retry gate is - static validation at Step 7b with N = 2.) -- Do not do **discovery** research yourself (which mechanism / which extension point / how does X work — exploring `vendor/`, sweeping transfer XMLs, fetching docs). Delegate to `spryker-feature-expert` — that is its job. **Confirmation** of a symbol you can already name (exact signature, spelling, stack position) is allowed inline with a `file:line` citation — a one-line grep does not need an agent dispatch. - When you *do* need to read project files directly (e.g. project namespaces from `composer.json`, install recipes from `config/install/*.yml`), prefer **native tools over `Bash`**: `Read` for files (relative paths from the project root, never absolute `/Users/...`), `Glob` for filename discovery, `Grep` for content search. When the session has no `Grep`/`Glob` tool, a read-only `grep -rn` / `find` from the project root is the fallback — never `sed -i`, `awk` rewrites or a `cd` + `&&` chain into another directory. -- Do not manipulate CSV files. Delegate to `spryker-data-seeder`. - Do not touch the database directly via any shell route. Reads go through `executeDatabaseQuery` (delegated to expert / verifier / debugger); writes go through the data-import path (delegated to data-seeder) or schema XML + propel migrations. - **Do not drive the browser from the main loop.** Verification UI work belongs to `spryker-verifier`; demo capture belongs to `spryker-screenshot-collector`. When a screenshot or verification result looks wrong, the answer is to **re-invoke the agent with sharper instructions** — never to load browser-automation tools into the main session and *"just check it yourself"*. Self-correction signal: if you're about to pull in any of the tools listed in the `spryker-runtime` skill's Browser tool map from the main loop, **stop** — that is main-loop bleed. The agents own the browser; the orchestrator delegates. This rule applies equally to *"just one quick screenshot to verify the agent's output"* — that quick check is still the agent's job. - Do not run `docker/sdk reset` or any environment-destructive command. When the change needs one, say so in the report; under the demo preset `demo-prep-wizard` runs it. - Do not produce MVP-grade ceremony when the chosen bar is PoC. If you have more than ~5 PHP classes in a PoC, you're building MVP — re-cut. -- Do not produce PoC-grade shortcuts when the chosen bar is MVP. Canonical patterns are required for MVP. -- Do not produce ceremony the Code-convention resolution didn't sanction when the bar is MVP either. A single-implementation interface outside the canonical seams — with no project rule and no feature-code precedent behind it — contradicts the plan's `Convention:` line and gets inlined, not shipped. -- Do not leave `[AI-DEBUG]` logs, `use LoggerTrait;` lines you added for debugging, `file_put_contents('/data/data/tmp/ai-debug.log', ...)` fallback writes, or `@group AITestCase` tags in committed code. Strip everything in Step 7b's cleanup pass. -- **Do not invoke the `static-validation` skill before Step 7b.** Its description triggers on any PHP edit, but the workflow owns the timing: only Step 7b runs static-validation, against the final stable diff. If you catch yourself reaching for it after Step 4 (edit), Step 5 (refresh), or any iteration of Step 7 (self-correct) — stop. Same applies to `phpcbf` / `phpcs` / `phpstan` invoked any other way. +- **Do not invoke the `static-validation` skill before Step 7b.** Same applies to `phpcbf` / `phpcs` / `phpstan` invoked any other way. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-customization/references/core-facade-extension.md b/plugins/spryker-ai-dev-sdk/skills/spryker-customization/references/core-facade-extension.md new file mode 100644 index 0000000..f47584f --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-customization/references/core-facade-extension.md @@ -0,0 +1,106 @@ +# Dependencies without new Bridges, and extending a core facade + +Companion of the `dependency-provider` rule. + +## Adding a New Dependency + +When adding a new dependency, use `$container->getLocator()` directly in the DependencyProvider. Never create a new Bridge class just to register a dependency. + +BAD — Creating a new Bridge class in the current module +```php +// src/[Org]/Zed/Order/Dependency/Facade/OrderToCalculationBridge.php ← do not create this +class OrderToCalculationBridge implements OrderToCalculationInterface +{ + public function __construct(protected readonly CalculationFacadeInterface $calculationFacade) {} + + public function recalculate(QuoteTransfer $quoteTransfer): QuoteTransfer + { + return $this->calculationFacade->recalculate($quoteTransfer); + } +} + +// OrderDependencyProvider.php +$container->set(static::FACADE_CALCULATION, function (Container $container): OrderToCalculationInterface { + return new OrderToCalculationBridge($container->getLocator()->calculation()->facade()); +}); +``` + +GOOD — Use `$container->getLocator()` directly +```php +// OrderDependencyProvider.php +$container->set(static::FACADE_CALCULATION, function (Container $container): CalculationFacadeInterface { + return $container->getLocator()->calculation()->facade(); +}); +``` + +## Extending a Core Module Used by Another Module (Project Level) + +When you need to **add a new method** to a core facade that is already consumed by another module via a bridge interface, do NOT subclass or copy the bridge. Instead: + +### Step 1 — Extend the bridge interface in the consuming module's project namespace + +```php +// src/[Org]/Zed/Cart/Dependency/Facade/CartToCalculationInterface.php +namespace [Org]\Zed\Cart\Dependency\Facade; + +use Spryker\Zed\Cart\Dependency\Facade\CartToCalculationInterface as SprykerCartToCalculationInterface; + +interface CartToCalculationInterface extends SprykerCartToCalculationInterface +{ + public function foo(): void; +} +``` + +### Step 2 — Extend the facade in the providing module's project namespace and implement the new interface + +```php +// src/[Org]/Zed/Calculation/Business/CalculationFacade.php +namespace [Org]\Zed\Calculation\Business; + +use [Org]\Zed\Cart\Dependency\Facade\CartToCalculationInterface; +use Spryker\Zed\Calculation\Business\CalculationFacade as SprykerCalculationFacade; + +class CalculationFacade extends SprykerCalculationFacade implements CartToCalculationInterface +{ + public function foo(): void + { + // project-level implementation + } +} +``` + +### Step 3 — Remove the bridge in the consuming module's DependencyProvider; use the locator directly + +```php +// src/[Org]/Zed/Cart/CartDependencyProvider.php +class CartDependencyProvider extends SprykerCartDependencyProvider +{ + public function provideBusinessLayerDependencies(Container $container): Container + { + parent::provideBusinessLayerDependencies($container); + + $container->set(static::FACADE_CALCULATION, function (Container $container): CartToCalculationInterface { + return $container->getLocator()->calculation()->facade(); + }); + + return $container; + } +} +``` + +### Step 4 — Update the Business Factory to return the extended interface + +```php +// src/[Org]/Zed/Cart/Business/CartBusinessFactory.php +use [Org]\Zed\Cart\Dependency\Facade\CartToCalculationInterface; + +class CartBusinessFactory extends SprykerCartBusinessFactory +{ + public function getCalculationFacade(): CartToCalculationInterface + { + return $this->getProvidedDependency(CartDependencyProvider::FACADE_CALCULATION); + } +} +``` + +> **Note:** Bridges are a deprecated concept. At the project level, never extend or subclass a core Bridge class — instead follow the pattern above: extend the bridge *interface* in the consuming module, extend the *facade* in the providing module, and wire directly via the locator. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-docs-research/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-docs-research/SKILL.md index b0ae8da..205d56a 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-docs-research/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-docs-research/SKILL.md @@ -1,6 +1,6 @@ --- name: spryker-docs-research -description: Research and summarize official Spryker public documentation — module behavior, configuration options, API/Glue references, architecture concepts, supported actors, feature/PBC names, and integration/installation guides. Use this whenever a task needs to understand how a Spryker feature, module, or pattern works according to the official docs BEFORE planning, writing a PRD, or implementing — for example "how does the OMS state machine work", "what are the installation steps for MerchantPortal", "is this behavior supported in Spryker", or any time you're about to describe Spryker behavior from memory. The product-requirement-document skill invokes this to ground PRDs in documented reality. Searches docs via MCP tools (Algolia, context7) or a no-MCP curl fallback and returns relevant documented content with source links. Docs-only — it does NOT read the installed codebase, modules, transfers, or endpoint paths. +description: "Searches the official Spryker documentation and returns cited passages on modules, configuration, APIs and install guides. Use before a PRD, plan or code that depends on Spryker behaviour." --- ## Why this exists @@ -81,10 +81,5 @@ Every piece of content carries its **Source** URL. Reproduce documentation subst ## Principles - **Docs before opinion.** Never describe Spryker behavior from memory when the documentation can confirm it. -- **Always Return comprehensive relevant content, not just pointers.** Hand back the relevant documentation substance (steps, requirements, options, constraints, config) so the caller can act on it — each tied to its source link — rather than a list of URLs to go read. -- **Short Algolia queries** (2–3 words) outperform long ones. -- **Cite sources.** Every piece of content and every claim carries its doc URL. -- **Public docs only.** If a question needs the installed code (exact module names, transfer fields, real endpoint paths), say so in "Open questions / gaps" — that is out of scope here and belongs to a code-investigation step. - **Docs are not trusted for identifier spellings.** The docs contradict themselves on exact names (`full-text` vs `full_text`, `string-facet` vs `string_facet`). Report the concept, but flag every field/index/route identifier as *"confirm in code or a live mapping"* — never present a doc spelling as the authoritative name. - **Anything you clone or download is ephemeral.** A docs-repo clone in the scratchpad is a working copy, not a deliverable — say so if you mention it (or clean it up); never report its path as a durable artifact. -- **Surface gaps loudly.** A missing tool or an unanswered question is a finding, not something to paper over. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md index da8f28b..db27299 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md @@ -1,16 +1,6 @@ --- name: spryker-feature-install -description: > - Install a Spryker feature into the project end to end, from a capability card or a feature name: - "install the X feature", "add spryker-feature/x", "integrate feature X", "install the X Glue API", - after find-existing-capability proposed an install, or a feature that spryker-upgrade Phase 6 - accepted. Resolves the feature, its required features and the release it needs (moving only the - modules it needs); parses the official install guide into a checklist with one row per step; - reconciles every row with the reference demo shop (plugin subset and order, merged config, files - the guide does not name); applies it in the project layer one guide section at a time; suggests - storefront placement; verifies each guide Verification block; and finds and proves the release - steps existing environments need (imports, republish, environment variables). Always confirms - before changing anything; never edits vendor/ or generated code; never auto-commits. +description: "Installs a Spryker feature end to end from its install guide, checked against the demo shop, with verification and release steps. Use for 'install the X feature' or after a reuse check." --- # Spryker Feature Install diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/README.md b/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/README.md index d953c93..04a7771 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/README.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/README.md @@ -63,7 +63,7 @@ flowchart TD | File | Role | |------|------| -| [`SKILL.md`](SKILL.md) | Command reference for both scripts, the **authoritative** invocation & command-discipline rules, and the flag cookbook (one worked example per command). | +| [`SKILL.md`](SKILL.md) | The **authoritative** invocation & command-discipline rules and the rules that apply to every run; the full command reference and one worked example per command are in `--help ` of each script. | | [`scripts/csv.php`](scripts/csv.php) | RFC-4180 CSV manipulation. Header-name access only, atomic writes, idempotent where sensible. | | [`scripts/validate.php`](scripts/validate.php) | Pre-boot consistency checks. Own CSV reader — no dependency on `csv.php`. | | [`scripts/csv.test.php`](scripts/csv.test.php) | Test suite for `csv.php`. | diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/SKILL.md index 4de3244..a33b82f 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/SKILL.md @@ -1,10 +1,12 @@ --- name: spryker-import-tools -description: "The engine (csv.php + validate.php) that project-data and the wizard drive to manipulate and validate Spryker data-import CSVs and import manifests — for WHAT data to change (add, adapt, reduce, clean up, an ad-hoc CSV edit), use project-data; come here for the mechanics of a command. csv.php: read/inspect/filter/delete/duplicate/set/replace/scale/apply-translations/append/add-row — reliable where shell tools (cut/awk/sed) corrupt multi-line quoted fields. validate.php: gate (the one-command verdict run before a rebuild or import), preflight, refs (incl. composite tuples), required, unique, absent, paths, product-refs, manifest-refs, threshold-glossary, orphan-files, sku-coverage, translation-coverage, inventory, manifest-diff, known-set — catches boot-aborting data statically in seconds. Concept-free: you supply columns/values/patterns; the tools do the mechanics and return compact JSON. Also home of the authoritative invocation & command-discipline rules every consumer skill follows." +description: "Reference for csv.php and validate.php: edit and validate data-import CSVs and manifests (gate, preflight, refs). Use for the mechanics of a command; project-data decides what changes." --- # spryker-import-tools +Boundary: for WHAT data to change (add, adapt, reduce, clean up, an ad-hoc CSV edit), use `project-data`; come here for the mechanics of a command. + Two self-contained PHP scripts under `scripts/`, both concept-free (they know nothing about stores/locales/currencies — **you** decide what to do; they do it correctly and print JSON): - **`csv.php`** — RFC-4180 CSV manipulation. - **`validate.php`** — pre-boot consistency checks (its own CSV reader; no dependency on csv.php). @@ -46,62 +48,15 @@ Before a rebuild on a project with real data, ask once; a deletion git cannot re --- -# csv.php — CSV operations - -Inspection (add `--plain` for line output — no JSON to parse): -- `read [--limit N]` — dump header + rows as JSON. **Takes one file** — passing several is a clean error (no silent truncation to the first; use `columns`/`count` for many-file inspection). -- `count [ …] [--plain]` — **data-row count per file, many files in one call.** `--plain` → `rowCount⇥file` per line. Use this for "how many rows across these N files" — **never a shell `for … do … done` loop with `| grep rowCount`**; one `count` call replaces the whole loop. -- `columns [ …] [--plain]` — header + row count. **Accepts many files in one call** (per-file output; a missing file is reported inline, batch survives). `--plain` → column names per line, with a `== ==` delimiter when multiple. -- `distinct … --column C [--plain]` — distinct values of a column with row counts, sorted by count desc (`--plain` → `count⇥value` per line); takes **many files** in one call (aggregated). **Use this to inspect data — never `awk`/`sort`/`uniq -c`** (they corrupt multi-line quoted fields). - -Files are positional and come before the flags (`columns --plain`, not `columns --plain `). `columns`/`count`/`distinct` report a specific `no input file given` error for the flags-first shape instead of the generic usage dump — read the error text, which names the argument order as the problem. - -Mutation — write with **`--out ` for one file, or `--in-place` for one-or-many files**. **Batch: list several files before the flags and add `--in-place` to apply the same op to all in a single command** (per-file report in `files[]`) — this is how you avoid a shell `for` loop. Multiple files without `--in-place` is an error. -- `filter ... (--where col=val … [--match exact|prefix|contains] | --in col=v1,v2,… | --in-file col=path) [--out f | --in-place]` — keep matching rows. `--where` repeatable (AND); `--in`/`--in-file` = set-membership. Without a target it previews: `matchedRows`/`resultRows` are the full counts, the echoed `rows` are capped at 20 (`--limit N` to raise) — the counts are the destructive-gate evidence, not the row dump. -- `delete ... (same conditions) [--out f | --in-place]` — drop matching rows. -- `duplicate-columns ... --from en_US --to fr_CA[,de_DE,…] [--skip-base url] (--out f | --in-place)` — for every `X.en_US` column, add `X.` copying the value; `--skip-base` leaves families alone. **`--to` takes a comma-list → all project locales in one call.** -- `duplicate-rows ... --column locale --from en_US --to fr_CA[,uk_UA,…] (--out f | --in-place)` — clone rows per `--to` value (glossary → all locales; store-relation rows → all stores). -- `set ... --column store --value US [--where col=val ...] (--out f | --in-place)` — set a column on matching rows (empty `--where` = all rows). -- `replace ... --column url.fr_CA --search /en/ --with /fr/ [--regex] [--where col=val] (--out f | --in-place)` — string/regex replace within an existing column. -- `scale ... --column value_gross [--column value_net] (--by 1.47 | --rates PLN=4.3,UAH=45 [--currency-column currency]) [--no-round] [--json-keys net_price,gross_price] [--where col=val] (--out f | --in-place)` — multiply numeric values (currency conversion); **`--column` is repeatable — net + gross scale together in one call** (`--column value_net --column value_gross`); `--rates` applies a per-currency factor in one call; `--json-keys` scales embedded price tiers. -- `derive ... --target value_gross --source value_net --factor 1.19 [--no-round] [--only-empty] [--where col=val] [--out f | --in-place]` — cross-column arithmetic `scale` can't do: writes `target = source × factor`, creating the target column if absent. Skips rows whose source is empty/non-numeric; a non-numeric/zero `--factor` is a hard error (never silently zeroes a column). `--only-empty` gap-fills (won't overwrite existing target values). E.g. fill gross from net + tax, or a base-currency price into a second column before converting. -- `select --columns a,b,c --out file` — project columns (single file, keep-list). -- `drop-columns ... (--column name | --suffix .de_DE)... [--out f | --in-place]` — remove columns; `--suffix` drops a whole family across files. Repeatable; a named column absent from a file is reported (per-file `skippedColumns`), not fatal; idempotent. -- `rename-columns ... --rename old:new [--rename old2:new2 …] [--out f | --in-place]` — rename header columns and the matching row keys, many files in one call (repeatable `--rename` = multiple pairs). A pair whose `old` is absent, or whose `new` already exists as a different column, is reported in `skippedColumns` (not fatal); idempotent; malformed `--rename` (no `:`) is a hard error. Use it instead of hand-authoring a near-duplicate file that differs only by column names — e.g. deriving `price_product_offer` from `product_price`: `replace` the values, `rename-columns` the ref column, done in two commands with no loop. -- `apply-translations ... --target-column name.uk_UA [--source-column name.en_US] --map map.csv (--out f | --in-place)` — apply a `source→target` value map to one column (map file has `source,target`). **Only the target column changes** — safe by construction. Exact match, multi-line-safe; unmapped values left as-is. -- `append --from [--dedupe-on ] (--out f | --in-place)` — **the row-adding op for authoring passes.** Appends every row of `rows.csv`, whose header must be a subset of the target's (columns the rows file lacks are written empty; a column the target lacks is a hard error); `--dedupe-on ` skips rows whose key already exists in the target. Writes LF, atomic. This is how new glossary keys, labels or store rows go into the one file per entity — never a second `_project.csv` source (the gate's `duplicateEntitySources` forbids it) and never a hand-rolled writer (Python's `csv` defaults to CRLF; `preflight` `lineEndings` flags it). -- `add-row --set col=value [--set col2=value …] (--out f | --in-place)` — append one row: repeatable `--set`, an unknown column is a hard error, unset columns are empty. Same LF/atomic guarantees as `append`. For more than a handful of rows, build a `rows.csv` and `append` it. - -Notes: all access is **by header name**, never index. A missing column returns a clean JSON error with exit `2`. Idempotent where sensible. Writes are **atomic** (temp file + rename — a crash mid-batch never leaves a truncated CSV) and **LF-terminated** (the repo is LF; `git add`'s `CRLF will be replaced by LF` warning means a file was written by something other than these tools). macOS/OrbStack bind-mounts lag — re-check a written file a beat later. **Counting: never `| grep -c`** — use `rowCount` (`columns`/`read`) or `matchedRows` (`filter` preview). **Batch, don't loop.** +# Commands ---- +`php /scripts/csv.php --help` and `php /scripts/validate.php --help` list every command with its synopsis, the output format and the exit codes. `--help ` prints the full explanation of one command, its flags and a worked example. Read the help of a command before its first use in a run; do not guess flags. -# validate.php — pre-boot checks - -Output: JSON `{status, check, findingCount, findings, errors}`, exit `0` clean, `1` warnings only (a warning-only check such as `sku-coverage`, or `gate` with warnings and no gating finding), `2` on a gating finding. Add `--quiet` to branch on the exit code alone. **Run `php /validate.php` with no arguments first** — it lists every check; the prose names only a subset of them. - -- **`gate [ …] [--locales a,b] [--base dir] [--baseline ] [--root dir]… [--strict] [--save ] [--quiet]` — the close-out command: one call, one verdict.** Runs `paths` + `preflight` + `manifest-refs` + `threshold-glossary` + `duplicate-keys` + `cms-block-store` (gating), `orphan-files` (gates only with `--strict`), and six warning-only checks over the active manifests and returns `{status, gatingCount, warningCount, summary[], checks{…}}`; exit `0` clean, `2` any gating finding, `1` warnings only. **`--save ` writes the report itself after running** and refuses when `baselineSafe` is false — this is how the baseline is captured (`php gate --save .ai-dev/gate-baseline.json`), never `gate > file`: the shell truncates the target before the gate runs, the gate reads its own empty baseline, and saves a falsely clean report. **Everything is auto-discovered when omitted:** the manifests (`data/import/local/full_.yml` for every region `deploy.dev.yml` boots, plus every literal `data:import --config=` in `config/install/docker.yml` — the vendor payment configs), the project locales (from the `locale-store` sources), the declared stores (from the `store` source — passed to every manifest so a vendor config naming a removed store is caught), and the baseline (`.ai-dev/gate-baseline.json`, else `.ai-dev/preflight-baseline.json`). `orphan-files` gates only under `--strict` (a fresh, un-consolidated demoshop legitimately carries files no manifest imports); use `--strict` for the project-data consolidation close-out and for `done`. **A saved gate report is the baseline of choice** — capture it on the untouched clone with `gate --save .ai-dev/gate-baseline.json`, and only new findings gate across every gating check (the shipped demoshop is not clean on `manifest-refs`/`threshold-glossary` either, which a preflight-only baseline cannot suppress). **Run this gate yourself before any `docker/sdk reset|clean-data|up|console data:import`** and stop on a gating finding. With a baseline on file, only gating findings the baseline does not hold count; with no baseline, any gating finding stops the rebuild verbs, and `data:import` proceeds (capture the baseline on the untouched clone). For the rebuild verbs (`reset`/`clean-data`/`up`), trusted rebuilds (a demo clone, first setup, or a recorded `standing_approval: { scope: rebuilds }`) run after a one-line announcement, a project with real data gets one question, and before the third and every later rebuild the decision log gets `rebuild #N: `; the step report states the rebuild count. `console data:import` needs no question: it is rung 1 of the ladder and stays cheap. Vendor-owned sources (`vendor/**`) are exempt from the project-data groups and checked for store references only; a vendor source absent on an un-booted clone (no `vendor/` yet) is not a finding. - -- **`preflight [--base dir]` — the manifest-wide invariant sweep `gate` runs for you (call it directly to drill into one manifest); one driver that auto-discovers and checks the boot-critical invariants across every file the manifest imports, so you never enumerate files by hand.** Reads the manifest's `source:` list and, by column shape, bundles four checks: **url.\ global uniqueness — cross-file, like the real `spy_url` constraint** (a product URL colliding with a category/merchant URL is caught; one dup aborts the 30–60 min install; **navigation-node sources are exempt** — a nav node's url is a link *target*, legitimately repeated across menus), **is_searchable.\ non-blank** (blank = silently unsearchable), **price completeness — gross-mode aware** (a missing/`0` `value_gross`, or a missing net in a net-only file, is a hard problem; a missing net *beside a present gross* is how the shipped gross-mode stores legitimately look → reported under non-gating `priceNetWarnings`/`warningCount`), and **base-before-relation import order** (`currency` before `currency-store`, `store` before every `*-store`, **and every store-definition entry — checked on its last occurrence — before the first product/category entity**; a 3rd store's `locale-store` appended after the catalog = a silently empty store). Also flags any manifest `source:` that doesn't exist. **`--baseline ` suppresses findings already present in that report** — capture a baseline on the untouched clone first, then only new findings gate (the shipped demoshop carries pre-existing quirks that are not yours to fix). It also runs **generate-mode required-shape checks** (`shapeWarnings`): `product-abstract` source has a `color_code` column (else 0 rows import silently), `visibility ∈ {PDP,PLP,Cart,∅}`, `product-abstract` imported with an `*approval-status` entity (else 0 search docs, invisibly), `merchant-product-offer` accompanied by `merchant-product`, and `tax_set_name ⊆` the tax source. Returns one grouped verdict (`problemCount`, then `unreadableSources`/`urlDuplicates`/`searchableBlanks`/`priceMissing`/`foreignLocaleColumns`/`foreignLocaleRows`/`shapeWarnings`/`orderViolations`), exit `2` if any. **Plus these invariant groups** (each imports without an error and surfaces only later; all gating, all baseline-suppressible): `headerOnlySources` (a source with 0 data rows — the delete-vs-empty decision was never made), `glossaryMultiLocale` (a `glossary` source carrying more than one `locale` — glossary is one file per locale), `duplicateEntitySources` (one `data_entity` from several sources in the same directory not distinguished by a store/locale token — the `.csv` + `_extra.csv` split), `storeDirMismatch` (a source under a `/` dir whose `store`/`store_name`/`included_store_names` name another store — the `cp -r` seeding leftover that boots a silently half-empty store), `undeclaredStore` (a store value not in the `store` source — a vendor config hardcoding a removed store aborts the reset after the project import reported Successful), `searchAttributeOverlap` (a key in both `product_search_attribute_map` and `product_search_attribute` — every facet count exactly doubled), `categoryTemplateUnknown` (`category.csv` `template_name` not in the category-template source — every category then fails, then every abstract, three importers later, aborting the install), `rootCategoryNotInMenu` (a root category with `is_in_menu` ≠ 1 — the category tree publishes `[]`), `approvalStatusMissing` (an abstract SKU with no approval-status row — the publisher writes nothing, silently), `priceNonInteger` (`value_gross`/`value_net`/`value_cost`/`amount`/`threshold` not an integer — Spryker money is minor units; a decimal renders 100x wrong), `embeddedPathsMissing` (a path inside a CSV cell — workflow XML, file assets — that does not exist; **relative** paths such as `file.csv`'s `common/common/files/X.pdf` are resolved against the base dir, `data/import/` and the CSV's own directory, so a relative asset reference is checked, never skipped), `lineEndings` (a manifest CSV containing CRLF — Python's `csv` writer default; the repo is LF and git flags it only at `add` time), `discountShipmentByName` (a discount `decision_rule_query_string`/`collector_query_string` clause `shipment-method`/`shipment-carrier` with a non-numeric value — both rules compare the numeric id, so `shipment-method = 'DHL Standard'` imports and never applies), `categoryStoreIncomplete` (a store whose `category_store` rows name some child categories but not others — `category-store` spreads the root's stores to children only when the root relation is first created, so a category added on a later import gets no store row and its page shows 0 products; state every category per store, included, excluded, or both lists empty = take the parent's stores). Shipment-price files are exempt from the empty-or-`0` price rule (free shipment is a real value). **Add `--locales ` to also flag any `.` column or `locale` row value that isn't in the project's set** — the "a finished project carries only its own locales" check, across `data/import/**` (the `absent` sweep misses that tree). One exemption: `en_US` rows in a `glossary` source are never foreign — the en_US glossary is the translator fallback layer every project imports (`project-data` adapt step 1), whichever locales the stores serve. Use the individual checks below to drill into a specific file; `preflight` is the sweep that replaces remembering to run each one everywhere. -- **`manifest-diff [--base dir]` — diff the `data_entity` lists of two import manifests.** Reports `missing` (entities the reference/demo manifest imports that the new one does not — each with its source **row count** so you can rank: rows ≈ product population → structural/required, rows ≪ → opt-in demo garnish) and `added`. Exit `2` if anything is missing. This is the mechanical guard against generate-mode silently dropping behavioural plumbing (e.g. `product-shipment-type`) — diff, then classify every omission as intentional-content-drop or must-keep-structural. -- **`known-set [] [--base dir] [--map ] [--skills ] [--emit-map [--out ]]` — the maintainability gate: keep `data/entity-map.yml` honest against the shipped manifest, and keep record counts out of the skills.** Defaults resolve relative to the script, so it runs from any cwd (default manifest `data/import/local/full_EU.yml`, default map `data/entity-map.yml`, default skills dir the plugin's `skills/`). Reports and gates (exit `2`) on: a manifest entity **missing from the map**; a **stale** map row the manifest no longer imports; a map `source` that isn't the file the manifest imports for that entity (or is gone from disk); any `class: unclassified` row (an undecided entity **blocks the boot** by design); a `structural` row with an empty `why`; and any **bare record count** (`N rows|files|entities|products|blocks|labels|SKUs|docs|CSVs|nodes|keys|columns|attributes|categories`) in a `.md` under the skills dir (a `0`/`~0` count or a `count-ok`-marked line is exempt). `--emit-map` regenerates the map skeleton from the manifest, **preserving the class/why of entities already classified** and marking new ones `unclassified` — a demo-data bump becomes a diff review, not a retype. It does not scan prose for stray identifiers/paths — `paths` and `product-refs` own that against the real files, where a ``-templated doc won't false-positive. -- `refs ... --column C [--column C2] (--in a,b,c | --ref-file F --ref-column K) [--split ,] [--composite]` — every value in the column(s) must be in the reference set. A **missing column is a finding**, never a silent pass. `--split` handles multi-value cells. **Multi-file:** pass several files — each column is checked only against the files that have it (a heterogeneous batch where `a.csv` has `key` and `b.csv` has `attribute_key` won't false-fail), and a column absent from every file is still flagged. (`--composite` uses the first file.) - - **`--composite`** treats the columns as one **tuple** and checks it against the ref file's `--ref-column`s (positional) — for cross-entity integrity. E.g. every `(merchant, store)` sold must exist in `merchant_store`. Plain `refs` would wrongly pass if each part exists independently. -- `required --column C [--column C2]` — cells must be non-empty (e.g. `is_searchable.` — a blank imports as silently unsearchable). -- `unique --column C` — no repeated values (empty cells ignored). E.g. `url.` — a duplicate fails the import. -- `absent [...] --string S [--string S2]` — none of the strings may appear (stale-literal sweep). **Directories are recursed**, so `absent config/ src/Pyz --string DE` sweeps whole trees in one call. A path resolving to nothing readable is a `CANNOT READ FILE` finding, never a silent pass. **Triage tool, not an absolute gate** — scope a hard check to files that must be zero-hit (`CodeBucketConfig.php`, `default_store.php`), classify the rest. -- `paths [--base dir]` — every `source:` in the import config resolves to an existing file. -- `product-refs (--keep-from : | --keep-in a,b,c)... [--pattern n1,n2] [--list-suffix _skus] [--exclude ]... [--exclude-column ]...` — **broad orphan scanner for a catalog reduction.** Walks every CSV under ``, auto-discovers each product-ref column (name in `--pattern`, default `sku,abstract_sku,concrete_sku,product_sku,product`; **plus any header carrying `sku` as an underscore token** — `sku_concrete`, `abstract_product_sku`, `alternative_product_concrete_sku`, …; plus any column ending in `--list-suffix`, default `_skus`, treated as a comma-list), reports every token not in the kept union set (`--keep-from` file:columns ∪ `--keep-in`). The JSON carries a `columns` **coverage summary** (a 100%-orphan column is usually a non-product code, e.g. `product_option.sku`; `--exclude-column` it) and the orphan `findings`. `--exclude ` skips files not in the active manifest. Exit 2 on any orphan. The coverage tool a catalog reduction needs (the reduce strategy in [[project-data]]). -- `manifest-refs [--base dir]` — **orphan sweep across the manifest's distinctive-key relations, in one command.** By column-name convention it builds each key family's producer set from the entity that defines it (`abstract_sku`←product-abstract, `concrete_sku`←product-concrete, `sku`←both, `merchant_reference`←merchant, `product_offer_reference`←product-offer/merchant-product-offer, `category_key`←category, `sales_unit_key`←product-measurement-sales-unit), then flags every consumer cell with no producer. Reports `checked` families and `unchecked` ones (producer entity absent from the manifest → not validated, never a false orphan). Exit 2 on any orphan. **`category_key` is list-valued** — the abstract importer `explode(',')`s it (`ProductAbstractWriterStep::getCategoryKeys()`), so a comma list is the shipped way to put a product in a second category; the check splits that family on `,` and reports one finding per unresolvable part, never per cell. Every other family stays single-value (splitting universally would mask real orphans in columns whose values legitimately contain a comma). **It is not the whole FK graph:** it covers only families whose column name is distinctive. Relations keyed on a **generic** column — `product-label-store`→`product-label` by `name`, `stock-address`→`stock` by `warehouse_name`, etc. — can't be represented without cross-entity false positives, so they are invisible here. **Heuristic for the gap:** any file the project **copied from a seeded demo dir whose parent set the project then replaced** (labels, sales units, warehouses, attributes) counts as unchecked until a targeted `refs --ref-file` against the project's own parent passes. Run `manifest-refs` as the cheap first net, then `refs --ref-file` per replaced-parent relation — don't treat a green `manifest-refs` as full referential integrity. -- `duplicate-keys [--base dir]` — **gating**: the same primary key written twice in one - source. Contradicting duplicates (two different values) gate; additive and identical ones are reported. -- `cms-block-store [--base dir]` — **gating**: a CMS block visible in one store and not - its twin, which renders as an empty slot on exactly one storefront. -- `orphan-files […] [--base dir]` — **the complement of `paths`**: lists every import asset under the roots — **every file type, not only CSV** (state-machine XML, SSP PDFs; manifests, READMEs and dotfiles are skipped) — that **no** manifest source references, **counting paths embedded in CSV cells as references** (workflow.csv `definition`; `file.csv` `path`) — **absolute `data/import/…` and relative** (`common/common/files/X.pdf`, resolved against the base dir, `data/import/` and the CSV's own directory), so a referenced PDF is never declared an orphan. (A check limited to CSV files, or to absolute paths, would report the workflow XML or the SSP PDFs as orphans, and deleting them breaks the install or leaves `file.csv` dangling.) `paths` proves every source resolves to a file; `orphan-files` proves every file is a source. Reports `onDisk`/`referenced` counts + the orphan `findings`; exit 2 on any orphan. The gate the project-data "Consolidate & clean up" pass uses to prove the on-disk tree equals the active manifest. -- `threshold-glossary --locales a,b [--base dir]` — **asserts every Sales-Order-Threshold row's message key resolves in each project locale's glossary.** The regular threshold (`data_entity: sales-order-threshold`) builds its key at runtime from type+store+currency (`sales-order-threshold....message`) and looks it up unconditionally — the empty `message_glossary_key` column is not an exemption. For every threshold row × locale, flags the (key, locale) pairs missing from the manifest's `glossary` sources. Reports `thresholdRows`/`thresholdFiles`/`glossaryFiles` so a `0` finding count from *no threshold file found* is visible, not falsely reassuring. Skips `merchant-relationship-sales-order-threshold` (auto-generated, never glossary-seeded). Exit 2 on any miss. Catches the green-boot-then-500-at-add-to-cart defect the boot itself won't surface (the [[project-data]] threshold gate). -- `sku-coverage [--base dir]` — **the complement of `manifest-refs`: which files is a SKU missing from?** For every SKU (`abstract_sku`/`concrete_sku`/`sku` families across the manifest's catalogue sources) it compares the set of files the SKU appears in against the modal set across all SKUs and reports the files a SKU is absent from that its peers are in (a product added mid-project absent from `merchant_product.csv` and `product_shipment_type.csv` → no "Sold by", **"No shipping types available for this product."** — both invisible to every outbound check, both visible only on screen). Runs inside `gate` as a **WARNING** (non-gating: a deliberately unassigned SKU is legitimate) — read the findings, don't wait for exit 2. **Run it after every product add**, standalone. -- `translation-coverage --from --to [||…] [--base dir]` — **untranslated text in a translated column**: for every `.` column with a `.` twin, the rows whose two cells are identical (non-empty, at least three letters) — an English copy left in a `.` column reads as translated to every other check. Not in `gate` (it needs the two locales named); run it after `duplicate-columns` and again when the translation is claimed done. -- `inventory [--base dir] [--plain]` — **the semantic read every referential check skips.** One line per manifest source: `data_entity`, source path, row count, and a sample of its free-text values (the first distinctive cells). This is the artifact the [[project-data]] consolidation pass records (in its evidence file) and classifies `project` / `generic-plumbing` / `demo-leftover` before `done` — the sample cells show, for example, another vertical's demo assets ("Example Asset A") that are still imported under a green `gate --strict`. Not a gate, by design: project-data closes on the classified inventory, not on a green gate alone. +Rules that apply to every run (the help of each named command has the detail): +- Files are positional and come before the flags. Batch many files in one command with `--in-place`; never a shell loop. Count with `rowCount`/`matchedRows` or `count --plain`, never `| grep -c`. +- Run `gate` yourself before any `docker/sdk reset|clean-data|up|console data:import` and stop on a gating finding. Capture the baseline on the untouched clone with `gate --save `, never `gate > file`. Use `gate --strict` for the project-data consolidation close-out and for `done`. +- `manifest-refs` is the first net, not full referential integrity: run `refs --ref-file` for each relation whose parent set the project replaced. +- Run `sku-coverage` after every product add. Record `inventory` in the evidence file and classify every line before `done`. Concept-free by design: new demoshop files/entities need no new code — point the checks at them. A green boot is still the correctness authority; these are the cheap early net. **If a tool cannot do something, a fallback is fine — but prefer the tool** (`awk`/`sed`/`python` corrupt multi-line quoted fields and prompt). @@ -111,21 +66,3 @@ Two files hold every demo-data literal the consumer skills rely on, so a demo-da - **`data/entity-map.yml`** — one row per shipped `data_entity`: its source **filename** (which often differs from the entity name — that mismatch is why the file exists), its **class** (`structural` = theme-independent plumbing kept regardless of catalog; `content` = theme-dependent demo data; `unclassified` = undecided, blocks boot), and, for structural rows, the **`why`**. The authoritative structural keep-set the `clean`/`minimal-baseline` keep-lists derive from. - **`references/demo-facts.md`** — the concrete **identifiers** (a real SKU pair, the `cms-block-email--` prefix + `block_key` column, the shipped product-label + navigation keys, the `shop_ui` colour keys, the manifest families), each paired with the command that re-derives it. **No record counts** — those are stated as their measuring command, never a stored number. - ---- - -# Flag cookbook (one worked example per command — copy, don't guess) - -Non-obvious flag behaviours: -- **`set` adds a missing column** — `csv set url.uk_UA.csv --column url.uk_UA --value /uk/` creates `url.uk_UA` if absent (not only sets an existing one). -- **prefix/substring match uses `--match`** — `csv filter cms_block.csv --where block_key=cms-block-email-- --match prefix` (there is no `--where-contains`; note the column is `block_key`, not `name`). -- **membership uses `--in` / `--in-file`** — `csv filter product_abstract.csv --in abstract_sku=A1,A2` or `--in-file abstract_sku=keep.txt` (one value per line). -- **`refs` reference set is `--in` OR `--ref-file`+`--ref-column`** — `validate refs offer_store.csv --column store --ref-file store.csv --ref-column name` (not `--in-file`). -- **`scale` scales net+gross together** — `csv scale product_price.csv --column value_net --column value_gross --rates PLN=4.3,UAH=45 --in-place`. -- **`product-refs` takes a directory + `--keep-from :`** (not a manifest) — `validate product-refs data/import/common --keep-from …/product_abstract.csv:abstract_sku`. -- **`preflight` / `manifest-diff` take a manifest yml** — `validate preflight data/import/local/full_EE.yml --base . --locales en_US,pl_PL,uk_UA`; `validate manifest-diff data/import/local/full_EU.yml full_EE.yml --base .`. -- **`known-set` runs from any cwd on its defaults** — `validate known-set --base ` (checks the map + the count gate); `validate known-set --emit-map --base --out /skeleton.yml` to regenerate the map skeleton for a diff review after a demo-data bump (`--out` writes the file itself, like `gate --save`; without it the skeleton is printed — never a `>` redirect, and never `/tmp`: use the session scratchpad). -- **`--baseline` takes a saved gate (or preflight) report — capture it with `--save`, never a redirect** — `validate gate --save .ai-dev/gate-baseline.json` on the untouched clone (the tool writes after running and refuses when `baselineSafe` is false; `gate > file` truncates the target first, the gate reads its own empty baseline and saves a falsely clean report). Then `validate gate --baseline .ai-dev/gate-baseline.json` gates only new findings (`gate` also auto-discovers that path). -- **`append` adds rows from a file, `add-row` adds one** — `csv append glossary.en_GB.csv --from new-keys.csv --dedupe-on key --in-place` (header of `new-keys.csv` ⊆ target's; missing columns empty); `csv add-row product_label.csv --set name=project-new --set is_active=1 --in-place` (unknown column = hard error). -- **`sku-coverage` / `inventory` take a manifest yml, like `preflight`** — `validate sku-coverage data/import/local/full_EU.yml --base .` after every product add; `validate inventory data/import/local/full_EU.yml --base . --plain` → record it in the evidence file and classify every line before `done`. -- **`read` is one file; `columns`/`count`/`distinct`/`filter`/`delete`/`set`/`scale`/`drop-columns` take many** (with `--in-place` for the mutations); `append`/`add-row` take one target file. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/scripts/csv.php b/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/scripts/csv.php index 78a65bf..17c595e 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/scripts/csv.php +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/scripts/csv.php @@ -857,6 +857,9 @@ function csv_row_key(array $row): string function csv_cli(array $argv): int { $command = $argv[1] ?? ''; + if ($command === '--help') { + return csv_help($argv[2] ?? null); + } $rest = array_slice($argv, 2); // Leading positional args (before the first --flag) are input files. This lets @@ -939,7 +942,37 @@ function csv_cli(array $argv): int function csv_usage(): int { - return csv_report(2, [], [ + return csv_report(2, [], csv_usage_lines()); +} + +/** + * `--help` lists the commands and the general rules; `--help ` prints the full + * explanation of one command. Plain text, exit 0; an unknown command is a JSON error, exit 2. + */ +function csv_help(?string $command): int +{ + $texts = csv_help_texts(); + if ($command === null) { + echo implode("\n", csv_usage_lines()) . "\n\n" . $texts['_general'] . "\n\nRun `csv.php --help ` for the full explanation of one command.\n"; + + return 0; + } + if ($command === '_general' || !isset($texts[$command])) { + $known = array_values(array_filter(array_keys($texts), static fn (string $k): bool => $k !== '_general')); + + return csv_report(2, [], [sprintf("--help: unknown command '%s'; commands: %s", $command, implode(', ', $known))]); + } + echo $texts[$command] . "\n"; + + return 0; +} + +/** + * @return list + */ +function csv_usage_lines(): array +{ + return [ 'usage: csv.php [...] [options]', 'Inspection (own output; --plain = line output; columns/distinct take many files):', ' read [--limit N]', @@ -961,7 +994,8 @@ function csv_usage(): int ' replace ... --column url.fr_CA --search /en/ --with /fr/ [--regex] [--where col=val] (--out f | --in-place)', ' scale ... --column value_gross (--by 1.08 | --rates PLN=4.3,UAH=45 [--currency-column currency]) [--no-round] [--json-keys a,b] [--where col=val] (--out f | --in-place)', ' derive ... --target value_gross --source value_net --factor 1.19 [--no-round] [--only-empty] [--where col=val] (--out f | --in-place) (target = source × factor; creates target column; skips empty/non-numeric source)', - ]); + 'Help: --help (this list and the general rules) | --help (full explanation and examples)', + ]; } /** @@ -1470,3 +1504,163 @@ function csv_plain(array $lines): int return 0; } + +/** + * Help text for `--help `. + * + * @return array + */ +function csv_help_texts(): array +{ + return [ + 'read' => <<<'TXT' +`read [--limit N]` — dump header + rows as JSON. Takes one file — passing several is a clean error +(no silent truncation to the first; use `columns`/`count` for many-file inspection). +TXT, + 'count' => <<<'TXT' +`count [ …] [--plain]` — data-row count per file, many files in one call. `--plain` → +`rowCount⇥file` per line. Use this for "how many rows across these N files" — never a shell `for … do +… done` loop with `| grep rowCount`; one `count` call replaces the whole loop. +TXT, + 'columns' => <<<'TXT' +`columns [ …] [--plain]` — header + row count. Accepts many files in one call (per-file +output; a missing file is reported inline, batch survives). `--plain` → column names per line, with a `== + ==` delimiter when multiple. +TXT, + 'distinct' => <<<'TXT' +`distinct … --column C [--plain]` — distinct values of a column with row counts, sorted by count +desc (`--plain` → `count⇥value` per line); takes many files in one call (aggregated). Use this to inspect +data — never `awk`/`sort`/`uniq -c` (they corrupt multi-line quoted fields). +TXT, + 'filter' => <<<'TXT' +`filter ... (--where col=val … [--match exact|prefix|contains] | --in col=v1,v2,… | --in-file +col=path) [--out f | --in-place]` — keep matching rows. `--where` repeatable (AND); `--in`/`--in-file` = +set-membership. Without a target it previews: `matchedRows`/`resultRows` are the full counts, the echoed +`rows` are capped at 20 (`--limit N` to raise) — the counts are the destructive-gate evidence, not the row +dump. + +Example / flag note: prefix/substring match uses `--match` — `csv filter cms_block.csv --where +block_key=cms-block-email-- --match prefix` (there is no `--where-contains`; note the column is `block_key`, +not `name`). + +Example / flag note: membership uses `--in` / `--in-file` — `csv filter product_abstract.csv --in +abstract_sku=A1,A2` or `--in-file abstract_sku=keep.txt` (one value per line). +TXT, + 'delete' => <<<'TXT' +`delete ... (same conditions) [--out f | --in-place]` — drop matching rows. + +Example / flag note: prefix/substring match uses `--match` — `csv filter cms_block.csv --where +block_key=cms-block-email-- --match prefix` (there is no `--where-contains`; note the column is `block_key`, +not `name`). + +Example / flag note: membership uses `--in` / `--in-file` — `csv filter product_abstract.csv --in +abstract_sku=A1,A2` or `--in-file abstract_sku=keep.txt` (one value per line). +TXT, + 'duplicate-columns' => <<<'TXT' +`duplicate-columns ... --from en_US --to fr_CA[,de_DE,…] [--skip-base url] (--out f | --in-place)` — +for every `X.en_US` column, add `X.` copying the value; `--skip-base` leaves families alone. `--to` takes +a comma-list → all project locales in one call. +TXT, + 'duplicate-rows' => <<<'TXT' +`duplicate-rows ... --column locale --from en_US --to fr_CA[,uk_UA,…] (--out f | --in-place)` — +clone rows per `--to` value (glossary → all locales; store-relation rows → all stores). +TXT, + 'set' => <<<'TXT' +`set ... --column store --value US [--where col=val ...] (--out f | --in-place)` — set a column on +matching rows (empty `--where` = all rows). + +Example / flag note: `set` adds a missing column — `csv set url.uk_UA.csv --column url.uk_UA --value /uk/` +creates `url.uk_UA` if absent (not only sets an existing one). +TXT, + 'replace' => <<<'TXT' +`replace ... --column url.fr_CA --search /en/ --with /fr/ [--regex] [--where col=val] (--out f | +--in-place)` — string/regex replace within an existing column. +TXT, + 'scale' => <<<'TXT' +`scale ... --column value_gross [--column value_net] (--by 1.47 | --rates PLN=4.3,UAH=45 +[--currency-column currency]) [--no-round] [--json-keys net_price,gross_price] [--where col=val] (--out f | +--in-place)` — multiply numeric values (currency conversion); `--column` is repeatable — net + gross scale +together in one call (`--column value_net --column value_gross`); `--rates` applies a per-currency factor in +one call; `--json-keys` scales embedded price tiers. + +Example / flag note: `scale` scales net+gross together — `csv scale product_price.csv --column value_net +--column value_gross --rates PLN=4.3,UAH=45 --in-place`. +TXT, + 'derive' => <<<'TXT' +`derive ... --target value_gross --source value_net --factor 1.19 [--no-round] [--only-empty] [--where +col=val] [--out f | --in-place]` — cross-column arithmetic `scale` can't do: writes `target = source × +factor`, creating the target column if absent. Skips rows whose source is empty/non-numeric; a +non-numeric/zero `--factor` is a hard error (never silently zeroes a column). `--only-empty` gap-fills (won't +overwrite existing target values). E.g. fill gross from net + tax, or a base-currency price into a second +column before converting. +TXT, + 'select' => <<<'TXT' +`select --columns a,b,c --out file` — project columns (single file, keep-list). +TXT, + 'drop-columns' => <<<'TXT' +`drop-columns ... (--column name | --suffix .de_DE)... [--out f | --in-place]` — remove columns; +`--suffix` drops a whole family across files. Repeatable; a named column absent from a file is reported +(per-file `skippedColumns`), not fatal; idempotent. +TXT, + 'rename-columns' => <<<'TXT' +`rename-columns ... --rename old:new [--rename old2:new2 …] [--out f | --in-place]` — rename header +columns and the matching row keys, many files in one call (repeatable `--rename` = multiple pairs). A pair +whose `old` is absent, or whose `new` already exists as a different column, is reported in `skippedColumns` +(not fatal); idempotent; malformed `--rename` (no `:`) is a hard error. Use it instead of hand-authoring a +near-duplicate file that differs only by column names — e.g. deriving `price_product_offer` from +`product_price`: `replace` the values, `rename-columns` the ref column, done in two commands with no loop. +TXT, + 'apply-translations' => <<<'TXT' +`apply-translations ... --target-column name.uk_UA [--source-column name.en_US] --map map.csv (--out f | +--in-place)` — apply a `source→target` value map to one column (map file has `source,target`). Only the +target column changes — safe by construction. Exact match, multi-line-safe; unmapped values left as-is. +TXT, + 'append' => <<<'TXT' +`append --from [--dedupe-on ] (--out f | --in-place)` — the row-adding op for +authoring passes. Appends every row of `rows.csv`, whose header must be a subset of the target's (columns the +rows file lacks are written empty; a column the target lacks is a hard error); `--dedupe-on ` skips rows +whose key already exists in the target. Writes LF, atomic. This is how new glossary keys, labels or store rows +go into the one file per entity — never a second `_project.csv` source (the gate's +`duplicateEntitySources` forbids it) and never a hand-rolled writer (Python's `csv` defaults to CRLF; +`preflight` `lineEndings` flags it). + +Example / flag note: `append` adds rows from a file, `add-row` adds one — `csv append glossary.en_GB.csv +--from new-keys.csv --dedupe-on key --in-place` (header of `new-keys.csv` ⊆ target's; missing columns +empty); `csv add-row product_label.csv --set name=project-new --set is_active=1 --in-place` (unknown column = +hard error). +TXT, + 'add-row' => <<<'TXT' +`add-row --set col=value [--set col2=value …] (--out f | --in-place)` — append one row: repeatable +`--set`, an unknown column is a hard error, unset columns are empty. Same LF/atomic guarantees as `append`. +For more than a handful of rows, build a `rows.csv` and `append` it. + +Example / flag note: `append` adds rows from a file, `add-row` adds one — `csv append glossary.en_GB.csv +--from new-keys.csv --dedupe-on key --in-place` (header of `new-keys.csv` ⊆ target's; missing columns +empty); `csv add-row product_label.csv --set name=project-new --set is_active=1 --in-place` (unknown column = +hard error). +TXT, + '_general' => <<<'TXT' +Inspection commands (read, count, columns, distinct): add `--plain` for line output — no JSON to parse. + +Files are positional and come before the flags (`columns --plain`, not `columns --plain `). +`columns`/`count`/`distinct` report a specific `no input file given` error for the flags-first shape instead +of the generic usage dump — read the error text, which names the argument order as the problem. + +Mutation — write with `--out ` for one file, or `--in-place` for one-or-many files. Batch: list +several files before the flags and add `--in-place` to apply the same op to all in a single command (per-file +report in `files[]`) — this is how you avoid a shell `for` loop. Multiple files without `--in-place` is an +error. + +Notes: all access is by header name, never index. A missing column returns a clean JSON error with exit `2`. +Idempotent where sensible. Writes are atomic (temp file + rename — a crash mid-batch never leaves a +truncated CSV) and LF-terminated (the repo is LF; `git add`'s `CRLF will be replaced by LF` warning means a +file was written by something other than these tools). macOS/OrbStack bind-mounts lag — re-check a written +file a beat later. Counting: never `| grep -c` — use `rowCount` (`columns`/`read`) or `matchedRows` +(`filter` preview). Batch, don't loop. + +Example / flag note: `read` is one file; +`columns`/`count`/`distinct`/`filter`/`delete`/`set`/`scale`/`drop-columns` take many (with `--in-place` for +the mutations); `append`/`add-row` take one target file. +TXT, + ]; +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/scripts/csv.test.php b/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/scripts/csv.test.php index 679f40e..0739064 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/scripts/csv.test.php +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/scripts/csv.test.php @@ -553,6 +553,32 @@ function check(string $name, bool $ok): void $orderJson = json_decode((string) shell_exec("{$php} {$lib} columns --plain " . escapeshellarg($ap) . ' 2>/dev/null'), true); check('CLI: a flag before the file names the actual problem', ($orderJson['status'] ?? '') === 'error' && str_contains(json_encode($orderJson), 'did you put a --flag before the file')); +// --- CLI: --help / --help --- +$helpRun = static function (string $args) use ($php, $lib): array { + $out = []; + $code = 0; + exec("{$php} {$lib} {$args} 2>&1", $out, $code); + + return [implode("\n", $out), $code]; +}; +[$helpAll, $helpAllCode] = $helpRun('--help'); +check('CLI --help: exit 0, lists the commands and points to --help ', $helpAllCode === 0 && str_contains($helpAll, 'usage: csv.php') && str_contains($helpAll, '--help ')); +check('CLI --help: prints the general rules (files before flags, atomic LF writes)', str_contains($helpAll, 'Files are positional and come before the flags') && str_contains($helpAll, 'LF-terminated')); +[$helpFilter, $helpFilterCode] = $helpRun('--help filter'); +check('CLI --help filter: exit 0, full explanation and the worked example', $helpFilterCode === 0 && str_contains($helpFilter, 'keep matching rows') && str_contains($helpFilter, '--match prefix')); +$usageCommands = []; +foreach (csv_usage_lines() as $line) { + if (preg_match('/^ ([a-z-]+) /', $line, $m)) { + $usageCommands[] = $m[1]; + } +} +$missingHelp = array_values(array_diff($usageCommands, array_keys(csv_help_texts()))); +check('CLI --help: every command in the usage list has a help text', $usageCommands !== [] && $missingHelp === []); +[$helpBad, $helpBadCode] = $helpRun('--help nope'); +check('CLI --help : exit 2 with a JSON error naming the known commands', $helpBadCode === 2 && str_contains((string) (json_decode($helpBad, true)['errors'][0] ?? ''), "unknown command 'nope'")); +[, $noArgCode] = $helpRun(''); +check('CLI with no argument still prints the usage error, exit 2', $noArgCode === 2); + // cleanup array_map('unlink', glob($tmp . '/*') ?: []); @rmdir($tmp); diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/scripts/validate.php b/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/scripts/validate.php index 773444f..3b8c3d9 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/scripts/validate.php +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/scripts/validate.php @@ -3740,6 +3740,9 @@ function validate_report_check(string $check, array $findings, array $context, b function validate_cli(array $argv): int { $check = $argv[1] ?? ''; + if ($check === '--help') { + return validate_help($argv[2] ?? null); + } $opts = validate_parse_opts(array_slice($argv, 2)); validate_quiet(isset($opts['quiet'])); @@ -4140,7 +4143,48 @@ function validate_cli(array $argv): int return validate_report_known_set(validate_known_set($manifest, $map, $skills, $base)); default: - return validate_report(2, $check, [], [ + return validate_report(2, $check, [], validate_usage_lines()); + } + } catch (Throwable $e) { + return validate_report(2, $check, [], [$e->getMessage()]); + } +} + +/** + * `--help` lists the checks, the output format and the exit codes; `--help ` prints the full + * explanation of one check. Plain text, exit 0; an unknown check is a JSON error, exit 2. + */ +function validate_help(?string $check): int +{ + $texts = validate_help_texts(); + $usage = validate_usage_lines(); + if ($check === null) { + echo implode("\n", $usage) . "\n\n" . $texts['_general'] . "\n\nRun `validate.php --help ` for the full explanation of one check.\n"; + + return 0; + } + if ($check !== '_general' && isset($texts[$check])) { + echo $texts[$check] . "\n"; + + return 0; + } + foreach ($usage as $line) { + if (str_starts_with($line, $check . ' ')) { + echo $line . "\n"; + + return 0; + } + } + + return validate_report(2, '--help', [], [sprintf("--help: unknown check '%s'", $check), $usage[0]]); +} + +/** + * @return list + */ +function validate_usage_lines(): array +{ + return [ 'usage: validate.php ...', 'import-order [...] [--base dir] — an action must not precede an action it depends on (GATE, gating)', 'store-coverage [...] [--base dir] [--stores a,b] — a declared store with zero rows where other stores have rows (GATE, warning)', @@ -4152,11 +4196,9 @@ function validate_cli(array $argv): int 'bundle-stock [...] — every concrete a bundle slot offers must have stock (GATE, warning)', 'tree-scope [...] — every project source under ONE top-level directory below data/import/ (GATE, warning)', 'demo-needs [] [...] [--base dir] — does the data support the demo: each named product exists and has a variant in stock, categories and blocks exist and are active, a named facet has more than one value among that beat\'s own products, the persona exists, and quoted wording is present verbatim in content rows or shipment/payment method names; a value that is not a SKU/key (prose) is listed under `skipped`, never a finding (not in gate: it needs a demo needs list)', - 'gate [ ...] [--locales a,b] [--base dir] [--baseline ] [--root dir]... [--strict] [--save ] [--quiet] — one verdict over paths+preflight+manifest-refs+threshold-glossary+duplicate-keys+cms-block-store (gating), orphan-files (gating only with --strict) and sku-coverage+store-coverage+locale-coverage+attribute-glossary+bundle-stock+tree-scope (warnings); --save writes the report AFTER the run (the only safe way to capture a baseline — never `>`); auto-discovers the booted regions\' data/import/local/full_*.yml + the install recipe\'s --config manifests, the project locales, and .ai-dev/gate-baseline.json (else preflight-baseline.json)']); - } - } catch (Throwable $e) { - return validate_report(2, $check, [], [$e->getMessage()]); - } + 'gate [ ...] [--locales a,b] [--base dir] [--baseline ] [--root dir]... [--strict] [--save ] [--quiet] — one verdict over paths+preflight+manifest-refs+threshold-glossary+duplicate-keys+cms-block-store (gating), orphan-files (gating only with --strict) and sku-coverage+store-coverage+locale-coverage+attribute-glossary+bundle-stock+tree-scope (warnings); --save writes the report AFTER the run (the only safe way to capture a baseline — never `>`); auto-discovers the booted regions\' data/import/local/full_*.yml + the install recipe\'s --config manifests, the project locales, and .ai-dev/gate-baseline.json (else preflight-baseline.json)', + 'Help: --help (this list, the output format and exit codes) | --help (full explanation and examples)', + ]; } /** @@ -4398,3 +4440,291 @@ function validate_report_manifest_diff(array $result): int return $exit; } + +/** + * Help text for `--help `. + * + * @return array + */ +function validate_help_texts(): array +{ + return [ + 'gate' => <<<'TXT' +`gate [ …] [--locales a,b] [--base dir] [--baseline ] [--root +dir]… [--strict] [--save ] [--quiet]` — the close-out command: one call, one verdict. Runs `paths` + +`preflight` + `manifest-refs` + `threshold-glossary` + `duplicate-keys` + `cms-block-store` (gating), +`orphan-files` (gates only with `--strict`), and six warning-only checks over the active manifests and returns +`{status, gatingCount, warningCount, summary[], checks{…}}`; exit `0` clean, `2` any gating finding, `1` +warnings only. `--save ` writes the report itself after running and refuses when `baselineSafe` is false +— this is how the baseline is captured (`php gate --save .ai-dev/gate-baseline.json`), never +`gate > file`: the shell truncates the target before the gate runs, the gate reads its own empty baseline, and +saves a falsely clean report. Everything is auto-discovered when omitted: the manifests +(`data/import/local/full_.yml` for every region `deploy.dev.yml` boots, plus every literal +`data:import --config=` in `config/install/docker.yml` — the vendor payment configs), the project +locales (from the `locale-store` sources), the declared stores (from the `store` source — passed to every +manifest so a vendor config naming a removed store is caught), and the baseline (`.ai-dev/gate-baseline.json`, +else `.ai-dev/preflight-baseline.json`). `orphan-files` gates only under `--strict` (a fresh, un-consolidated +demoshop legitimately carries files no manifest imports); use `--strict` for the project-data consolidation +close-out and for `done`. A saved gate report is the baseline of choice — capture it on the untouched clone +with `gate --save .ai-dev/gate-baseline.json`, and only new findings gate across every gating check (the +shipped demoshop is not clean on `manifest-refs`/`threshold-glossary` either, which a preflight-only baseline +cannot suppress). Run this gate yourself before any `docker/sdk reset|clean-data|up|console data:import` and +stop on a gating finding. With a baseline on file, only gating findings the baseline does not hold count; with +no baseline, any gating finding stops the rebuild verbs, and `data:import` proceeds (capture the baseline on +the untouched clone). For the rebuild verbs (`reset`/`clean-data`/`up`), trusted rebuilds (a demo clone, first +setup, or a recorded `standing_approval: { scope: rebuilds }`) run after a one-line announcement, a project +with real data gets one question, and before the third and every later rebuild the decision log gets `rebuild +#N: `; the step report states the rebuild count. `console data:import` needs no +question: it is rung 1 of the ladder and stays cheap. Vendor-owned sources (`vendor/`) are exempt from the +project-data groups and checked for store references only; a vendor source absent on an un-booted clone (no +`vendor/` yet) is not a finding. + +Example / flag note: `--baseline` takes a saved gate (or preflight) report — capture it with `--save`, never +a redirect — `validate gate --save .ai-dev/gate-baseline.json` on the untouched clone (the tool writes after +running and refuses when `baselineSafe` is false; `gate > file` truncates the target first, the gate reads its +own empty baseline and saves a falsely clean report). Then `validate gate --baseline +.ai-dev/gate-baseline.json` gates only new findings (`gate` also auto-discovers that path). +TXT, + 'preflight' => <<<'TXT' +`preflight [--base dir]` — the manifest-wide invariant sweep `gate` runs for you (call +it directly to drill into one manifest); one driver that auto-discovers and checks the boot-critical +invariants across every file the manifest imports, so you never enumerate files by hand. Reads the manifest's +`source:` list and, by column shape, bundles four checks: url.\ global uniqueness — cross-file, +like the real `spy_url` constraint (a product URL colliding with a category/merchant URL is caught; one dup +aborts the 30–60 min install; navigation-node sources are exempt — a nav node's url is a link *target*, +legitimately repeated across menus), is_searchable.\ non-blank (blank = silently unsearchable), price +completeness — gross-mode aware (a missing/`0` `value_gross`, or a missing net in a net-only file, is a hard +problem; a missing net *beside a present gross* is how the shipped gross-mode stores legitimately look → +reported under non-gating `priceNetWarnings`/`warningCount`), and base-before-relation import order +(`currency` before `currency-store`, `store` before every `*-store`, and every store-definition entry — +checked on its last occurrence — before the first product/category entity; a 3rd store's `locale-store` +appended after the catalog = a silently empty store). Also flags any manifest `source:` that doesn't exist. +`--baseline ` suppresses findings already present in that report — capture a +baseline on the untouched clone first, then only new findings gate (the shipped demoshop carries pre-existing +quirks that are not yours to fix). It also runs generate-mode required-shape checks (`shapeWarnings`): +`product-abstract` source has a `color_code` column (else 0 rows import silently), `visibility ∈ +{PDP,PLP,Cart,∅}`, `product-abstract` imported with an `*approval-status` entity (else 0 search docs, +invisibly), `merchant-product-offer` accompanied by `merchant-product`, and `tax_set_name ⊆` the tax source. +Returns one grouped verdict (`problemCount`, then +`unreadableSources`/`urlDuplicates`/`searchableBlanks`/`priceMissing`/`foreignLocaleColumns`/`foreignLocaleRows`/`shapeWarnings`/`orderViolations`), +exit `2` if any. Plus these invariant groups (each imports without an error and surfaces only later; all +gating, all baseline-suppressible): `headerOnlySources` (a source with 0 data rows — the delete-vs-empty +decision was never made), `glossaryMultiLocale` (a `glossary` source carrying more than one `locale` — +glossary is one file per locale), `duplicateEntitySources` (one `data_entity` from several sources in the same +directory not distinguished by a store/locale token — the `.csv` + `_extra.csv` split), +`storeDirMismatch` (a source under a `/` dir whose `store`/`store_name`/`included_store_names` name +another store — the `cp -r` seeding leftover that boots a silently half-empty store), `undeclaredStore` (a +store value not in the `store` source — a vendor config hardcoding a removed store aborts the reset after +the project import reported Successful), `searchAttributeOverlap` (a key in both +`product_search_attribute_map` and `product_search_attribute` — every facet count exactly doubled), +`categoryTemplateUnknown` (`category.csv` `template_name` not in the category-template source — every +category then fails, then every abstract, three importers later, aborting the install), +`rootCategoryNotInMenu` (a root category with `is_in_menu` ≠ 1 — the category tree publishes `[]`), +`approvalStatusMissing` (an abstract SKU with no approval-status row — the publisher writes nothing, +silently), `priceNonInteger` (`value_gross`/`value_net`/`value_cost`/`amount`/`threshold` not an integer — +Spryker money is minor units; a decimal renders 100x wrong), `embeddedPathsMissing` (a path inside a CSV cell +— workflow XML, file assets — that does not exist; relative paths such as `file.csv`'s +`common/common/files/X.pdf` are resolved against the base dir, `data/import/` and the CSV's own directory, so +a relative asset reference is checked, never skipped), `lineEndings` (a manifest CSV containing CRLF — +Python's `csv` writer default; the repo is LF and git flags it only at `add` time), `discountShipmentByName` +(a discount `decision_rule_query_string`/`collector_query_string` clause `shipment-method`/`shipment-carrier` +with a non-numeric value — both rules compare the numeric id, so `shipment-method = 'DHL Standard'` imports +and never applies), `categoryStoreIncomplete` (a store whose `category_store` rows name some child categories +but not others — `category-store` spreads the root's stores to children only when the root relation is first +created, so a category added on a later import gets no store row and its page shows 0 products; state every +category per store, included, excluded, or both lists empty = take the parent's stores). Shipment-price files +are exempt from the empty-or-`0` price rule (free shipment is a real value). Add `--locales +` to also flag any `.` column or `locale` row value that isn't in the project's set +— the "a finished project carries only its own locales" check, across `data/import/` (the `absent` sweep +misses that tree). One exemption: `en_US` rows in a `glossary` source are never foreign — the en_US glossary +is the translator fallback layer every project imports (`project-data` adapt step 1), whichever locales the +stores serve. Use the individual checks below to drill into a specific file; `preflight` is the sweep that +replaces remembering to run each one everywhere. + +Example / flag note: `preflight` / `manifest-diff` take a manifest yml — `validate preflight +data/import/local/full_EE.yml --base . --locales en_US,pl_PL,uk_UA`; `validate manifest-diff +data/import/local/full_EU.yml full_EE.yml --base .`. + +Example / flag note: `--baseline` takes a saved gate (or preflight) report — capture it with `--save`, never +a redirect — `validate gate --save .ai-dev/gate-baseline.json` on the untouched clone (the tool writes after +running and refuses when `baselineSafe` is false; `gate > file` truncates the target first, the gate reads its +own empty baseline and saves a falsely clean report). Then `validate gate --baseline +.ai-dev/gate-baseline.json` gates only new findings (`gate` also auto-discovers that path). +TXT, + 'manifest-diff' => <<<'TXT' +`manifest-diff [--base dir]` — diff the `data_entity` lists of two import +manifests. Reports `missing` (entities the reference/demo manifest imports that the new one does not — each +with its source row count so you can rank: rows ≈ product population → structural/required, rows ≪ → +opt-in demo garnish) and `added`. Exit `2` if anything is missing. This is the mechanical guard against +generate-mode silently dropping behavioural plumbing (e.g. `product-shipment-type`) — diff, then classify +every omission as intentional-content-drop or must-keep-structural. + +Example / flag note: `preflight` / `manifest-diff` take a manifest yml — `validate preflight +data/import/local/full_EE.yml --base . --locales en_US,pl_PL,uk_UA`; `validate manifest-diff +data/import/local/full_EU.yml full_EE.yml --base .`. +TXT, + 'known-set' => <<<'TXT' +`known-set [] [--base dir] [--map ] [--skills ] [--emit-map [--out ]]` +— the maintainability gate: keep `data/entity-map.yml` honest against the shipped manifest, and keep record +counts out of the skills. Defaults resolve relative to the script, so it runs from any cwd (default manifest +`data/import/local/full_EU.yml`, default map `data/entity-map.yml`, default skills dir the plugin's +`skills/`). Reports and gates (exit `2`) on: a manifest entity missing from the map; a stale map row the +manifest no longer imports; a map `source` that isn't the file the manifest imports for that entity (or is +gone from disk); any `class: unclassified` row (an undecided entity blocks the boot by design); a `structural` +row with an empty `why`; and any bare record count (`N +rows|files|entities|products|blocks|labels|SKUs|docs|CSVs|nodes|keys|columns|attributes|categories`) in a +`.md` under the skills dir (a `0`/`~0` count or a `count-ok`-marked line is exempt). `--emit-map` regenerates +the map skeleton from the manifest, preserving the class/why of entities already classified and marking new +ones `unclassified` — a demo-data bump becomes a diff review, not a retype. It does not scan prose for stray +identifiers/paths — `paths` and `product-refs` own that against the real files, where a +``-templated doc won't false-positive. + +Example / flag note: `known-set` runs from any cwd on its defaults — `validate known-set --base ` +(checks the map + the count gate); `validate known-set --emit-map --base --out +/skeleton.yml` to regenerate the map skeleton for a diff review after a demo-data bump (`--out` +writes the file itself, like `gate --save`; without it the skeleton is printed — never a `>` redirect, and +never `/tmp`: use the session scratchpad). +TXT, + 'refs' => <<<'TXT' +`refs ... --column C [--column C2] (--in a,b,c | --ref-file F --ref-column K) [--split ,] [--composite]` +— every value in the column(s) must be in the reference set. A missing column is a finding, never a silent +pass. `--split` handles multi-value cells. Multi-file: pass several files — each column is checked only +against the files that have it (a heterogeneous batch where `a.csv` has `key` and `b.csv` has `attribute_key` +won't false-fail), and a column absent from every file is still flagged. (`--composite` uses the first file.) +`--composite` treats the columns as one tuple and checks it against the ref file's `--ref-column`s +(positional) — for cross-entity integrity. E.g. every `(merchant, store)` sold must exist in +`merchant_store`. Plain `refs` would wrongly pass if each part exists independently. + +Example / flag note: `refs` reference set is `--in` OR `--ref-file`+`--ref-column` — `validate refs +offer_store.csv --column store --ref-file store.csv --ref-column name` (not `--in-file`). +TXT, + 'required' => <<<'TXT' +`required --column C [--column C2]` — cells must be non-empty (e.g. `is_searchable.` — a +blank imports as silently unsearchable). +TXT, + 'unique' => <<<'TXT' +`unique --column C` — no repeated values (empty cells ignored). E.g. `url.` — a duplicate +fails the import. +TXT, + 'absent' => <<<'TXT' +`absent [...] --string S [--string S2]` — none of the strings may appear (stale-literal +sweep). Directories are recursed, so `absent config/ src/Pyz --string DE` sweeps whole trees in one call. A +path resolving to nothing readable is a `CANNOT READ FILE` finding, never a silent pass. Triage tool, not an +absolute gate — scope a hard check to files that must be zero-hit (`CodeBucketConfig.php`, +`default_store.php`), classify the rest. +TXT, + 'paths' => <<<'TXT' +`paths [--base dir]` — every `source:` in the import config resolves to an existing +file. +TXT, + 'product-refs' => <<<'TXT' +`product-refs (--keep-from : | --keep-in a,b,c)... [--pattern n1,n2] [--list-suffix _skus] +[--exclude ]... [--exclude-column ]...` — broad orphan scanner for a catalog reduction. Walks +every CSV under ``, auto-discovers each product-ref column (name in `--pattern`, default +`sku,abstract_sku,concrete_sku,product_sku,product`; plus any header carrying `sku` as an underscore token — +`sku_concrete`, `abstract_product_sku`, `alternative_product_concrete_sku`, …; plus any column ending in +`--list-suffix`, default `_skus`, treated as a comma-list), reports every token not in the kept union set +(`--keep-from` file:columns ∪ `--keep-in`). The JSON carries a `columns` coverage summary (a 100%-orphan +column is usually a non-product code, e.g. `product_option.sku`; `--exclude-column` it) and the orphan +`findings`. `--exclude ` skips files not in the active manifest. Exit 2 on any orphan. The coverage +tool a catalog reduction needs (the reduce strategy in [[project-data]]). + +Example / flag note: `product-refs` takes a directory + `--keep-from :` (not a manifest) — +`validate product-refs data/import/common --keep-from …/product_abstract.csv:abstract_sku`. +TXT, + 'manifest-refs' => <<<'TXT' +`manifest-refs [--base dir]` — orphan sweep across the manifest's distinctive-key +relations, in one command. By column-name convention it builds each key family's producer set from the entity +that defines it (`abstract_sku`←product-abstract, `concrete_sku`←product-concrete, `sku`←both, +`merchant_reference`←merchant, `product_offer_reference`←product-offer/merchant-product-offer, +`category_key`←category, `sales_unit_key`←product-measurement-sales-unit), then flags every consumer cell +with no producer. Reports `checked` families and `unchecked` ones (producer entity absent from the manifest +→ not validated, never a false orphan). Exit 2 on any orphan. `category_key` is list-valued — the abstract +importer `explode(',')`s it (`ProductAbstractWriterStep::getCategoryKeys()`), so a comma list is the shipped +way to put a product in a second category; the check splits that family on `,` and reports one finding per +unresolvable part, never per cell. Every other family stays single-value (splitting universally would mask +real orphans in columns whose values legitimately contain a comma). It is not the whole FK graph: it covers +only families whose column name is distinctive. Relations keyed on a generic column — +`product-label-store`→`product-label` by `name`, `stock-address`→`stock` by `warehouse_name`, etc. — +can't be represented without cross-entity false positives, so they are invisible here. Heuristic for the gap: +any file the project copied from a seeded demo dir whose parent set the project then replaced (labels, sales +units, warehouses, attributes) counts as unchecked until a targeted `refs --ref-file` against the project's +own parent passes. Run `manifest-refs` as the cheap first net, then `refs --ref-file` per replaced-parent +relation — don't treat a green `manifest-refs` as full referential integrity. +TXT, + 'duplicate-keys' => <<<'TXT' +`duplicate-keys [--base dir]` — gating: the same primary key written twice in one +source. Contradicting duplicates (two different values) gate; additive and identical ones are reported. +TXT, + 'cms-block-store' => <<<'TXT' +`cms-block-store [--base dir]` — gating: a CMS block visible in one store and not its +twin, which renders as an empty slot on exactly one storefront. +TXT, + 'orphan-files' => <<<'TXT' +`orphan-files […] [--base dir]` — the complement of `paths`: lists +every import asset under the roots — every file type, not only CSV (state-machine XML, SSP PDFs; manifests, +READMEs and dotfiles are skipped) — that no manifest source references, counting paths embedded in CSV cells +as references (workflow.csv `definition`; `file.csv` `path`) — absolute `data/import/…` and relative +(`common/common/files/X.pdf`, resolved against the base dir, `data/import/` and the CSV's own directory), so a +referenced PDF is never declared an orphan. (A check limited to CSV files, or to absolute paths, would report +the workflow XML or the SSP PDFs as orphans, and deleting them breaks the install or leaves `file.csv` +dangling.) `paths` proves every source resolves to a file; `orphan-files` proves every file is a source. +Reports `onDisk`/`referenced` counts + the orphan `findings`; exit 2 on any orphan. The gate the project-data +"Consolidate & clean up" pass uses to prove the on-disk tree equals the active manifest. +TXT, + 'threshold-glossary' => <<<'TXT' +`threshold-glossary --locales a,b [--base dir]` — asserts every Sales-Order-Threshold +row's message key resolves in each project locale's glossary. The regular threshold (`data_entity: +sales-order-threshold`) builds its key at runtime from type+store+currency +(`sales-order-threshold....message`) and looks it up unconditionally — the empty +`message_glossary_key` column is not an exemption. For every threshold row × locale, flags the (key, locale) +pairs missing from the manifest's `glossary` sources. Reports `thresholdRows`/`thresholdFiles`/`glossaryFiles` +so a `0` finding count from *no threshold file found* is visible, not falsely reassuring. Skips +`merchant-relationship-sales-order-threshold` (auto-generated, never glossary-seeded). Exit 2 on any miss. +Catches the green-boot-then-500-at-add-to-cart defect the boot itself won't surface (the [[project-data]] +threshold gate). +TXT, + 'sku-coverage' => <<<'TXT' +`sku-coverage [--base dir]` — the complement of `manifest-refs`: which files is a SKU +missing from? For every SKU (`abstract_sku`/`concrete_sku`/`sku` families across the manifest's catalogue +sources) it compares the set of files the SKU appears in against the modal set across all SKUs and reports the +files a SKU is absent from that its peers are in (a product added mid-project absent from +`merchant_product.csv` and `product_shipment_type.csv` → no "Sold by", "No shipping types available for this +product." — both invisible to every outbound check, both visible only on screen). Runs inside `gate` as a +WARNING (non-gating: a deliberately unassigned SKU is legitimate) — read the findings, don't wait for exit +2. Run it after every product add, standalone. + +Example / flag note: `sku-coverage` / `inventory` take a manifest yml, like `preflight` — `validate +sku-coverage data/import/local/full_EU.yml --base .` after every product add; `validate inventory +data/import/local/full_EU.yml --base . --plain` → record it in the evidence file and classify every line +before `done`. +TXT, + 'translation-coverage' => <<<'TXT' +`translation-coverage --from --to [||…] [--base dir]` — +untranslated text in a translated column: for every `.` column with a `.` twin, the rows +whose two cells are identical (non-empty, at least three letters) — an English copy left in a `.` column +reads as translated to every other check. Not in `gate` (it needs the two locales named); run it after +`duplicate-columns` and again when the translation is claimed done. +TXT, + 'inventory' => <<<'TXT' +`inventory [--base dir] [--plain]` — the semantic read every referential check skips. +One line per manifest source: `data_entity`, source path, row count, and a sample of its free-text values (the +first distinctive cells). This is the artifact the [[project-data]] consolidation pass records (in its +evidence file) and classifies `project` / `generic-plumbing` / `demo-leftover` before `done` — the sample +cells show, for example, another vertical's demo assets ("Example Asset A") that are still imported under a +green `gate --strict`. Not a gate, by design: project-data closes on the classified inventory, not on a green +gate alone. + +Example / flag note: `sku-coverage` / `inventory` take a manifest yml, like `preflight` — `validate +sku-coverage data/import/local/full_EU.yml --base .` after every product add; `validate inventory +data/import/local/full_EU.yml --base . --plain` → record it in the evidence file and classify every line +before `done`. +TXT, + '_general' => <<<'TXT' +Output: JSON `{status, check, findingCount, findings, errors}`, exit `0` clean, `1` warnings only (a +warning-only check such as `sku-coverage`, or `gate` with warnings and no gating finding), `2` on a gating +finding. Add `--quiet` to branch on the exit code alone. Run `php /validate.php` with no arguments first +— it lists every check; the prose names only a subset of them. +TXT, + ]; +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/scripts/validate.test.php b/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/scripts/validate.test.php index 40e521d..e291c2d 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/scripts/validate.test.php +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-import-tools/scripts/validate.test.php @@ -1174,6 +1174,34 @@ function check(string $name, bool $ok): void check('demo-needs: a shipment method name / payment method name in the brief is found in shipment.csv / payment_method.csv', array_values($shipMissing) === ['Overnight Express']); // recursive: $tmp now contains a subdir (sub/) from the absent directory-recursion tests +// --- CLI: --help / --help --- +$helpRun = static function (string $args) use ($php, $lib): array { + $out = []; + $code = 0; + exec("{$php} {$lib} {$args} 2>&1", $out, $code); + + return [implode("\n", $out), $code]; +}; +[$helpAll, $helpAllCode] = $helpRun('--help'); +check('CLI --help: exit 0, lists the checks, the output format and points to --help ', $helpAllCode === 0 && str_contains($helpAll, 'usage: validate.php') && str_contains($helpAll, 'findingCount') && str_contains($helpAll, '--help ')); +[$helpGate, $helpGateCode] = $helpRun('--help gate'); +check('CLI --help gate: exit 0, full explanation incl. --save instead of a redirect', $helpGateCode === 0 && str_contains($helpGate, 'the close-out command') && str_contains($helpGate, 'never') && str_contains($helpGate, '--save')); +[$helpRefs] = $helpRun('--help refs'); +check('CLI --help refs: carries the worked example', str_contains($helpRefs, '--ref-file store.csv --ref-column name')); +[$helpBundle, $helpBundleCode] = $helpRun('--help bundle-stock'); +check('CLI --help : prints its usage line', $helpBundleCode === 0 && str_starts_with($helpBundle, 'bundle-stock ')); +preg_match('/<([a-z|-]+)>/', validate_usage_lines()[0], $m); +$undocumented = []; +foreach (explode('|', $m[1] ?? '') as $name) { + [, $code] = $helpRun('--help ' . $name); + if ($code !== 0) { + $undocumented[] = $name; + } +} +check('CLI --help: every check in the usage list has help', ($m[1] ?? '') !== '' && $undocumented === []); +[$helpBad, $helpBadCode] = $helpRun('--help zzz'); +check('CLI --help : exit 2 with a JSON error', $helpBadCode === 2 && str_contains((string) (json_decode($helpBad, true)['errors'][0] ?? ''), "unknown check 'zzz'")); + $tmpIt = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($tmp, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST); foreach ($tmpIt as $entry) { $entry->isDir() ? @rmdir($entry->getPathname()) : @unlink($entry->getPathname()); diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-profiler/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-profiler/SKILL.md index 8f68584..f2b5f6b 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-profiler/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-profiler/SKILL.md @@ -1,15 +1,6 @@ --- name: spryker-profiler -description: > - Read and configure the Spryker/Symfony WebProfiler. Use when someone asks why a page, - endpoint or Back Office screen is slow, wants the slowest request, asks how many queries a - page runs, suspects an N+1, wants Redis, Elasticsearch, Yves→Zed or external HTTP call counts, - or wants before/after evidence for a performance fix; also for what a request logged or - threw, which controller handled it, or what the audit log recorded. Covers setup too: - enabling the profiler for Yves, Zed/Back Office, Backend Gateway, Backend API, Glue or - Merchant Portal, a missing toolbar or empty collector, adding SQL/Redis/Elasticsearch - collectors. Use it before claiming a change improved or hurt performance: read the recorded - measurements instead of guessing. +description: "Reads and configures the Spryker WebProfiler: slow requests, query counts, N+1, Redis, search and HTTP calls, exceptions. Use for performance questions or to prove a performance fix." --- # Reading Spryker profiler data diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-qa-coverage/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-qa-coverage/SKILL.md index 558481f..2f2167f 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-qa-coverage/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-qa-coverage/SKILL.md @@ -1,14 +1,6 @@ --- name: spryker-qa-coverage -description: > - Hands-on QA of a Spryker feature against the running application: turns a PRD or feature - description into a checklist and test cases (happy path, negative, authorization, edge - cases), runs them through spryker-runtime (Back Office and storefront in the browser, CLI, - HTTP/API, database/Redis/queue checks) and reports pass/fail with evidence. Use when a - feature is done, mid-development, or as a smoke test after a refactor — "test this", "does - this still work", "did my refactor break anything", "make sure it works in the back office", - or a PRD with "is this implemented correctly?". Does not write automated tests - (codecept-functional, cypress-tests), run static analysis (static-validation) or fix code. +description: "Runs manual QA of a Spryker feature on the running app: test cases from a PRD, run in browser, CLI and API, pass/fail with evidence. Use for 'test this' or a smoke test after a refactor." --- # Spryker QA & Testing (from PRD → checklist → execute → report) @@ -192,15 +184,8 @@ ALWAYS structure the final report like this: ## Red flags — stop and reconsider -- "I'll just run phpstan/spryker-ci to check it" → NO. This skill never runs static analysis. -- "I'll write a Codeception test for this" → NO. That's `codecept-functional`. Here you execute against the running app. - "Only the happy path matters" → NO. Corner and authorization cases are where features break; cover all five buckets (Scale/NFR when an envelope is supplied — else note its absence). - "It probably works" / "the code looks right" → NO. QA reports *observed* behavior with evidence, not inferences from code. -- "The endpoint returns 200, so the feature works" → NO. A synthetic/endpoint hit is a layer below the UI. If the AC is a user flow, prove it through the real UI (E2E); otherwise mark it `PASS (server only)` and keep the UI-flow case FAIL/BLOCKED. Reading code is fine to *understand what to test* — it is never a substitute for *observing* the running flow. -- "The button did nothing once, so it's a blocker" → NO. Reproduce on ≥3 fresh loads (hard reload + navigate-back) and rule out your own driver first. Spryker Zed front-end bootstrap bugs are often intermittent races — works-on-some-loads is a *minor/flaky* finding, not a blocker. One dead load is a hypothesis, not a verdict. -- "Server works (Mode 5 = 200) and the UI is dead — clean story, done" → NO. That split is the signature of a *prematurely-closed* investigation. Mode 5 proves the server only; keep driving the real button to completion across reloads before you fail the UI case. -- "I'll fix the bug I found" → NO. Report it; offer handoff; don't change product code. -- "Mark it passed even though I couldn't run it" → NO. That's BLOCKED, not PASS. ## Supporting files - **[test-case-template.md](test-case-template.md)** — the per-case structure and a worked example. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-refresher/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-refresher/SKILL.md index 3e78953..a52f485 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-refresher/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-refresher/SKILL.md @@ -1,17 +1,6 @@ --- name: spryker-refresher -description: > - Use this skill whenever code, schema, frontend, or config changes have just - been applied and the system needs to be refreshed so the changes take effect. - Triggers - "run post-change commands", "refresh after edits", "regenerate - transfers", "rebuild the frontend", "clear caches after this change", - "warm up the caches", "what do I need to run after changing X", "make - these changes take effect", "post-change orchestration". Owns the - file-pattern to Spryker console command mapping drawn from the project's - install recipes. Runs the commands in dependency order and reports - results. Never edits source code. Boundary: a change to data/import/** - rows takes effect through project-data's reset ladder (boot-and-verify - §3b), not here — this skill only re-runs an importer for added rows. +description: "Runs the console commands that make changed code, schema, frontend or config take effect, in dependency order. Use after edits: 'regenerate transfers', 'rebuild the frontend'." --- # Spryker Refresher @@ -162,12 +151,6 @@ Do not take the Glue applications from an install recipe: `config/install/docker ## What you do NOT do -- Do not edit source files. Read-only on code, write-only on caches/builds via console commands. - Do not run destructive commands — anything from a `destructive*.yml` recipe, or any command that drops, deletes, truncates, or wipes data, schemas, indices, queues, or storage. Full demoshop resets (e.g. `docker/sdk reset`) are out of scope. -- Do not run `docker/sdk reset` itself. -- Do not skip dependents after a failure. Stop, report, let the caller decide. -- Do not run the entire install chain when only a subset is needed. Be surgical. -- Do not run commands across multiple stores / regions without the caller specifying which one. -- Do not skip the install-recipe read. The mapping in this prompt is a starting point; the recipes are the source of truth for this project's command ordering and flags - except for the set of Glue applications, which comes from `public/Glue*/index.php` and the deploy file. Do not run a recipe's `GLUE_APPLICATION=GLUE_STOREFRONT` step when that application has no `index.php`. - Do not prepend `cd /absolute/path && ...` to any `Bash` command. The harness already runs every `Bash` invocation in the project root — `cd` shifts the command to a different allowlist pattern and causes permission prompts. - **Do not omit `cache:class-resolver:build` after any `.php` change under a project namespace directory in `src/`.** Without it, the override file lands in the project layer, but Spryker keeps resolving to the vendor class because the resolver map wasn't rebuilt. Self-correction signal: if your file list contains any `src//**/*.php` (new or edited) and your command plan doesn't include `docker/sdk console cache:class-resolver:build`, stop and add it before reporting. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-runtime/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-runtime/SKILL.md index 6608982..b45445f 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-runtime/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-runtime/SKILL.md @@ -1,6 +1,6 @@ --- name: spryker-runtime -description: Use to actually RUN the Spryker application and observe real behavior, and to perform manual testing / QA against a real authenticated session — log in to Yves storefront, the Back Office, Merchant Portal, drive the UI in Chrome, run `docker/sdk cli console` commands, and call Yves/Glue endpoints over HTTP. Trigger whenever you need to manually test or QA a feature, walk through a user flow as a specific actor, confirm how an existing flow behaves before writing a PRD/spec/plan, reproduce a bug, verify a fix end-to-end, inspect what an endpoint returns, check which actors/roles exist at /user, or "run the app", "manually test this", "do a QA pass", "log in to backoffice", "call this endpoint", "execute this console command". Reusable building block for the PRD and verification skills. +description: "Runs and operates the Spryker app: logs in to storefront, Back Office and Merchant Portal, drives the UI, runs console commands, calls Glue. Use for manual tests, bug reproduction or checks." --- # Spryker Local Runtime — Run, Log In, Operate diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/SKILL.md index ea88c85..57e8342 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/SKILL.md @@ -1,17 +1,6 @@ --- name: spryker-upgrade -description: >- - Upgrade this Spryker project's modules/features to a newer release. First records baselines - (tests, PHPStan, code sniffer, evaluator and a crawl of the whole Back Office) and checks whether - the project's customisations are covered by tests, offering Facade/Client-level functional tests - where they are not. Then aligns dev tooling, the Docker SDK and the deploy files with the reference - demo shop of the target release, resolves the constraint blockers that stop a release-group bump, - and detects the silent damage (PHP 8.3 typed-member fatals, dead method overrides, shadowed - Twig/component changes, replaced plugin stacks, broken config constants, transfer strict - mismatches, vendor packages that must move together). Deprecated plugins are analysed for the - developer to decide; every major module bump needs its migration guide. Trigger on "upgrade the - project", "update to latest release", "update spryker modules/features", "run the upgrade", or any - request to bump spryker-feature/* or spryker/* packages. +description: "Upgrades a Spryker project's modules and features to a newer release with baselines, test coverage, constraint fixes and damage detection. Use for 'upgrade the project' or a package bump." --- # Spryker Project Upgrade @@ -561,15 +550,10 @@ Ask before committing or opening a pull request. ## Hard rules +- Offline / lookup failure → say so and stop for that module; never invent migration steps. - All state lives in `.spryker-upgrade/state/` (gitignored); never commit baselines, reports, the reference demo shop clone or `*.merge-conflict` artifacts. Prefer explicit `git add ` over `git add -A` while a Lane 2 pass is in flight. -- Offline / lookup failure → say so and stop for that module; never invent migration steps. -- Damage is fixed: MISSING plugins, fatals, shadowed vendor changes, new Back Office failures. - Deprecated plugins and APIs are an analysed list the developer decides on at gate #3 — never - ignored, never swapped without that decision. -- Tests pin behaviour through the Facade or the public Client/Service, before the upgrade. Never - tests for Factory, Config or DependencyProvider classes, and no getter/wiring tests. - Never claim "verified" for what could not run: a suite already red, unrunnable, or not touching the customised modules proves nothing; without a booted Back Office the visual and data-migration results are unverified; declined tests at gate #1 mean the report names the static-only lanes. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps.md b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps.md new file mode 100644 index 0000000..406d398 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps.md @@ -0,0 +1,305 @@ +# coverage-gaps.php + +Static analyser that finds project code without meaningful tests. It doesn't run tests and doesn't need Xdebug or +PCOV: it parses `src/` and each `tests/Test/` directory with `nikic/php-parser`, loads classes with Reflection and follows calls +the way the Spryker kernel wires them. + +It answers four questions: + +1. Which project classes and methods are not reached by any test? +2. Which classes extending core (overrides) are not reached by any test? +3. Through which entry point (Facade, Client, Service, Plugin, Controller) should a test be written to cover them? +4. Which code has no caller in production at all, so it should be deleted instead of tested? + +## Requirements + +The script checks these at startup. If something is missing it prints what to install and exits with code 2. + +| Requirement | Version | Why | Install | +|---|---|---|---| +| PHP | >= 8.1 (tested on 8.3 and 8.4) | `match`, nullsafe calls, `ReflectionClass::isEnum()`. Below 8.0 the file can't even be parsed, so the check can't run | — | +| Composer dependencies | `vendor/autoload.php` in the project root | autoloads project, core and parser classes | `composer install` | +| `nikic/php-parser` | ^5.0 (tested on 5.7) | parses PHP files; uses the v5 API `ParserFactory::createForNewestSupportedVersion()` | `composer require --dev nikic/php-parser:^5.0` | +| `spryker/kernel` | any current version | the analysed project must be a Spryker project; the kernel's naming conventions are used to resolve classes | — | +| `symfony/form`, `spryker/gui` | optional | only used by the `--skip-ui-definitions` rules; without them those rules don't match | — | +| `phpunit/phpunit` | >= 10 (tested on 11.5) | only for the tests (attributes such as `#[DataProvider]`) | `composer require --dev phpunit/phpunit` | + +The `spryker-sdk/ai-dev` package requires `nikic/php-parser` (>= 5.0) and `spryker/kernel`, so a project that has the +package installed has both. + +The project root is the working directory, or the nearest directory above it that has `composer.json` and a Spryker +source or config tree. Set `SPRYKER_PROJECT_ROOT` to name it explicitly. The location of the script is never used: +`bootstrap.php`, one level above the script, finds the root, as it does for the other `spryker-upgrade` scripts. + +## Running + +From the project root. `$UP` is the `scripts/` directory of the `spryker-upgrade` skill. The script loads project +classes, so use a PHP that can load them: host PHP, or `docker/sdk cli php ` when the script is inside the +project tree. Progress goes to stderr, the report to stdout. + +```bash +php $UP/coverage-gaps/coverage-gaps.php # full report +php $UP/coverage-gaps/coverage-gaps.php --module=Cart # one module +php $UP/coverage-gaps/coverage-gaps.php --hide-unused --skip-ui-definitions > report.txt +php $UP/coverage-gaps/coverage-gaps.php --json > report.json +``` + +A full run takes about 30 seconds. + +## Flags + +All flags are optional and can be combined. + +| Flag | Effect | +|---|---| +| `--layer=Zed` | Report only one application layer: `Zed`, `Client`, `Yves`, `Glue`, `Service` or `Shared` | +| `--module=Cart` | Report only one module | +| `--only-untested` | Hide partially tested classes and keep only classes without any test | +| `--no-entries` | Skip the "test via" lookup and section 3. Faster | +| `--no-unused` | Skip unused-code detection and section 4 | +| `--hide-unused` | Detect unused code, then drop it from all lists and counts. Section 4 is not printed. Wins over `--no-unused` | +| `--skip-ui-definitions` | Also skip form definitions, form expander plugins and table definitions (see [Skip rules](#skip-rules)) | +| `--skip-layer=Yves,Glue` | Ignore layers the project doesn't use, for example a project without a storefront or without Glue. Comma-separated or repeated, any case. Classes of those layers are not reported or counted, are not production callers for the unused-code check (code only they call becomes unused), and are never suggested as "test via". An unknown layer name exits with code 1 | +| `--show-skipped` | List the skipped methods per reason in the summary. By default only the count per reason is printed | +| `--why=FQCN` | Print to stderr the call paths from entry points to the untested methods of a class. Write `/` instead of `\`, because `docker/sdk` strips backslashes: `--why=Pyz/Zed/Cart/Business/Model/Foo` | +| `--root=DIR` | Analyse another project directory. Its `src/` dirs are autoloaded; `vendor/` is still this project's. Used by the tests | +| `--json` | Print the result as JSON instead of the text report | +| `--help` | Print the flags | + +## Report + +### 1. Project classes + +Classes without a core parent, grouped by `Layer/Module`. + +``` + ✗ Pyz\Zed\Foo\Business\Model\Bar ← ✗ no test at all, ◐ partially tested (n/m methods) + file: src/Pyz/Zed/Foo/Business/Model/Bar.php + untested: doX(), doY() [unused] ← [unused] = no production caller + test via: Pyz\Zed\Foo\…\FooFacade::doSomething() ← entry point to test it through +``` + +The "test via" line can also say: + +- `directly (public API of this class); registered in XDependencyProvider::getYPlugins()`: the class is itself an entry point. +- `— unused in production code: delete instead of testing`: every untested method is unused. +- `— no entry point found`: nothing in the module API creates it. This is dead code or wired dynamically. +- `unit test of …` (Glue and Yves only): see [Glue and Yves: unit-test suggestions](#glue-and-yves-unit-test-suggestions). + +### 2. Classes extending core + +The same layout, plus `extends: `. A class counts as core-extended when its nearest non-project ancestor +is a real core class, from `SprykerShop`, `SprykerEco`, `Spryker`, `SprykerSdk` or `SprykerFeature`. Kernel classes +(`Spryker\*\Kernel\*`) and core bases named `Abstract*` don't count, so a plugin extending `AbstractPlugin` is a +project class. + +### 3. Core entry points that execute the untested overrides + +Section 2 inverted: for each entry point, the untested overrides it executes, sorted by how many it covers. For +Facade, Client and Service entry points it also lists the registered plugins that call that method, with the +DependencyProvider method that registers them. + +### 4. Unused code + +Methods and classes with no caller in production code. Tests are excluded, so a method used only by tests is unused. + +- `(whole class unused)`: every method of the class is unused. +- `[tests only]`: only tests call it. The test keeps dead code alive. + +### Summary + +The summary has: + +- the number of classes and methods in scope and the percentage reached by tests; +- the counts of untested and partially tested classes, for project classes and for core-extended classes; +- the number of unused methods, or how many were hidden with `--hide-unused`; +- the thin plugins counted as covered through their delegates, with the list; +- the number of skipped methods per reason; the list of methods only with `--show-skipped`. + +## Logic + +### Scope: what is analysed + +- **Project dirs:** every directory in `src/` except `Generated`, `Orm` and `SprykerConfig`. Each one is a project + namespace that resolves before core, in the order of `KernelConstants::CORE_NAMESPACES`. +- **Excluded paths:** `/Dependency/` (bridges and plugin interfaces), `/Controller/`, `/Persistence/Propel/`, `/Theme/`. +- **Excluded files:** `*Config.php`, `*DependencyProvider.php`, `*Factory.php`, `*Interface.php`, `*Constants.php`, + `*Controller.php`, `*Stub.php`. +- **Excluded classes:** interfaces, traits, abstract classes, enums, and classes without methods of their own. +- **Counted methods:** methods declared in the class itself, except `__construct`: + - public methods; + - protected and private methods **only when they override** a parent or interface method, i.e. the new behaviour of + an override (for example `PriceManager::applyOriginUnitPrices()` or a Console `execute()`). + + Pure protected/private helpers are not counted: a test of the public method of the same class covers them. Methods + inherited from a parent or a trait are counted in the class that declares them. +- **Unused detection checks every method,** helpers included: a dead protected method is still reported in section 4. + +Excluded classes are still analysed: calls are followed through them. They just aren't reported. + +### Coverage: what "reached by a test" means + +Every method of every test class in a `tests/Test/` directory is a starting point: `tests/PyzTest/` by default, +another name in a project with its own namespace. `_support`, `_generated`, `_data` and +`_output` are skipped. From there the analyser builds a call graph. A method is tested when the graph reaches it. + +To resolve calls, the analyser infers types: + +| Source | How | +|---|---| +| `$this->tester->getFacade()`, `getClient()`, `getService()`, `getFactory()`, `getRepository()`, `getEntityManager()` | Module taken from the test namespace `Test\\\…`; `getFacade('Other')` uses the given module | +| `getLocator()->foo()->facade()` / `client()` / `service()` / `queryContainer()` | Resolved for module `Foo` | +| Kernel getters inside classes: `getFactory()`, `getFacade()`, `getRepository()`, `getConfig()`, … | Resolved for the class's own module and layer, project namespaces first | +| `getProvidedDependency(XDependencyProvider::CONST)` | Follows the `$container->set(CONST, closure)` in the module's DependencyProvider, including plugin stack getters overridden in Pyz | +| `new X(...)` | Constructor arguments are mapped to properties, including promoted properties and arguments forwarded to `parent::__construct()` | +| `$x->addStep($y)`, `setPlugins(...)` on a local object | Setter arguments are mapped to properties **per factory method**. A step added in `createTaxImporter()` doesn't leak into other importers built from the same class | +| Method arguments | Argument types flow into the callee's parameters | +| Properties without a known value | Declared or `@var` type; `XInterface` resolves to `X` in the same module, project first | +| `foreach`, `catch (X $e)`, local variables | Tracked within the method | +| `$this->stub->call('/module/gateway/action')` | Resolved to `GatewayController::actionAction()` in Zed | +| `create(XForm::class)` | Edges to the form's `buildForm()`, `configureOptions()`, … | +| `parent::m()`, `self::m()`, `static::m()`, `$this->m()` | Resolved against the runtime class, so template methods in an abstract parent reach the subclass implementation | + +**Mocks don't count.** `createMock()` returns no type, so calling a method on a mock doesn't mark anything as tested. + +### Thin plugins: covered through their delegates + +A `*Plugin` method counts as covered without its own test when all of these hold: + +- it has no logic: at most 3 statements and no `if`, loops, `switch`, `match`, ternary or `try`; +- it calls at least one project method that is in the report's scope; +- every such method is tested. + +Calls to factories, config and kernel getters are ignored for this check. The rule doesn't verify which arguments the +plugin passes on. + +### Skip rules + +Skipped methods are neither listed nor counted. The summary prints how many were skipped per reason; `--show-skipped` +also lists them. + +| Reason | Rule | +|---|---| +| application bootstrap | Class name ends with `Bootstrap`. The whole class is skipped | +| routing/resource configuration plugin | Class implements `ResourceInterface`, `JsonApiResourceInterface`, `ResourceRoutePluginInterface`, `ProtectedRouteAuthorizationConfigProviderPluginInterface` (Glue) or `RouteProviderPluginInterface` (Yves). The whole class is skipped; routing is verified by HTTP tests | +| client method only calls a Zed stub | `*Client` method in the Client layer without logic whose only project callees are `*Stub` methods (factory calls aside). The logic lives in Zed | +| declarative: only returns constant data | The whole body is `return ;`, where data is a scalar, a constant, `X::class`, an array of those, `new X()` or fluent setters with data on it, such as `(new XTransfer())->setA('a')->setB(Y::B)` | +| form/table definition (`--skip-ui-definitions` only) | In classes implementing Symfony `FormTypeInterface`: `buildForm()`, `configureOptions()`, `getBlockPrefix()`, `getName()` and `add*()` methods without branches, loops or closures. Form expander plugins (any interface named `*FormExpanderPluginInterface`, e.g. `ProductAbstractFormExpanderPluginInterface`, `MerchantFormExpanderPluginInterface`): the whole class, logic included. In classes extending Gui `AbstractTable`: `configure()`. Form **data provider** expanders (`*FormDataProviderExpanderPluginInterface`) are not skipped: they load data | + +The rules are checked in this order: class rules (bootstrap, routing, form expander plugins), stub-only, UI definitions, +declarative. A method +gets the first reason that matches. + +### Entry points ("test via" and section 3) + +A second call graph is built for the modules that have gaps, starting from: + +- the module's Facade, Client and Service, public methods; +- plugins and event subscribers of the module that are registered with `new X()` in any project DependencyProvider; +- project classes of the module named `*Plugin`, `*Console`, `*Widget`, `*Facade`, `*Client` or `*Service`; +- project and core controllers of the module, `*Action()` methods. + +For each untested method the analyser walks the graph backwards and stops at the first entry points it meets. +`--why` prints those paths. + +### Glue and Yves: unit-test suggestions + +Glue and Yves modules have no Facade, so a class there is often reached only from a controller action, i.e. only over +HTTP. Pointing at the controller would suggest an HTTP test, which this script can't see. So when **every** entry point +of a Glue or Yves class is a controller action, the report suggests a unit test instead: + +``` + ✗ Pyz\Glue\CustomerCompanySyncBackendApi\Mapper\CustomerCompanySyncMapper + untested: mapRequestAttributesToRequestTransfer(), … + test via: unit test of Pyz\Glue\CustomerCompanySyncBackendApi\…\CustomerCompanySyncProcessor::assignCustomerToCompany() — it runs this class + create it with CustomerCompanySyncBackendApiFactory::createCustomerCompanySyncProcessor() + reached over HTTP from Pyz\Glue\CustomerCompanySyncBackendApi\…\CustomerCompanySyncResourceController::postAction() + (an HTTP test - Glue API Cest, Cypress - also covers it, but HTTP tests are not counted by this script) +``` + +- **What to test:** the first method the controller calls on the path to the untested class. Factory methods and the + controller's own helpers (such as `executeIndexAction()`) are skipped. If that method belongs to the untested class + itself, the line says `unit test of this class: …`; otherwise `… — it runs this class`. +- **create it with:** the module factory method (project or core) that instantiates that class. Create the object the + same way in the test, with the real factory. +- **reached over HTTP from:** the controller actions on the path, for context. + +If any entry point isn't a controller (a plugin, a widget or a Facade), the normal "test via" list is shown. + +### Unused code + +A third call graph covers all project code, every method of every class, with tests excluded. Layers ignored with +`--skip-layer` are left out of this graph, of the class references and of the Twig scan. + +A method is **live** when it is reachable from one of these roots: + +- **Framework-called methods:** magic methods, controller `*Action()` methods, and methods that override or implement + a non-project class or interface (core plugin interfaces, core overrides, Symfony and Codeception contracts). +- **Names referenced dynamically:** a method name used in a call whose receiver type is unknown, in a string literal + (callables such as `[$this, 'x']`), or in a Twig template (`item.name` counts for `name`, `getName`, `isName` and + `hasName`). + +A class is unused as a whole when nothing in production code references it. References are `new X`, `X::m()`, +`X::class`, `instanceof X`, `catch (X)` and `extends X`, searched in the project dirs, `config/` and `public/`. Classes +the kernel resolves by naming convention are never reported as unreferenced: `Facade`, `Client`, `Service`, +`Repository`, `EntityManager`, `QueryContainer`, `Config` and controllers. + +## JSON output + +`--json` prints a single object: + +```json +{ + "projectOrgs": ["Pyz"], + "summary": {"classes": 476, "methods": 1293, "testedMethods": 599, "hiddenUnusedMethods": 0}, + "gaps": { + "Pyz\\Zed\\Foo\\Business\\Model\\Bar": { + "section": "project | core-extended", + "core": "Spryker\\… or null", + "file": "src/Pyz/…", + "untested": true, + "missing": ["doX"], + "unusedMissing": ["doX"], + "testVia": ["Pyz\\Zed\\Foo\\Business\\FooFacade::doSomething"], + "suggestedUnitTests": [ + {"test": "Pyz\\Glue\\…\\BarProcessor::process", "createWith": "BarFactory::createBarProcessor()", "reachedFrom": ["Pyz\\Glue\\…\\BarResourceController::postAction"]} + ] + } + }, + "entryPoints": {"Pyz\\…\\FooFacade::doSomething": ["Pyz\\…\\ExtendedBar"]}, + "unused": {"Pyz\\…\\Orphan": {"methods": ["run"], "testsOnly": [], "wholeClass": true}}, + "coveredByDelegates": {"Pyz\\…\\BarPlugin": ["expand"]}, + "skippedStubOnly": {"Pyz\\…\\FooClient": ["getRemote"]}, + "skipped": {"Pyz\\…\\FooClient": {"getRemote": "client method only calls a Zed stub"}} +} +``` + +## Limitations + +- **HTTP tests are not followed.** Glue Cest, Yves acceptance and Cypress tests call endpoints, so classes behind + controllers look untested even when an HTTP test covers them. For Glue and Yves the report therefore suggests a + unit test of the class the controller calls. +- **Analysis is approximate.** Argument types are merged over all call sites, so "test via" can list more entry + points than strictly needed. Dispatch on runtime data, such as `switch ($type)` in + `DataImportBusinessFactory::getDataImporterByType()`, counts every branch as reachable. +- **Unresolved calls keep code alive.** A call on an untyped receiver keeps every method with that name alive, so + unused detection misses some dead code rather than reporting live code. +- **Naming heuristics.** The `Abstract*` and `*Bootstrap` rules match on class names. + +## Tests + +The tests run the script as a separate process against a fixture project with one example per rule. The examples and +the expected result for each are described in [`coverage-gaps/fixture/README.md`](coverage-gaps/fixture/README.md). + +```bash +vendor/bin/phpunit --no-configuration $UP/coverage-gaps/coverage-gaps/CoverageGapsTest.php +``` + +The tests pass the project root to the script as `SPRYKER_PROJECT_ROOT`: the value of that variable when it is set, +otherwise the nearest directory above the test file that has `composer.json` and `vendor/autoload.php`. + +The fixture extends and implements core classes of `Cart`, `CartExtension`, `GlueApplicationExtension`, +`ProductManagementExtension` and `ShopApplication`. The tests for those rules fail when the `vendor/` in use does not +have these classes. Set `SPRYKER_PROJECT_ROOT` to a project that has them. + +The fixture contains dead and untested code on purpose. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps.php new file mode 100644 index 0000000..dd07135 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps.php @@ -0,0 +1,2634 @@ += 8.1, Composer vendor/, nikic/php-parser ^5.0, a Spryker project (checked at startup). + * + * Reports: + * 1. Project classes (no core parent) whose methods are not reached by any test. + * 2. Classes extending a core class whose own/overridden methods are not reached by any test. + * 3. Entry points (Facade / Client / Service / Plugin / Controller) through which the untested + * core-extended classes are executed - i.e. where to write a test for the new behaviour. + * Rules: thin plugins that only delegate to tested project code count as covered. + * Skipped (not listed, not counted): application bootstraps (*Bootstrap), routing/resource plugins (Glue resource and + * route plugins, Yves route providers), Client methods that only forward to a Zed stub, declarative methods whose + * whole body returns constant data (constants, scalars, X::class, arrays/transfers built from them) and, with + * --skip-ui-definitions, form field definitions, form expander plugins and Table::configure(). + * 4. Unused code: methods not reachable from any framework entry in production code (tests excluded) - + * delete them instead of writing tests. + * + * "Reached by a test" = a method is called from a test class in tests/Test (mocks excluded) directly, or transitively: + * Facade -> Factory -> new Model(...) -> constructor dependencies -> plugin stacks from DependencyProviders + * -> Zed stubs -> Gateway controllers. HTTP-based tests (Glue Cest, Cypress) are not followed. + * + * Usage (from the project root; $UP is the scripts directory of the spryker-upgrade skill). The project root is the + * working directory or SPRYKER_PROJECT_ROOT, never the location of this file. The script loads project classes, so + * run it with a PHP that can load them: host PHP, or `docker/sdk cli php ` when this file is inside the project. + * php $UP/coverage-gaps/coverage-gaps.php + * php $UP/coverage-gaps/coverage-gaps.php --layer=Zed --module=Cart --only-untested --no-entries --no-unused --hide-unused --skip-ui-definitions --show-skipped --skip-layer=Yves,Glue --why=Pyz/Zed/Cart/Business/Model/Foo --root=. --json > report.json + * + * Flags (all optional, combinable): + * --layer=Zed only one application layer: Zed|Client|Yves|Glue|Service|Shared + * --module=Cart only one module + * --only-untested hide partially tested classes, keep classes without any test + * --no-entries skip the "test via" lookup and section 3 (faster) + * --no-unused skip the unused-code detection and section 4 + * --hide-unused detect unused code, then drop it from the lists and counts (no section 4); wins over --no-unused + * --skip-layer=Yves,Glue ignore layers the project does not use (comma-separated or repeated): their classes are + * not reported or counted, are no production callers for the unused-code check (code only they + * call becomes unused) and are no entry points for "test via" + * --show-skipped list the skipped methods per reason in the summary (by default only the counts) + * --skip-ui-definitions also skip form definitions (buildForm, configureOptions, getBlockPrefix, add* methods + * without logic), whole form expander plugins (*FormExpanderPluginInterface) and Table::configure() + * --why=FQCN print to stderr the call paths from entry points to the untested methods of FQCN; + * write "/" instead of "\" - docker/sdk strips backslashes + * --root=DIR analyse another project dir (its src/ dirs are autoloaded; vendor/ stays this project's) + * --json print the result as JSON instead of the text report + * --help print the flags + * + * Tests (fixture project with one example per rule: coverage-gaps/fixture/README.md): + * vendor/bin/phpunit $UP/coverage-gaps/coverage-gaps/CoverageGapsTest.php + * Progress goes to stderr, the report to stdout. + */ + +declare(strict_types=1); + +use PhpParser\Node; +use PhpParser\Node\Expr; +use PhpParser\Node\Identifier; +use PhpParser\Node\Name; +use PhpParser\Node\Scalar\String_; +use PhpParser\Node\Stmt; +use PhpParser\NodeFinder; +use PhpParser\NodeTraverser; +use PhpParser\NodeVisitor\NameResolver; +use PhpParser\Parser; +use PhpParser\ParserFactory; + +ini_set('memory_limit', '-1'); +error_reporting(E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED); + +require __DIR__ . '/../bootstrap.php'; + +$root = spryker_upgrade_project_root(); +defined('APPLICATION_ROOT_DIR') || define('APPLICATION_ROOT_DIR', $root); + +/** + * Requirements (see coverage-gaps.md): + * - PHP >= 8.1 + * - Composer dependencies installed (vendor/autoload.php in the project root) + * - nikic/php-parser ^5.0 composer require --dev nikic/php-parser:^5.0 + * - spryker/kernel the analysed project must be a Spryker project + * Optional: symfony/form and spryker/gui (only used by --skip-ui-definitions rules). + * + * @return list problems, empty when everything is installed + */ +function coverageGapsRequirementProblems(string $root): array +{ + if (PHP_VERSION_ID < 80100) { + return [sprintf('PHP >= 8.1 is required, running %s.', PHP_VERSION)]; + } + if (!is_file($root . '/vendor/autoload.php')) { + return [sprintf('Composer dependencies are not installed: %s/vendor/autoload.php not found. Run: composer install', $root)]; + } + require_once $root . '/vendor/autoload.php'; + + $problems = []; + $installed = static fn (string $package): ?string => class_exists(Composer\InstalledVersions::class) && Composer\InstalledVersions::isInstalled($package) + ? Composer\InstalledVersions::getPrettyVersion($package) + : null; + if (!class_exists(PhpParser\ParserFactory::class)) { + $problems[] = 'nikic/php-parser is not installed. Run: composer require --dev nikic/php-parser:^5.0'; + } elseif (!method_exists(PhpParser\ParserFactory::class, 'createForNewestSupportedVersion')) { + $problems[] = sprintf( + 'nikic/php-parser ^5.0 is required, installed: %s. Run: composer require --dev nikic/php-parser:^5.0', + $installed('nikic/php-parser') ?? 'an older version', + ); + } + if (!class_exists('Spryker\\Zed\\Kernel\\Business\\AbstractFacade')) { + $problems[] = 'spryker/kernel is not installed: this tool analyses Spryker projects (Spryker\\Zed\\Kernel\\Business\\AbstractFacade not found).'; + } + + return $problems; +} + +$requirementProblems = coverageGapsRequirementProblems($root); +if ($requirementProblems !== []) { + fwrite(STDERR, "coverage-gaps.php: requirements not met\n - " . implode("\n - ", $requirementProblems) . "\n"); + exit(2); +} + +final class Ast +{ + private Parser $parser; + + private NodeFinder $finder; + + /** @var array>}> */ + private array $cache = []; + + public function __construct(private int $limit = 600) + { + $this->parser = (new ParserFactory())->createForNewestSupportedVersion(); + $this->finder = new NodeFinder(); + } + + public function file(string $path): array + { + return $this->load($path)['stmts']; + } + + public function method(string $path, string $name, int $line): ?Stmt\ClassMethod + { + $best = null; + foreach ($this->load($path)['methods'][strtolower($name)] ?? [] as $method) { + if ($best === null || abs($method->getStartLine() - $line) < abs($best->getStartLine() - $line)) { + $best = $method; + } + } + + return $best; + } + + private function load(string $path): array + { + if (isset($this->cache[$path])) { + $entry = $this->cache[$path]; + unset($this->cache[$path]); + + return $this->cache[$path] = $entry; + } + if (count($this->cache) >= $this->limit) { + unset($this->cache[array_key_first($this->cache)]); + } + + $stmts = []; + try { + $stmts = $this->parser->parse((string)file_get_contents($path)) ?? []; + $traverser = new NodeTraverser(); + $traverser->addVisitor(new NameResolver()); + $stmts = $traverser->traverse($stmts); + } catch (Throwable) { + $stmts = []; + } + + $methods = []; + foreach ($this->finder->findInstanceOf($stmts, Stmt\ClassMethod::class) as $method) { + $methods[$method->name->toLowerString()][] = $method; + } + + return $this->cache[$path] = ['stmts' => $stmts, 'methods' => $methods]; + } +} + +final class Kernel +{ + /** Same order as KernelConstants::CORE_NAMESPACES in config_default.php. */ + public const CORE_ORGS = ['SprykerShop', 'SprykerEco', 'Spryker', 'SprykerSdk', 'SprykerFeature']; + + /** src/ dirs that are generated or configuration, not project code. */ + public const NON_PROJECT_DIRS = ['Generated', 'Orm', 'SprykerConfig']; + + /** @var list project namespaces first (they override core), then core */ + public array $orgs; + + private string $modulePattern; + + private const KERNEL_PATTERN = '/^Spryker\\\\\w+\\\\Kernel\\\\/'; + + public const KERNEL_GETTERS = [ + 'getFacade', 'getBusinessFactory', 'getFactory', 'getClient', 'getService', 'getRepository', + 'getEntityManager', 'getQueryContainer', 'getConfig', 'getProvidedDependency', 'getLocator', + ]; + + private array $exists = []; + + /** + * @param list $projectOrgs + */ + public function __construct(public array $projectOrgs) + { + $this->orgs = array_merge($projectOrgs, self::CORE_ORGS); + $this->modulePattern = '/^(' . implode('|', array_map('preg_quote', $this->orgs)) . ')\\\\(Zed|Client|Yves|Glue|Service|Shared)\\\\(\w+)\\\\(.+)$/'; + } + + /** + * Project namespaces = directories in src/ except generated/config ones. + * + * @return list + */ + public static function detectProjectOrgs(string $root): array + { + $orgs = []; + foreach (glob($root . '/src/*', GLOB_ONLYDIR) ?: [] as $dir) { + if (!in_array(basename($dir), self::NON_PROJECT_DIRS, true)) { + $orgs[] = basename($dir); + } + } + + return $orgs; + } + + public function isProject(string $class): bool + { + return in_array(strstr(ltrim(self::base($class), '\\') . '\\', '\\', true), $this->projectOrgs, true); + } + + private array $refl = []; + + private array $resolved = []; + + /** + * Strips the call-site suffix of an object token ("Class#Factory::method" -> "Class"). + */ + public static function base(string $type): string + { + $position = strpos($type, '#'); + + return $position === false ? $type : substr($type, 0, $position); + } + + public function exists(string $class): bool + { + $class = self::base($class); + if (!isset($this->exists[$class])) { + try { + $this->exists[$class] = class_exists($class) || interface_exists($class) || trait_exists($class); + } catch (Throwable) { + $this->exists[$class] = false; + } + } + + return $this->exists[$class]; + } + + public function refl(string $class): ?ReflectionClass + { + $class = self::base($class); + if (!array_key_exists($class, $this->refl)) { + $this->refl[$class] = $this->exists($class) ? new ReflectionClass($class) : null; + } + + return $this->refl[$class]; + } + + /** + * @return array{org: string, layer: string, module: string, part: string}|null + */ + public function moduleOf(string $class): ?array + { + if (!preg_match($this->modulePattern, ltrim(self::base($class), '\\'), $m)) { + return null; + } + $rest = explode('\\', $m[4]); + + return ['org' => $m[1], 'layer' => $m[2], 'module' => $m[3], 'part' => count($rest) > 1 ? $rest[0] : '']; + } + + public function isKernel(string $class): bool + { + return (bool)preg_match(self::KERNEL_PATTERN, $class); + } + + public function isTracked(string $class): bool + { + return $this->moduleOf($class) !== null && !$this->isKernel($class); + } + + public function isConcrete(string $class): bool + { + $rc = $this->refl($class); + + return $rc !== null && !$rc->isInterface() && !$rc->isAbstract() && !$rc->isTrait(); + } + + public function resolve(string $layer, string $module, string $relative): ?string + { + $key = "$layer|$module|$relative"; + if (!array_key_exists($key, $this->resolved)) { + $this->resolved[$key] = null; + foreach ($this->orgs as $org) { + $class = "$org\\$layer\\$module\\$relative"; + if ($this->isConcrete($class)) { + $this->resolved[$key] = $class; + + break; + } + } + } + + return $this->resolved[$key]; + } + + /** + * Concrete class for a type: itself (Pyz override first) or, for `XInterface`, the class `X` of the same module. + */ + public function implementationOf(string $type): ?string + { + $type = ltrim($type, '\\'); + if (!$this->isConcrete($type) && str_ends_with($type, 'Interface')) { + $type = substr($type, 0, -strlen('Interface')); + } + $info = $this->moduleOf($type); + if ($info === null || $this->isKernel($type)) { + return null; + } + $relative = substr($type, strlen("{$info['org']}\\{$info['layer']}\\{$info['module']}\\")); + + return $this->resolve($info['layer'], $info['module'], $relative); + } + + /** + * Controller classes of a module in all organizations (Pyz and core). + * + * @return list + */ + public function controllersOf(string $layer, string $module): array + { + $controllers = []; + foreach ($this->orgs as $org) { + $file = null; + foreach (["{$module}DependencyProvider", "{$module}Config", "{$module}Factory", "{$module}BusinessFactory"] as $anchor) { + $rc = $this->refl("$org\\$layer\\$module\\$anchor"); + if ($rc !== null && $rc->getFileName()) { + $file = $rc->getFileName(); + + break; + } + } + if ($file === null) { + continue; + } + $controllerDir = dirname($file) . ($layer === 'Zed' ? '/Communication/Controller' : '/Controller'); + $namespace = "$org\\$layer\\$module\\" . ($layer === 'Zed' ? 'Communication\\Controller\\' : 'Controller\\'); + foreach (glob($controllerDir . '/*Controller.php') ?: [] as $controllerFile) { + $class = $namespace . basename($controllerFile, '.php'); + if ($this->isConcrete($class)) { + $controllers[] = $class; + } + } + } + + return $controllers; + } + + public function isKernelCall(string $class, string $method): bool + { + if (!in_array($method, self::KERNEL_GETTERS, true)) { + return false; + } + $rc = $this->refl($class); + if ($rc === null || !$rc->hasMethod($method)) { + return true; + } + + return $this->isKernel($rc->getMethod($method)->getDeclaringClass()->getName()); + } + + /** + * @return list + */ + public function kernelTypes(string $class, string $getter): array + { + $m = $this->moduleOf($class); + if ($m === null) { + return []; + } + + $resolved = $this->getterTarget($m['layer'], $m['module'], $m['part'], $getter); + + return $resolved === null ? [] : [$resolved]; + } + + public function getterTarget(string $layer, string $module, string $part, string $getter): ?string + { + return match ($getter) { + 'getFacade' => $this->resolve('Zed', $module, "Business\\{$module}Facade"), + 'getBusinessFactory' => $this->resolve('Zed', $module, "Business\\{$module}BusinessFactory"), + 'getFactory' => $this->factoryOf($layer, $module, $part), + 'getClient' => $this->resolve('Client', $module, "{$module}Client"), + 'getService' => $this->resolve('Service', $module, "{$module}Service"), + 'getRepository' => $this->resolve('Zed', $module, "Persistence\\{$module}Repository"), + 'getEntityManager' => $this->resolve('Zed', $module, "Persistence\\{$module}EntityManager"), + 'getQueryContainer' => $this->resolve('Zed', $module, "Persistence\\{$module}QueryContainer"), + 'getConfig' => $this->resolve($layer, $module, "{$module}Config"), + default => null, + }; + } + + public function locatorTarget(string $module, string $kind): ?string + { + return match ($kind) { + 'facade' => $this->resolve('Zed', $module, "Business\\{$module}Facade"), + 'client' => $this->resolve('Client', $module, "{$module}Client"), + 'service' => $this->resolve('Service', $module, "{$module}Service"), + 'queryContainer' => $this->resolve('Zed', $module, "Persistence\\{$module}QueryContainer"), + default => null, + }; + } + + private function factoryOf(string $layer, string $module, string $part): ?string + { + return match ($layer) { + 'Zed' => match ($part) { + 'Business' => $this->resolve('Zed', $module, "Business\\{$module}BusinessFactory"), + 'Persistence' => $this->resolve('Zed', $module, "Persistence\\{$module}PersistenceFactory"), + default => $this->resolve('Zed', $module, "Communication\\{$module}CommunicationFactory"), + }, + 'Service' => $this->resolve('Service', $module, "{$module}ServiceFactory"), + 'Client', 'Yves', 'Glue' => $this->resolve($layer, $module, "{$module}Factory"), + default => null, + }; + } +} + +final class Scope +{ + /** + * @param array> $vars + * @param array{0: string, 1: string}|null $testModule [layer, module] of a test class + */ + public function __construct( + public string $runtime, + public string $declaring, + public array $vars = [], + public ?array $testModule = null, + public string $site = '', + public ?string $node = null, + ) { + } +} + +/** + * Builds a call graph between methods (nodes "Runtime::method@Declaring") with a light type inference. + */ +final class Analyzer +{ + private const TEST_PREFIX = '@test:'; + + private const TEST_GETTERS = ['getFacade', 'getClient', 'getService', 'getFactory', 'getBusinessFactory', 'getRepository', 'getEntityManager']; + + private const FORM_FACTORY_METHODS = ['create', 'createNamed', 'createBuilder', 'createNamedBuilder', 'createForm']; + + private const FORM_METHODS = ['buildForm', 'configureOptions', 'buildView', 'finishView', 'getBlockPrefix', 'getName']; + + private const ARRAY_FUNCTIONS = ['array_merge', 'array_values', 'array_replace', 'array_filter', 'iterator_to_array', 'array_reverse']; + + /** @var array> */ + public array $edges = []; + + /** @var array */ + public array $nodes = []; + + /** @var array */ + public array $processed = []; + + /** @var array method names called on a receiver whose type could not be inferred */ + public array $unresolvedNames = []; + + private array $queue = []; + + private array $byRuntime = []; + + private array $propTypes = []; + + private array $paramTypes = []; + + private array $ctorMaps = []; + + private array $declaredProps = []; + + private array $returnMemo = []; + + private array $inProgress = []; + + private array $dpMemo = []; + + private array $testClasses = []; + + private NodeFinder $finder; + + /** @var (Closure(string): bool)|null */ + private ?Closure $restrict = null; + + public function __construct(private Kernel $kernel, private Ast $ast) + { + $this->finder = new NodeFinder(); + } + + /** + * Clears the graph but keeps learned type information. + */ + public function resetGraph(?Closure $restrict): void + { + $this->edges = []; + $this->processed = []; + $this->queue = []; + $this->byRuntime = []; + $this->unresolvedNames = []; + $this->restrict = $restrict; + } + + /** + * @param list $dirs test directories, one per test namespace (tests/PyzTest, tests/Test, ...) + * + * @return list seed node keys (all methods of test classes) + */ + public function registerTests(array $dirs): array + { + $iterator = new AppendIterator(); + foreach ($dirs as $dir) { + $iterator->append(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS))); + } + foreach ($iterator as $file) { + $path = $file->getPathname(); + if ($file->getExtension() !== 'php' || preg_match('#/_(support|generated|data|output)/#', $path)) { + continue; + } + foreach ($this->finder->findInstanceOf($this->ast->file($path), Stmt\Class_::class) as $class) { + if ($class->namespacedName === null) { + continue; + } + $fqcn = $class->namespacedName->toString(); + $parts = explode('\\', $fqcn); + $methods = []; + foreach ($class->getMethods() as $method) { + $methods[$method->name->toString()] = $method; + } + $this->testClasses[$fqcn] = [ + 'module' => count($parts) > 3 ? [$parts[1], $parts[2]] : null, + 'parent' => $class->extends?->toString(), + 'methods' => $methods, + 'props' => [], + ]; + } + } + + foreach (array_keys($this->testClasses) as $fqcn) { + $this->collectTestProps($fqcn); + } + + $seeds = []; + foreach ($this->testClasses as $fqcn => $test) { + foreach (array_keys($test['methods']) as $method) { + $key = $this->node(self::TEST_PREFIX . $fqcn, $method); + if ($key !== null) { + $seeds[] = $key; + } + } + } + + return $seeds; + } + + public function testFileCount(): int + { + return count($this->testClasses); + } + + /** + * For a thin delegating method (no own logic) returns the [declaring class, method] pairs it calls; null otherwise. + * Uses a throw-away graph: call it before building the next phase. + * + * @return list|null + */ + public function delegateCallees(string $class, string $method): ?array + { + $key = $this->node($class, $method); + $fn = $key === null ? null : $this->methodAst($class, $this->nodes[$key][1], $method); + if ($fn === null || $fn->stmts === null || count($fn->stmts) > 3) { + return null; + } + $logic = $this->finder->findFirst($fn->stmts, static fn (Node $n): bool => $n instanceof Stmt\If_ + || $n instanceof Stmt\Foreach_ || $n instanceof Stmt\For_ || $n instanceof Stmt\While_ || $n instanceof Stmt\Do_ + || $n instanceof Stmt\Switch_ || $n instanceof Stmt\TryCatch || $n instanceof Expr\Match_ || $n instanceof Expr\Ternary); + if ($logic !== null) { + return null; + } + $this->resetGraph(static fn (string $runtime): bool => $runtime === $class); + $this->seed($key); + $this->run(); + + return array_values(array_map(fn (string $to): array => [$this->nodes[$to][1], $this->nodes[$to][2]], array_keys($this->edges[$key] ?? []))); + } + + public function seed(string $key): void + { + $this->enqueue($key); + } + + public function run(): void + { + while ($this->queue) { + $this->processNode(array_pop($this->queue)); + } + } + + /** + * Returns a node key for calling $method on an object of class $runtime, or null when not analysable. + */ + public function node(string $runtime, string $method, ?string $lookupClass = null): ?string + { + if (str_starts_with($runtime, self::TEST_PREFIX)) { + if ($this->testMethod(substr($runtime, strlen(self::TEST_PREFIX)), $method) === null) { + return null; + } + $key = $runtime . '::' . $method; + $this->nodes[$key] ??= [$runtime, $runtime, $method]; + + return $key; + } + if (!$this->kernel->isTracked($runtime)) { + return null; + } + $rc = $this->kernel->refl($lookupClass ?? $runtime); + if ($rc === null || !$rc->hasMethod($method)) { + return null; + } + $rm = $rc->getMethod($method); + $declaring = $rm->getDeclaringClass()->getName(); + if ($rm->isAbstract() || $this->kernel->isKernel($declaring)) { + return null; + } + $key = $runtime . '::' . $rm->getName() . '@' . $declaring; + $this->nodes[$key] ??= [$runtime, $declaring, $rm->getName()]; + + return $key; + } + + private function enqueue(string $key): void + { + if (isset($this->processed[$key])) { + return; + } + $runtime = $this->nodes[$key][0]; + if ($this->restrict !== null && !str_starts_with($runtime, self::TEST_PREFIX) && !($this->restrict)($runtime)) { + return; + } + $this->processed[$key] = true; + $this->byRuntime[$runtime][$key] = true; + $this->queue[] = $key; + } + + private function addEdge(string $from, ?string $to): void + { + if ($to === null) { + return; + } + $this->edges[$from][$to] = true; + $this->enqueue($to); + } + + private function processNode(string $key): void + { + [$runtime, $declaring, $method] = $this->nodes[$key]; + $fn = $this->methodAst($runtime, $declaring, $method); + if ($fn === null || $fn->stmts === null) { + return; + } + $scope = $this->scopeFor($runtime, $declaring, $declaring . '::' . $method); + $scope->node = $key; + $scope->vars = $this->computeVars($fn, $scope); + + $calls = $this->finder->find($fn->stmts, static fn (Node $n): bool => $n instanceof Expr\MethodCall + || $n instanceof Expr\NullsafeMethodCall + || $n instanceof Expr\StaticCall + || $n instanceof Expr\New_ + || $n instanceof Expr\Assign); + + foreach ($calls as $call) { + if ($call instanceof Expr\MethodCall || $call instanceof Expr\NullsafeMethodCall) { + $this->processMethodCall($key, $call, $scope); + + continue; + } + if ($call instanceof Expr\StaticCall) { + $this->processStaticCall($key, $call, $scope); + + continue; + } + if ($call instanceof Expr\New_) { + $this->typeOf($call, $scope); + if ($call->class instanceof Name && !$call->class->isSpecialClassName()) { + $this->addEdge($key, $this->node($call->class->toString(), '__construct')); + } + + continue; + } + if ($this->isThisProperty($call->var) && !str_starts_with($runtime, self::TEST_PREFIX)) { + $this->addPropTypes($runtime, $call->var->name->toString(), $this->typeOf($call->expr, $scope)); + } + } + } + + private function processMethodCall(string $from, Expr\MethodCall|Expr\NullsafeMethodCall $call, Scope $scope): void + { + if (!$call->name instanceof Identifier) { + return; + } + $name = $call->name->toString(); + + if ($name === 'call' && isset($call->args[0]) && $call->args[0] instanceof Node\Arg && $call->args[0]->value instanceof String_) { + $this->addEdge($from, $this->gatewayNode($call->args[0]->value->value)); + } + + foreach ($this->formTypesIn($name, $call->args) as $formType) { + foreach (self::FORM_METHODS as $formMethod) { + $this->addEdge($from, $this->node($formType, $formMethod)); + } + } + + $receivers = $this->typeOf($call->var, $scope); + if ($receivers === []) { + $this->unresolvedNames[$name] = true; + } + foreach ($receivers as $receiver) { + if (str_starts_with($receiver, self::TEST_PREFIX)) { + $this->addEdge($from, $this->node($receiver, $name)); + + continue; + } + if ($this->kernel->isKernelCall($receiver, $name)) { + continue; + } + if ($call->args !== [] && str_contains($receiver, '#')) { + $this->recordArgs($receiver, $name, $call->args, $scope); + } + $to = $this->node($receiver, $name); + $this->recordParamTypes($to, $call->args, $scope); + $this->addEdge($from, $to); + } + } + + /** + * Symfony form types passed as `X::class` to a form factory call are executed by Symfony. + * + * @return list + */ + private function formTypesIn(string $method, array $args): array + { + if (!in_array($method, self::FORM_FACTORY_METHODS, true)) { + return []; + } + $types = []; + foreach (array_slice($args, 0, 2) as $arg) { + if ($arg instanceof Node\Arg && $arg->value instanceof Expr\ClassConstFetch && $arg->value->class instanceof Name + && $arg->value->name instanceof Identifier && $arg->value->name->toLowerString() === 'class') { + $class = $arg->value->class->toString(); + if ($this->kernel->isTracked($class) && is_subclass_of($class, 'Symfony\\Component\\Form\\FormTypeInterface')) { + $types[] = $class; + } + } + } + + return $types; + } + + private function processStaticCall(string $from, Expr\StaticCall $call, Scope $scope): void + { + if (!$call->class instanceof Name || !$call->name instanceof Identifier) { + return; + } + $name = $call->name->toString(); + $class = $call->class->toLowerString(); + + if ($class === 'parent') { + $parent = $this->kernel->refl($scope->declaring)?->getParentClass(); + if ($parent) { + $this->addEdge($from, $this->node($scope->runtime, $name, $parent->getName())); + } + + return; + } + if ($class === 'self' || $class === 'static') { + $this->addEdge($from, $this->node($scope->runtime, $name)); + + return; + } + $this->addEdge($from, $this->node($call->class->toString(), $name)); + } + + private function gatewayNode(string $url): ?string + { + if (!preg_match('#^/([a-z0-9-]+)/gateway/([a-z0-9-]+)$#', $url, $m)) { + return null; + } + $module = str_replace(' ', '', ucwords(str_replace('-', ' ', $m[1]))); + $action = lcfirst(str_replace(' ', '', ucwords(str_replace('-', ' ', $m[2])))) . 'Action'; + $controller = $this->kernel->resolve('Zed', $module, 'Communication\\Controller\\GatewayController'); + + return $controller === null ? null : $this->node($controller, $action); + } + + /** + * @return list + */ + private function typeOf(?Node $expr, Scope $scope, int $depth = 0): array + { + if ($expr === null || $depth > 30) { + return []; + } + + return match (true) { + $expr instanceof Expr\Variable => is_string($expr->name) + ? ($expr->name === 'this' ? [$scope->runtime] : ($scope->vars[$expr->name] ?? [])) + : [], + $expr instanceof Expr\PropertyFetch, $expr instanceof Expr\NullsafePropertyFetch => $this->isThisProperty($expr) + ? $this->propTypesFor($scope, $expr->name->toString()) + : [], + $expr instanceof Expr\MethodCall, $expr instanceof Expr\NullsafeMethodCall => $this->methodCallType($expr, $scope, $depth), + $expr instanceof Expr\StaticCall => $this->staticCallType($expr, $scope), + $expr instanceof Expr\New_ => $this->newType($expr, $scope, $depth), + $expr instanceof Expr\Array_ => $this->union(array_map( + fn ($item) => $item === null ? [] : $this->typeOf($item->value, $scope, $depth + 1), + $expr->items, + )), + $expr instanceof Expr\FuncCall => $expr->name instanceof Name && in_array($expr->name->toLowerString(), self::ARRAY_FUNCTIONS, true) + ? $this->union(array_map(fn ($arg) => $arg instanceof Node\Arg ? $this->typeOf($arg->value, $scope, $depth + 1) : [], $expr->args)) + : [], + $expr instanceof Expr\Ternary => $this->union([$this->typeOf($expr->if, $scope, $depth + 1), $this->typeOf($expr->else, $scope, $depth + 1)]), + $expr instanceof Expr\BinaryOp\Coalesce => $this->union([$this->typeOf($expr->left, $scope, $depth + 1), $this->typeOf($expr->right, $scope, $depth + 1)]), + $expr instanceof Expr\Assign => $this->typeOf($expr->expr, $scope, $depth + 1), + $expr instanceof Expr\Match_ => $this->union(array_map(fn ($arm) => $this->typeOf($arm->body, $scope, $depth + 1), $expr->arms)), + default => [], + }; + } + + private function methodCallType(Expr\MethodCall|Expr\NullsafeMethodCall $expr, Scope $scope, int $depth): array + { + if (!$expr->name instanceof Identifier) { + return []; + } + $name = $expr->name->toString(); + + $locator = $this->locatorType($expr, $name); + if ($locator !== null) { + return $locator; + } + + $types = []; + foreach ($this->typeOf($expr->var, $scope, $depth + 1) as $receiver) { + if ($expr->args !== [] && (str_starts_with($receiver, self::TEST_PREFIX) || !$this->kernel->isKernelCall($receiver, $name))) { + $this->recordParamTypes($this->node($receiver, $name), $expr->args, $scope, $depth); + } + $types[] = $this->callReturnTypes($receiver, $name, $expr->args); + } + $types = $this->union($types); + + if ($types === [] && $scope->testModule !== null && in_array($name, self::TEST_GETTERS, true)) { + return $this->testGetterType($name, $expr->args, $scope->testModule); + } + + return $types; + } + + private function locatorType(Expr\MethodCall|Expr\NullsafeMethodCall $expr, string $name): ?array + { + if (!in_array($name, ['facade', 'client', 'service', 'queryContainer'], true)) { + return null; + } + $moduleCall = $expr->var; + if (!$moduleCall instanceof Expr\MethodCall || !$moduleCall->name instanceof Identifier) { + return null; + } + $locatorCall = $moduleCall->var; + if (!$locatorCall instanceof Expr\MethodCall || !$locatorCall->name instanceof Identifier || $locatorCall->name->toString() !== 'getLocator') { + return null; + } + $target = $this->kernel->locatorTarget(ucfirst($moduleCall->name->toString()), $name); + + return $target === null ? [] : [$target]; + } + + private function testGetterType(string $name, array $args, array $testModule): array + { + [$layer, $module] = $testModule; + if (isset($args[0]) && $args[0] instanceof Node\Arg && $args[0]->value instanceof String_) { + $module = $args[0]->value->value; + } + $part = in_array($name, ['getRepository', 'getEntityManager'], true) ? 'Persistence' : 'Business'; + $target = $this->kernel->getterTarget($layer, $module, $part, $name); + + return $target === null ? [] : [$target]; + } + + private function staticCallType(Expr\StaticCall $expr, Scope $scope): array + { + if (!$expr->class instanceof Name || !$expr->name instanceof Identifier) { + return []; + } + $name = $expr->name->toString(); + + return match ($expr->class->toLowerString()) { + 'parent' => ($parent = $this->kernel->refl($scope->declaring)?->getParentClass()) + ? $this->returnTypes($scope->runtime, $name, $parent->getName()) + : [], + 'self', 'static' => $this->callReturnTypes($scope->runtime, $name, $expr->args), + default => [], + }; + } + + private function newType(Expr\New_ $expr, Scope $scope, int $depth): array + { + if (!$expr->class instanceof Name) { + return []; + } + $class = $expr->class->isSpecialClassName() ? Kernel::base($scope->runtime) : $expr->class->toString(); + if (!$this->kernel->isTracked($class)) { + return []; + } + $this->recordArgs($class, '__construct', $expr->args, $scope, $depth); + + return [$class]; + } + + private function callReturnTypes(string $receiver, string $method, array $args): array + { + if (!str_starts_with($receiver, self::TEST_PREFIX) && $this->kernel->isKernelCall($receiver, $method)) { + return match ($method) { + 'getProvidedDependency' => $this->dependencyTypes($receiver, $args), + 'getLocator' => [], + default => $this->kernel->kernelTypes($receiver, $method), + }; + } + + return $this->returnTypes($receiver, $method); + } + + private function returnTypes(string $runtime, string $method, ?string $lookupClass = null): array + { + $key = $this->node($runtime, $method, $lookupClass); + if ($key === null) { + return []; + } + if (isset($this->returnMemo[$runtime][$key])) { + return $this->returnMemo[$runtime][$key]; + } + if (isset($this->inProgress[$key])) { + return []; + } + $this->inProgress[$key] = true; + + [, $declaring] = $this->nodes[$key]; + $fn = $this->methodAst($runtime, $declaring, $this->nodes[$key][2]); + $types = []; + if ($fn !== null && $fn->stmts !== null) { + $scope = $this->scopeFor($runtime, $declaring, $declaring . '::' . $this->nodes[$key][2]); + $scope->node = $key; + $scope->vars = $this->computeVars($fn, $scope); + $types = $this->union(array_map(fn (Expr $e) => $this->typeOf($e, $scope), $this->findReturns($fn->stmts))); + if ($types === []) { + $types = $this->hintTypes($fn->returnType); + } + } + + unset($this->inProgress[$key]); + + return $this->returnMemo[$runtime][$key] = $types; + } + + /** + * Resolves `$this->getProvidedDependency(XDependencyProvider::CONST)` through the module DependencyProvider closures. + */ + private function dependencyTypes(string $class, array $args): array + { + $arg = $args[0] ?? null; + if (!$arg instanceof Node\Arg || !$arg->value instanceof Expr\ClassConstFetch || !$arg->value->name instanceof Identifier) { + return []; + } + $constant = $arg->value->name->toString(); + $module = $this->kernel->moduleOf($class); + if ($module === null) { + return []; + } + $provider = $this->kernel->resolve($module['layer'], $module['module'], $module['module'] . 'DependencyProvider'); + if ($provider === null) { + return []; + } + $memoKey = $provider . '|' . $constant; + if (isset($this->dpMemo[$memoKey])) { + return $this->dpMemo[$memoKey]; + } + $this->dpMemo[$memoKey] = []; + + $types = []; + for ($rc = $this->kernel->refl($provider); $rc && !$this->kernel->isKernel($rc->getName()); $rc = $rc->getParentClass()) { + $file = $rc->getFileName(); + if (!$file) { + continue; + } + foreach ($this->providerClosures($this->ast->file($file), $constant) as $closure) { + $scope = $this->scopeFor($provider, $rc->getName(), $provider . '::' . $constant); + $scope->vars = $this->computeVars($closure, $scope); + $returns = $closure instanceof Expr\ArrowFunction ? [$closure->expr] : $this->findReturns($closure->stmts); + foreach ($returns as $return) { + $types[] = $this->typeOf($return, $scope); + } + } + } + + return $this->dpMemo[$memoKey] = $this->union($types); + } + + /** + * @return list + */ + private function providerClosures(array $stmts, string $constant): array + { + $closures = []; + $isConstant = static fn ($node): bool => $node instanceof Expr\ClassConstFetch + && $node->name instanceof Identifier + && $node->name->toString() === $constant; + $unwrap = static function ($node) { + if ($node instanceof Expr\MethodCall && isset($node->args[0]) && $node->args[0] instanceof Node\Arg) { + $node = $node->args[0]->value; + } + + return $node instanceof Expr\Closure || $node instanceof Expr\ArrowFunction ? $node : null; + }; + + foreach ($this->finder->find($stmts, static fn (Node $n): bool => $n instanceof Expr\MethodCall || $n instanceof Expr\Assign) as $node) { + if ($node instanceof Expr\MethodCall) { + if ($node->name instanceof Identifier && in_array($node->name->toString(), ['set', 'extend'], true) + && count($node->args) >= 2 && $node->args[0] instanceof Node\Arg && $isConstant($node->args[0]->value)) { + $closures[] = $unwrap($node->args[1]->value); + } + + continue; + } + if ($node->var instanceof Expr\ArrayDimFetch && $isConstant($node->var->dim)) { + $closures[] = $unwrap($node->expr); + } + } + + return array_values(array_filter($closures)); + } + + /** + * Argument types flow into the callee's parameters (context-insensitive, merged over all call sites). + */ + private function recordParamTypes(?string $key, array $args, Scope $scope, int $depth = 0): void + { + if ($key === null || $args === []) { + return; + } + [$runtime, $declaring, $method] = $this->nodes[$key]; + $fn = $this->methodAst($runtime, $declaring, $method); + if ($fn === null) { + return; + } + $names = []; + $variadic = null; + foreach ($fn->params as $index => $param) { + if ($param->var instanceof Expr\Variable && is_string($param->var->name)) { + $names[$param->var->name] = $index; + } + if ($param->variadic) { + $variadic = $index; + } + } + $changed = false; + foreach ($args as $position => $arg) { + if (!$arg instanceof Node\Arg) { + continue; + } + $index = $arg->name !== null ? ($names[$arg->name->toString()] ?? null) : ($variadic !== null && $position >= $variadic ? $variadic : $position); + if ($index === null || !isset($fn->params[$index])) { + continue; + } + $types = $this->typeOf($arg->value, $scope, $depth + 1); + $new = array_diff($types, $this->paramTypes[$key][$index] ?? []); + if ($new !== []) { + $this->paramTypes[$key][$index] = array_values(array_merge($this->paramTypes[$key][$index] ?? [], $new)); + $changed = true; + } + } + if ($changed) { + unset($this->returnMemo[$runtime]); + if (isset($this->processed[$key])) { + $this->queue[] = $key; + } + } + } + + /** + * Remembers which classes are passed into properties, via constructor or setter-like methods (`addStep()`, `setPlugins()`). + */ + private function recordArgs(string $class, string $method, array $args, Scope $scope, int $depth = 0): void + { + $map = $this->paramPropMap($class, $method); + if ($map['props'] === []) { + return; + } + foreach ($args as $position => $arg) { + if (!$arg instanceof Node\Arg) { + continue; + } + $index = $position; + if ($arg->name !== null) { + $index = $map['names'][$arg->name->toString()] ?? null; + } elseif ($arg->unpack || ($map['variadic'] !== null && $position >= $map['variadic'])) { + $index = $map['variadic']; + } + if ($index === null || !isset($map['props'][$index])) { + continue; + } + $types = $this->typeOf($arg->value, $scope, $depth + 1); + foreach ($map['props'][$index] as $prop) { + $this->addPropTypes($class, $prop, $types); + } + } + } + + /** + * @return array{props: array>, names: array, variadic: int|null} + */ + private function paramPropMap(string $class, string $method): array + { + $class = Kernel::base($class); + $memoKey = $class . '::' . $method; + if (isset($this->ctorMaps[$memoKey])) { + return $this->ctorMaps[$memoKey]; + } + $map = ['props' => [], 'names' => [], 'variadic' => null]; + $rc = $this->kernel->refl($class); + $rm = $rc !== null && $rc->hasMethod($method) ? $rc->getMethod($method) : null; + $fn = $rm && $rm->getFileName() ? $this->ast->method($rm->getFileName(), $method, (int)$rm->getStartLine()) : null; + if ($fn !== null) { + foreach ($fn->params as $index => $param) { + if (!$param->var instanceof Expr\Variable || !is_string($param->var->name)) { + continue; + } + $map['names'][$param->var->name] = $index; + if ($param->flags !== 0) { + $map['props'][$index][] = $param->var->name; + } + if ($param->variadic) { + $map['variadic'] = $index; + } + } + foreach ($this->finder->findInstanceOf($fn->stmts ?? [], Expr\Assign::class) as $assign) { + $value = $assign->expr instanceof Expr\BinaryOp\Coalesce ? $assign->expr->left : $assign->expr; + $target = $assign->var instanceof Expr\ArrayDimFetch ? $assign->var->var : $assign->var; + if ($this->isThisProperty($target) && $value instanceof Expr\Variable && is_string($value->name) + && isset($map['names'][$value->name])) { + $map['props'][$map['names'][$value->name]][] = $target->name->toString(); + } + } + $map = $this->forwardParentArgs($map, $fn, $rm, $method); + } + + return $this->ctorMaps[$memoKey] = $map; + } + + /** + * Follows `parent::__construct($a, $b)` so arguments forwarded to the parent land in the parent's properties. + */ + private function forwardParentArgs(array $map, Stmt\ClassMethod $fn, ReflectionMethod $rm, string $method): array + { + $parent = $rm->getDeclaringClass()->getParentClass(); + if (!$parent) { + return $map; + } + foreach ($this->finder->findInstanceOf($fn->stmts ?? [], Expr\StaticCall::class) as $call) { + if (!$call->class instanceof Name || $call->class->toLowerString() !== 'parent' + || !$call->name instanceof Identifier || $call->name->toLowerString() !== strtolower($method)) { + continue; + } + $parentMap = $this->paramPropMap($parent->getName(), $method); + foreach ($call->args as $position => $arg) { + if (!$arg instanceof Node\Arg || !$arg->value instanceof Expr\Variable || !is_string($arg->value->name) + || !isset($map['names'][$arg->value->name])) { + continue; + } + $parentIndex = $parentMap['variadic'] !== null && $position >= $parentMap['variadic'] ? $parentMap['variadic'] : $position; + foreach ($parentMap['props'][$parentIndex] ?? [] as $prop) { + $map['props'][$map['names'][$arg->value->name]][] = $prop; + } + } + } + + return $map; + } + + private function addPropTypes(string $runtime, string $prop, array $types): void + { + $known = $this->propTypes[$runtime][$prop] ?? []; + $new = array_diff($types, $known); + if ($new === []) { + return; + } + $this->propTypes[$runtime][$prop] = array_values(array_merge($known, $new)); + unset($this->returnMemo[$runtime]); + foreach (array_keys($this->byRuntime[$runtime] ?? []) as $key) { + $this->queue[] = $key; + } + } + + private function propTypesFor(Scope $scope, string $prop): array + { + if (str_starts_with($scope->runtime, self::TEST_PREFIX)) { + return $this->testProp(substr($scope->runtime, strlen(self::TEST_PREFIX)), $prop); + } + $runtime = $scope->runtime; + $known = $this->union([$this->propTypes[$runtime][$prop] ?? [], $this->propTypes[Kernel::base($runtime)][$prop] ?? []]); + if ($known !== []) { + return $known; + } + if (!isset($this->declaredProps[$runtime][$prop])) { + $this->declaredProps[$runtime][$prop] = $this->declaredPropTypes($runtime, $prop); + } + + return $this->declaredProps[$runtime][$prop]; + } + + /** + * Fallback when no instantiation was seen: the declared (or @var) type, an interface resolved by Spryker naming. + */ + private function declaredPropTypes(string $class, string $prop): array + { + $rc = $this->kernel->refl($class); + if ($rc === null || !$rc->hasProperty($prop)) { + return []; + } + $property = $rc->getProperty($prop); + $type = $property->getType(); + $name = $type instanceof ReflectionNamedType && !$type->isBuiltin() ? $type->getName() : null; + if ($name === null && preg_match('/@var\s+\\\\?([A-Za-z_][\w\\\\]*)/', (string)$property->getDocComment(), $m)) { + $name = $m[1]; + } + $implementation = $name === null ? null : $this->kernel->implementationOf($name); + + return $implementation === null ? [] : [$implementation]; + } + + /** + * Flow-insensitive variable types: parameters, assignments and foreach values. + */ + private function computeVars(Stmt\ClassMethod|Expr\Closure|Expr\ArrowFunction $fn, Scope $scope): array + { + $vars = []; + foreach ($fn->params as $index => $param) { + if ($param->var instanceof Expr\Variable && is_string($param->var->name)) { + $types = $this->union([$this->hintTypes($param->type), $scope->node !== null ? ($this->paramTypes[$scope->node][$index] ?? []) : []]); + if ($types !== []) { + $vars[$param->var->name] = $types; + } + } + } + $body = $fn instanceof Expr\ArrowFunction ? [$fn->expr] : ($fn->stmts ?? []); + foreach ($this->finder->findInstanceOf($body, Stmt\Catch_::class) as $catch) { + if ($catch->var !== null && is_string($catch->var->name)) { + $vars[$catch->var->name] = $this->union([$vars[$catch->var->name] ?? [], ...array_map(fn (Name $t) => $this->hintTypes($t), $catch->types)]); + } + } + $scope->vars = $vars; + + $nodes = $this->finder->find($body, static fn (Node $n): bool => $n instanceof Expr\Assign || $n instanceof Stmt\Foreach_); + if ($nodes === []) { + return $vars; + } + for ($pass = 0; $pass < 2; $pass++) { + foreach ($nodes as $node) { + $target = $node instanceof Expr\Assign ? $node->var : $node->valueVar; + $value = $node->expr; + if ($target instanceof Expr\ArrayDimFetch) { + $target = $target->var; + } + if (!$target instanceof Expr\Variable || !is_string($target->name)) { + continue; + } + $types = $this->typeOf($value, $scope); + if ($types !== []) { + $vars[$target->name] = $this->union([$vars[$target->name] ?? [], $types]); + $scope->vars = $vars; + } + } + } + + return $this->deriveConfiguredObjects($body, $vars, $scope); + } + + /** + * A local object configured via setter-like calls (`$broker->addStep(...)`) becomes a per-call-site token + * ("Class#Declaring::method"), so steps/plugins added in one factory method do not leak into all other instances. + */ + private function deriveConfiguredObjects(array $body, array $vars, Scope $scope): array + { + $calls = $this->finder->find($body, static fn (Node $n): bool => $n instanceof Expr\MethodCall + && $n->var instanceof Expr\Variable && is_string($n->var->name) && $n->var->name !== 'this' + && $n->name instanceof Identifier && $n->args !== []); + foreach ($calls as $call) { + $variable = $call->var->name; + if (!isset($vars[$variable])) { + continue; + } + $types = []; + foreach ($vars[$variable] as $type) { + if (str_starts_with($type, self::TEST_PREFIX) || $this->paramPropMap($type, $call->name->toString())['props'] === []) { + $types[] = $type; + + continue; + } + $token = Kernel::base($type) . '#' . $scope->site; + if ($token !== $type) { + foreach ($this->propTypes[$type] ?? [] as $prop => $propTypes) { + $this->addPropTypes($token, $prop, $propTypes); + } + } + $scope->vars[$variable] = $this->union([array_diff($scope->vars[$variable], [$type]), [$token]]); + $this->recordArgs($token, $call->name->toString(), $call->args, $scope); + $types[] = $token; + } + $vars[$variable] = array_values(array_unique($types)); + $scope->vars = $vars; + } + + return $vars; + } + + private function hintTypes(?Node $type): array + { + if ($type instanceof Node\NullableType) { + $type = $type->type; + } + if ($type instanceof Node\UnionType) { + return $this->union(array_map(fn ($t) => $this->hintTypes($t), $type->types)); + } + if (!$type instanceof Name || $type->isSpecialClassName()) { + return []; + } + $class = $type->toString(); + + return $this->kernel->isTracked($class) && $this->kernel->isConcrete($class) ? [$class] : []; + } + + /** + * @return list + */ + private function findReturns(array $stmts): array + { + $returns = []; + $stack = $stmts; + while ($stack) { + $node = array_pop($stack); + if (is_array($node)) { + array_push($stack, ...$node); + + continue; + } + if (!$node instanceof Node || $node instanceof Expr\Closure || $node instanceof Expr\ArrowFunction + || $node instanceof Stmt\Class_ || $node instanceof Stmt\Function_) { + continue; + } + if ($node instanceof Stmt\Return_ && $node->expr !== null) { + $returns[] = $node->expr; + } + foreach ($node->getSubNodeNames() as $name) { + $stack[] = $node->$name; + } + } + + return $returns; + } + + public function methodNode(string $class, string $method): ?Stmt\ClassMethod + { + $key = $this->node($class, $method); + + return $key === null ? null : $this->methodAst($class, $this->nodes[$key][1], $method); + } + + private function methodAst(string $runtime, string $declaring, string $method): ?Stmt\ClassMethod + { + if (str_starts_with($runtime, self::TEST_PREFIX)) { + return $this->testMethod(substr($runtime, strlen(self::TEST_PREFIX)), $method); + } + $rc = $this->kernel->refl($declaring); + if ($rc === null || !$rc->hasMethod($method)) { + return null; + } + $rm = $rc->getMethod($method); + $file = $rm->getFileName(); + + return $file ? $this->ast->method($file, $method, (int)$rm->getStartLine()) : null; + } + + private function scopeFor(string $runtime, string $declaring, string $site = ''): Scope + { + $testModule = null; + if (str_starts_with($runtime, self::TEST_PREFIX)) { + $testModule = $this->testClasses[substr($runtime, strlen(self::TEST_PREFIX))]['module'] ?? null; + } + + return new Scope($runtime, $declaring, [], $testModule, $site !== '' ? $site : $declaring); + } + + private function testMethod(string $fqcn, string $method): ?Stmt\ClassMethod + { + for ($class = $fqcn; $class !== null && isset($this->testClasses[$class]); $class = $this->testClasses[$class]['parent']) { + if (isset($this->testClasses[$class]['methods'][$method])) { + return $this->testClasses[$class]['methods'][$method]; + } + } + + return null; + } + + private function testProp(string $fqcn, string $prop): array + { + $types = []; + for ($class = $fqcn; $class !== null && isset($this->testClasses[$class]); $class = $this->testClasses[$class]['parent']) { + $types[] = $this->testClasses[$class]['props'][$prop] ?? []; + } + + return $this->union($types); + } + + private function collectTestProps(string $fqcn): void + { + $runtime = self::TEST_PREFIX . $fqcn; + for ($pass = 0; $pass < 2; $pass++) { + foreach ($this->testClasses[$fqcn]['methods'] as $method) { + $assigns = $this->finder->findInstanceOf($method->stmts ?? [], Expr\Assign::class); + $assigns = array_filter($assigns, fn (Expr\Assign $a): bool => $this->isThisProperty($a->var)); + if ($assigns === []) { + continue; + } + $scope = $this->scopeFor($runtime, $runtime); + $scope->vars = $this->computeVars($method, $scope); + foreach ($assigns as $assign) { + $prop = $assign->var->name->toString(); + $this->testClasses[$fqcn]['props'][$prop] = $this->union([ + $this->testClasses[$fqcn]['props'][$prop] ?? [], + $this->typeOf($assign->expr, $scope), + ]); + } + } + } + } + + private function isThisProperty(?Node $node): bool + { + return ($node instanceof Expr\PropertyFetch || $node instanceof Expr\NullsafePropertyFetch) + && $node->var instanceof Expr\Variable + && $node->var->name === 'this' + && $node->name instanceof Identifier; + } + + /** + * @param list> $lists + * + * @return list + */ + private function union(array $lists): array + { + return $lists === [] ? [] : array_values(array_unique(array_merge(...$lists))); + } +} + +final class ProjectScanner +{ + private const EXCLUDED_PATH = '#/(Dependency|Controller|Persistence/Propel|Theme)/#'; + + private const EXCLUDED_FILE = '/(Config|DependencyProvider|Factory|Interface|Constants|Controller|Stub)\.php$/'; + + public function __construct(private Kernel $kernel) + { + } + + /** + * @return list, allMethods: list, layer: string, module: string}> + */ + public function scan(string $root): array + { + $classes = []; + foreach ($this->projectFiles($root) as $path => $class) { + $relative = substr($path, strlen($root) + 1); + if (preg_match(self::EXCLUDED_PATH, $relative) || preg_match(self::EXCLUDED_FILE, $relative)) { + continue; + } + $rc = $this->kernel->refl($class); + if ($rc === null || $rc->getFileName() !== $path || $rc->isInterface() || $rc->isTrait() || $rc->isAbstract() || $rc->isEnum()) { + continue; + } + $methods = []; + $allMethods = []; + foreach ($rc->getMethods() as $method) { + if ($method->getDeclaringClass()->getName() !== $class || $method->getFileName() !== $path || $method->getName() === '__construct') { + continue; + } + $allMethods[] = $method->getName(); + if ($method->isPublic() || $this->isOverride($rc, $method->getName())) { + $methods[] = $method->getName(); + } + } + if ($allMethods === []) { + continue; + } + $module = $this->kernel->moduleOf($class); + $classes[] = [ + 'class' => $class, + 'file' => $relative, + 'core' => $this->coreParent($rc), + 'methods' => $methods, + 'allMethods' => $allMethods, + 'layer' => $module['layer'] ?? '?', + 'module' => $module['module'] ?? '?', + ]; + } + usort($classes, static fn (array $a, array $b): int => strcmp($a['class'], $b['class'])); + + return $classes; + } + + /** + * Every PHP file of every project namespace dir, mapped to the class name derived from its path (PSR-4). + * + * @return array path => class + */ + public function projectFiles(string $root): array + { + $files = []; + foreach ($this->kernel->projectOrgs as $org) { + $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("$root/src/$org", FilesystemIterator::SKIP_DOTS)); + foreach ($iterator as $file) { + if ($file->getExtension() === 'php') { + $path = $file->getPathname(); + $files[$path] = str_replace('/', '\\', substr($path, strlen("$root/src/"), -4)); + } + } + } + + return $files; + } + + /** + * A non-public method counts only when it overrides a parent or interface method (new behaviour of an override). + * Pure protected/private helpers are reached through the public methods of the same class. + */ + private function isOverride(ReflectionClass $rc, string $method): bool + { + $parent = $rc->getParentClass(); + if ($parent && $parent->hasMethod($method)) { + return true; + } + foreach ($rc->getInterfaces() as $interface) { + if ($interface->hasMethod($method)) { + return true; + } + } + + return false; + } + + /** + * Nearest core ancestor that carries domain behaviour (Kernel classes and Abstract* bases do not count). + */ + private function coreParent(ReflectionClass $rc): ?string + { + for ($parent = $rc->getParentClass(); $parent; $parent = $parent->getParentClass()) { + $name = $parent->getName(); + $org = strstr($name, '\\', true); + if (in_array($org, $this->kernel->projectOrgs, true)) { + continue; + } + if (!in_array($org, Kernel::CORE_ORGS, true) || $this->kernel->isKernel($name) || str_starts_with($parent->getShortName(), 'Abstract')) { + return null; + } + + return $name; + } + + return null; + } +} + +/** + * Methods that are not worth a test: they are neither listed nor counted. + */ +final class SkipRules +{ + public const REASON_BOOTSTRAP = 'application bootstrap'; + + public const REASON_ROUTING = 'routing/resource configuration plugin'; + + public const REASON_STUB_ONLY = 'client method only calls a Zed stub'; + + public const REASON_UI = 'form/table definition (--skip-ui-definitions)'; + + public const REASON_DECLARATIVE = 'declarative: only returns constant data'; + + /** Plugins that only declare routes/resources; they are verified by HTTP tests, not unit tests. */ + private const ROUTING_INTERFACES = [ + 'Spryker\\Glue\\GlueApplicationExtension\\Dependency\\Plugin\\ResourceInterface', + 'Spryker\\Glue\\GlueJsonApiConventionExtension\\Dependency\\Plugin\\JsonApiResourceInterface', + 'Spryker\\Glue\\GlueApplicationExtension\\Dependency\\Plugin\\ResourceRoutePluginInterface', + 'Spryker\\Glue\\GlueBackendApiApplicationAuthorizationConnectorExtension\\Dependency\\Plugin\\ProtectedRouteAuthorizationConfigProviderPluginInterface', + 'Spryker\\Yves\\RouterExtension\\Dependency\\Plugin\\RouteProviderPluginInterface', + ]; + + private const FORM_TYPE = 'Symfony\\Component\\Form\\FormTypeInterface'; + + private const GUI_TABLE = 'Spryker\\Zed\\Gui\\Communication\\Table\\AbstractTable'; + + private const FORM_DEFINITION_METHODS = ['buildForm', 'configureOptions', 'getBlockPrefix', 'getName']; + + /** Plugins adding fields to a core form, e.g. ProductAbstractFormExpanderPluginInterface, MerchantFormExpanderPluginInterface. */ + private const FORM_EXPANDER_INTERFACE_PATTERN = '/FormExpanderPluginInterface$/'; + + private NodeFinder $finder; + + public function __construct(private Kernel $kernel, private Analyzer $analyzer, private bool $skipUiDefinitions) + { + $this->finder = new NodeFinder(); + } + + /** + * @param array{class: string, layer: string, methods: list} $class + * + * @return array method => reason + */ + public function skippedMethodsOf(array $class): array + { + $name = $class['class']; + $rc = $this->kernel->refl($name); + if ($rc === null) { + return []; + } + $classReason = $this->classReason($name, $rc); + if ($classReason !== null) { + return array_fill_keys($class['methods'], $classReason); + } + + $isForm = $this->skipUiDefinitions && interface_exists(self::FORM_TYPE) && $rc->implementsInterface(self::FORM_TYPE); + $isTable = $this->skipUiDefinitions && class_exists(self::GUI_TABLE) && $rc->isSubclassOf(self::GUI_TABLE); + $isClient = $class['layer'] === 'Client' && str_ends_with($name, 'Client'); + $skipped = []; + foreach ($class['methods'] as $method) { + $fn = $this->analyzer->methodNode($name, $method); + $reason = match (true) { + $isClient && $this->isStubOnly($name, $method) => self::REASON_STUB_ONLY, + $isForm && (in_array($method, self::FORM_DEFINITION_METHODS, true) || (str_starts_with($method, 'add') && $fn !== null && !$this->hasLogic($fn))) => self::REASON_UI, + $isTable && $method === 'configure' => self::REASON_UI, + $fn !== null && $this->isDeclarative($fn) => self::REASON_DECLARATIVE, + default => null, + }; + if ($reason !== null) { + $skipped[$method] = $reason; + } + } + + return $skipped; + } + + private function classReason(string $name, ReflectionClass $rc): ?string + { + if (str_ends_with($name, 'Bootstrap')) { + return self::REASON_BOOTSTRAP; + } + foreach (self::ROUTING_INTERFACES as $interface) { + if (interface_exists($interface) && $rc->implementsInterface($interface)) { + return self::REASON_ROUTING; + } + } + if ($this->skipUiDefinitions && preg_grep(self::FORM_EXPANDER_INTERFACE_PATTERN, $rc->getInterfaceNames())) { + return self::REASON_UI; + } + + return null; + } + + /** + * Thin client method whose only project callee is a Zed stub (factory calls aside). + */ + private function isStubOnly(string $class, string $method): bool + { + $callees = $this->analyzer->delegateCallees($class, $method) ?? []; + $stubCalls = array_filter($callees, static fn (array $c): bool => str_ends_with($c[0], 'Stub')); + $otherCalls = array_filter($callees, static fn (array $c): bool => !str_ends_with($c[0], 'Stub') && !str_ends_with($c[0], 'Factory')); + + return $stubCalls !== [] && $otherCalls === []; + } + + /** + * The whole body is `return ;`. + */ + private function isDeclarative(Stmt\ClassMethod $fn): bool + { + $stmts = $fn->stmts ?? []; + + return count($stmts) === 1 && $stmts[0] instanceof Stmt\Return_ && $this->isConstantData($stmts[0]->expr); + } + + /** + * Scalars, constants, `X::class`, arrays of those, and objects built from them: + * `new X()` / `new X('a')` and fluent setters on them: `(new XTransfer())->setA('a')->setB(Y::B)`. + */ + private function isConstantData(?Node $expr): bool + { + return match (true) { + $expr instanceof Node\Scalar, $expr instanceof Expr\ClassConstFetch, $expr instanceof Expr\ConstFetch => true, + $expr instanceof Expr\UnaryMinus => $this->isConstantData($expr->expr), + $expr instanceof Expr\Array_ => !array_filter($expr->items, fn ($item): bool => $item !== null + && (!$this->isConstantData($item->value) || ($item->key !== null && !$this->isConstantData($item->key)))), + $expr instanceof Expr\New_ => $expr->class instanceof Name && $this->areConstantArgs($expr->args), + $expr instanceof Expr\MethodCall => ($expr->var instanceof Expr\New_ || $expr->var instanceof Expr\MethodCall) + && $this->isConstantData($expr->var) && $this->areConstantArgs($expr->args), + default => false, + }; + } + + private function areConstantArgs(array $args): bool + { + foreach ($args as $arg) { + if (!$arg instanceof Node\Arg || $arg->unpack || !$this->isConstantData($arg->value)) { + return false; + } + } + + return true; + } + + private function hasLogic(Stmt\ClassMethod $fn): bool + { + return $this->finder->findFirst($fn->stmts ?? [], static fn (Node $n): bool => $n instanceof Stmt\If_ + || $n instanceof Stmt\Foreach_ || $n instanceof Stmt\For_ || $n instanceof Stmt\While_ || $n instanceof Stmt\Do_ + || $n instanceof Stmt\Switch_ || $n instanceof Stmt\TryCatch || $n instanceof Expr\Match_ || $n instanceof Expr\Ternary + || $n instanceof Expr\Closure || $n instanceof Expr\ArrowFunction) !== null; + } +} + +final class Report +{ + private const MAX_ENTRIES = 4; + + private const MAX_PLUGINS = 3; + + private array $registeredIn = []; + + private array $pluginCalls = []; + + public function __construct(private Kernel $kernel, private Ast $ast, private Analyzer $analyzer) + { + } + + /** + * Scans project DependencyProviders for `new X()` registrations. + */ + public function collectRegistrations(array $projectFiles): void + { + $finder = new NodeFinder(); + foreach (array_keys($projectFiles) as $path) { + if (!str_ends_with($path, 'DependencyProvider.php')) { + continue; + } + $provider = basename($path, '.php'); + foreach ($finder->findInstanceOf($this->ast->file($path), Stmt\ClassMethod::class) as $method) { + foreach ($finder->findInstanceOf($method->stmts ?? [], Expr\New_::class) as $new) { + if ($new->class instanceof Name && !$new->class->isSpecialClassName()) { + $this->registeredIn[$new->class->toString()][] = $provider . '::' . $method->name->toString() . '()'; + } + } + } + } + } + + /** + * "XFactory::createY()" — the method of the module factory (project or core) that instantiates the class. + */ + public function factoryMethodCreating(string $class): ?string + { + $info = $this->kernel->moduleOf($class); + $factory = $info === null ? null : $this->kernel->getterTarget($info['layer'], $info['module'], $info['part'], 'getFactory'); + $finder = new NodeFinder(); + for ($rc = $factory === null ? null : $this->kernel->refl($factory); $rc && !$this->kernel->isKernel($rc->getName()); $rc = $rc->getParentClass()) { + foreach ($finder->findInstanceOf($this->ast->file((string)$rc->getFileName()), Stmt\ClassMethod::class) as $method) { + $creates = $finder->findFirst($method->stmts ?? [], static fn (Node $n): bool => $n instanceof Expr\New_ + && $n->class instanceof Name && $n->class->toString() === $class); + if ($creates !== null) { + return $rc->getShortName() . '::' . $method->name->toString() . '()'; + } + } + } + + return null; + } + + /** + * @return list "XDependencyProvider::method()" where the class is instantiated + */ + public function registrationsOf(string $class): array + { + return array_values(array_unique($this->registeredIn[$class] ?? [])); + } + + /** + * @return list + */ + public function registeredPluginsOf(string $layer, string $module): array + { + $plugins = []; + foreach (array_keys($this->registeredIn) as $class) { + $info = $this->kernel->moduleOf($class); + if ($info !== null && $info['module'] === $module && preg_match('/(Plugin|Subscriber)$/', $class) && $this->kernel->isConcrete($class)) { + $plugins[] = $class; + } + } + + return $plugins; + } + + /** + * @return list "Plugin (registered in X::y())" lines for plugins calling $facade::$method + */ + public function pluginsCalling(string $facade, string $method): array + { + $info = $this->kernel->moduleOf($facade); + if ($info === null) { + return []; + } + $lines = []; + foreach ($this->registeredPluginsOf($info['layer'], $info['module']) as $plugin) { + if (in_array($method, $this->facadeCallsOf($plugin), true)) { + $lines[] = $this->short($plugin) . ' (registered in ' . implode(', ', array_unique($this->registeredIn[$plugin])) . ')'; + } + } + + return $lines; + } + + private function facadeCallsOf(string $plugin): array + { + if (isset($this->pluginCalls[$plugin])) { + return $this->pluginCalls[$plugin]; + } + $calls = []; + $finder = new NodeFinder(); + for ($rc = $this->kernel->refl($plugin); $rc && !$this->kernel->isKernel($rc->getName()); $rc = $rc->getParentClass()) { + if (!$rc->getFileName()) { + continue; + } + foreach ($finder->findInstanceOf($this->ast->file($rc->getFileName()), Expr\MethodCall::class) as $call) { + if ($call->name instanceof Identifier && $call->var instanceof Expr\MethodCall && $call->var->name instanceof Identifier + && in_array($call->var->name->toString(), ['getFacade', 'getClient', 'getService'], true)) { + $calls[] = $call->name->toString(); + } + } + } + + return $this->pluginCalls[$plugin] = array_values(array_unique($calls)); + } + + /** + * Methods the framework calls: magic methods, overrides/implementations of non-project classes and interfaces + * (plugin interfaces, core overrides, Symfony/Codeception contracts) and controller actions. + */ + public function isFrameworkCalled(string $class, string $method): bool + { + if (str_starts_with($method, '__') || (str_ends_with($method, 'Action') && str_ends_with($class, 'Controller'))) { + return true; + } + $rc = $this->kernel->refl($class); + if ($rc === null) { + return true; + } + for ($parent = $rc->getParentClass(); $parent; $parent = $parent->getParentClass()) { + if (!$this->kernel->isProject($parent->getName()) && $parent->hasMethod($method)) { + return true; + } + } + foreach ($rc->getInterfaces() as $interface) { + if (!$this->kernel->isProject($interface->getName()) && $interface->hasMethod($method)) { + return true; + } + } + + return false; + } + + /** + * Classes referenced in production code (`new X`, `X::m()`, `X::class`, `instanceof X`, `catch (X)`, `extends X`) outside their own file. + * Scans project dirs plus config/ and public/ (bootstraps, application config). + * + * @param array $projectFiles + * + * @return array + */ + public function referencedClasses(string $root, array $projectFiles): array + { + $paths = array_keys($projectFiles); + foreach (['config', 'public'] as $dir) { + if (!is_dir("$root/$dir")) { + continue; + } + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator("$root/$dir", FilesystemIterator::SKIP_DOTS)) as $file) { + if ($file->getExtension() === 'php') { + $paths[] = $file->getPathname(); + } + } + } + $references = []; + $finder = new NodeFinder(); + foreach ($paths as $path) { + $own = $projectFiles[$path] ?? null; + $nodes = $finder->find($this->ast->file($path), static fn (Node $n): bool => $n instanceof Expr\New_ + || $n instanceof Expr\StaticCall || $n instanceof Expr\ClassConstFetch || $n instanceof Expr\Instanceof_ || $n instanceof Stmt\Catch_ + || ($n instanceof Stmt\Class_ && $n->extends !== null)); + foreach ($nodes as $node) { + $names = match (true) { + $node instanceof Stmt\Catch_ => $node->types, + $node instanceof Stmt\Class_ => [$node->extends], + default => [$node->class], + }; + foreach ($names as $name) { + if ($name instanceof Name && !$name->isSpecialClassName() && $name->toString() !== $own) { + $references[$name->toString()] = true; + } + } + } + } + + return $references; + } + + /** + * Classes the Spryker kernel resolves by naming convention (never instantiated explicitly). + */ + public function isKernelResolved(string $class): bool + { + $info = $this->kernel->moduleOf($class); + if ($info === null) { + return false; + } + $module = $info['module']; + $short = substr($class, strrpos($class, '\\') + 1); + + return in_array($short, ["{$module}Facade", "{$module}Client", "{$module}Service", "{$module}Repository", "{$module}EntityManager", "{$module}QueryContainer", "{$module}Config"], true) + || str_ends_with($short, 'Controller'); + } + + /** + * Method names referenced dynamically: string literals in project PHP (callables, `[$this, 'x']`) + * and Twig attribute/method access (`item.name` -> name/getName/isName/hasName). + * + * @param array $projectFiles + * + * @return array + */ + public function namesReferencedAsText(string $root, array $projectFiles, array $skipLayers = []): array + { + $names = []; + $finder = new NodeFinder(); + foreach (array_keys($projectFiles) as $path) { + foreach ($finder->findInstanceOf($this->ast->file($path), String_::class) as $string) { + if (preg_match('/^[a-zA-Z_]\w*$/', $string->value)) { + $names[$string->value] = true; + } + } + } + foreach ($this->kernel->projectOrgs as $org) { + $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("$root/src/$org", FilesystemIterator::SKIP_DOTS)); + foreach ($iterator as $file) { + $layer = explode('/', substr($file->getPathname(), strlen("$root/src/$org/")))[0]; + if (in_array($layer, $skipLayers, true)) { + continue; + } + if ($file->getExtension() !== 'twig' || !preg_match_all('/\.([a-zA-Z_]\w*)/', (string)file_get_contents($file->getPathname()), $m)) { + continue; + } + foreach ($m[1] as $name) { + foreach ([$name, 'get' . ucfirst($name), 'is' . ucfirst($name), 'has' . ucfirst($name)] as $candidate) { + $names[$candidate] = true; + } + } + } + } + + return $names; + } + + public function short(string $class): string + { + $info = $this->kernel->moduleOf($class); + + return $info === null + ? $class + : "{$info['org']}\\{$info['layer']}\\{$info['module']}\\…\\" . substr($class, strrpos($class, '\\') + 1); + } + + public function nodeLabel(string $key): string + { + [$runtime, , $method] = $this->analyzer->nodes[$key]; + $runtime = Kernel::base($runtime); + + return $this->short($runtime) . '::' . $method . '()'; + } +} + +// --------------------------------------------------------------------------------------------------------------------- + +$options = getopt('', ['layer:', 'module:', 'only-untested', 'no-entries', 'no-unused', 'hide-unused', 'skip-ui-definitions', 'show-skipped', 'skip-layer:', 'why:', 'root:', 'json', 'help']); +if (isset($options['help'])) { + echo "Usage: php coverage-gaps.php [--layer=Zed|Client|Yves|Glue|Service|Shared] [--module=Cart] [--only-untested]\n" + . " [--no-entries] [--no-unused] [--hide-unused] [--skip-ui-definitions] [--show-skipped] [--skip-layer=Yves,Glue]\n" + . " [--why=FQCN] [--root=DIR] [--json]\n" + . " --skip-layer=L ignore layers the project does not use (comma-separated or repeated): not reported, not counted,\n" + . " not production callers for unused code, not entry points\n" + . " --only-untested hide partially tested classes\n" + . " --no-entries skip the 'test via' lookup and section 3\n" + . " --no-unused skip unused-code detection and section 4\n" + . " --hide-unused detect unused code and drop it from the lists and counts (wins over --no-unused)\n" + . " --skip-ui-definitions also skip form field definitions (buildForm, add*Field without logic), form expander plugins and Table::configure()\n" + . " --show-skipped list the skipped methods per reason (by default only the counts are printed)\n" + . " --why=FQCN print the call paths from entry points to the untested methods of FQCN (use / instead of \\ when running via docker/sdk)\n" + . " --root=DIR analyse another project dir (its src/ dirs are autoloaded, vendor/ stays this project's)\n" + . " --json print the result as JSON instead of the text report\n"; + exit(0); +} +if (isset($options['hide-unused'])) { + unset($options['no-unused']); +} +if (isset($options['root'])) { + $root = realpath($options['root']) ?: $options['root']; + if (!is_dir($root . '/src')) { + fwrite(STDERR, "--root: no src/ directory in $root\n"); + exit(1); + } + $rootOrgs = Kernel::detectProjectOrgs($root); + spl_autoload_register(static function (string $class) use ($root, $rootOrgs): void { + $org = strstr($class, '\\', true); + $file = $root . '/src/' . str_replace('\\', '/', $class) . '.php'; + if (in_array($org, $rootOrgs, true) && is_file($file)) { + require_once $file; + } + }, true, true); +} +if (isset($options['why'])) { + $options['why'] = ltrim(str_replace('/', '\\', $options['why']), '\\'); +} +$skipLayers = []; +foreach ((array)($options['skip-layer'] ?? []) as $value) { + foreach (array_filter(array_map('trim', explode(',', (string)$value))) as $layer) { + $layer = ucfirst(strtolower($layer)); + if (!in_array($layer, ['Zed', 'Client', 'Yves', 'Glue', 'Service', 'Shared'], true)) { + fwrite(STDERR, "--skip-layer: unknown layer '$layer', use Zed, Client, Yves, Glue, Service or Shared\n"); + exit(1); + } + $skipLayers[$layer] = $layer; + } +} +$skipLayers = array_values($skipLayers); +$log = static fn (string $message) => fwrite(STDERR, sprintf("[%5.1fs] %s\n", microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'], $message)); + +$kernel = new Kernel(Kernel::detectProjectOrgs($root)); +$ast = new Ast(); +$analyzer = new Analyzer($kernel, $ast); +$report = new Report($kernel, $ast, $analyzer); +$scanner = new ProjectScanner($kernel); +$isIgnoredLayer = static fn (string $class): bool => in_array($kernel->moduleOf($class)['layer'] ?? '', $skipLayers, true); +$projectFiles = $scanner->projectFiles($root); +// --skip-layer: code of ignored layers is neither reported nor a production caller nor an entry point. +$projectFilesInUse = array_filter($projectFiles, static fn (string $class): bool => !$isIgnoredLayer($class)); +if ($skipLayers !== []) { + $log('Ignoring layers: ' . implode(', ', $skipLayers)); +} + +$log('Scanning src/{' . implode(',', $kernel->projectOrgs) . '} ...'); +$classes = $scanner->scan($root); +$classes = array_values(array_filter($classes, static fn (array $c): bool => !in_array($c['layer'], $skipLayers, true) + && (!isset($options['layer']) || $c['layer'] === $options['layer']) + && (!isset($options['module']) || $c['module'] === $options['module']))); +$log(sprintf('%d classes with own methods in scope', count($classes))); + +// Every tests/Test directory is a test namespace: PyzTest by default, another name in a project with its own namespace. +$testDirs = glob($root . '/tests/*Test', GLOB_ONLYDIR) ?: []; +$log($testDirs === [] + ? 'No tests/Test directory found: every method counts as untested' + : 'Following calls from tests/{' . implode(',', array_map('basename', $testDirs)) . '} ...'); +$seeds = $analyzer->registerTests($testDirs); +foreach ($seeds as $seed) { + $analyzer->seed($seed); +} +$analyzer->run(); +$tested = []; +foreach (array_keys($analyzer->processed) as $key) { + [, $declaring, $method] = $analyzer->nodes[$key]; + $tested[$declaring][$method] = true; +} +$log(sprintf('%d test classes, %d reached methods', $analyzer->testFileCount(), count($analyzer->processed))); + +// Thin plugins: a plugin method that only delegates to tested project code counts as covered. +$inScope = array_flip(array_column($classes, 'class')); +$coveredByDelegates = []; +foreach ($classes as $class) { + if (!str_ends_with($class['class'], 'Plugin')) { + continue; + } + foreach ($class['methods'] as $method) { + if (isset($tested[$class['class']][$method])) { + continue; + } + $callees = array_filter($analyzer->delegateCallees($class['class'], $method) ?? [], static fn (array $c): bool => isset($inScope[$c[0]])); + if ($callees !== [] && !array_filter($callees, static fn (array $c): bool => !isset($tested[$c[0]][$c[1]]))) { + $coveredByDelegates[$class['class']][$method] = true; + } + } +} + +// Skip rules: bootstraps, routing plugins, stub-only client methods, declarative methods, (optionally) UI definitions. +// Skipped methods are not listed and not counted. +$skipRules = new SkipRules($kernel, $analyzer, isset($options['skip-ui-definitions'])); +$skipped = []; +foreach ($classes as $class) { + $reasons = $skipRules->skippedMethodsOf($class); + if ($reasons !== []) { + $skipped[$class['class']] = $reasons; + } +} +$skippedByReason = static function (string $reason) use ($skipped): array { + $result = []; + foreach ($skipped as $class => $reasons) { + $methods = array_keys(array_filter($reasons, static fn (string $r): bool => $r === $reason)); + if ($methods !== []) { + $result[$class] = $methods; + } + } + + return $result; +}; +$withoutSkipped = static fn (array $class): array => array_values(array_filter( + $class['methods'], + static fn (string $m): bool => !isset($skipped[$class['class']][$m]), +)); + +$gaps = []; +foreach ($classes as $class) { + $class['methods'] = $withoutSkipped($class); + $missing = array_values(array_filter($class['methods'], static fn (string $m): bool => !isset($tested[$class['class']][$m]) + && !isset($coveredByDelegates[$class['class']][$m]))); + if ($missing === [] || (isset($options['only-untested']) && count($missing) !== count($class['methods']))) { + continue; + } + $class['missing'] = $missing; + $class['untested'] = count($missing) === count($class['methods']); + $gaps[] = $class; +} + +// Unused code: production call graph over all project code (tests excluded), liveness from framework roots. +$unused = []; +if (!isset($options['no-unused'])) { + $log('Building production call graph for unused-code detection ...'); + $analyzer->resetGraph(static fn (string $runtime): bool => $kernel->isProject($runtime) && !$isIgnoredLayer($runtime)); + foreach ($projectFilesInUse as $path => $class) { + $rc = $kernel->refl($class); + if ($rc === null || $rc->getFileName() !== $path || $rc->isInterface()) { + continue; + } + // Concrete classes also get their inherited project methods, so template methods (`$this->getX()` in an + // abstract parent) resolve to the subclass implementation. + foreach ($rc->getMethods() as $method) { + $declaring = $method->getDeclaringClass()->getName(); + if ($declaring === $class || (!$rc->isAbstract() && $kernel->isProject($declaring))) { + $key = $analyzer->node($class, $method->getName()); + if ($key !== null) { + $analyzer->seed($key); + } + } + } + } + $analyzer->run(); + + $referencedNames = $analyzer->unresolvedNames + $report->namesReferencedAsText($root, $projectFilesInUse, $skipLayers); + $queue = []; + foreach (array_keys($analyzer->processed) as $key) { + [, $declaring, $method] = $analyzer->nodes[$key]; + if (isset($referencedNames[$method]) || $report->isFrameworkCalled($declaring, $method)) { + $queue[] = $key; + } + } + $live = array_fill_keys($queue, true); + while ($queue) { + foreach (array_keys($analyzer->edges[array_pop($queue)] ?? []) as $to) { + if (!isset($live[$to])) { + $live[$to] = true; + $queue[] = $to; + } + } + } + $liveMethods = []; + foreach (array_keys($live) as $key) { + $liveMethods[$analyzer->nodes[$key][1]][$analyzer->nodes[$key][2]] = true; + } + $referencedClasses = $report->referencedClasses($root, $projectFilesInUse); + foreach ($classes as $class) { + $isReferenced = isset($referencedClasses[$class['class']]) || $report->isKernelResolved($class['class']); + $dead = !$isReferenced + ? $class['allMethods'] + : array_values(array_filter($class['allMethods'], static fn (string $m): bool => !isset($liveMethods[$class['class']][$m]))); + if ($dead !== []) { + $unused[$class['class']] = $dead; + } + } + $log(sprintf('%d live methods, %d unused methods in %d classes', count($live), array_sum(array_map('count', $unused)), count($unused))); +} + +// --hide-unused: unused methods are neither listed nor counted; classes left without methods disappear. +$hiddenUnused = 0; +if (isset($options['hide-unused']) && $unused !== []) { + $hiddenUnused = array_sum(array_map('count', $unused)); + $withoutUnused = static function (array $item, string $key) use ($unused): array { + $item[$key] = array_values(array_diff($item[$key], $unused[$item['class']] ?? [])); + + return $item; + }; + $classes = array_values(array_filter( + array_map(static fn (array $c): array => $withoutUnused($withoutUnused($c, 'methods'), 'allMethods'), $classes), + static fn (array $c): bool => $c['allMethods'] !== [], + )); + $gaps = array_values(array_filter( + array_map(static fn (array $g): array => $withoutUnused($withoutUnused($g, 'methods'), 'missing'), $gaps), + static fn (array $g): bool => $g['missing'] !== [], + )); + foreach ($gaps as $index => $gap) { + $gaps[$index]['untested'] = count($gap['missing']) === count($gap['methods']); + } + $unused = []; +} + +// Entry points: build a module-restricted graph from Facade/Client/Service/Plugin/Controller/Console entries. +$entriesByClass = []; +$unitTestSuggestions = []; +$entryKeys = []; +if (!isset($options['no-entries']) && $gaps !== []) { + $report->collectRegistrations($projectFilesInUse); + $modules = []; + foreach ($gaps as $gap) { + $modules[$gap['layer'] . '|' . $gap['module']] = [$gap['layer'], $gap['module']]; + } + $moduleNames = array_flip(array_column($modules, 1)); + $analyzer->resetGraph(static fn (string $runtime): bool => isset($moduleNames[$kernel->moduleOf($runtime)['module'] ?? '']) && !$isIgnoredLayer($runtime)); + + $log(sprintf('Building entry-point graph for %d modules ...', count($modules))); + $entryClasses = []; + foreach ($modules as [$layer, $module]) { + foreach (['getFacade' => 'Business', 'getClient' => '', 'getService' => ''] as $getter => $part) { + $class = $kernel->getterTarget($layer, $module, $part, $getter); + if ($class !== null) { + $entryClasses[$class] = true; + } + } + foreach ($report->registeredPluginsOf($layer, $module) as $plugin) { + $entryClasses[$plugin] = true; + } + } + foreach ($classes as $class) { + if (isset($modules[$class['layer'] . '|' . $class['module']]) + && preg_match('/(Plugin|Console|Widget|Facade|Client|Service)$/', $class['class'])) { + $entryClasses[$class['class']] = true; + } + } + foreach ($modules as [$layer, $module]) { + foreach ($kernel->controllersOf($layer, $module) as $controller) { + $entryClasses[$controller] = true; + } + } + + foreach (array_keys($entryClasses) as $class) { + if ($isIgnoredLayer($class)) { + continue; + } + $rc = $kernel->refl($class); + if ($rc === null || !$kernel->isConcrete($class)) { + continue; + } + foreach ($rc->getMethods() as $method) { + $name = $method->getName(); + $isEntry = $method->isPublic() ? !str_starts_with($name, '__') : $name === 'execute'; + if (str_ends_with($class, 'Widget') && $name === '__construct') { + $isEntry = true; + } + $key = $isEntry ? $analyzer->node($class, $name) : null; + if ($key !== null) { + $entryKeys[$key] = true; + $analyzer->seed($key); + } + } + } + $analyzer->run(); + $log(sprintf('%d entry methods, %d reachable methods', count($entryKeys), count($analyzer->processed))); + + $reverse = []; + foreach ($analyzer->edges as $from => $targets) { + foreach (array_keys($targets) as $to) { + $reverse[$to][$from] = true; + } + } + $nodesByDeclaring = []; + foreach (array_keys($analyzer->processed) as $key) { + $nodesByDeclaring[$analyzer->nodes[$key][1]][$analyzer->nodes[$key][2]][] = $key; + } + + foreach ($gaps as $gap) { + $queue = []; + foreach ($gap['missing'] as $method) { + array_push($queue, ...($nodesByDeclaring[$gap['class']][$method] ?? [])); + } + $visited = array_fill_keys($queue, null); + $found = []; + while ($queue) { + $key = array_shift($queue); + if (isset($entryKeys[$key])) { + $found[$key] = true; + + continue; + } + foreach (array_keys($reverse[$key] ?? []) as $caller) { + if (!array_key_exists($caller, $visited)) { + $visited[$caller] = $key; + $queue[] = $caller; + } + } + } + $entriesByClass[$gap['class']] = array_keys($found); + + // Glue/Yves: when only controller actions (HTTP) reach the class, suggest a unit test of the class the + // controller calls (found on the path), created through the module factory. + $isHttpOnly = $found !== [] && in_array($gap['layer'], ['Glue', 'Yves'], true) + && !array_filter(array_keys($found), static fn (string $entry): bool => !str_ends_with(Kernel::base($analyzer->nodes[$entry][0]), 'Controller')); + if ($isHttpOnly) { + foreach (array_keys($found) as $entry) { + $hop = $visited[$entry]; + while ($hop !== null && preg_match('/(Factory|Controller)$/', Kernel::base($analyzer->nodes[$hop][0]))) { + $hop = $visited[$hop]; + } + if ($hop === null) { + continue; + } + $testClass = Kernel::base($analyzer->nodes[$hop][0]); + $test = $testClass . '::' . $analyzer->nodes[$hop][2]; + $unitTestSuggestions[$gap['class']][$test] ??= [ + 'test' => $test, + 'class' => $testClass, + 'createWith' => $report->factoryMethodCreating($testClass), + 'reachedFrom' => [], + ]; + $unitTestSuggestions[$gap['class']][$test]['reachedFrom'][] = Kernel::base($analyzer->nodes[$entry][0]) . '::' . $analyzer->nodes[$entry][2]; + } + } + + if (($options['why'] ?? null) === $gap['class']) { + fwrite(STDERR, sprintf("\n--why %s: %d graph nodes of this class, %d entry points\n", $gap['class'], count(array_filter(array_keys($visited), static fn ($k) => $visited[$k] === null)), count($found))); + foreach (array_keys($found) as $entry) { + $path = []; + for ($key = $entry; $key !== null; $key = $visited[$key]) { + $path[] = $report->nodeLabel($key); + } + fwrite(STDERR, ' ' . implode("\n → ", $path) . "\n"); + } + } + } +} + +// --------------------------------------------------------------------------------------------------------------------- + +$printClass = static function (array $gap) use ($report, $analyzer, $entriesByClass, $unitTestSuggestions, $options, $unused): void { + $deadMethods = array_flip($unused[$gap['class']] ?? []); + $total = count($gap['methods']); + $marker = $gap['untested'] ? '✗' : '◐'; + echo " $marker {$gap['class']}" . ($gap['untested'] ? '' : sprintf(' (%d/%d methods tested)', $total - count($gap['missing']), $total)) . "\n"; + echo " file: {$gap['file']}\n"; + if ($gap['core'] !== null) { + echo " extends: {$gap['core']}\n"; + } + echo ' untested: ' . implode(', ', array_map(static fn (string $m): string => "$m()" . (isset($deadMethods[$m]) ? ' [unused]' : ''), $gap['missing'])) . "\n"; + if (!array_diff($gap['missing'], array_keys($deadMethods))) { + echo " test via: — unused in production code: delete instead of testing (see section 4)\n"; + + return; + } + if (isset($options['no-entries'])) { + return; + } + $entries = $entriesByClass[$gap['class']] ?? []; + if ($entries === []) { + echo " test via: — no entry point found (not created by a factory/DP reachable from the module API: dead code or wired dynamically)\n"; + + return; + } + if (isset($unitTestSuggestions[$gap['class']])) { + foreach (array_values($unitTestSuggestions[$gap['class']]) as $index => $suggestion) { + echo $index === 0 ? ' test via: ' : ' '; + echo $suggestion['class'] === $gap['class'] + ? 'unit test of this class: ' . $report->short($suggestion['class']) . '::' . substr($suggestion['test'], strrpos($suggestion['test'], ':') + 1) . "()\n" + : 'unit test of ' . $report->short($suggestion['class']) . '::' . substr($suggestion['test'], strrpos($suggestion['test'], ':') + 1) . "() — it runs this class\n"; + if ($suggestion['createWith'] !== null) { + echo " create it with {$suggestion['createWith']}\n"; + } + $controllers = array_map(static fn (string $action): string => $report->short(substr($action, 0, strpos($action, '::'))) . substr($action, strpos($action, '::')) . '()', array_unique($suggestion['reachedFrom'])); + echo ' reached over HTTP from ' . implode(', ', $controllers) . "\n"; + } + printf(" (an HTTP test - %s - also covers it, but HTTP tests are not counted by this script)\n", $gap['layer'] === 'Glue' ? 'Glue API Cest, Cypress' : 'Yves acceptance Cest, Cypress'); + + return; + } + $lines = []; + $direct = false; + foreach ($entries as $entry) { + if (Kernel::base($analyzer->nodes[$entry][0]) === $gap['class']) { + $direct = true; + + continue; + } + $lines[] = $report->nodeLabel($entry); + } + if ($direct) { + $registrations = $report->registrationsOf($gap['class']); + array_unshift($lines, 'directly (public API of this class)' . ($registrations ? '; registered in ' . implode(', ', $registrations) : '')); + } + foreach (array_slice($lines, 0, 4) as $index => $line) { + echo ($index === 0 ? ' test via: ' : ' ') . $line . "\n"; + } + if (count($lines) > 4) { + echo ' … +' . (count($lines) - 4) . " more\n"; + } +}; + +$printSection = static function (string $title, array $items) use ($printClass): void { + $untested = count(array_filter($items, static fn (array $g): bool => $g['untested'])); + echo "\n" . str_repeat('=', 100) . "\n"; + printf("%s — %d without any test, %d partially tested\n", $title, $untested, count($items) - $untested); + echo str_repeat('=', 100) . "\n"; + $currentModule = null; + usort($items, static fn (array $a, array $b): int => [$a['layer'], $a['module'], !$a['untested'], $a['class']] <=> [$b['layer'], $b['module'], !$b['untested'], $b['class']]); + foreach ($items as $item) { + if ($currentModule !== $item['layer'] . '/' . $item['module']) { + $currentModule = $item['layer'] . '/' . $item['module']; + echo "\n$currentModule\n"; + } + $printClass($item); + } +}; + +$projectGaps = array_values(array_filter($gaps, static fn (array $g): bool => $g['core'] === null)); +$extendedGaps = array_values(array_filter($gaps, static fn (array $g): bool => $g['core'] !== null)); + +if (isset($options['json'])) { + $label = static fn (string $key): string => Kernel::base($analyzer->nodes[$key][0]) . '::' . $analyzer->nodes[$key][2]; + $result = [ + 'projectOrgs' => $kernel->projectOrgs, + 'ignoredLayers' => $skipLayers, + 'summary' => [ + 'classes' => count($classes), + 'methods' => $allMethods = array_sum(array_map(static fn (array $c): int => count($withoutSkipped($c)), $classes)), + 'testedMethods' => $allMethods - array_sum(array_map(static fn (array $g): int => count($g['missing']), $gaps)), + 'hiddenUnusedMethods' => $hiddenUnused, + ], + 'gaps' => [], + 'entryPoints' => [], + 'unused' => [], + 'coveredByDelegates' => array_map('array_keys', $coveredByDelegates), + 'skippedStubOnly' => $skippedByReason(SkipRules::REASON_STUB_ONLY), + 'skipped' => $skipped, + ]; + foreach ($gaps as $gap) { + $entries = $entriesByClass[$gap['class']] ?? []; + $result['gaps'][$gap['class']] = [ + 'section' => $gap['core'] === null ? 'project' : 'core-extended', + 'core' => $gap['core'], + 'file' => $gap['file'], + 'untested' => $gap['untested'], + 'missing' => $gap['missing'], + 'unusedMissing' => array_values(array_intersect($gap['missing'], $unused[$gap['class']] ?? [])), + 'testVia' => array_values(array_unique(array_map($label, $entries))), + 'suggestedUnitTests' => array_map(static fn (array $s): array => [ + 'test' => $s['test'], + 'createWith' => $s['createWith'], + 'reachedFrom' => array_values(array_unique($s['reachedFrom'])), + ], array_values($unitTestSuggestions[$gap['class']] ?? [])), + ]; + if ($gap['core'] !== null) { + foreach ($entries as $entry) { + $result['entryPoints'][$label($entry)][] = $gap['class']; + } + } + } + $classInfo = array_column($classes, null, 'class'); + foreach ($unused as $class => $dead) { + $result['unused'][$class] = [ + 'methods' => $dead, + 'testsOnly' => array_values(array_filter($dead, static fn (string $m): bool => isset($tested[$class][$m]))), + 'wholeClass' => count($dead) === count($classInfo[$class]['allMethods']), + ]; + } + echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR) . "\n"; + exit(0); +} + +$printSection('1. Project classes', $projectGaps); +$printSection('2. Classes extending core', $extendedGaps); + +if (!isset($options['no-entries'])) { + $byEntry = []; + foreach ($extendedGaps as $gap) { + foreach ($entriesByClass[$gap['class']] ?? [] as $entry) { + $byEntry[$entry][] = $gap['class']; + } + } + uksort($byEntry, static fn (string $a, string $b): int => count($byEntry[$b]) <=> count($byEntry[$a]) ?: strcmp($a, $b)); + + echo "\n" . str_repeat('=', 100) . "\n"; + printf("3. Core entry points that execute the untested overrides — %d entry points\n", count($byEntry)); + echo str_repeat('=', 100) . "\n"; + foreach ($byEntry as $entry => $covered) { + [$runtime, , $method] = $analyzer->nodes[$entry]; + $runtime = Kernel::base($runtime); + echo "\n → " . $runtime . '::' . $method . "()\n"; + foreach ($covered as $class) { + echo " covers: $class\n"; + } + if (preg_match('/(Facade|Client|Service)$/', $runtime)) { + $plugins = $report->pluginsCalling($runtime, $method); + foreach (array_slice($plugins, 0, 3) as $plugin) { + echo " plugin: $plugin\n"; + } + if (count($plugins) > 3) { + echo ' … +' . (count($plugins) - 3) . " more plugins\n"; + } + } + } +} + +if (!isset($options['no-unused']) && !isset($options['hide-unused'])) { + $classInfo = array_column($classes, null, 'class'); + $wholeClasses = count(array_filter($unused, static fn (array $dead, string $class): bool => count($dead) === count($classInfo[$class]['allMethods']), ARRAY_FILTER_USE_BOTH)); + echo "\n" . str_repeat('=', 100) . "\n"; + printf("4. Unused code — %d methods in %d classes have no caller in production code (%d whole classes)\n", array_sum(array_map('count', $unused)), count($unused), $wholeClasses); + echo " [tests only] = called only from tests; the test keeps dead code alive\n"; + echo str_repeat('=', 100) . "\n"; + $currentModule = null; + foreach ($unused as $class => $dead) { + $info = $classInfo[$class]; + if ($currentModule !== $info['layer'] . '/' . $info['module']) { + $currentModule = $info['layer'] . '/' . $info['module']; + echo "\n$currentModule\n"; + } + $whole = count($dead) === count($info['allMethods']); + echo " ✗ $class" . ($whole ? ' (whole class unused)' : '') . "\n"; + echo " file: {$info['file']}\n"; + echo ' unused: ' . implode(', ', array_map(static fn (string $m): string => "$m()" . (isset($tested[$class][$m]) ? ' [tests only]' : ''), $dead)) . "\n"; + } +} + +$allMethods = array_sum(array_map(static fn (array $c): int => count($withoutSkipped($c)), $classes)); +$missingMethods = array_sum(array_map(static fn (array $g): int => count($g['missing']), $gaps)); +echo "\n" . str_repeat('-', 100) . "\n"; +printf( + "Summary: %d classes / %d methods in scope; %d methods reached by tests (%.1f%%).\n" + . " Project: %d untested, %d partial. Core-extended: %d untested, %d partial.\n" + . (isset($options['hide-unused']) + ? sprintf(" Unused in production code: %d methods hidden and not counted (--hide-unused).\n", $hiddenUnused) + : sprintf(" Unused in production code: %d methods in %d classes.\n", array_sum(array_map('count', $unused)), count($unused))) + . " Thin plugins counted as covered via their tested delegates: %d methods in %d plugins.\n" + . " Skipped (not listed, not counted): %d methods in %d classes.\n", + count($classes), + $allMethods, + $allMethods - $missingMethods, + $allMethods ? ($allMethods - $missingMethods) / $allMethods * 100 : 0, + count(array_filter($projectGaps, static fn (array $g): bool => $g['untested'])), + count(array_filter($projectGaps, static fn (array $g): bool => !$g['untested'])), + count(array_filter($extendedGaps, static fn (array $g): bool => $g['untested'])), + count(array_filter($extendedGaps, static fn (array $g): bool => !$g['untested'])), + array_sum(array_map('count', $coveredByDelegates)), + count($coveredByDelegates), + array_sum(array_map('count', $skipped)), + count($skipped), +); +if ($coveredByDelegates !== []) { + echo " Covered via tested delegates (thin plugins):\n"; + foreach ($coveredByDelegates as $plugin => $methods) { + echo " - $plugin::" . implode('(), ', array_keys($methods)) . "()\n"; + } +} +foreach ([SkipRules::REASON_BOOTSTRAP, SkipRules::REASON_ROUTING, SkipRules::REASON_STUB_ONLY, SkipRules::REASON_UI, SkipRules::REASON_DECLARATIVE] as $reason) { + $classesByReason = $skippedByReason($reason); + if ($classesByReason === []) { + continue; + } + printf(" Skipped — %s: %d methods in %d classes\n", $reason, array_sum(array_map('count', $classesByReason)), count($classesByReason)); + if (!isset($options['show-skipped'])) { + continue; + } + foreach ($classesByReason as $class => $methods) { + echo " - $class::" . implode('(), ', $methods) . "()\n"; + } +} +if ($skipped !== [] && !isset($options['show-skipped'])) { + echo " Use --show-skipped to list the skipped methods.\n"; +} +if ($skipLayers !== []) { + echo ' Ignored layers: ' . implode(', ', $skipLayers) . " (not reported, not production callers, not entry points).\n"; +} +echo "Note: static analysis — HTTP tests (Glue Cest, Cypress) and dynamically resolved calls are not followed.\n"; diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/CoverageGapsTest.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/CoverageGapsTest.php new file mode 100644 index 0000000..391b10f --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/CoverageGapsTest.php @@ -0,0 +1,638 @@ += 10 (attributes) in addition to the script's requirements (see ../coverage-gaps.md). + */ + +declare(strict_types=1); + +namespace PyzTest\Tools\CoverageGaps; + +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\TestCase; + +final class CoverageGapsTest extends TestCase +{ + private const SCRIPT = __DIR__ . '/../coverage-gaps.php'; + + private const FIXTURE = __DIR__ . '/fixture'; + + private const FACADE = 'Example\Zed\Gizmo\Business\GizmoFacade'; + + private const MODEL = 'Example\Zed\Gizmo\Business\Model\\'; + + private const PLUGIN = 'Example\Zed\Gizmo\Communication\Plugin\\'; + + private const FORM = 'Example\Zed\Gizmo\Communication\Form\GizmoForm'; + + private const TABLE = 'Example\Zed\Gizmo\Communication\Table\GizmoTable'; + + private const REASON_DECLARATIVE = 'declarative: only returns constant data'; + + private const REASON_UI = 'form/table definition (--skip-ui-definitions)'; + + /** + * @var array + */ + private static array $runs = []; + + public function testGivenSrcDirsWhenScanningThenEveryProjectDirIsAnalysedAndGeneratedOrmConfigAreSkipped(): void + { + $result = $this->runJson(); + + $this->assertSame(['Example', 'ExampleExtra'], $result['projectOrgs']); + $this->assertArrayHasKey('ExampleExtra\Zed\Extra\Business\ExtraFacade', $result['gaps']); + $this->assertSame([], array_filter(array_keys($result['gaps']), static fn (string $class): bool => str_starts_with($class, 'Generated\\'))); + } + + public function testGivenInfrastructureFilesWhenScanningThenFactoriesProvidersStubsControllersInterfacesAndAbstractsAreNotReported(): void + { + $result = $this->runJson(); + + $reported = array_merge(array_keys($result['gaps']), array_keys($result['unused'])); + $this->assertSame([], preg_grep('/(Factory|DependencyProvider|Stub|Controller|Interface|AbstractGreeter)$/', $reported)); + } + + public function testGivenFacadeTestWhenAnalysingThenOnlyFacadeMethodsWithoutTestAreMissing(): void + { + $gap = $this->runJson()['gaps'][self::FACADE]; + + $this->assertFalse($gap['untested']); + $this->assertEqualsCanonicalizing(['format', 'runOtherSteps', 'addItems'], $gap['missing']); + } + + /** + * @return array + */ + public static function provideIndirectlyTestedClasses(): array + { + return [ + 'constructor dependency (promoted property)' => [self::MODEL . 'Rounder'], + 'object configured by a setter in the tested factory method' => [self::MODEL . 'DefaultStep'], + 'plugin stack from the DependencyProvider' => [self::PLUGIN . 'GizmoExpanderPlugin'], + 'template method called from the abstract parent' => [self::MODEL . 'HelloGreeter'], + 'thin plugin delegating to tested code' => [self::PLUGIN . 'CalculatorItemExpanderPlugin'], + ]; + } + + #[DataProvider('provideIndirectlyTestedClasses')] + public function testGivenClassReachedFromATestWhenAnalysingThenItIsNotReported(string $class): void + { + $this->assertArrayNotHasKey($class, $this->runJson()['gaps']); + } + + /** + * @return array}> + */ + public static function provideCountedMethods(): array + { + return [ + 'pure protected helper is not counted' => [self::MODEL . 'Formatter', ['format']], + 'protected override of a core method is counted' => ['Example\Zed\Gizmo\Communication\Console\GizmoConsole', ['execute']], + 'protected implementations of abstract parent methods are counted' => [self::TABLE, ['configure', 'prepareData']], + ]; + } + + /** + * @param list $missing + */ + #[DataProvider('provideCountedMethods')] + public function testGivenNonPublicMethodsWhenCountingThenOnlyOverridesAreCounted(string $class, array $missing): void + { + $this->assertEqualsCanonicalizing($missing, $this->runJson()['gaps'][$class]['missing']); + } + + public function testGivenModelWithOneUnreachedMethodWhenAnalysingThenOnlyThatMethodIsMissing(): void + { + $gap = $this->runJson()['gaps'][self::MODEL . 'Calculator']; + + $this->assertFalse($gap['untested']); + $this->assertSame(['unusedHelper'], $gap['missing']); + $this->assertSame(['unusedHelper'], $gap['unusedMissing']); + } + + /** + * @return array + */ + public static function provideUntestedClassesWithEntryPoint(): array + { + return [ + 'only a mock is used in the test' => [self::MODEL . 'Formatter', self::FACADE . '::format'], + 'same importer class, but set up by an untested factory method' => [self::MODEL . 'OtherStep', self::FACADE . '::runOtherSteps'], + ]; + } + + #[DataProvider('provideUntestedClassesWithEntryPoint')] + public function testGivenUntestedClassWhenAnalysingThenItIsReportedWithTheFacadeMethodToTestItThrough(string $class, string $entryPoint): void + { + $gap = $this->runJson()['gaps'][$class]; + + $this->assertSame('project', $gap['section']); + $this->assertTrue($gap['untested']); + $this->assertSame([$entryPoint], $gap['testVia']); + } + + /** + * @return array + */ + public static function provideGlueClassesReachedOnlyOverHttp(): array + { + return [ + 'class called by the controller' => ['Example\Glue\GizmosRestApi\Processor\GizmoProcessor'], + 'class behind it' => ['Example\Glue\GizmosRestApi\Mapper\GizmoMapper'], + ]; + } + + #[DataProvider('provideGlueClassesReachedOnlyOverHttp')] + public function testGivenGlueClassReachedOnlyFromControllerWhenAnalysingThenUnitTestOfTheControllerCalleeIsSuggested(string $class): void + { + $this->assertSame( + [[ + 'test' => 'Example\Glue\GizmosRestApi\Processor\GizmoProcessor::process', + 'createWith' => 'GizmosRestApiFactory::createGizmoProcessor()', + 'reachedFrom' => ['Example\Glue\GizmosRestApi\Controller\GizmosResourceController::getAction'], + ]], + $this->runJson()['gaps'][$class]['suggestedUnitTests'], + ); + } + + public function testGivenZedClassWithFacadeEntryPointWhenAnalysingThenNoUnitTestSuggestionIsMade(): void + { + $this->assertSame([], $this->runJson()['gaps'][self::MODEL . 'Formatter']['suggestedUnitTests']); + } + + public function testGivenUntestedClassExtendingCoreWhenAnalysingThenItIsInCoreSectionWithCoreParentAndEntryPoint(): void + { + $result = $this->runJson(); + $class = self::MODEL . 'ExtendedStorageProvider'; + + $this->assertSame('core-extended', $result['gaps'][$class]['section']); + $this->assertSame('Spryker\Zed\Cart\Business\StorageProvider\NonPersistentProvider', $result['gaps'][$class]['core']); + $this->assertSame([self::FACADE . '::addItems'], $result['gaps'][$class]['testVia']); + $this->assertSame([$class], $result['entryPoints'][self::FACADE . '::addItems']); + } + + public function testGivenThinPluginDelegatingToTestedCodeWhenAnalysingThenItIsCountedAsCoveredByDelegates(): void + { + $this->assertSame( + [self::PLUGIN . 'CalculatorItemExpanderPlugin' => ['expandItems']], + $this->runJson()['coveredByDelegates'], + ); + } + + /** + * @return array + */ + public static function provideNotDelegateCoveredPlugins(): array + { + return [ + 'thin plugin, but the delegate is untested' => [self::PLUGIN . 'FormatterItemExpanderPlugin'], + 'delegate is tested, but the plugin has own logic' => [self::PLUGIN . 'ConditionalItemExpanderPlugin'], + ]; + } + + #[DataProvider('provideNotDelegateCoveredPlugins')] + public function testGivenPluginNotQualifyingAsThinDelegateWhenAnalysingThenItStaysReported(string $plugin): void + { + $this->assertSame(['expandItems'], $this->runJson()['gaps'][$plugin]['missing']); + } + + public function testGivenClientMethodOnlyCallingZedStubWhenAnalysingThenItIsSkippedAndOtherClientMethodsStay(): void + { + $result = $this->runJson(); + + $this->assertSame(['Example\Client\Gizmo\GizmoClient' => ['getRemoteGizmo']], $result['skippedStubOnly']); + $this->assertSame(['getRemoteGizmo' => 'client method only calls a Zed stub'], $result['skipped']['Example\Client\Gizmo\GizmoClient']); + $this->assertSame(['readLocal'], $result['gaps']['Example\Client\Gizmo\GizmoClient']['missing']); + } + + /** + * @return array}> + */ + public static function provideSkippedClasses(): array + { + return [ + 'Glue resource route plugin' => [ + 'Example\Glue\GizmosRestApi\Plugin\GizmosResourceRoutePlugin', + 'routing/resource configuration plugin', + ['configure', 'getResourceType', 'getController', 'getResourceAttributesClassName'], + ], + 'Yves route provider plugin' => ['Example\Yves\GizmoPage\Plugin\Router\GizmoPageRouteProviderPlugin', 'routing/resource configuration plugin', ['addRoutes']], + 'application bootstrap' => ['Example\Glue\GizmoApplication\Bootstrap\GizmoBootstrap', 'application bootstrap', ['boot']], + ]; + } + + /** + * @param list $methods + */ + #[DataProvider('provideSkippedClasses')] + public function testGivenConfigurationOnlyClassWhenAnalysingThenAllItsMethodsAreSkipped(string $class, string $reason, array $methods): void + { + $result = $this->runJson(); + + $this->assertArrayNotHasKey($class, $result['gaps']); + $this->assertSame(array_fill_keys($methods, $reason), $result['skipped'][$class]); + } + + public function testGivenDeclarativeMethodsWhenAnalysingThenOnlyThoseAreSkippedAndLogicStaysReported(): void + { + $result = $this->runJson(); + $class = self::MODEL . 'MandatoryColumns'; + + $this->assertSame(['getMandatoryColumns' => self::REASON_DECLARATIVE, 'getDefaultQuote' => self::REASON_DECLARATIVE], $result['skipped'][$class]); + $this->assertSame(['isSatisfiedBy'], $result['gaps'][$class]['missing']); + } + + /** + * @return array, array}> + */ + public static function provideUiDefinitions(): array + { + return [ + 'form, default' => ['', ['buildForm', 'addNameField', 'addTypeField', 'normalizeName'], ['getBlockPrefix' => self::REASON_DECLARATIVE]], + 'form, --skip-ui-definitions' => [ + '--skip-ui-definitions', + ['addTypeField', 'normalizeName'], + ['buildForm' => self::REASON_UI, 'getBlockPrefix' => self::REASON_UI, 'addNameField' => self::REASON_UI], + ], + ]; + } + + /** + * @param list $missing + * @param array $skipped + */ + #[DataProvider('provideUiDefinitions')] + public function testGivenFormWhenAnalysingThenFieldDefinitionsAreSkippedOnlyWithTheFlag(string $flag, array $missing, array $skipped): void + { + $result = $flag === '' ? $this->runJson() : $this->runJson($flag); + + $this->assertEqualsCanonicalizing($missing, $result['gaps'][self::FORM]['missing']); + $this->assertEqualsCanonicalizing($skipped, $result['skipped'][self::FORM]); + } + + public function testGivenFormExpanderPluginWhenAnalysingThenWholeClassIsSkippedOnlyWithTheFlag(): void + { + $class = self::PLUGIN . 'GizmoProductAbstractFormExpanderPlugin'; + + $this->assertSame(['expand'], $this->runJson()['gaps'][$class]['missing']); + $this->assertArrayNotHasKey($class, $this->runJson('--skip-ui-definitions')['gaps']); + $this->assertSame(['expand' => self::REASON_UI], $this->runJson('--skip-ui-definitions')['skipped'][$class]); + } + + public function testGivenFormDataProviderExpanderPluginWhenSkippingUiDefinitionsThenItStaysReported(): void + { + $class = self::PLUGIN . 'GizmoProductAbstractFormDataProviderExpanderPlugin'; + + $this->assertSame(['expand'], $this->runJson('--skip-ui-definitions')['gaps'][$class]['missing']); + $this->assertArrayNotHasKey($class, $this->runJson('--skip-ui-definitions')['skipped']); + } + + public function testGivenGuiTableWhenAnalysingThenConfigureIsSkippedOnlyWithTheFlag(): void + { + $default = $this->runJson(); + $withFlag = $this->runJson('--skip-ui-definitions'); + + $this->assertEqualsCanonicalizing(['configure', 'prepareData'], $default['gaps'][self::TABLE]['missing']); + $this->assertSame(['prepareData'], $withFlag['gaps'][self::TABLE]['missing']); + $this->assertSame(['configure' => self::REASON_UI], $withFlag['skipped'][self::TABLE]); + } + + /** + * @return array, list, bool}> + */ + public static function provideUnusedCode(): array + { + return [ + 'class referenced nowhere' => [self::MODEL . 'Orphan', ['doNothing'], [], true], + 'methods called nowhere, protected included' => [self::MODEL . 'Calculator', ['unusedHelper', 'unusedProtected'], [], false], + 'facade method called only by tests' => [self::FACADE, ['legacyOnlyInTests'], ['legacyOnlyInTests'], false], + 'class reachable only from a tests-only method' => [self::MODEL . 'Legacy', ['run'], ['run'], true], + ]; + } + + /** + * @param list $methods + * @param list $testsOnly + */ + #[DataProvider('provideUnusedCode')] + public function testGivenCodeWithoutProductionCallerWhenAnalysingThenItIsReportedAsUnused(string $class, array $methods, array $testsOnly, bool $wholeClass): void + { + $this->assertSame( + ['methods' => $methods, 'testsOnly' => $testsOnly, 'wholeClass' => $wholeClass], + $this->runJson()['unused'][$class], + ); + } + + /** + * @return array + */ + public static function provideLiveClasses(): array + { + return [ + 'plugin implementing a core interface' => [self::PLUGIN . 'FormatterItemExpanderPlugin'], + 'console command (framework calls execute)' => ['Example\Zed\Gizmo\Communication\Console\GizmoConsole'], + 'plugin from a project plugin stack' => [self::PLUGIN . 'GizmoExpanderPlugin'], + 'step added by a factory method' => [self::MODEL . 'OtherStep'], + 'template method implementation' => [self::MODEL . 'HelloGreeter'], + 'core override used by a controller' => [self::MODEL . 'ExtendedStorageProvider'], + ]; + } + + #[DataProvider('provideLiveClasses')] + public function testGivenCodeCalledInProductionWhenAnalysingThenItIsNotReportedAsUnused(string $class): void + { + $this->assertArrayNotHasKey($class, $this->runJson()['unused']); + } + + public function testGivenHideUnusedFlagWhenAnalysingThenUnusedCodeIsNeitherListedNorCounted(): void + { + $default = $this->runJson(); + $hidden = $this->runJson('--hide-unused'); + $unusedMethodCount = array_sum(array_map(static fn (array $u): int => count($u['methods']), $default['unused'])); + + $this->assertSame([], $hidden['unused']); + $this->assertArrayNotHasKey(self::MODEL . 'Orphan', $hidden['gaps']); + $this->assertArrayNotHasKey(self::MODEL . 'Calculator', $hidden['gaps']); + $this->assertArrayHasKey(self::MODEL . 'Formatter', $hidden['gaps']); + $this->assertSame($unusedMethodCount, $hidden['summary']['hiddenUnusedMethods']); + $this->assertLessThan($default['summary']['methods'], $hidden['summary']['methods']); + } + + public function testGivenNoUnusedFlagWhenAnalysingThenUnusedDetectionIsSkipped(): void + { + $result = $this->runJson('--no-unused'); + + $this->assertSame([], $result['unused']); + $this->assertSame([], $result['gaps'][self::MODEL . 'Calculator']['unusedMissing']); + } + + public function testGivenOnlyUntestedFlagWhenAnalysingThenPartiallyTestedClassesAreHidden(): void + { + $gaps = $this->runJson('--only-untested')['gaps']; + + $this->assertArrayNotHasKey(self::FACADE, $gaps); + $this->assertArrayNotHasKey(self::MODEL . 'Calculator', $gaps); + $this->assertArrayHasKey(self::MODEL . 'Formatter', $gaps); + } + + public function testGivenNoEntriesFlagWhenAnalysingThenNoEntryPointsAreResolved(): void + { + $result = $this->runJson('--no-entries'); + + $this->assertSame([], $result['entryPoints']); + $this->assertSame([], array_merge(...array_column(array_values($result['gaps']), 'testVia'))); + } + + /** + * @return array}> + */ + public static function provideFilters(): array + { + return [ + 'module' => ['--module=Extra', ['ExampleExtra\Zed\Extra\Business\ExtraFacade']], + 'layer' => ['--layer=Client', ['Example\Client\Gizmo\GizmoClient', 'Example\Client\Gizmo\Reader\LocalReader']], + ]; + } + + /** + * @param list $expectedClasses + */ + #[DataProvider('provideFilters')] + public function testGivenFilterFlagWhenAnalysingThenOnlyMatchingClassesAreReported(string $flag, array $expectedClasses): void + { + $this->assertEqualsCanonicalizing($expectedClasses, array_keys($this->runJson($flag)['gaps'])); + } + + /** + * @return array}> + */ + public static function provideSkipLayerFlags(): array + { + return [ + 'comma-separated' => [['--skip-layer=Yves,Glue']], + 'repeated, any case' => [['--skip-layer=yves', '--skip-layer=GLUE']], + ]; + } + + /** + * @param list $flags + */ + #[DataProvider('provideSkipLayerFlags')] + public function testGivenSkippedLayersWhenAnalysingThenTheirClassesAreNotReported(array $flags): void + { + $result = $this->runJson(...$flags); + + $this->assertSame(['Yves', 'Glue'], $result['ignoredLayers']); + $reported = array_merge(array_keys($result['gaps']), array_keys($result['unused']), array_keys($result['skipped'])); + $this->assertSame([], preg_grep('/^Example\\\\(Yves|Glue)\\\\/', $reported)); + $this->assertArrayHasKey(self::MODEL . 'Formatter', $result['gaps']); + } + + public function testGivenCodeCalledOnlyFromASkippedLayerWhenAnalysingThenItBecomesUnused(): void + { + $default = $this->runJson(); + $withoutYves = $this->runJson('--skip-layer=Yves,Glue'); + + $this->assertArrayNotHasKey('Example\Client\Gizmo\Reader\LocalReader', $default['unused']); + $this->assertSame(['read'], $withoutYves['unused']['Example\Client\Gizmo\Reader\LocalReader']['methods']); + $this->assertContains('readLocal', $withoutYves['unused']['Example\Client\Gizmo\GizmoClient']['methods']); + } + + public function testGivenUnknownLayerWhenRunningThenItFails(): void + { + $result = $this->runScript(['--root=' . self::FIXTURE, '--skip-layer=Frontend']); + + $this->assertSame(1, $result['exitCode']); + $this->assertStringContainsString("unknown layer 'Frontend'", $result['stderr']); + } + + public function testGivenDefaultFlagsWhenPrintingTextReportThenAllSectionsAndRuleListsArePrinted(): void + { + $output = $this->runReport()['stdout']; + + $expectedLines = [ + '1. Project classes', '2. Classes extending core', '3. Core entry points', '4. Unused code', 'delete instead of testing', + 'Covered via tested delegates (thin plugins)', 'Skipped — application bootstrap', 'Skipped — routing/resource configuration plugin', + 'Skipped — client method only calls a Zed stub', 'Skipped — declarative: only returns constant data', + 'unit test of this class: Example\Glue\GizmosRestApi\…\GizmoProcessor::process()', + 'unit test of Example\Glue\GizmosRestApi\…\GizmoProcessor::process() — it runs this class', + 'create it with GizmosRestApiFactory::createGizmoProcessor()', + 'reached over HTTP from Example\Glue\GizmosRestApi\…\GizmosResourceController::getAction()', + '(an HTTP test - Glue API Cest, Cypress - also covers it, but HTTP tests are not counted by this script)', + ]; + foreach ($expectedLines as $expected) { + $this->assertStringContainsString($expected, $output); + } + } + + public function testGivenDefaultFlagsWhenPrintingTextReportThenSkippedMethodsAreOnlyCounted(): void + { + $output = $this->runReport()['stdout']; + + $this->assertStringContainsString('Skipped — application bootstrap: 1 methods in 1 classes', $output); + $this->assertStringContainsString('Use --show-skipped to list the skipped methods.', $output); + $this->assertStringNotContainsString('GizmoBootstrap::boot()', $output); + } + + public function testGivenShowSkippedFlagWhenPrintingTextReportThenSkippedMethodsAreListed(): void + { + $output = $this->runReport('--show-skipped')['stdout']; + + $this->assertStringContainsString('- Example\Glue\GizmoApplication\Bootstrap\GizmoBootstrap::boot()', $output); + $this->assertStringContainsString('- Example\Client\Gizmo\GizmoClient::getRemoteGizmo()', $output); + $this->assertStringNotContainsString('Use --show-skipped', $output); + } + + public function testGivenWhyFlagWhenAnalysingThenCallPathFromEntryPointIsPrinted(): void + { + $stderr = $this->runReport('--why=Example/Zed/Gizmo/Business/Model/OtherStep')['stderr']; + + $this->assertMatchesRegularExpression('/GizmoFacade::runOtherSteps\(\)\s+→ .*StepImporter::import\(\)\s+→ .*OtherStep::execute\(\)/s', $stderr); + } + + /** + * @return array}> + */ + public static function provideMissingRequirements(): array + { + return [ + 'composer dependencies not installed' => [null, ['Composer dependencies are not installed', 'Run: composer install']], + 'php-parser not installed' => [' [ + ' $expectedMessages + */ + #[DataProvider('provideMissingRequirements')] + public function testGivenMissingRequirementWhenRunningThenItExitsWithInstallInstructions(?string $autoloadContent, array $expectedMessages): void + { + $projectDir = sys_get_temp_dir() . '/coverage-gaps-requirements-' . bin2hex(random_bytes(4)); + mkdir($projectDir, 0777, true); + file_put_contents($projectDir . '/composer.json', '{}'); + if ($autoloadContent !== null) { + mkdir($projectDir . '/vendor'); + file_put_contents($projectDir . '/vendor/autoload.php', $autoloadContent); + } + + $result = $this->runScript([], $projectDir); + array_map('unlink', array_filter([$projectDir . '/composer.json', $projectDir . '/vendor/autoload.php'], 'is_file')); + array_map('rmdir', array_filter([$projectDir . '/vendor', $projectDir], 'is_dir')); + + $this->assertSame(2, $result['exitCode']); + $this->assertStringContainsString('requirements not met', $result['stderr']); + foreach ($expectedMessages as $expectedMessage) { + $this->assertStringContainsString($expectedMessage, $result['stderr']); + } + } + + public function testGivenWorkingDirectoryOutsideAProjectWhenRunningThenItExitsWithoutUsingItsOwnLocation(): void + { + $process = proc_open( + [PHP_BINARY, self::SCRIPT], + [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], + $pipes, + sys_get_temp_dir(), + array_diff_key(getenv(), ['SPRYKER_PROJECT_ROOT' => true]), + ); + fclose($pipes[1]); + $stderr = (string)stream_get_contents($pipes[2]); + fclose($pipes[2]); + + $this->assertSame(2, proc_close($process)); + $this->assertStringContainsString('Could not find a Spryker project root', $stderr); + } + + public function testGivenSeveralTestNamespacesWhenAnalysingThenEveryTestsOrgTestDirectoryIsRead(): void + { + $stderr = $this->runReport('--json')['stderr']; + + $this->assertStringContainsString('Following calls from tests/{ExampleTest,PyzTest}', $stderr); + $this->assertStringContainsString('2 test classes', $stderr); + } + + public function testGivenRootWithoutSrcWhenRunningThenItFails(): void + { + $result = $this->runScript(['--root=' . __DIR__]); + + $this->assertSame(1, $result['exitCode']); + $this->assertStringContainsString('no src/ directory', $result['stderr']); + } + + /** + * @return array + */ + private function runJson(string ...$flags): array + { + $result = $this->runReport('--json', ...$flags); + + return json_decode($result['stdout'], true, 512, JSON_THROW_ON_ERROR); + } + + /** + * @return array{stdout: string, stderr: string, exitCode: int} + */ + private function runReport(string ...$flags): array + { + $key = implode(' ', $flags); + if (!isset(self::$runs[$key])) { + self::$runs[$key] = $this->runScript(['--root=' . self::FIXTURE, ...$flags]); + $this->assertSame(0, self::$runs[$key]['exitCode'], self::$runs[$key]['stderr']); + } + + return self::$runs[$key]; + } + + /** + * The directory whose vendor/ the script loads: SPRYKER_PROJECT_ROOT when set, otherwise the nearest ancestor of + * this file with composer.json and vendor/autoload.php. + */ + private static function projectRoot(): string + { + $explicit = getenv('SPRYKER_PROJECT_ROOT'); + if (is_string($explicit) && $explicit !== '') { + return $explicit; + } + $dir = __DIR__; + while (!is_file($dir . '/composer.json') || !is_file($dir . '/vendor/autoload.php')) { + $parent = dirname($dir); + if ($parent === $dir) { + self::fail('No directory with composer.json and vendor/autoload.php above ' . __DIR__ . '; set SPRYKER_PROJECT_ROOT.'); + } + $dir = $parent; + } + + return $dir; + } + + /** + * @param list $arguments + * + * @return array{stdout: string, stderr: string, exitCode: int} + */ + private function runScript(array $arguments, ?string $projectRoot = null): array + { + $environment = ['SPRYKER_PROJECT_ROOT' => $projectRoot ?? self::projectRoot()] + getenv(); + $process = proc_open([PHP_BINARY, self::SCRIPT, ...$arguments], [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, null, $environment); + $stdout = (string)stream_get_contents($pipes[1]); + $stderr = (string)stream_get_contents($pipes[2]); + fclose($pipes[1]); + fclose($pipes[2]); + + return ['stdout' => $stdout, 'stderr' => $stderr, 'exitCode' => proc_close($process)]; + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/README.md b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/README.md new file mode 100644 index 0000000..3555a6c --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/README.md @@ -0,0 +1,62 @@ +# coverage-gaps.php fixture project + +A tiny Spryker-like project used by `../CoverageGapsTest.php`. Every class is an example of one rule of +`../../coverage-gaps.php`. The code is parsed and reflected, never executed. + +Run the analyser on it, from the project root (`$UP` is the `scripts/` directory of the `spryker-upgrade` skill): + +```bash +php $UP/coverage-gaps/coverage-gaps.php --root=$UP/coverage-gaps/coverage-gaps/fixture +``` + +Run the tests: + +```bash +vendor/bin/phpunit --no-configuration $UP/coverage-gaps/coverage-gaps/CoverageGapsTest.php +``` + +## Layout + +| Path | Purpose | +|---|---| +| `src/Example/`, `src/ExampleExtra/` | Two project dirs: every dir in `src/` is project code | +| `src/Generated/` | Ignored, like `Orm` and `SprykerConfig` | +| `tests/PyzTest/Zed/Gizmo/Business/GizmoFacadeTest.php` | The test that sets the expected results; it calls the facade through `$this->tester->getFacade()` | +| `tests/ExampleTest/Zed/Gizmo/Business/GizmoFacadeCalculateTest.php` | A second test namespace: every `tests/Test/` directory is read. It calls a facade method that the first test also calls, so it changes no expected result | + +## Examples + +Classes are in `src/Example/Zed/Gizmo/` unless stated otherwise. + +| Class | Rule | Expected result | +|---|---|---| +| `Business/GizmoFacade` | Facade methods called from the test count as tested | Partial: `format`, `runOtherSteps`, `addItems` missing | +| `Business/Model/Calculator` | Reached via facade → factory → `new Calculator()` | Partial: `unusedHelper` missing and unused; the protected `unusedProtected()` is not counted but is reported as unused | +| `Business/Model/Rounder` | Constructor dependency (promoted property) | Tested | +| `Business/Model/Formatter` | Only a mock (`createMock`) is used in the test; `pad()` is a pure protected helper | Untested, test via `GizmoFacade::format()`; only `format()` is counted | +| `Business/Model/DefaultStep` | `$importer->addStep(...)` in the tested factory method | Tested | +| `Business/Model/OtherStep` | Same `StepImporter` class, but configured by an untested factory method (setter injection is tracked per call site) | Untested, test via `GizmoFacade::runOtherSteps()` | +| `Communication/Plugin/GizmoExpanderPlugin` | Plugin stack resolved via `GizmoDependencyProvider` | Tested | +| `Business/Model/HelloGreeter` | Template method called from the abstract project parent `AbstractGreeter` | Tested, not unused | +| `Business/Model/ExtendedStorageProvider` | Extends core `NonPersistentProvider` | Section 2, entry point `GizmoFacade::addItems()` | +| `Communication/Plugin/CalculatorItemExpanderPlugin` | Thin plugin delegating to tested code | Counted as covered by delegates | +| `Communication/Plugin/FormatterItemExpanderPlugin` | Thin plugin, but the delegate is untested | Reported | +| `Communication/Plugin/ConditionalItemExpanderPlugin` | Delegate is tested, but the plugin has its own logic (`if`) | Reported | +| `src/Example/Client/Gizmo/GizmoClient::getRemoteGizmo()` | Client method that only calls a Zed stub | Skipped | +| `src/Example/Client/Gizmo/GizmoClient::readLocal()` | Client method with a client-side dependency | Reported | +| `Business/Model/Orphan` | Referenced nowhere | Unused, whole class | +| `GizmoFacade::legacyOnlyInTests()` and `Business/Model/Legacy` | Called only by tests | Unused, `[tests only]` | +| `Communication/Console/GizmoConsole` | `execute()` is called by the framework; production caller of the facade | Not unused | +| `Communication/Controller/IndexController` | Controllers are excluded from the report but are production callers | Not reported | +| `*BusinessFactory`, `*DependencyProvider`, `*Stub`, `*Interface` | Infrastructure files | Not reported | +| `Business/Model/MandatoryColumns` | `getMandatoryColumns()` returns an array of constants; `getDefaultQuote()` builds a transfer from constants | Both skipped as declarative; `isSatisfiedBy()` reported | +| `src/Example/Glue/GizmosRestApi/Plugin/GizmosResourceRoutePlugin` | Implements `ResourceRoutePluginInterface` | Whole class skipped (routing) | +| `src/Example/Yves/GizmoPage/Plugin/Router/GizmoPageRouteProviderPlugin` | Implements `RouteProviderPluginInterface` | Whole class skipped (routing) | +| `src/Example/Glue/GizmoApplication/Bootstrap/GizmoBootstrap` | `*Bootstrap` | Whole class skipped | +| `Communication/Form/GizmoForm` | Symfony form | Default: only `getBlockPrefix()` skipped (declarative). With `--skip-ui-definitions`: `buildForm()`, `getBlockPrefix()` and `addNameField()` skipped; `addTypeField()` (has an `if`) and `normalizeName()` stay | +| `src/Example/Glue/GizmosRestApi/Processor/GizmoProcessor` | Reached only from `GizmosResourceController::getAction()` (through a controller helper) | `unit test of this class`, create with `GizmosRestApiFactory::createGizmoProcessor()` | +| `src/Example/Glue/GizmosRestApi/Mapper/GizmoMapper` | Behind the processor | `unit test of GizmoProcessor::process() — it runs this class` | +| `Communication/Plugin/GizmoProductAbstractFormExpanderPlugin` | Form expander plugin (`*FormExpanderPluginInterface`), has a loop and an `if` | Reported by default; whole class skipped with `--skip-ui-definitions` | +| `Communication/Plugin/GizmoProductAbstractFormDataProviderExpanderPlugin` | Form data provider expander (loads data) | Always reported | +| `src/Example/Yves/GizmoPage/Controller/GizmoController` | The only production caller of `GizmoClient::readLocal()` | With `--skip-layer=Yves`, `readLocal()` and `LocalReader` become unused; no `Example\Yves` or `Example\Glue` class is reported | +| `Communication/Table/GizmoTable` | Gui `AbstractTable` | With `--skip-ui-definitions`: `configure()` skipped; `prepareData()` stays | diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Client/Gizmo/GizmoClient.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Client/Gizmo/GizmoClient.php new file mode 100644 index 0000000..9092509 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Client/Gizmo/GizmoClient.php @@ -0,0 +1,23 @@ + skipped (nothing to test client-side). + public function getRemoteGizmo(): string + { + return $this->getFactory()->createGizmoStub()->getRemoteGizmo(); + } + + // Has a real client-side dependency -> listed as untested. + public function readLocal(): string + { + return $this->getFactory()->createLocalReader()->read(); + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Client/Gizmo/GizmoFactory.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Client/Gizmo/GizmoFactory.php new file mode 100644 index 0000000..e195212 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Client/Gizmo/GizmoFactory.php @@ -0,0 +1,20 @@ + whole class skipped. +class GizmoBootstrap +{ + protected float $startedAt = 0.0; + + public function boot(): void + { + $this->startedAt = microtime(true); + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Glue/GizmosRestApi/Controller/GizmosResourceController.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Glue/GizmosRestApi/Controller/GizmosResourceController.php new file mode 100644 index 0000000..349590a --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Glue/GizmosRestApi/Controller/GizmosResourceController.php @@ -0,0 +1,23 @@ +executeGetAction(1); + } + + // A controller helper is skipped on the path: the suggestion is the processor, not this method. + protected function executeGetAction(int $id): array + { + return $this->getFactory()->createGizmoProcessor()->process($id); + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Glue/GizmosRestApi/GizmosRestApiFactory.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Glue/GizmosRestApi/GizmosRestApiFactory.php new file mode 100644 index 0000000..9460d96 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Glue/GizmosRestApi/GizmosRestApiFactory.php @@ -0,0 +1,20 @@ +createGizmoMapper()); + } + + public function createGizmoMapper(): GizmoMapper + { + return new GizmoMapper(); + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Glue/GizmosRestApi/Mapper/GizmoMapper.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Glue/GizmosRestApi/Mapper/GizmoMapper.php new file mode 100644 index 0000000..3729933 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Glue/GizmosRestApi/Mapper/GizmoMapper.php @@ -0,0 +1,12 @@ + "unit test of GizmoProcessor::process() - it runs this class". +class GizmoMapper +{ + public function map(int $id): array + { + return ['id' => $id * 1]; + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Glue/GizmosRestApi/Plugin/GizmosResourceRoutePlugin.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Glue/GizmosRestApi/Plugin/GizmosResourceRoutePlugin.php new file mode 100644 index 0000000..27a941f --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Glue/GizmosRestApi/Plugin/GizmosResourceRoutePlugin.php @@ -0,0 +1,33 @@ + whole class skipped. +class GizmosResourceRoutePlugin extends AbstractPlugin implements ResourceRoutePluginInterface +{ + public function configure(ResourceRouteCollectionInterface $resourceRouteCollection): ResourceRouteCollectionInterface + { + $resourceRouteCollection->addGet('getAction', true); + + return $resourceRouteCollection; + } + + public function getResourceType(): string + { + return 'gizmos'; + } + + public function getController(): string + { + return 'gizmos-resource'; + } + + public function getResourceAttributesClassName(): string + { + return 'Generated\Shared\Transfer\RestGizmosAttributesTransfer'; + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Glue/GizmosRestApi/Processor/GizmoProcessor.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Glue/GizmosRestApi/Processor/GizmoProcessor.php new file mode 100644 index 0000000..7c9218d --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Glue/GizmosRestApi/Processor/GizmoProcessor.php @@ -0,0 +1,18 @@ + "unit test of this class", created with GizmosRestApiFactory::createGizmoProcessor(). +class GizmoProcessor +{ + public function __construct(protected GizmoMapper $mapper) + { + } + + public function process(int $id): array + { + return $this->mapper->map($id); + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Yves/GizmoPage/Controller/GizmoController.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Yves/GizmoPage/Controller/GizmoController.php new file mode 100644 index 0000000..6ace3c1 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Yves/GizmoPage/Controller/GizmoController.php @@ -0,0 +1,17 @@ + $this->getFactory()->getGizmoClient()->readLocal()]; + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Yves/GizmoPage/GizmoPageFactory.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Yves/GizmoPage/GizmoPageFactory.php new file mode 100644 index 0000000..9714db5 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Yves/GizmoPage/GizmoPageFactory.php @@ -0,0 +1,14 @@ + whole class skipped. +class GizmoPageRouteProviderPlugin implements RouteProviderPluginInterface +{ + public function addRoutes(RouteCollection $routeCollection): RouteCollection + { + $routeCollection->add('gizmo', new Route('/gizmo')); + + return $routeCollection; + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/GizmoBusinessFactory.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/GizmoBusinessFactory.php new file mode 100644 index 0000000..ba6c682 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/GizmoBusinessFactory.php @@ -0,0 +1,78 @@ +createRounder()); + } + + public function createRounder(): Rounder + { + return new Rounder(); + } + + public function createFormatter(): Formatter + { + return new Formatter(); + } + + public function createDefaultImporter(): StepImporter + { + $importer = new StepImporter(); + $importer->addStep(new DefaultStep()); + + return $importer; + } + + public function createOtherImporter(): StepImporter + { + $importer = new StepImporter(); + $importer->addStep(new OtherStep()); + + return $importer; + } + + public function createExpander(): Expander + { + return new Expander($this->getExpanderPlugins()); + } + + /** + * @return array<\Example\Zed\Gizmo\Dependency\Plugin\GizmoExpanderPluginInterface> + */ + public function getExpanderPlugins(): array + { + return $this->getProvidedDependency(GizmoDependencyProvider::PLUGINS_EXPANDER); + } + + public function createGreeter(): HelloGreeter + { + return new HelloGreeter(); + } + + public function createStorageProvider(): ExtendedStorageProvider + { + return new ExtendedStorageProvider([], []); + } + + public function createLegacy(): Legacy + { + return new Legacy(); + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/GizmoFacade.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/GizmoFacade.php new file mode 100644 index 0000000..b00aa90 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/GizmoFacade.php @@ -0,0 +1,61 @@ + facade -> factory -> Calculator -> Rounder (constructor dependency). + public function calculate(int $value): int + { + return $this->getFactory()->createCalculator()->calculate($value); + } + + // Not tested: Formatter is reported with "test via GizmoFacade::format()". + public function format(int $value): string + { + return $this->getFactory()->createFormatter()->format($value); + } + + // Tested: only DefaultStep is added to this importer (setter injection is tracked per call site). + public function runSteps(): void + { + $this->getFactory()->createDefaultImporter()->import(); + } + + // Not tested: OtherStep must NOT be counted as tested just because the same StepImporter class is tested. + public function runOtherSteps(): void + { + $this->getFactory()->createOtherImporter()->import(); + } + + // Tested: plugin stack resolved through GizmoDependencyProvider. + public function expand(int $value): int + { + return $this->getFactory()->createExpander()->expand($value); + } + + // Tested: template method of an abstract project parent resolves to the subclass. + public function greet(): string + { + return $this->getFactory()->createGreeter()->greet(); + } + + // Not tested: runs a class that extends a core class -> section 2 / entry point. + public function addItems(CartChangeTransfer $cartChangeTransfer): QuoteTransfer + { + return $this->getFactory()->createStorageProvider()->addItems($cartChangeTransfer); + } + + // Called only from tests -> unused, [tests only]. + public function legacyOnlyInTests(): string + { + return $this->getFactory()->createLegacy()->run(); + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/AbstractGreeter.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/AbstractGreeter.php new file mode 100644 index 0000000..d373da4 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/AbstractGreeter.php @@ -0,0 +1,13 @@ +getGreeting(); + } + + abstract protected function getGreeting(): string; +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Calculator.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Calculator.php new file mode 100644 index 0000000..7dc02d5 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Calculator.php @@ -0,0 +1,27 @@ +rounder->round($value * 2); + } + + // Never called anywhere -> untested + unused (Calculator is partially tested). + public function unusedHelper(): int + { + return abs(-42); + } + + // Protected helper called nowhere -> not counted for coverage, but still reported as unused. + protected function unusedProtected(): int + { + return abs(-1); + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/DefaultStep.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/DefaultStep.php new file mode 100644 index 0000000..3658b79 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/DefaultStep.php @@ -0,0 +1,11 @@ + tested. +class DefaultStep implements StepInterface +{ + public function execute(): void + { + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Expander.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Expander.php new file mode 100644 index 0000000..362961e --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Expander.php @@ -0,0 +1,28 @@ + + */ + protected array $expanderPlugins; + + /** + * @param array<\Example\Zed\Gizmo\Dependency\Plugin\GizmoExpanderPluginInterface> $expanderPlugins + */ + public function __construct(array $expanderPlugins) + { + $this->expanderPlugins = $expanderPlugins; + } + + public function expand(int $value): int + { + foreach ($this->expanderPlugins as $expanderPlugin) { + $value = $expanderPlugin->expandValue($value); + } + + return $value; + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/ExtendedStorageProvider.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/ExtendedStorageProvider.php new file mode 100644 index 0000000..c32e7e0 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/ExtendedStorageProvider.php @@ -0,0 +1,16 @@ + section 2, test via GizmoFacade::addItems(). +class ExtendedStorageProvider extends NonPersistentProvider +{ + public function addItems(CartChangeTransfer $cartChangeTransfer): QuoteTransfer + { + return parent::addItems($cartChangeTransfer); + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Formatter.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Formatter.php new file mode 100644 index 0000000..6df797f --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Formatter.php @@ -0,0 +1,18 @@ + untested. +class Formatter +{ + public function format(int $value): string + { + return $this->pad((string)$value); + } + + // Pure protected helper (no override) -> not counted; it is reached through format(). + protected function pad(string $value): string + { + return str_pad($value, 2, '0', STR_PAD_LEFT); + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/HelloGreeter.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/HelloGreeter.php new file mode 100644 index 0000000..87708b2 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/HelloGreeter.php @@ -0,0 +1,12 @@ + tested and not unused. +class HelloGreeter extends AbstractGreeter +{ + protected function getGreeting(): string + { + return ucfirst('hello'); + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Legacy.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Legacy.php new file mode 100644 index 0000000..4fd631f --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Legacy.php @@ -0,0 +1,12 @@ + unused, [tests only]. +class Legacy +{ + public function run(): string + { + return implode(',', ['legacy']); + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/MandatoryColumns.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/MandatoryColumns.php new file mode 100644 index 0000000..aac6daf --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/MandatoryColumns.php @@ -0,0 +1,30 @@ + skipped. + public function getMandatoryColumns(): array + { + return ['sku', static::COLUMN_NAME]; + } + + // Declarative (transfer built from constants with fluent setters) -> skipped. + public function getDefaultQuote(): QuoteTransfer + { + return (new QuoteTransfer())->setCartNote('default')->setPriceMode(static::PRICE_MODE); + } + + // Real logic -> reported. + public function isSatisfiedBy(array $row): bool + { + return !array_diff($this->getMandatoryColumns(), array_keys($row)); + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Orphan.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Orphan.php new file mode 100644 index 0000000..3c34cce --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Orphan.php @@ -0,0 +1,11 @@ + whole class unused. +class Orphan +{ + public function doNothing(): void + { + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/OtherStep.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/OtherStep.php new file mode 100644 index 0000000..8f1d72e --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/OtherStep.php @@ -0,0 +1,11 @@ + untested, test via GizmoFacade::runOtherSteps(). +class OtherStep implements StepInterface +{ + public function execute(): void + { + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Rounder.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Rounder.php new file mode 100644 index 0000000..63f9f10 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/Rounder.php @@ -0,0 +1,12 @@ + + */ + protected array $steps = []; + + public function addStep(StepInterface $step): void + { + $this->steps[] = $step; + } + + public function import(): void + { + foreach ($this->steps as $step) { + $step->execute(); + } + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/StepInterface.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/StepInterface.php new file mode 100644 index 0000000..5e151b4 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Business/Model/StepInterface.php @@ -0,0 +1,8 @@ +getFacade()->calculate(1); + $this->getFacade()->format(1); + $this->getFacade()->runSteps(); + $this->getFacade()->runOtherSteps(); + $this->getFacade()->expand(1); + $this->getFacade()->greet(); + + return static::CODE_SUCCESS; + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Controller/IndexController.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Controller/IndexController.php new file mode 100644 index 0000000..7267d60 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Controller/IndexController.php @@ -0,0 +1,20 @@ +getFacade()->addItems(new CartChangeTransfer()); + + return []; + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Form/GizmoForm.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Form/GizmoForm.php new file mode 100644 index 0000000..9ce8045 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Form/GizmoForm.php @@ -0,0 +1,43 @@ +addNameField($builder)->addTypeField($builder, $options['required'] ?? false); + } + + public function getBlockPrefix(): string + { + return 'gizmo'; + } + + public function addNameField(FormBuilderInterface $builder): static + { + $builder->add('name', TextType::class); + + return $this; + } + + public function addTypeField(FormBuilderInterface $builder, bool $required): static + { + if ($required) { + $builder->add('type', TextType::class); + } + + return $this; + } + + public function normalizeName(string $name): string + { + return trim($name); + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/CalculatorItemExpanderPlugin.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/CalculatorItemExpanderPlugin.php new file mode 100644 index 0000000..164e17c --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/CalculatorItemExpanderPlugin.php @@ -0,0 +1,21 @@ + counted as covered. +class CalculatorItemExpanderPlugin extends AbstractPlugin implements ItemExpanderPluginInterface +{ + public function expandItems(CartChangeTransfer $cartChangeTransfer): CartChangeTransfer + { + $this->getFacade()->calculate(1); + + return $cartChangeTransfer; + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/ConditionalItemExpanderPlugin.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/ConditionalItemExpanderPlugin.php new file mode 100644 index 0000000..7fd735b --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/ConditionalItemExpanderPlugin.php @@ -0,0 +1,23 @@ + still listed. +class ConditionalItemExpanderPlugin extends AbstractPlugin implements ItemExpanderPluginInterface +{ + public function expandItems(CartChangeTransfer $cartChangeTransfer): CartChangeTransfer + { + if ($cartChangeTransfer->getItems()->count() > 0) { + $this->getFacade()->calculate(1); + } + + return $cartChangeTransfer; + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/FormatterItemExpanderPlugin.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/FormatterItemExpanderPlugin.php new file mode 100644 index 0000000..6c2443e --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/FormatterItemExpanderPlugin.php @@ -0,0 +1,21 @@ + still listed. +class FormatterItemExpanderPlugin extends AbstractPlugin implements ItemExpanderPluginInterface +{ + public function expandItems(CartChangeTransfer $cartChangeTransfer): CartChangeTransfer + { + $this->getFacade()->format(1); + + return $cartChangeTransfer; + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/GizmoExpanderPlugin.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/GizmoExpanderPlugin.php new file mode 100644 index 0000000..10c7faf --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/GizmoExpanderPlugin.php @@ -0,0 +1,15 @@ + tested. +class GizmoExpanderPlugin extends AbstractPlugin implements GizmoExpanderPluginInterface +{ + public function expandValue(int $value): int + { + return $value + 1; + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/GizmoProductAbstractFormDataProviderExpanderPlugin.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/GizmoProductAbstractFormDataProviderExpanderPlugin.php new file mode 100644 index 0000000..9bb5f3e --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/GizmoProductAbstractFormDataProviderExpanderPlugin.php @@ -0,0 +1,18 @@ +getSku() !== null; + + return $formData; + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/GizmoProductAbstractFormExpanderPlugin.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/GizmoProductAbstractFormExpanderPlugin.php new file mode 100644 index 0000000..4a14a8e --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Plugin/GizmoProductAbstractFormExpanderPlugin.php @@ -0,0 +1,23 @@ +all()) as $name) { + if (str_starts_with((string)$name, 'general_')) { + $builder->get((string)$name)->add('is_gizmo', CheckboxType::class, ['required' => false]); + } + } + + return $builder; + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Table/GizmoTable.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Table/GizmoTable.php new file mode 100644 index 0000000..d28c0a8 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Communication/Table/GizmoTable.php @@ -0,0 +1,22 @@ +setHeader(['name' => 'Name']); + + return $config; + } + + protected function prepareData(TableConfiguration $config) + { + return array_map(static fn (array $row): array => $row, []); + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Dependency/Plugin/GizmoExpanderPluginInterface.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Dependency/Plugin/GizmoExpanderPluginInterface.php new file mode 100644 index 0000000..a40cb8b --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Example/Zed/Gizmo/Dependency/Plugin/GizmoExpanderPluginInterface.php @@ -0,0 +1,8 @@ +set(static::PLUGINS_EXPANDER, function () { + return $this->getExpanderPlugins(); + }); + + return $container; + } + + /** + * @return array<\Example\Zed\Gizmo\Dependency\Plugin\GizmoExpanderPluginInterface> + */ + protected function getExpanderPlugins(): array + { + return [new GizmoExpanderPlugin()]; + } + + /** + * Registrations (what a project DependencyProvider of another module would do). + * + * @return array + */ + protected function getRegisteredPlugins(): array + { + return [ + new CalculatorItemExpanderPlugin(), + new FormatterItemExpanderPlugin(), + new ConditionalItemExpanderPlugin(), + new GizmoConsole(), + ]; + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/ExampleExtra/Zed/Extra/Business/ExtraFacade.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/ExampleExtra/Zed/Extra/Business/ExtraFacade.php new file mode 100644 index 0000000..6554f94 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/ExampleExtra/Zed/Extra/Business/ExtraFacade.php @@ -0,0 +1,14 @@ + scanned too. +class ExtraFacade extends AbstractFacade +{ + public function ping(): string + { + return strrev('gnop'); + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Generated/Ignored/IgnoredThing.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Generated/Ignored/IgnoredThing.php new file mode 100644 index 0000000..64ebe3a --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/src/Generated/Ignored/IgnoredThing.php @@ -0,0 +1,11 @@ +assertSame(2, $this->tester->getFacade()->calculate(1)); + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/tests/PyzTest/Zed/Gizmo/Business/GizmoFacadeTest.php b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/tests/PyzTest/Zed/Gizmo/Business/GizmoFacadeTest.php new file mode 100644 index 0000000..37edfa6 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/scripts/coverage-gaps/coverage-gaps/fixture/tests/PyzTest/Zed/Gizmo/Business/GizmoFacadeTest.php @@ -0,0 +1,47 @@ +assertSame(2, $this->tester->getFacade()->calculate(1)); + } + + public function testRunSteps(): void + { + $this->tester->getFacade()->runSteps(); + } + + public function testExpand(): void + { + $this->assertSame(2, $this->tester->getFacade()->expand(1)); + } + + public function testGreet(): void + { + $facade = $this->tester->getFacade(); + + $this->assertSame('hello', $facade->greet()); + } + + public function testLegacy(): void + { + $this->assertSame('legacy', $this->tester->getFacade()->legacyOnlyInTests()); + } + + public function testMockedFormatterDoesNotCount(): void + { + $formatter = $this->createMock(Formatter::class); + $formatter->format(1); + } +} diff --git a/plugins/spryker-ai-dev-sdk/skills/static-validation/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/static-validation/SKILL.md index 6c965e1..1c3a425 100644 --- a/plugins/spryker-ai-dev-sdk/skills/static-validation/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/static-validation/SKILL.md @@ -1,16 +1,6 @@ --- name: static-validation -description: > - Run Spryker static analysis over only the code that changed versus a base branch — PHP (phpcbf, - phpcs, phpmd/architecture-sniffer, phpstan) and frontend (eslint, stylelint, prettier for - js/ts/scss/css/less/html across Yves, Back Office and Merchant Portal) — after implementing or - editing code, before commit, or as an interim check while iterating. Trigger on "validate", "lint", - "check code", "run static analysis", "fix phpcs/phpstan", "run QA on changes", "static check the - diff", "lint the changed modules", "check js/css/scss I changed", "lint my Yves/Merchant Portal - change", "check code vs master/main", "static-check the branch". Works from any git worktree, auto- - detects or takes a base branch (master, main or any ref), validates only added/changed files, and - groups PHP by changed files (files scope) or by every Spryker module with a changed file (module - scope — validates the whole module). +description: "Runs Spryker static analysis (phpcs, phpstan, phpmd, eslint, stylelint, prettier) on the files changed against a base branch. Use after edits, before a commit, or for 'lint' or 'validate'." --- # static-validation diff --git a/plugins/spryker-ai-dev-sdk/skills/technical-specification/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/technical-specification/SKILL.md index ab4e873..4370c50 100644 --- a/plugins/spryker-ai-dev-sdk/skills/technical-specification/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/technical-specification/SKILL.md @@ -1,6 +1,6 @@ --- name: technical-specification -description: Use when the user asks for a technical specification (tech spec) or a technical design document for a new Spryker feature, from a PRD or from business requirements. Creates the spec in steps with the user — a template first, then module dependency graph, ERD, transfer model, flow (sequence) diagrams, module API, test coverage outline, and risks — all as Mermaid diagrams and method signatures, with no implementation code. +description: "Writes a technical specification for a new Spryker feature step by step: module graph, ERD, transfers, sequence diagrams, API, tests, risks. Use when asked for a tech spec or design doc." user-invocable: true --- diff --git a/plugins/spryker-ai-dev-sdk/skills/translate-content/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/translate-content/SKILL.md index 6f1284d..b220253 100644 --- a/plugins/spryker-ai-dev-sdk/skills/translate-content/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/translate-content/SKILL.md @@ -1,6 +1,6 @@ --- name: translate-content -description: "Use when actually translating a Spryker project's storefront content into a project locale — glossary and/or catalog/CMS/navigation/labels — the opt-in localization pass that project setup defers: 'localize uk_UA', 'translate the shop content into Polish', 'the storefront is still English in my locale'. Standalone on a project, or offered by the wizard after boot; strictly per-locale and opt-in." +description: "Translates the storefront content of a Spryker project (glossary, catalog, CMS, navigation) into one project locale at a time. Use for 'localize ' or 'translate the shop content'." --- # translate-content diff --git a/plugins/spryker-ai-dev-sdk/skills/yves-atomic-frontend/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/yves-atomic-frontend/SKILL.md index 1d15df7..c2a5558 100644 --- a/plugins/spryker-ai-dev-sdk/skills/yves-atomic-frontend/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/yves-atomic-frontend/SKILL.md @@ -1,18 +1,12 @@ --- name: yves-atomic-frontend -description: > - Use when creating, extending, or overriding Spryker Yves storefront frontend code in a project — atomic - components, templates, views, Widgets — and their Twig, SCSS, and TypeScript. Triggers: "create a new - molecule", "override the product item", "extend the cart item component", "create a widget", "style this - component", "why isn't my style applied", "the component isn't initializing", fixing Yves lint errors. - Also for diagnosis: "my change did not show up", a Twig/SCSS edit with no visible effect, stale styles or - a cached template, verifying a UI fix by measuring the rendered page. Always use for any Yves Theme/ - work; not for linting a diff (static-validation) or rebrands (brand-project). Which change a page needs - belongs to `match-reference-design`, the rows a component renders to `project-data`. +description: "Creates, extends or overrides Yves storefront components, templates, views and widgets (Twig, SCSS, TypeScript). Use for any Yves theme work or a frontend change that does not show up." --- # Spryker Yves Atomic Frontend +Boundary: not for linting a diff (`static-validation`) or rebrands (`brand-project`). Which change a page needs belongs to `match-reference-design`, the rows a component renders to `project-data`. + Non-negotiables live in the `yves-frontend` rule — read it from `/rules/yves-frontend.md`, or skip it where the project has the rules installed and the harness is already applying them. This skill is the workflow. `{ProjectNamespace}` = the namespace the project writes to — its custom namespace if one is defined (listed first in `KernelConstants::PROJECT_NAMESPACES`, `config/Shared/config_default.php`), otherwise `Pyz`. diff --git a/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/SKILL.md index 860ea1f..aad47b3 100644 --- a/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/SKILL.md @@ -1,15 +1,6 @@ --- name: yves-twig-integration -description: > - Optional storefront step after a Spryker feature install or upgrade: suggests where the - feature's Yves widgets and components belong in the project's own Twig templates, using the - vendor templates as the reference for what goes where and the project's design for how it looks, - and applies only the placements the developer picks. Integration guides wire the backend - (plugins, config, schema) but leave Yves templates to the project, and a project that overrides a - vendor template loses every widget call inside it, so a registered widget renders nothing. Use - when spryker-feature-install or spryker-upgrade offers the storefront step, or when the user asks - "place the X widget", "why is widget X not shown", "integrate the feature into our storefront", - "which widgets does our shop not render". Never applies anything without the developer's choice. +description: "Suggests where a feature's Yves widgets belong in the project's own Twig templates and applies the placements the developer picks. Use after a feature install or when a widget is not shown." --- # Yves Twig Integration @@ -117,8 +108,6 @@ Leave the changes unstaged for review; never commit without the developer's conf ## What you do not do -- Do not apply a placement the developer did not pick, and do not treat a `missing` item as a defect. -- Do not paste vendor markup or vendor classes into a project template; reuse the project's patterns. - Do not place by line number, and do not replace a project override with a fresh copy of the vendor template. +- Do not treat a `missing` item as a defect. - Do not edit `vendor/`, `src/Generated/` or build output. -- Do not place a `not_registered` widget before its registration exists.