diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index d2d9b8d..937c9e2 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ { "name": "spryker-ai-dev-sdk", "description": "Set of setup tools, skills and agents for Spryker project development.", - "version": "0.8.0", + "version": "0.10.0", "author": { "name": "Spryker Systems GmbH", "email": "support@spryker.com" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 467f6b8..e0344c0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -63,6 +63,9 @@ jobs: - name: Rule sync script run: bash tests/scripts/test-sync-rules.sh + - name: Feature install scripts + run: php tests/scripts/feature-install/feature-install.test.php + - name: Stop guard, under both harnesses run: php plugins/spryker-ai-dev-sdk/hooks/hooks.test.php diff --git a/plugins/spryker-ai-dev-sdk/.claude-plugin/plugin.json b/plugins/spryker-ai-dev-sdk/.claude-plugin/plugin.json index e236365..ba0c6bb 100644 --- a/plugins/spryker-ai-dev-sdk/.claude-plugin/plugin.json +++ b/plugins/spryker-ai-dev-sdk/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "spryker-ai-dev-sdk", - "version": "0.8.0", + "version": "0.10.0", "description": "Set of setup tools, skills and agents for Spryker project development. Works with Claude Code and GitHub Copilot.", "author": { "name": "Spryker Systems GmbH", 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 e6f7862..c1cbcb0 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 @@ -56,6 +56,8 @@ When a structured Spryker MCP tool can answer a question, **use it — do not** | Tool | Use For | |------|---------| +| `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 | @@ -90,7 +92,7 @@ Spryker transfer XMLs, schema XMLs, and config PHP files are small enough that ` ## Approach 1. **Run the mandatory checklist** above. State its key outputs (applicable primitives, reinvention flags, scope confirmation) at the top of your answer. -2. **Identify the feature / problem class.** Use the `spryker-docs-research` skill to confirm the concept and scope. **For enumerating the modules involved, use `getSprykerModules` (reads project + vendor directly) — not docs.** Docs may list modules that aren't installed in this project. If MCP is unavailable, fall back to `composer.json` / `composer.lock` and direct inspection of `vendor/spryker/` and each project-namespace directory under `src/`. Docs are for *concepts*; project + vendor are for *what's actually here*. +2. **Identify the feature / problem class.** For "which module / feature does X", "does Spryker already do X" and "how do I build X" questions, **start with `searchSprykerCapabilities`** (then `getSprykerCapability` on the top hits) and follow the `find-existing-capability` skill's verdicts: a capability that ships is extended or installed (`spryker-feature-install`), and a hit counts toward the reinvention flags in the checklist above. A miss is not proof of absence; cross-check with docs and `getSprykerModules` before saying Spryker has no X. If the tools are not connected, `find-existing-capability` describes the web fallback. Then use the `spryker-docs-research` skill to confirm the concept and scope. **For enumerating the modules involved, use `getSprykerModules` (reads project + vendor directly) — not docs.** Docs may list modules that aren't installed in this project. If MCP is unavailable, fall back to `composer.json` / `composer.lock` and direct inspection of `vendor/spryker/` and each project-namespace directory under `src/`. Docs are for *concepts*; project + vendor are for *what's actually here*. 3. **Build the explanation at the depth the question requires.** Cover: - What the feature does — capabilities, types, behaviour. - Key concepts and terminology. 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 3d9004d..a1ba364 100644 --- a/plugins/spryker-ai-dev-sdk/agents/spryker-verifier.agent.md +++ b/plugins/spryker-ai-dev-sdk/agents/spryker-verifier.agent.md @@ -40,7 +40,7 @@ Then wait ~500ms for the stylesheet to re-fetch, then assert. Same applies to bu `spryker-qa-coverage` covers permission-gated-failures-aren't-defects, picking the actor whose role matches, the reproduce-before-fail (≥3 loads) discipline for inert-button claims, and ruling out stale cache / the inert Zed-JS bootstrap race before failing. Apply all of that. The two points that bind *tighter* for an assertion-only gate: -- **Login failure is a credentials question, not a defect — report, don't debug.** If a login attempt fails (401, "invalid credentials", redirect back to login, role-mismatch), **stop and return BLOCKED** naming the account that failed and the credential needed. Do not try alternate emails/passwords, do not invoke `spryker-issue-diagnoser`, do not dig through logs. (`spryker-runtime` covers the DB lookup for real accounts; if that still doesn't authenticate, return BLOCKED.) +- **Login failure is a credentials question, not a defect — report, don't debug.** If a login attempt fails (401, "invalid credentials", redirect back to login, role-mismatch), **stop and return BLOCKED** naming the account that failed and the credential needed. Do not try alternate emails/passwords, do not invoke `spryker-issue-diagnoser`, do not dig through logs. (`spryker-runtime` covers the DB lookup for real accounts; if that still doesn't authenticate, return BLOCKED.) One read-only check separates the two causes: compare the fixture password with the account's stored hash (`password_verify` against the `spy_customer` / `spy_user` row). No match → **BLOCKED (credentials)**, naming the credential needed. Match, yet the login still fails → **BLOCKED (environment: authentication)**: the account is right and the stack's login path is broken (in one trial, every fixture customer got a Glue 401 although the hashes matched and the OAuth table had never issued a token). Say so under `## Environment caveats` and recommend `spryker-issue-diagnoser` to the caller instead of failing feature criteria. - **A permission-gated denial maps to a verdict, not a FAIL.** When an action fails because the test user's role lacks the required permission plugin, that's expected behavior — mark **BLOCKED** (naming the missing permission) or switch to a user who has it. Never mark the AC FAIL or escalate to `spryker-issue-diagnoser` for a defect that doesn't exist. ## Running in the browser @@ -48,8 +48,9 @@ Then wait ~500ms for the stylesheet to re-fetch, then assert. Same applies to bu **Drive the local shop through a browser-automation MCP server**, not a built-in browser pane that prompts the person for each action on a local host. The `spryker-runtime` skill's **Browser tool map** gives the tool name for each capability under Claude in Chrome and under Playwright MCP. - **Seeded credentials are test fixtures, and logging in with them is part of your task.** They - live in the repository (the customer rows and the installer user config); read the account you need and - use it. Never guess a password, and do not report a login-gated criterion as unverifiable: the executor + live in the repository (the customer rows, the installer user config, and the E2E fixtures under + `tests/cypress-tests/cypress/fixtures/**`, which carry the customer emails and a shared `defaultPassword`); + read the account you need and use it. Never print a password in the report; name the fixture file instead. Never guess a password, and do not report a login-gated criterion as unverifiable: the executor that spawned you does not log in, so the login is yours to perform. When your prompt says the browser is already logged in as the user you need, confirm it on the first page and skip the login; if it is not, log in yourself. @@ -89,7 +90,7 @@ For each AC: 1. **Restate the AC in your own words.** If compound (*"X happens AND Y happens AND Z happens"*), enumerate each part separately. **Every part is verified individually** — a PASS verdict requires all parts asserted, not a subset. 2. **Decompose into observable assertions; pick the right surface(s)** (UI / API / DB / Console — `spryker-qa-coverage` chooses the lightest mode that genuinely proves each and tags the execution layer; for a user-facing AC that means the real UI path, not a cheaper endpoint hit). Each part of the AC must have at least one assertion targeting it directly — not a related-but-different one. *"The page loaded without errors"* does not substitute for *"the new badge displayed the value X"*. -3. **Confirm preconditions** (logged-in user with the right role, target entity exists). If a precondition isn't met, mark **BLOCKED** (noting the missing precondition) and stop — do not seed data yourself. +3. **Confirm preconditions** (logged-in user with the right role, target entity exists). If a precondition isn't met, mark **BLOCKED** (noting the missing precondition) and stop — do not seed data yourself. **Authenticate once before the first AC, per surface the ACs use:** one storefront login, one Glue `access-tokens` request, one Back Office login. A failure there blocks every AC on that surface: return early with the cause (credentials or environment, see the login rule above) instead of running each AC into the same wall. 4. **Execute assertions adversarially — try to fail the AC.** For each assertion ask: *"What's the most realistic way this could be broken? If it were broken, would my current assertion catch it?"* If it can't distinguish broken from working (e.g. you're only asserting absence-of-errors), strengthen it. 5. **Capture concrete evidence per assertion** — actual values, screenshots or GIFs (use `spryker-runtime`'s capture flow; where GIF recording is unavailable, a numbered screenshot per step), actual DB rows. *"It looked right"* is not evidence. Evidence must be reproducible by a third party. 6. **Verdict per AC** — use `spryker-qa-coverage`'s status vocabulary so the report is unified: 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 f63118c..808c570 100644 --- a/plugins/spryker-ai-dev-sdk/skills/demo-intake/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/demo-intake/SKILL.md @@ -101,6 +101,8 @@ work and add customization files that were not requested. A brief that spans cla before anything starts; the adjacent class is never done silently (work-classes.md, "when one request spans several classes"). +When unsure whether the platform already offers a briefing item (*already works* versus customization), the capability map answers it: `find-existing-capability` maps a requirement to what Spryker ships and what the project has installed. Intake itself stays read-only; name the item as a question for the owner skill rather than running that search here. + ## 3. Source fidelity — a gap is reported, never closed Attributes, prices, copy and imagery come from the **source** (the supplied export, the customer's site). diff --git a/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/README.md b/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/README.md new file mode 100644 index 0000000..6efb278 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/README.md @@ -0,0 +1,50 @@ +# find-existing-capability + +The **reuse gate** for Spryker feature work: before anything new is designed or built, find out whether Spryker already ships it, and whether the project already has it. + +Agents in Spryker projects tend to build a new module for something a package already provides. Searching `vendor/` only finds what is installed and what you already suspect. This skill searches the **capability map** instead - 590 cards, one per shipped Spryker capability - and reads the project's `composer.lock` to say what is installed, partly installed or missing. + +It is report-only. It recommends; it never installs or edits anything. + +## When it triggers + +At the start of any feature work in a Spryker project: "build / add / implement X", "we need a system for X", "new module for X", scoping a PRD, "is there something in Spryker for X", "extend X", and when a customer requirement list or briefing has to be mapped to what Spryker offers. It is not for changing one already-identified behaviour (that is `spryker-customization` or `spryker-bugfix`). + +## Flow schema + +```mermaid +flowchart TD + A([Feature request / requirement list]) --> B["1 - Capability nouns + synonyms
3-6 short queries per requirement"] + B --> C["2 - searchSprykerCapabilities
one call per query, merge by slug"] + C --> T{"Tool available?"} + T -- "no" --> T0{"Server registered?"} + T0 -- "no" --> T2["Say so once, point to ai-dev-setup Step 3
run scripts/capability-search.php
(weaker ranking, say so)"] --> D + T0 -- "yes, not connected" --> T1["Start server, ask for an MCP reload
after two failures: the same script
PHP or network fails: INDEX.md + card"] --> D + T -- "yes" --> D["3 - getSprykerCapability
on the top hits
read What it does, Extend don't duplicate,
Extension points, Install, Related cards"] + D --> V{"4 - Verdict per hit"} + V -- "installed" --> V1["Extend it
extension points + getSprykerModuleMap
then spryker-customization"] + V -- "partially_installed" --> V2["Install the missing part
API packages only if that API is exposed
then spryker-feature-install"] + V -- "not_installed" --> V3["Install the feature, then extend
name + docs guide + composer line
then spryker-feature-install"] + V -- "card status partial" --> V4["Build only the gap
the card says what is missing"] + V -- "no relevant hit" --> V5["Cross-check: docs search,
getSprykerModules, project grep
then building new is allowed"] + V1 --> R + V2 --> R + V3 --> R + V4 --> R + V5 --> R(["5 - Verdict table + Reuse decision block
user decides"]) +``` + +## Tools + +Matched by tool name (server names are install-specific): `searchSprykerCapabilities`, `getSprykerCapability`, `getSprykerModuleMap`, `getSprykerModules`, `searchAlgoliaDocumentation`. Without the MCP server the skill first checks whether the server is registered at all (`.mcp.json`, `.vscode/mcp.json`, the harness's list); if not, it points to `ai-dev-setup` Step 3 once and skips the start-and-reload loop. The fallback is the bundled `scripts/capability-search.php`, which reads the published `index.json` (cached 24 h; `--index` or `CAPABILITY_MAP_INDEX_URL` for a mirror or a local file), searches it and prints the same fields as the tool, with `installStatus` computed from `composer.lock`; its ranking is simpler than the tool's. Only when PHP or the network fails does it fetch `INDEX.md` and `.md` from `https://spryker-capability-map.s3.eu-central-1.amazonaws.com/` and compare the card's packages to `composer.lock` by hand. + +## Output + +A verdict table (requirement, capability and card, verdict, next step) and one **Reuse decision** block per capability: capability, verdict, evidence, "may already cover this" (an installed card matching through its title or synonyms, e.g. `shopping-list` for a wishlist request), existing project wiring (plugins, routes, widgets already tied to the card's modules), next step, and the card link `https://spryker-capability-map.s3.eu-central-1.amazonaws.com/.md`. + +## Design decisions baked in + +- **Reuse before build.** A shipped capability is extended or installed, not rebuilt; a PRD for it reads "configure / extend / install X". +- **A miss is not proof of absence.** A map miss triggers a docs search, a module check and a project grep; "Spryker has no X" is never claimed from the map alone. +- **Cards describe the latest release.** On an older project, the installed code is checked before a card detail is relied on, and `spryker-upgrade` is suggested when the project is behind. +- **Report-only.** Installing is `spryker-feature-install`, building is `spryker-customization`, and the user chooses. 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 new file mode 100644 index 0000000..ca1abe8 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/SKILL.md @@ -0,0 +1,137 @@ +--- +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. +--- + +# Find Existing Capability - the reuse gate + +Before anything new is designed, find out whether Spryker already ships it. Agents in Spryker projects keep building modules for things a package already provides (a project built "budgets" while `PurchasingControl` ships them). Searching `vendor/` only finds what is installed and only what you already suspect; the **capability map** covers every shipped capability, installed or not. + +The map is 590 cards, one per capability: what it does, its modules, its feature metapackage (`spryker-feature/`), public surface, extension points, data model, configuration, data flow, storefront surface, related cards, an "Extend, don't duplicate" line and an Install section. It describes the **latest Spryker release line**. Planned (unreleased) capabilities are not in it; `partial` cards are, and say what is missing. + +**This skill reports and recommends. It never installs, edits or builds anything.** The user decides what happens next. + +## When to run, when to skip + +Run when the work **adds a capability** (a new module, feature, integration or behaviour area) or when the question is "does Spryker already do X". Skip when the request changes one specific, already-identified existing behaviour (fix this plugin, change that label, tweak this price rule) - that is `spryker-customization` or `spryker-bugfix` directly. + +## Required tools + +Match tools by **tool name** (server names vary by install; some clients namespace them as `mcp____`). Both ship with the Spryker tooling MCP server. + +| Tool | Purpose | +|---|---| +| `searchSprykerCapabilities(query, limit = 10)` | Ranked capability search. `query` is space-separated domain terms, 3+ characters each (short terms such as `sso` or `oms` match whole words only). Returns hits with `slug`, `capability`, `status`, `matched`, `installStatus` (`installed`, `partially_installed`, `not_installed`, or `unknown` without `composer.lock`), `features`, `missingPackages`, `missingOptionalPackages` (API packages), `composerRequire`, `extend`, `url`, plus `source` (`stale` flag) and a `note`. | +| `getSprykerCapability(slug)` | The full card: `synonyms`, `features[]`, `modules[]` (package, path, installed, version), `composerRequire` and `sections` ("What it does", "Public surface (entry points)", "Extension points", "Data model", "Extend, don't duplicate", "Install", "Configuration", "Data flow", "Storefront surface", "Related cards"). | +| `getSprykerModuleMap` | Exact classes, facades and plugin interfaces of an installed module. | +| `getSprykerModules` | Which modules the project has, and the exact module names. | +| `searchAlgoliaDocumentation` | Official docs search, for the "no relevant hit" cross-check. | + +A tool error (for example "Unknown capability", "The query needs at least one term", or the map cannot be loaded) is a failure, not an empty result: report its message and use the fallback below. + +**If the capability tools are not available**, first tell the two causes apart. The server is **not registered** when no `ai-dev:mcp-server` entry exists in the project's MCP config files (`.mcp.json`, `.vscode/mcp.json`) and the harness's MCP server list does not show it. It is **registered but not connected** when an entry exists and the tools are still missing. + +- **Not registered:** say so once, in one line - the project has not run `ai-dev-setup` Step 3 (it registers the server; `.mcp.json` is its project-scoped option) - and go straight to the script fallback below. Do not start the stack or ask for a reload: there is nothing to reconnect. Offer `ai-dev-setup` at the end of the report as the way to get the tools in a new session. +- **Registered but not connected:** try to start the server the way `product-requirement-document` does - the underlying server backs the local app, so `script -q /dev/null docker/sdk run` (or `up`) brings it up - then ask the user to reload the MCP connection (the harness's MCP command) and wait for confirmation. After a second failed reconnect, use the fallback. + +**Fallback.** Run the bundled script from the project root. It reads `index.json` (cached 24 h), searches it and prints, per hit, the fields the tool returns (`slug`, `capability`, `status`, `matched`, `installStatus` from `composer.lock`, `features`, `missingPackages`, `missingOptionalPackages`, `composerRequire`, `url`), so the rest of this skill applies unchanged: + +```bash +php /scripts/capability-search.php "wishlist" "shopping list" "budget spending limit" [--limit=10] [--index=] [--lock=] +``` + +Each quoted argument is one query (Step 1). It prints a one-line summary, then one line of JSON; the mirror can also be set with the `CAPABILITY_MAP_INDEX_URL` environment variable. Exit code 2 is a usage error, 3 means the index could not be loaded. In place of `getSprykerCapability`, fetch the hit's `url` (the card). + +If PHP is not available or the script cannot load the index, use the **web fallback**: + +1. Fetch `https://spryker-capability-map.s3.eu-central-1.amazonaws.com/INDEX.md` with the harness's web fetch tool, or `curl -s`. It has one entry per card with its modules, features and synonyms. +2. Search it for each term and its synonyms yourself; note the candidate slugs. +3. Fetch each candidate card from `https://spryker-capability-map.s3.eu-central-1.amazonaws.com/.md`. +4. Compare the card's `vendor/spryker/` modules and its `spryker-feature/` against the project's `composer.lock` by hand (the built-in file read/search tools). + +Say plainly in the report that you used a fallback and that **ranking is weaker** in that mode (the script scores by title, synonyms, modules and body text, simpler than the tool; the web fallback has no scoring and no computed install status), so a miss means less. + +## Step 1 - Extract the capability nouns + +From the request, pull the **capability nouns** (what the business calls the thing) and add the **synonyms** a Spryker doc or module would use. Examples: "budgets" also reads "spending limit", "cost center", "purchasing control"; "wishlist" also "shopping list"; "approval" also "workflow", "order confirmation"; "SSO" also "identity provider", "OAuth", "login". + +Several short queries beat one long one. Build 3-6 queries of 1-3 terms each: the main noun, each synonym cluster, and the surface when it matters (`budget`, `spending limit cost center`, `approval company`, `glue checkout`). Skip filler words and terms under 3 characters except well-known acronyms. + +For a requirement list or briefing, do this **per requirement row**, not once for the whole document. + +## Step 2 - Search + +Call `searchSprykerCapabilities` once per query. Merge the hits by `slug` and keep, per slug, which queries hit it and what `matched` says: a hit on `capability` (the title or synonyms) is strong, a hit on `modules` is good, a hit only on `body` is weak and must be judged by reading the card. Matching is stem- and substring-based, so check that the matched term means what you meant: "loyalty points" also hits `service-point` through `point`. Drop such hits instead of reporting them. + +Relay the response's `note` and check `source.stale`: when `true`, the map was served from a stale cache; say so. A search with no hits on the first query is not the end - try the synonyms before moving on. + +## Step 3 - Open the top hits + +Call `getSprykerCapability` for each plausible hit (usually the top 1-3 per requirement). Read, in this order: "What it does" (does it really cover the need), "Extend, don't duplicate", "Extension points", "Install", and "Related cards" (a `[[slug]]` link may be the real match; open it). Check `status`: `shipped` or `partial`. + +## Step 4 - Decide per hit + +One verdict per capability, driven by the card's `status` and the computed `installStatus` (read from the project's `composer.lock`; "installed" means the packages are present, not that the project wired them in - confirm the registered plugins in the project layer before promising a behaviour works today). + +| Condition | Verdict | What to report and propose | +|---|---|---| +| `installed` | **Extend it** | Name the card's extension points and plugin interfaces and its "Extend, don't duplicate" line. Call `getSprykerModuleMap` for the module(s) to get the exact classes. Grep the project namespace for what the project already built on it. Hand the implementation to `spryker-customization` as configure / extend work. | +| `partially_installed` | **Install the missing part** | List `missingPackages` and say whether they matter. API packages (`*-rest-api`, `*-storefront-api`, `*-backend-api`) are listed separately in `missingOptionalPackages` and are needed only when the project exposes that API. If a package that matters is missing, propose installing it through `spryker-feature-install`. | +| `not_installed` | **Install the feature, then extend it** | Propose the feature (name, the docs install guide URL from the card's Install section, the card's `composerRequire` line) via `spryker-feature-install`, then extending it. Do not propose building from scratch. When the card lists **several features**, they are alternatives (each ships some of the card's modules, e.g. `wishlist` and `marketplace-wishlist`) and `composerRequire` names the missing module packages instead: pick the feature that matches the project (marketplace or not, B2B or B2C) from the Install section. | +| `unknown` | **Check by hand** | The project has no readable `composer.lock`. Say so, and compare the card's packages with `composer.json` and `vendor/` yourself. | +| card `status` is `partial` | **Build only the gap** | Show what the card says is missing. Reuse the shipped part (install or extend per the rows above) and scope the new build to the gap only. | +| no relevant hit | **Building new is allowed - after the cross-check** | See below. | + +**A miss is not proof of absence.** Before concluding that Spryker has nothing: run `searchAlgoliaDocumentation` (or the `spryker-docs-research` skill) with the synonyms, check `getSprykerModules` for a module the project already has under a different name, and grep the project namespace. Report "no capability-map hit, no docs hit, no project module" as what you found. **Never claim "Spryker has no X" from the map alone.** + +**One request, several hits.** When two cards cover parts of the request, give each its own verdict and say how they combine. When a hit only partly matches (it does half of what was asked), say which half. + +**Installed near-equivalent.** When the main verdict is install or build, and an **installed** card matches the need through its title or synonyms (`shopping-list`, with the synonyms "wish list" and "save for later", for a wishlist request), report it as **"may already cover this"** next to the main verdict, with the synonym that matched and what it would not do. The user may prefer the installed alternative to a new install. + +**Leftover project wiring.** Whatever the verdict, grep the project namespace (`src//`, the `psr-4` prefix in `composer.json`; skip `src/Generated` and `src/Orm`) for the card's modules (module names, `Spryker\...\` namespaces) and its plugin classes, and list what is already wired: plugins in dependency providers, content types, route patterns, widgets. A project can carry wiring for a feature that is not installed (the project once had it, or a demo shop removed it partly), and that changes the install scope. + +## Version drift + +The map describes the latest release line. The project may be older. When a capability matters and a module's installed `version` (from the card's `modules[]`) looks old for the feature, read the module's code in `vendor/spryker/` or call `getSprykerModuleMap` before relying on a card detail (an extension point, a Glue resource, a config key). When the verdict is an install, say that the project is older than the map, and hand it to `spryker-feature-install` anyway: its Phase 1 finds the release the feature needs and decides whether that takes an upgrade. Do not propose `spryker-upgrade` from this skill. + +## Step 5 - Report + +End with a verdict table and one **Reuse decision** block per capability that matters. + +```markdown +| Requirement | Capability (card) | Verdict | Next step | +|---|---|---|---| +| Per-department spending limits | Budgets and cost centers (`purchasing-control`) | not installed - install, then extend | /spryker-feature-install spryker-feature/purchasing-control | +``` + +```markdown +## Reuse decision + +- Capability: +- Verdict: extend (installed) | install missing part | install feature then extend | build only the gap | build new (no relevant hit) +- Evidence: +- May already cover this: +- Existing wiring: +- Next step: +- Card: https://spryker-capability-map.s3.eu-central-1.amazonaws.com/.md +``` + +State what you did not verify (a version-drift check you skipped, a fallback search, an API package you assumed is not needed). Then stop and let the user choose. A PRD for something that ships is framed as "configure / extend / install X", not "build X". + +## 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. diff --git a/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/scripts/capability-search.php b/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/scripts/capability-search.php new file mode 100644 index 0000000..4d7d3cb --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/scripts/capability-search.php @@ -0,0 +1,429 @@ +" ["" ...] [--limit=10] [--index=] [--lock=] [--json] + * + * Each positional argument is one query of space-separated terms (3+ characters; short terms + * match whole words only), like the tool's `query`. Run several short queries in one call. + * --index index.json URL or local file; a mirror. Default: env CAPABILITY_MAP_INDEX_URL, then + * https://spryker-capability-map.s3.eu-central-1.amazonaws.com/index.json + * --lock composer.lock to read (default: /composer.lock) + * --json print only the JSON line (no summary line) + * + * Output: a one-line summary, then one line of compact JSON + * {queries: [{query, terms, count, hits[]}], source: {url, stale}, note}. + * A downloaded index is cached for 24 hours in CAPABILITY_MAP_STATE_DIR (default: + * /ai-dev-capability-map); an expired cache is used, flagged stale, when the download fails. + * Exit code: 0 on success (also with no hits), 2 on a usage error, 3 when the index cannot be loaded. + */ + +declare(strict_types=1); + +const CAPSEARCH_DEFAULT_INDEX_URL = 'https://spryker-capability-map.s3.eu-central-1.amazonaws.com/index.json'; +const CAPSEARCH_CACHE_TTL = 86400; +const CAPSEARCH_TIMEOUT = 15; +const CAPSEARCH_MIN_TERM_LENGTH = 3; +const CAPSEARCH_SHORT_TERM_LENGTH = 4; +const CAPSEARCH_MIN_STEM_LENGTH = 3; +const CAPSEARCH_MAX_LIMIT = 50; +const CAPSEARCH_STEM_SUFFIXES = ['ies', 'es', 's']; +const CAPSEARCH_STATUS_RANK = ['shipped' => 0, 'partial' => 1, 'planned' => 2]; +const CAPSEARCH_OPTIONAL_MARKERS = ['-rest-api', '-storefront-api', '-backend-api']; +const CAPSEARCH_NOTE = 'Fallback search (no MCP server): ranking is weaker than the tool. The map describes the latest Spryker release line; ' + . 'an installed package may be older than its card. No hit is not proof that Spryker lacks the capability: also search the documentation and the installed modules before building new.'; + +function capsearch_fail(string $message, int $code): never +{ + fwrite(STDERR, $message . "\n"); + exit($code); +} + +/** + * @return array{queries: array, limit: int, index: string, lock: string|null, json: bool} + */ +function capsearch_parse_args(array $argv): array +{ + $queries = []; + $limit = 10; + $index = null; + $lock = null; + $json = false; + + foreach (array_slice($argv, 1) as $arg) { + if (str_starts_with($arg, '--limit=')) { + $limit = max(1, min(CAPSEARCH_MAX_LIMIT, (int)substr($arg, 8))); + } elseif (str_starts_with($arg, '--index=')) { + $index = substr($arg, 8); + } elseif (str_starts_with($arg, '--lock=')) { + $lock = substr($arg, 7); + } elseif ($arg === '--json') { + $json = true; + } elseif (str_starts_with($arg, '--')) { + capsearch_fail("Unknown option: $arg", 2); + } else { + $queries[] = $arg; + } + } + + if ($queries === []) { + capsearch_fail('Usage: php capability-search.php "" ["" ...] [--limit=10] [--index=] [--lock=] [--json]', 2); + } + + if ($index === null || $index === '') { + $env = getenv('CAPABILITY_MAP_INDEX_URL'); + $index = is_string($env) && $env !== '' ? $env : CAPSEARCH_DEFAULT_INDEX_URL; + } + + return ['queries' => $queries, 'limit' => $limit, 'index' => $index, 'lock' => $lock, 'json' => $json]; +} + +function capsearch_project_root(): ?string +{ + $explicit = getenv('SPRYKER_PROJECT_ROOT'); + if (is_string($explicit) && $explicit !== '') { + $real = realpath($explicit); + + return $real === false ? null : $real; + } + + $dir = (string)getcwd(); + while (true) { + if (is_file($dir . '/composer.json')) { + return $dir; + } + $parent = dirname($dir); + if ($parent === $dir) { + return null; + } + $dir = $parent; + } +} + +/** + * @return array|null package name (lowercase) => version, null without a readable composer.lock + */ +function capsearch_installed_packages(?string $lockPath): ?array +{ + if ($lockPath === null || !is_file($lockPath)) { + return null; + } + + $lock = json_decode((string)file_get_contents($lockPath), true); + if (!is_array($lock)) { + return null; + } + + $installed = []; + foreach (['packages', 'packages-dev'] as $section) { + foreach ($lock[$section] ?? [] as $package) { + if (is_array($package) && isset($package['name'])) { + $installed[strtolower((string)$package['name'])] = (string)($package['version'] ?? ''); + } + } + } + + return $installed; +} + +function capsearch_decode_index(string $content): ?array +{ + $index = json_decode($content, true); + + return is_array($index) && isset($index['cards']) && is_array($index['cards']) ? $index : null; +} + +function capsearch_download(string $url): ?string +{ + if (function_exists('curl_init')) { + $handle = curl_init($url); + curl_setopt_array($handle, [CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_TIMEOUT => CAPSEARCH_TIMEOUT, CURLOPT_FAILONERROR => true]); + $body = curl_exec($handle); + + return is_string($body) ? $body : null; + } + + $context = stream_context_create(['http' => ['timeout' => CAPSEARCH_TIMEOUT], 'https' => ['timeout' => CAPSEARCH_TIMEOUT]]); + $body = @file_get_contents($url, false, $context); + + return is_string($body) ? $body : null; +} + +/** + * @return array{cards: array>, stale: bool} + */ +function capsearch_load_index(string $source): array +{ + $isUrl = (bool)preg_match('#^https?://#i', $source); + + if (!$isUrl) { + $content = is_file($source) ? (string)file_get_contents($source) : ''; + $index = capsearch_decode_index($content); + if ($index === null) { + capsearch_fail("The capability map index could not be read from $source", 3); + } + + return ['cards' => $index['cards'], 'stale' => false]; + } + + $stateDir = getenv('CAPABILITY_MAP_STATE_DIR'); + $stateDir = is_string($stateDir) && $stateDir !== '' ? $stateDir : sys_get_temp_dir() . '/ai-dev-capability-map'; + $cacheFile = $stateDir . '/index-' . substr(md5($source), 0, 12) . '.json'; + + if (is_file($cacheFile) && time() - (int)filemtime($cacheFile) < CAPSEARCH_CACHE_TTL) { + $index = capsearch_decode_index((string)file_get_contents($cacheFile)); + if ($index !== null) { + return ['cards' => $index['cards'], 'stale' => false]; + } + } + + $body = capsearch_download($source); + $index = $body === null ? null : capsearch_decode_index($body); + if ($index !== null) { + if (is_dir($stateDir) || @mkdir($stateDir, 0775, true)) { + $tmp = $cacheFile . '.' . getmypid() . '.tmp'; + if (@file_put_contents($tmp, $body) !== false) { + @rename($tmp, $cacheFile); + } + } + + return ['cards' => $index['cards'], 'stale' => false]; + } + + $index = is_file($cacheFile) ? capsearch_decode_index((string)file_get_contents($cacheFile)) : null; + if ($index !== null) { + return ['cards' => $index['cards'], 'stale' => true]; + } + + capsearch_fail("The capability map could not be loaded from $source (download failed, no cache). Use the INDEX.md and card fetch fallback.", 3); +} + +/** + * @return array + */ +function capsearch_extract_terms(string $query): array +{ + $terms = preg_split('/[\s,;]+/u', mb_strtolower(trim($query)), -1, PREG_SPLIT_NO_EMPTY) ?: []; + + return array_values(array_unique(array_filter($terms, fn (string $term): bool => mb_strlen($term) >= CAPSEARCH_MIN_TERM_LENGTH))); +} + +function capsearch_stem(string $term): string +{ + foreach (CAPSEARCH_STEM_SUFFIXES as $suffix) { + if (str_ends_with($term, $suffix) && mb_strlen($term) - mb_strlen($suffix) >= CAPSEARCH_MIN_STEM_LENGTH) { + return mb_substr($term, 0, -mb_strlen($suffix)); + } + } + + return $term; +} + +function capsearch_count(string $term, string $lowerText): int +{ + $total = 0; + foreach (array_unique([capsearch_stem($term), $term]) as $variant) { + if (mb_strlen($variant) <= CAPSEARCH_SHORT_TERM_LENGTH) { + $total += (int)preg_match_all('/\b' . preg_quote($variant, '/') . '\w{0,2}\b/u', $lowerText); + + continue; + } + $total += substr_count($lowerText, $variant); + } + + return $total; +} + +/** + * @param array $card + * @param array $terms + * + * @return array{card: array, matched: array>, sortKey: array}|null + */ +function capsearch_score_card(array $card, array $terms): ?array +{ + $strongText = mb_strtolower(($card['capability'] ?? '') . ' ' . implode(' ', $card['synonyms'] ?? [])); + $moduleText = mb_strtolower(implode(' ', $card['modules'] ?? [])); + $bodyText = mb_strtolower(implode("\n", $card['sections'] ?? [])); + + $strongWeight = 0; + $strong = $modules = $body = []; + foreach ($terms as $term) { + $count = capsearch_count($term, $strongText); + $strongWeight += $count; + if ($count > 0) { + $strong[] = $term; + } + if (capsearch_count($term, $moduleText) > 0) { + $modules[] = $term; + } + if (capsearch_count($term, $bodyText) > 0) { + $body[] = $term; + } + } + + if ($strong === [] && $modules === [] && $body === []) { + return null; + } + + $bodyOnly = array_values(array_diff($body, $strong, $modules)); + + return [ + 'card' => $card, + 'matched' => ['capability' => $strong, 'modules' => $modules, 'body' => $bodyOnly], + 'sortKey' => [-count($strong), -$strongWeight, -count($modules), -count($bodyOnly), CAPSEARCH_STATUS_RANK[$card['status'] ?? ''] ?? 3], + ]; +} + +/** + * @param array $card + * @param array|null $installed + * + * @return array + */ +function capsearch_install_status(array $card, ?array $installed): array +{ + $features = []; + foreach ($card['features'] ?? [] as $name) { + $key = strtolower((string)$name); + $features[] = ['name' => $name, 'installed' => $installed === null ? null : isset($installed[$key]), 'version' => $installed[$key] ?? null]; + } + + $modules = []; + foreach ($card['modules'] ?? [] as $path) { + if (!str_starts_with((string)$path, 'vendor/')) { + continue; + } + $package = strtolower(substr((string)$path, 7)); + $optional = false; + foreach (CAPSEARCH_OPTIONAL_MARKERS as $marker) { + $optional = $optional || str_contains($package, $marker); + } + $modules[] = ['package' => $package, 'optional' => $optional, 'installed' => $installed === null ? null : isset($installed[$package])]; + } + + $missing = fn (array $entries, string $key): array => array_values(array_map(fn (array $e) => $e[$key], array_filter($entries, fn (array $e): bool => $e['installed'] === false))); + $required = array_filter($modules, fn (array $m): bool => !$m['optional']); + $missingPackages = $missing($required, 'package'); + $missingOptional = $missing(array_filter($modules, fn (array $m): bool => $m['optional']), 'package'); + $missingFeatures = $missing($features, 'name'); + + if ($installed === null) { + $status = 'unknown'; + } else { + $checked = $required ?: $modules; + if ($checked === []) { + $status = count($missingFeatures) < count($features) ? 'installed' : 'not_installed'; + } else { + $count = count(array_filter($checked, fn (array $m): bool => $m['installed'] === true)); + $status = $count === count($checked) ? 'installed' : ($count > 0 ? 'partially_installed' : 'not_installed'); + } + } + + // One feature is required by name; several features are alternatives, so the missing module packages are named instead. + $toRequire = count($features) === 1 && $missingFeatures !== [] ? $missingFeatures : $missingPackages; + $composerRequire = $status === 'installed' || $toRequire === [] ? null : 'composer require ' . implode(' ', $toRequire); + + return [ + 'installStatus' => $status, + 'features' => $features, + 'missingPackages' => $missingPackages, + 'missingOptionalPackages' => $missingOptional, + 'composerRequire' => $composerRequire, + ]; +} + +function capsearch_card_url(string $indexSource, array $card): string +{ + $isUrl = (bool)preg_match('#^https?://#i', $indexSource); + $base = $isUrl ? substr($indexSource, 0, (int)strrpos($indexSource, '/') + 1) : CAPSEARCH_DEFAULT_INDEX_URL; + $base = $isUrl ? $base : substr($base, 0, (int)strrpos($base, '/') + 1); + + return $base . ($card['file'] ?? ''); +} + +/** + * @param array> $cards + * @param array|null $installed + * + * @return array + */ +function capsearch_run_query(string $query, array $cards, ?array $installed, int $limit, string $indexSource): array +{ + $terms = capsearch_extract_terms($query); + $scored = []; + foreach ($cards as $card) { + if (($card['status'] ?? '') === 'planned') { + continue; + } + $hit = $terms === [] ? null : capsearch_score_card($card, $terms); + if ($hit !== null) { + $scored[] = $hit; + } + } + usort($scored, fn (array $a, array $b): int => $a['sortKey'] <=> $b['sortKey']); + + $hits = []; + foreach (array_slice($scored, 0, $limit) as $hit) { + $card = $hit['card']; + $hits[] = [ + 'slug' => basename((string)($card['file'] ?? ''), '.md'), + 'capability' => $card['capability'] ?? '', + 'status' => $card['status'] ?? '', + 'matched' => $hit['matched'], + ] + capsearch_install_status($card, $installed) + ['url' => capsearch_card_url($indexSource, $card)]; + } + + return ['query' => $query, 'terms' => $terms, 'count' => count($hits), 'hits' => $hits]; +} + +function capsearch_main(array $argv): void +{ + $args = capsearch_parse_args($argv); + + $lockPath = $args['lock']; + if ($lockPath === null) { + $root = capsearch_project_root(); + $lockPath = $root === null ? null : $root . '/composer.lock'; + } + $installed = capsearch_installed_packages($lockPath); + + $index = capsearch_load_index($args['index']); + + $queries = []; + $summary = []; + foreach ($args['queries'] as $query) { + $result = capsearch_run_query($query, $index['cards'], $installed, $args['limit'], $args['index']); + $queries[] = $result; + $top = array_slice(array_map(fn (array $h): string => $h['slug'] . ' (' . $h['installStatus'] . ')', $result['hits']), 0, 3); + $summary[] = '"' . $query . '": ' . ($result['count'] === 0 ? 'no hits' : implode(', ', $top)); + } + + $output = [ + 'queries' => $queries, + 'source' => ['url' => $args['index'], 'stale' => $index['stale']], + 'note' => CAPSEARCH_NOTE, + ]; + + if (!$args['json']) { + echo 'capability-search: ' . implode(' | ', $summary) + . ($installed === null ? ' [no composer.lock: installStatus unknown]' : '') + . ($index['stale'] ? ' [stale cache]' : '') . "\n"; + } + echo json_encode($output, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n"; +} + +capsearch_main($argv); 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 5f09398..18bd61b 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 @@ -50,6 +50,7 @@ Default to **narrow and sharp**; expand only where the user asks for detail. Cut **Before any requirement, story, or design, investigate.** Requirements written from memory drift from how Spryker actually works. Do this in three layers — **code first, then docs, then (for existing flows) the running app**: the codebase facts are cheap inline calls that settle most questions outright and tell you exactly what the expensive docs research should target. **Two of the three layers are opt-in — ASK the user before running them** (steps 2 and 3 below). Step 1 (codebase facts) is always done. 1. **Codebase facts — inline, first, using the Spryker tooling MCP server.** Establish against the real install what exists and pin down exact names — this is where the decisive findings usually come from. Match tools by **tool name** (server names vary by install; some clients namespace as `mcp____`): + - `searchSprykerCapabilities` - **the FIRST call, before the module tools below.** Search the Spryker capability map with the feature's nouns and their synonyms (several short queries) to learn whether Spryker already ships this capability, and whether the project has it installed. Open the top hits with `getSprykerCapability`. Follow the `find-existing-capability` skill for the queries, the per-hit verdicts and the fallback when the tool is unavailable. **A PRD for something that ships is framed as "configure / extend / install X", not "build X"**: installed means extend, partially or not installed means install the feature first (`spryker-feature-install`), and only a `partial` card's gap or a miss that survives the docs and module cross-check is "build". - `getSprykerModules` — confirm the module exists and get its exact name. - `getSprykerModuleMap` — the module's API surface: find the **controller + action** behind the feature, the **plugins / extension points** it hooks into, and whether the capability already ships. (For Yves, routes come from `RouteProviderPlugin`s; for Glue, the resource name from a `ResourceRoutePlugin`.) - `getTransferStructureByName` — real field names/types for any transfer a story touches. Never invent transfer fields. @@ -127,7 +128,7 @@ Run the **scenario lint pass** (see the checklist in [gherkin-guide.md](gherkin- ## Critical Requirements ### 1. Research before requirements — code first -Codebase facts (step 1) are not optional and come **first** — module names, transfer fields, controller/actions, and endpoint paths trace to the inline codebase tools (`getSprykerModules`/`getSprykerModuleMap`/`getTransferStructureByName` + `deploy.dev.yml`), never guessed, and they target the docs research that follows. Docs research (step 2) and running-app validation (step 3) are **opt-in — ask the user first**. Docs research, when run, is dispatched to **`spryker-docs-research` subagent(s) with your harness's subagent tool** (parallel subagents with explicit non-overlap boundaries when the feature spans multiple concepts) so documented behavior/actors trace to the merged subagent briefs — with the stated harness fallback (consent, else inline) when subagent dispatch isn't permitted; existing-flow behavior traces to what `spryker-runtime` observed. If the tooling MCP server is down, start it and ask the user to reload the MCP connection before falling back to the built-in file read/search tools. +Codebase facts (step 1) are not optional and come **first** - whether Spryker already ships the capability comes from `searchSprykerCapabilities` (the first call), and module names, transfer fields, controller/actions, and endpoint paths trace to the inline codebase tools (`getSprykerModules`/`getSprykerModuleMap`/`getTransferStructureByName` + `deploy.dev.yml`), never guessed, and they target the docs research that follows. Docs research (step 2) and running-app validation (step 3) are **opt-in — ask the user first**. Docs research, when run, is dispatched to **`spryker-docs-research` subagent(s) with your harness's subagent tool** (parallel subagents with explicit non-overlap boundaries when the feature spans multiple concepts) so documented behavior/actors trace to the merged subagent briefs — with the stated harness fallback (consent, else inline) when subagent dispatch isn't permitted; existing-flow behavior traces to what `spryker-runtime` observed. If the tooling MCP server is down, start it and ask the user to reload the MCP connection before falling back to the built-in file read/search tools. ### 2. Strict actor assignment Every story names one canonical actor from [actors.md](actors.md). One actor per story — if two actors are involved, split the story. @@ -202,7 +203,7 @@ Ask the user at Phase 8 which location: ## Interactive Workflow Checklist -- [ ] Phase 0: Gathered codebase facts inline **first** (`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 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 diff --git a/plugins/spryker-ai-dev-sdk/skills/product-requirement-document/workflow.md b/plugins/spryker-ai-dev-sdk/skills/product-requirement-document/workflow.md index 885b65e..734b436 100644 --- a/plugins/spryker-ai-dev-sdk/skills/product-requirement-document/workflow.md +++ b/plugins/spryker-ai-dev-sdk/skills/product-requirement-document/workflow.md @@ -15,6 +15,7 @@ Ground everything in real Spryker before drafting — **code first, then docs**: **Step 0.1 — Codebase facts (inline, first, Spryker tooling MCP server)** Establish against the real install what exists and pin exact names — match tools by tool name (server names vary by install): +- `searchSprykerCapabilities` - **first call, before the module tools.** Search the Spryker capability map with the feature's nouns and synonyms (several short queries), then open the top hits with `getSprykerCapability`, to learn whether Spryker already ships the capability and whether the project has it installed. See the `find-existing-capability` skill for queries, per-hit verdicts and the no-MCP fallback. **A PRD for something that ships is framed as "configure / extend / install X", not "build X"** (installed: extend; partially or not installed: install the feature first via `spryker-feature-install`; a `partial` card: only the gap is built). - `getSprykerModules` — exact module name(s). - `getSprykerModuleMap` — controller+action behind the feature, plugins/extension points, whether it already ships. (Yves routes from `RouteProviderPlugin`s; Glue resource from a `ResourceRoutePlugin`.) **Take vendor paths from the map's output — never guess `Business/...` sub-paths.** - `getTransferStructureByName` — real transfer field names/types. Never invent fields. @@ -32,7 +33,7 @@ If the feature modifies or extends an existing flow, ask the user: *"This extend **Step 0.4 — Hold the findings** Keep what you gathered: real module/transfer names always; documented behavior (if researched) and observed behavior (if validated) when applicable. They feed Phases 3–5 directly. Do not invent any of these later. -**CHECKPOINT:** Do not draft requirements until codebase facts (incl. the project-overlap sweep) are gathered, the opt-in questions (docs / running-app validation) have been asked, and any tool gaps are surfaced to the user. +**CHECKPOINT:** Do not draft requirements until codebase facts (incl. the capability-map search and the project-overlap sweep) are gathered, the opt-in questions (docs / running-app validation) have been asked, and any tool gaps are surfaced to the user. ### Phase 1: Initial Requirements Gathering 🔄 INTERACTIVE 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 17fe1d8..dc5da99 100644 --- a/plugins/spryker-ai-dev-sdk/skills/project-data/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/project-data/SKILL.md @@ -22,6 +22,7 @@ You drive the `spryker-import-tools` scripts (`csv.php` + `validate.php`) with j Ad-hoc **add / edit / filter / one-off remove** on import data that isn't one of the above is the same tools driven directly (`csv filter`/`delete`/`set`/`duplicate-*` → `validate` → apply) — no separate strategy; use the shared core and the closest reference for the cascade rules. +- **A data hand-off from `spryker-feature-install`** (`.ai-dev/feature-install//data-handoff-
.md`) is an ad-hoc add with a fixed row list: add exactly the rows it names, to the files it names, with the project's locales and stores; change no other row. Apply with the reset ladder below, then report per hand-off row: added, or not added with the reason. The feature skill checks the result and owns the checklist. - Standalone (a user asks directly), classify their words against the table — **never make them name a strategy or a file.** "Add demo data for my shop" → generate. "Drop the demo customers" → cleanup. "We only sell heat-recovery" → reduce. If the request is ambiguous, ask one plain question. - In the **wizard**, `data.mode` picks it: `adapt`→adapt, `clean`→clean, `generate`→generate, `leave`→skip entirely; plus a `reduce` pass after adapt if `reduce_catalog ≠ keep:all`. `generate` carries a **`source` axis**: `authored` (interactive authoring — the not-hands-off warning attaches here) or `dataset: ` (a supplied structured catalogue: the path plus a field mapping; conversion into the import CSVs goes through `php append`/`add-row`, and where a JSON→CSV conversion needs a script, state it as a deviation in the step report with the reason, write LF, and run `php preflight ` right after). Never record an invented marker (`authoring: none`) to mean "dataset" — use the axis. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-customization/README.md b/plugins/spryker-ai-dev-sdk/skills/spryker-customization/README.md index dbf85a4..3f09f41 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-customization/README.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-customization/README.md @@ -9,6 +9,8 @@ focused work to the `spryker-*` subagents and skills at the points the workflow are fixed up front — a quality bar (PoC or MVP) and which phases run — and user-facing interaction is deliberately compressed into two gates: one consolidated planning round, and the commit. +Work that adds a new capability passes the reuse gate first (`find-existing-capability`): a capability Spryker already ships is extended, and a feature that is not installed is installed through `spryker-feature-install` before any custom code is written. + It **never auto-commits**, never pushes, and never works on the user's current branch. ## When it triggers 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 d89e7c7..1d2bb19 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-customization/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-customization/SKILL.md @@ -168,6 +168,8 @@ A short ask ("hide this label") still gets a one-line intake before any edit — ## Step 3: Plan +**Reuse gate - before the solution design, when the work adds a new capability rather than changing an existing one** (a new module, feature or integration area; not a tweak to a behaviour you can already name): run the `find-existing-capability` skill (`/find-existing-capability`, or `/spryker-ai-dev-sdk:find-existing-capability` on a plugin install) on the PRD's capabilities, or reuse its Reuse decision if the PRD step already produced one. A shipped capability is extended, not rebuilt: **installed** means the plan extends it through the card's extension points; **partial** means the plan builds only the gap; **not installed** or **partially installed** means the plan starts with installing the feature through `spryker-feature-install` (after the user agrees), and custom code comes after the feature is in. Only "no relevant hit" after the cross-check lets the plan build from scratch, and the plan says that the check ran. Record the verdict in `decisions.md`. + **Before planning, always invoke `spryker-feature-expert`** for every Spryker domain the PRD touches. The division of labour is **discovery vs confirmation**: - **Discovery is the expert's, never yours.** *Which* mechanism, *which* extension point, *how does feature X work*, *which fields does this transfer have*, *which modules exist* — sweeping questions where the expert's synthesis beats raw grepping (`getTransferStructureByName`, `getInterfaceMethodsByNamespace`, `getSprykerModules`, docs). If the expert's first answer isn't enough, ask a more specific follow-up — don't fall back to exploratory grep of `vendor/spryker/`. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-customization/references/delegation.md b/plugins/spryker-ai-dev-sdk/skills/spryker-customization/references/delegation.md index c677348..d74f187 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-customization/references/delegation.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-customization/references/delegation.md @@ -29,10 +29,13 @@ These are **skills** (loaded into the main session), not subagents. Invoke each | Skill | When to invoke | |---|---| +| `find-existing-capability` | Step 3, before the solution design - when the work adds a new capability rather than changing an existing one. Searches the Spryker capability map and returns a reuse verdict (extend / install / build the gap / build new). Report-only. | +| `spryker-feature-install` | Step 3 - when the reuse gate says a shipped feature is `not_installed` or `partially_installed` and the user agrees to install it, before any custom code. Installs the feature per its official guide. | | `product-requirement-document` | Step 0c — when the user has no PRD (or wants to create/refresh one) before intake. Creates the business-facing PRD that Step 1 reads. | | `spryker-refresher` | Step 5 — post-change commands (composer dumpautoload, codegen, schema, cache clears, frontend builds, cache warmups). Mandatory; the orchestrator must not run `docker/sdk console` / `docker/sdk cli composer` inline during Step 5. | | `spryker-qa-coverage` | Step 6 (when the QA-thorough phase is on) — expand the AC list + scale envelope into a 5-bucket test plan before invoking the verifier. | | `ai-runtime-debugging` | When you need to see runtime values that aren't surfacing in logs / DB / browser state — during Step 4 build or Step 7 self-correct. Teaches the `[AI-DEBUG]` tagged-log pattern and optional XDebug step-debug. Always paired with a cleanup pass in Step 7b. | | `cypress-tests` | Step 7a (when the Cypress E2E phase is on) — once all ACs are green, fix / improve / add a Cypress E2E spec locking in the user-visible behavior, run it targeted + the suite's quality gate. | | `yves-atomic-frontend` | Step 4 — before the first write to any `.scss` / `.ts` / atomic-component file under `Theme/default/components/`. | +| `yves-twig-integration` | Step 4 - when the work relies on a core widget or component that the storefront does not render, or after `spryker-feature-install`: suggests where the vendor templates place it in templates the project overrides, and places the picked ones in the project's design. | | `static-validation` | Step 7b — lint / phpcs / phpstan over the final diff before commit. | diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md new file mode 100644 index 0000000..ed3967c --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md @@ -0,0 +1,117 @@ +# spryker-feature-install + +Install a Spryker feature into a project **end to end**, from a capability card or a feature name: +resolve the feature, its required features and the release it needs; turn the official install guide +into a checklist with one row per step; reconcile each row with the reference demo shop; apply it in +the project layer; suggest storefront placement; verify; and prove the release steps that existing +environments need. + +Where `find-existing-capability` decides "install it instead of building it", this skill does the +install — always after the developer confirms the feature, packages, release and optional +integrations. + +## When it triggers + +"Install the X feature", "add `spryker-feature/x`", "integrate feature X", "install the X Glue API", +after `find-existing-capability` proposed an install (`not_installed` / `partially_installed`), or a +feature that `spryker-upgrade` Phase 6 accepted. + +## Flow schema + +```mermaid +flowchart TD + A([Feature name or capability card]) --> P0["0 - Preflight and baselines
stack, container sync, vendor vs lock,
frontend deps; PHPStan, sniffer, tests, crawl"] + P0 --> B["1 - Resolve
card: feature, required features, guide
install release; modules the feature needs"] + B --> UP{"Another feature package
or a root pin must move?"} + UP -- "yes" --> X(["Stop: offer spryker-upgrade"]) + UP -- "no" --> S["2 - Sources
guide, prerequisite guides,
reference demo shop and its history"] + S --> C["3 - Checklist and confirmation
parse-integration-guide, check-feature-installed
data classes; developer gate #1"] + C --> R["4 - Reconcile
find-feature-change adds reference-only rows
decision per row; gate: check-checklist decide"] + R --> I["5 - Install
composer, check-lock-diff, override checks
one guide section at a time, spryker-refresher
gate: check-feature-installed --wiring"] + I --> Y["5b - Storefront placement
yves-integration-scan suggestions
yves-twig-integration on the developer's pick"] + Y --> V["6 - Verify
auth precondition, spryker-verifier per
Verification row, baselines compared"] + V --> T["6b - Tests
port the reference tests, add functional,
API or Cypress tests the project runs"] + T --> RS["7 - Release steps
diff-release-steps, prove with
deployed vs fresh comparison"] + RS --> RP(["8 - Report
status: check-dod DONE or NOT DONE"]) +``` + +## Scripts + +`$FI` in every example is `/scripts`. Run the scripts from the project root; +`SPRYKER_PROJECT_ROOT` overrides it. All run on host PHP, with no Spryker bootstrap. + +| Script | Phase | What it answers | +|---|---|---| +| `parse-integration-guide.php` | 3 | which steps does the guide have, of which kind, in which scenario? | +| `check-feature-installed.php` | 3 (`--mark`), 5 (`--wiring`) | which modules and wiring does the project have already; is the decided wiring in place; which plugins belong to modules the project does not install? | +| `find-feature-change.php` | 4 | which pull request brought the feature into the reference demo shop, and which of its files does no row name? | +| `check-checklist.php` | 4 (`--phase decide`), 8 (`--phase report`) | is every row decided; is every row done, every verification passed, and the feature covered by a passing test? | +| `check-needed-moves.php` | 5 | which moved packages does the feature need, and which only moved because composer could move them? | +| `check-lock-diff.php` | 5 | which packages moved outside the feature's dependency tree; does a required package have a dev constraint? | +| `glossary-key-check.php` | 5 | which translation keys the feature uses (Twig, PHP mail subjects and messages) or ships have no glossary row for a project locale? | +| `check-data-manifests.php` | 5 | is every data file the install wrote imported by a manifest a deploy recipe runs? | +| `compare-baselines.php` | 0, 6 | does every baseline hold a result; did PHPStan, the sniffer, the tests, the Back Office crawl, the storage counts or a frontend build regress? | +| `diff-release-steps.php` | 7 | which commands, imports, republishes and variables does the deploy recipe not cover? | +| `dump-state.php` | 7 | is a deployed environment the same as a fresh install? Dumps tables and search indices without ids and timestamps, and compares two dumps | +| `check-dod.php` | 8 | is the integration DONE? Each of the ten Definition of Done items, met or not, from the evidence in the state directory | + +`lib.php` is the shared library. The baselines and the override checks reuse +`../spryker-upgrade/scripts/`; storefront placement uses `../yves-twig-integration/scripts/`. The +maintainer test suite is not part of the plugin: it lives in the plugin repository, in +`tests/scripts/feature-install/`. + +## State + +Everything a run writes is in the project, under `.ai-dev/feature-install//`: + +| Path | Content | +|---|---| +| `state.md` | The phase table: phase, status, evidence; the install release and added modules | +| `sources/` | The guides, the feature `composer.json`, the reference demo shop clone and its history | +| `checklist.json` | One row per guide step, with its decision, status and verdict | +| `dod.json` | The Definition of Done evidence no script can measure: scope, baselines, accepted module moves, after-install checks, texts the agent wrote (listed for review), accepted unproven release steps | +| `composer.lock.before` | The lock before the install | +| `baseline/` | The tool output before the install (the file names `spryker-upgrade` uses), and the crawl and counts reports | +| `after/` | The same tools after the install, and the frontend build output with its exit code | +| `data-handoff-
.md` | The fixed row lists for `project-data` | +| `release-steps.md` | The release-steps log | +| `report.md` | The install report for colleagues, written only when `check-dod.php` says DONE (`references/report.md`) | + +## The checklist row + +| Field | Content | +|---|---| +| `id`, `guide`, `section`, `lines` | Where the step comes from | +| `kind` | `composer`, `config`, `schema`, `event`, `transfer`, `oms`, `navigation`, `glossary`, `data-row`, `data-import`, `plugin`, `route`, `widget`, `queue`, `search-index`, `frontend`, `code`, `recipe`, `deploy`, `console`, `verification`, `test`, `linked-guide`, `unknown` | +| `tag` | `required`, `optional-scenario:`, `demo-data`, `fresh-install-only` | +| `data_class` | Data rows only: `feature-data`, `project-content`, `demo-data`, or null until decided | +| `target` | The file, the command, the plugin class, or the linked page | +| `plugins`, `packages`, `env` | The plugin classes a snippet wires, the packages a composer line requires, the environment variables a snippet reads | +| `source` | `guide`, or `reference-only` for a file only the reference demo shop changed | +| `reference` | `same`, `differs` or `absent`, with the reference path | +| `decision` | `apply-guide`, `apply-reference`, `merge`, `already-present`, `skip:` | +| `status` | `open`, `done`, `skipped`, `failed` | +| `verdict`, `verdict_note` | Verification rows: `PASS`, `FAIL`, `BLOCKED`, or `ACCEPTED` with the note | + +A plugin row with a class name as its `target` and a `note` comes from a plugin table that has no +wiring snippet in the guide: the guide lists the plugin and shows nowhere how to wire it. + +## Design decisions baked in + +- **The status comes from the Definition of Done.** `check-dod.php` decides DONE or NOT DONE; a blocker stops the run when it is found. +- **Confirm before changing.** Nothing is required or edited before the developer agrees to the + feature, release, constraint and optional integrations. +- **Every step is a row; every row is decided.** The checklist gates block the install and the + report while a row is undecided or open. +- **The reference demo shop decides the plugin subset and order; the project decides its config.** + The reference is `b2b-demo-marketplace` for every project type; plugins of capabilities the + project does not have are skipped. +- **The release the feature needs, not the latest.** The feature may move the modules it needs; + another feature package or a third-party root pin means an upgrade. +- **The guide is the source of truth for steps; the installed code for names.** +- **Project layer only.** Never `vendor/`, `src/Generated/` or `src/Orm/`. +- **The feature is covered by tests** in the suites the project runs; only the developer can waive it. +- **Release steps are proven.** A command the guide runs locally is a release step until a recipe + covers it. +- **Blocked is not failed.** A failed fixture login makes logged-in checks BLOCKED (environment). +- **No destructive commands, no auto-commit.** 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 new file mode 100644 index 0000000..da8f28b --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md @@ -0,0 +1,410 @@ +--- +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. +--- + +# Spryker Feature Install + +Take a Spryker feature from "not in the project" to "installed, wired, verified and releasable". +The goal is the documented integration, not a lookalike: a feature that ships is installed, then +extended, not rebuilt. Typical entry: `find-existing-capability` returned `not_installed` or +`partially_installed` and the developer agreed to install. + +## Non-negotiables — read these before Phase 0, re-read them on every compaction + +1. **Nothing changes before the developer confirms** the feature, the packages, the release, the + optional integrations and the branch (gate #1, Phase 3). +2. **One feature per run, at the release the feature needs.** A feature that exists at the + project's release installs at that release. A feature of a later release may move the modules it + needs; it may not move another `spryker-feature/*` package — that is a release upgrade, and the + run stops and offers `spryker-upgrade` (Phase 1). + *Failure signature:* a `composer require` that moves another `spryker-feature/*` package. +3. **Every guide step is a checklist row, and every row gets a decision.** The guide is never + followed from the prose. A step the parser cannot classify is a row of kind `unknown`, decided by + hand. `check-checklist.php` blocks the install while a row has no decision, and the report while a + row is open. *Failure signature:* an edit to a project file that no checklist row names. +4. **Merge into existing config and plugin stacks; never overwrite them.** The guide shows values + for a fresh project. A `...` in a guide snippet always means merge. + *Failure signature:* a diff line that removes a project value the guide does not name. +5. **The reference demo shop decides the plugin subset and order; the project decides its existing + config.** A guide plugin that the reference does not wire is a question for the developer. A + plugin of a capability the project does not have (merchants, company accounts, marketplace + offers) is not a step. +6. **Data rows go to `project-data`.** This skill writes no row in `data/import/**`. +7. **A command the guide runs locally is a release step until a recipe covers it** (Phase 7). +8. **The installed feature is covered by tests** in the suites the project runs (Phase 6b). Without + them, the next upgrade has nothing that notices the feature stopped working. Only the developer + can waive this, with a reason. +9. **Project layer only, and no shortcuts:** never `vendor/`, `src/Generated/`, `src/Orm/` or a + hand-edited `composer.lock`; never `dev-*` constraints or `--ignore-platform-reqs`; never a + suppression; never `docker/sdk reset` or `clean-data`; never a commit or push without the + developer's yes. Ask first before you write to a database by hand or change a user account. + Content you write yourself (translations, CMS text) is recorded, and the report lists it for + review. +10. **The status is `check-dod.php`'s, never yours** (§ Definition of Done). A blocker stops the run + when you find it (§ Blockers). + +## Definition of Done + +A feature integration is **DONE** only when all ten items hold, each one with its evidence in +`$STATE`. `php $FI/check-dod.php $STATE` decides it from that evidence. + +| # | Item | Evidence | +|---|---|---| +| 1 | The developer confirmed the scope: feature, install release, update mode, branch. | `dod.json` `scope` (Phase 3) | +| 2 | Every baseline ran and holds a result: PHPStan, sniffer, tests, Back Office crawl, storage and search counts. | `baseline/` tool output, `compare-baselines.php` (Phase 0) | +| 3 | Only modules the feature needs moved; every other move has the developer's reason. | `composer.lock.before` vs `composer.lock`, `check-needed-moves.php`; `dod.json` `accepted_moves` (Phase 5) | +| 4 | Every checklist row is decided, and done or skipped with a reason. | `checklist.json` | +| 5 | The decided wiring is in place. | `checklist.json` and the project's DependencyProviders | +| 6 | No regression against the baselines, and the Yves, Zed and Merchant Portal builds pass. | `after/` tool output, `compare-baselines.php` (Phase 6) | +| 7 | Every verification passed. BLOCKED and FAIL are not done; ACCEPTED counts with the developer's note. | `checklist.json` verdicts (Phase 6) | +| 8 | Passing tests cover the feature, or the developer waived them with a reason. | `checklist.json` `test` rows and their files, `tests_waived` (Phase 6b) | +| 9 | Every data file the install wrote is imported by a manifest a recipe runs, and every text you wrote is recorded for review. | `dod.json` `data_files`, `check-data-manifests.php`; `dod.json` `authored_content` (Phase 5) | +| 10 | Every release step is verified, or the developer accepted shipping it unproven. | `release-steps.md`; `dod.json` `release_steps_accepted` (Phase 7) | + +Items 2, 3, 5, 6, 8 and 9 are measured from files, not from what you write down. `dod.json` holds +only what no file shows: the scope, the developer's reasons, the texts you wrote, the data files the +hand-off wrote, and waivers (`"waived": {"baseline:": ""}`, `"check:"`). Its +format is in the header of `scripts/check-dod.php`. Only the developer's answer can make a waiver or +a reason. + +**The status is `check-dod.php`'s first line.** While it says `NOT DONE`, every message to the +developer opens with that line and the unmet items, the words "installed", "works", "done" or +"ready" do not describe the run, and nothing is offered for review. The install report +([references/report.md](references/report.md)) is written only after `DONE`. + +## Blockers + +A blocker is anything that stops a Definition of Done item from being met and that the install +itself cannot fix: a login that fails, a baseline that cannot run, a missing frontend dependency +tree, a check that needs a decision or data only the developer has. + +1. **Stop when you find it**, in the phase where you find it. Do not continue with the next phase + and report it at the end. +2. Record it in `dod.json` (`blocked: `) and in `state.md`. +3. Ask the developer, in one question: what blocks which item, and the options — fix it (with what + you need from them), waive the item with their reason, or stop the run. +4. Continue only on their answer. + +**Plan tracking is mandatory.** After Phase 0, create one task per phase in your harness's task +list, and keep the phase table in `$STATE/state.md`: it survives a compaction. + +**Locations.** `$FI` is `/scripts`, `$UP` is `/../spryker-upgrade/scripts`, +`$YI` is `/../yves-twig-integration/scripts`. `` is the path reported as +`Base directory for this skill:` when this skill loaded. `$STATE` is +`.ai-dev/feature-install//` in the project. Substitute each one inline as a literal +path; never set a shell variable and never `cd`. Run every script from the project root. + +**Delegation.** Invoke skills by slash command (`/spryker-refresher`, or +`/spryker-ai-dev-sdk:spryker-refresher` on a plugin install). Agent names carry the plugin prefix +on a plugin install, and the separator differs by harness (see +`../spryker-customization/references/delegation.md`). Siblings: `find-existing-capability`, +`spryker-docs-research`, `spryker-refresher`, `project-data`, `yves-twig-integration`, +`boot-and-verify`, `spryker-upgrade`; agents `spryker-verifier` and `spryker-issue-diagnoser`. + +## Tools + +Match tools by **tool name** (server names vary by install; some clients namespace them +`mcp____`). + +| Tool | Use | +|---|---| +| `searchSprykerCapabilities`, `getSprykerCapability` | Resolve the feature; the card's Install section, modules and `installStatus` (from `composer.lock`). | +| `searchAlgoliaDocumentation` | Find install guide pages; `github_api_url` is the markdown. | +| `getSprykerModules`, `getSprykerModuleMap` | What the project has now; exact plugin interfaces. | +| `getTransferStructureByName` | Transfer fields before a transfer XML edit. | + +**If the capability tools are not available**, tell the two causes apart, as `find-existing-capability` +describes: + +- **Not registered** (no `ai-dev:mcp-server` entry in `.mcp.json` or `.vscode/mcp.json`, and the + harness's MCP server list does not show it): go straight to the script below. There is nothing to + reconnect. +- **Registered but not connected:** start the server and ask the developer for a reload. After two + failed reconnects, use the script. + +The script searches the same capability map and reads `composer.lock`. Run it from the project root, +one quoted argument per query (the feature name and its synonyms): + +```bash +php /../find-existing-capability/scripts/capability-search.php "recurring orders" "subscription order" "scheduled reorder" +``` + +Per hit it prints `slug`, `installStatus`, `features`, `missingPackages`, `composerRequire` and +`url`. In place of `getSprykerCapability`, fetch the hit's `url`: it is the card. Without PHP or +network, use the web fallback of `find-existing-capability` (`INDEX.md`). **Never guess a card slug +or a package name.** Record in `state.md` that the search ran through a fallback. + +## Phase 0 — Preflight and baselines + +1. Run the checks in [references/environment-preflight.md](references/environment-preflight.md). A + stack that is down, a container that does not see the host files, a `vendor/` behind + `composer.lock` or a broken frontend dependency tree is a **pre-existing environment issue**, not + a feature failure. A plan-only run (Phases 1–4) needs no stack. +2. Create `$STATE/state.md` with the phase table (Phase, Status, Evidence). Copy `composer.lock` to + `$STATE/composer.lock.before`. +3. Before the install (Phase 5), record the baselines. The `$UP` scripts write into the directory + that `SPRYKER_UPGRADE_STATE_DIR` names: + ```bash + SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/check-plugin-usage.php || true + SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/check-config-constants.php || true + SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/check-dead-overrides.php snapshot + SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/twig-shadow-map.php snapshot + script -q /dev/null docker/sdk cli php -d memory_limit=2048M vendor/bin/phpstan analyze -c phpstan.neon src/ -l 6 2>&1 | tee $STATE/baseline/phpstan-baseline-run.txt + script -q /dev/null docker/sdk cli vendor/bin/console code:sniff:style 2>&1 | tee $STATE/baseline/sniff-baseline.txt + script -q /dev/null docker/sdk testing codecept run --no-exit 2>&1 | tee $STATE/baseline/codecept-baseline.txt + SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline SPRYKER_BACKOFFICE_USER= SPRYKER_BACKOFFICE_PASSWORD= php $UP/backoffice-smoke.php --url --baseline + ``` + For the storage and search counts, copy `$UP/storage-search-counts.php` into `$STATE/baseline/` + and run it in the container with `--snapshot before`. +4. Check the baselines: `php $FI/compare-baselines.php $STATE` — every line under "Baselines" is + `ok`. Red tests and existing findings are a valid baseline: they are what the project had before. + A baseline that did not run, or that an environment problem made fail (a failed login writes no + crawl baseline), is a blocker: stop and ask now (§ Blockers). Only the developer can waive it. + +## Phase 1 — Resolve the feature and its release + +1. **The feature.** From a card: `getSprykerCapability(slug)`. From a name: `searchSprykerCapabilities` + (or the search script, § Tools) with the name and its synonyms, then open the best card. Its Install section lists the + `spryker-feature/` package and guide URL, `Requires features:`, the Glue API guide and the + Storefront API packages. A card with several features offers alternatives: take the one that + matches the project. +2. **What is there.** `installed` → nothing to install: hand back to `find-existing-capability` + (extend it). `partially_installed` → install only `missingPackages`. +3. **Required features first.** The candidates are the card's `Requires features:` and the guide's + Prerequisites table. A prerequisite is **optional** when the guide says so (`(optional)` in the + table, or the text below the table; the parser records it as `optional: true` in Phase 3) or when + the feature package's `composer.json` does not require it. Check each one against + `composer.lock`: + - a missing required one is its own run, before this one: offer it; + - a missing optional one: ask whether to install it first. When the developer declines, the + guide rows that need it are `skip: not installed`; `check-feature-installed.php` + reports their classes as not in `vendor/`. +4. **The project type** in `state.md`: B2B or B2C, with or without marketplace. Phase 4 uses it. +5. **The install release.** Read the project's release (`spryker-feature/spryker-core` in + `composer.lock`) and the releases of the feature (`composer show -a spryker-feature/`). The + feature exists at the project's release → that is the install release. The feature first exists + in a later release → that first release is the install release. +6. **Dry-run the install, always, in the container**, also at the project's own release: the + project's modules are often older than the versions the feature needs, so the require moves + modules even then. Run it twice and compare: + `composer require spryker-feature/:^ -w --dry-run` (direct dependencies only) + and the same with `-W` (all dependencies). + - A conflict that names a `spryker/*` module and a minimum version → add + `spryker/:^` to the same `require` and dry-run again, until it resolves. + - Show the developer the result of both: how many packages each installs, updates and removes, + every major bump, and every removal. Recommend the one that moves less, unless it does not + resolve. Each major bump needs its migration guide, as `spryker-upgrade` Lane 0 describes. + - Stop and offer `spryker-upgrade` (`/spryker-upgrade`, or `/spryker-ai-dev-sdk:spryker-upgrade` + on a plugin install) when another `spryker-feature/*` package must move, a conflict names a + package that is not a `spryker/*` module (a root pin of a Symfony or other third-party + package), the same package comes back in a later round, or nothing resolves. Name the + blocking packages from the composer output. + Record in `state.md` the install release, the added modules, and both dry-run results. + +## Phase 2 — Collect the sources + +Read [references/sources.md](references/sources.md) on entry. Put everything in `$STATE/sources/`: +the install guide (the docs page and the include it wraps, plus `_config.yml`), every prerequisite +and linked guide, the `spryker-feature/` `composer.json` at the install release, the reference +demo shop at that release tag, and its history as a bare clone. Record in `state.md` each source that +was not found. + +## Phase 3 — Checklist and confirmation (developer gate #1) + +1. Parse the guide, then append each prerequisite and linked guide: + ```bash + php $FI/parse-integration-guide.php $STATE/sources/docs/ --docs-root $STATE/sources/docs --release --out $STATE/checklist.json + php $FI/parse-integration-guide.php --docs-root $STATE/sources/docs --out $STATE/checklist.json --append + ``` + Exit 1: open each `unknown` row at its `lines` and set its `kind` by hand. +2. `php $FI/check-feature-installed.php $STATE/checklist.json --mark` — modules already installed, + and wiring rows already present (`already-present`). +3. Give every data row its `data_class` ([references/data-classes.md](references/data-classes.md)). +4. **Present one confirmation block and wait for the answer** (your harness's question tool, else + in chat). It carries: + - the feature, the packages `composer require` adds, the install release, the modules Phase 1 + added, and required features to install first; + - the update mode, `-w` or `-W`, with the moves of each from the Phase 1 dry runs; + - each missing optional prerequisite: install it first, or skip the rows that need it; + - the version constraint in the project's style (`^` for features, `^x.y.z` for + modules); + - the optional blocks, one choice each: every `optional-scenario:*` tag, the Glue, Storefront and + Backend APIs (default: only the APIs the project already exposes), and demo data; + - that storefront placement comes after the backend steps, as a suggestion list; + - the environment: a bootstrap when the preflight found the stack down; any pre-existing issue; + - the branch: `ai-feature/` from `HEAD` when `git status` is clean; else ask first; + - the tests that will cover the feature (Phase 6b): the suites the project has, and the + reference tests to port; + - commits: one per guide section (recommended), or none until the report. + + Set `skip:` on every row of a block the developer did not choose. Record the answer in + `dod.json` `scope` (`feature`, `install_release`, `update_mode`, `branch`, and `confirmed`: the + developer's answer in their words). + +## Phase 4 — Reconcile + +Read [references/reconcile.md](references/reconcile.md) on entry. + +1. Add the files the reference changed for the feature that no row names: + ```bash + php $FI/find-feature-change.php --repo $STATE/sources/reference-history.git --package spryker-feature/ --checklist $STATE/checklist.json --add-rows + ``` + Exit 1: record that no reference change was found; the guide rows are then the only source. +2. For each row without a decision, compare it with the reference demo shop at the same place. Set + `reference` (`same`, `differs`, `absent`, with the path) and `decision` (`apply-guide`, + `apply-reference`, `merge`, `already-present`, `skip:`) by the reconcile rules. +3. Gate: `php $FI/check-checklist.php $STATE/checklist.json --phase decide` exits 0. + +## Phase 5 — Install + +1. Run the `composer` rows in the container, with the install release, the modules Phase 1 added, + and the update mode the developer chose. On a conflict, report it and stop. Then: + ```bash + php $FI/check-needed-moves.php --before $STATE/composer.lock.before --accepted $STATE/dod.json + ``` + It judges every moved package: `needed` (a requirer or a conflict rules out its old version), + `not needed` (its old version satisfies every requirer), or `unknown`. Move each `not needed` + package back to its version in `composer.lock.before` (`composer require :`, + then restore the constraint), and run the check again until only `needed` moves are left. A move + that stays without being needed needs the developer's reason in `dod.json` `accepted_moves`; + accepting the update mode at gate #1 is not a reason for each move. +2. When any module moved, check the project's customisations against it: + ```bash + SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/check-typed-members.php + SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/check-dead-overrides.php verify + SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/twig-shadow-map.php diff + ``` + A finding is damage from the module move: resolve it as `spryker-upgrade` Lanes 1 and 2 + describe, before the first guide section. +3. Work through the guide sections in guide order; prerequisite guides first. Per section, by + [references/apply-steps.md](references/apply-steps.md): + - apply the section's rows by their decision; set `status: done` or `failed` on each; + - hand the section's data rows to `project-data` (the hand-off format in + [references/data-classes.md](references/data-classes.md)). Record the files it wrote in + `dod.json` `data_files`, then `php $FI/check-data-manifests.php ...`: each file must be + imported by a manifest that a deploy recipe runs, for every environment that needs the rows; + - glossary: `php $FI/glossary-key-check.php --package= --locales=` lists the keys the feature uses or ships that have no row for a project locale; + - text the guide or the module does not ship (a translation for a project locale, CMS text) is + content you write (or hand to `translate-content`): record each file in `dod.json` + `authored_content` (`file`, `what`). The report lists it under "What was validated and how" + as "not validated — needs a review", like any code you wrote; + - schema rows: run `propel:diff` and show the migration before `propel:migrate`; the guide's + `propel:install` is for a fresh local database only; + - codegen and setup: `spryker-refresher` with the changed files, then the section's own setup + commands; + - re-run `check-plugin-usage.php` and `check-config-constants.php`; a new finding blocks the + next section; + - commit the section, if the developer chose commits. +4. Gate: `php $FI/check-feature-installed.php $STATE/checklist.json --wiring` exits 0. + +## Phase 5b — Storefront placement (optional, suggested) + +Only when the feature has Yves code and the project has a storefront. Install guides register +widgets; every vendor template the project overrides has lost the vendor's calls to them. + +1. `php $YI/yves-integration-scan.php --package=,...` for the feature's Yves + packages. +2. Present its suggestion table; ask which placements to apply (all, some, none). A + `not_registered` item is an unfinished `widget` row: finish it in Phase 5 first. +3. On a pick, invoke `yves-twig-integration` (`/yves-twig-integration`, or + `/spryker-ai-dev-sdk:yves-twig-integration`) with the picked items. On "none", record the table as + a follow-up. In an unattended run, apply nothing: the table goes into the report. + +## Phase 6 — Verify (developer gate #2) + +1. **Authentication first** for every check that needs a login: one fixture customer login through + Glue (`POST /access-tokens`) and one through Yves. Test credentials come from + `tests/cypress-tests/cypress/fixtures/**` and the project's seed files; never ask for or print + real credentials. A failed login makes the logged-in checks **BLOCKED (environment)**: hand it to + `spryker-issue-diagnoser`. +2. Give every `verification` row that is not skipped to the `spryker-verifier` agent as one + acceptance criterion, in the guide's words. Record `verdict` PASS, FAIL or BLOCKED with the + evidence path. Weigh a FAIL as a hypothesis before acting: browser problems look like feature + failures. +3. Run the baseline tools again, into `$STATE/after/` with the same commands as in Phase 0: + `phpstan-after.txt`, `sniff-after.txt`, `codecept-after.txt`; the Back Office crawl without + `--baseline` (same `SPRYKER_UPGRADE_STATE_DIR`: it marks each failure that is in the baseline); + the storage and search counts with `--snapshot after`, then `--compare before after`. Run each + frontend build the project has into `after/yves-build.txt`, `after/zed-build.txt`, + `after/mp-build.txt`, each ending with its exit code + (`… 2>&1 | tee ; echo "exit ${PIPESTATUS[0]}" >> `). Then + `php $FI/compare-baselines.php $STATE`: every line is `ok`. A new failure is this run's damage. +4. `getSprykerCapability(slug)` shows `installed` (or `partially_installed` for API packages skipped + on purpose). +5. A FAIL goes to `spryker-issue-diagnoser`; fix its root cause as a checklist row. A FAIL or + BLOCKED that stays goes to the developer: fix it, or accept it (`verdict: ACCEPTED` with a + `verdict_note`: who and why). + +## Phase 6b — Cover the feature with tests + +The tests pin what Phase 6 verified, so the next upgrade notices when the feature stops working. +Write them after Phase 6 passes, never before: a test written on a broken install pins the damage. + +1. **Find what the project runs.** Functional tests: `codeception.yml` and suites under + `tests/Test/` (Zed, Client, Yves, Glue). E2E tests: `cypress.config.*` or a + `tests/cypress*` directory. Use only the kinds the project already has; do not introduce a + framework. +2. **Start from the reference.** The `test` rows that `find-feature-change.php` added are the + reference demo shop's tests for the feature. Port each one into the project's namespace, fixtures + and data, or skip it with the reason (a scenario the developer declined, a capability the project + lacks). +3. **Cover what the reference does not.** One test per behaviour the feature adds, not per class: + - backend behaviour (a Verification row with a Back Office, API or database result, a plugin + stack the feature extends): a functional test through the Facade or the public Client or + Service, written with `codecept-functional`; + - an API block the developer chose: a Glue API test in the project's Glue suite; + - a storefront or Back Office flow, when the project has Cypress: an E2E test with + `cypress-tests`. + + The rules of [../spryker-upgrade/references/testing.md](../spryker-upgrade/references/testing.md) + apply: no tests for `*Factory`, `*Config` or `*DependencyProvider` classes, no getter or wiring + tests, no mocks of the feature's own modules. +4. **Each test is a checklist row** of kind `test`, with the test file as its `target`. Set + `status: done` only after it passes in the booted environment. Run the project's suite again: the + new tests must not turn an existing test red. +5. **A project without any test suite:** ask the developer. Only their answer can set + `tests_waived` in `checklist.json` (who and why); the report then names the feature as not + covered by tests. + +## Phase 7 — Release steps + +Do [references/release-steps.md](references/release-steps.md) exactly, in its order: list the +candidates with `php $FI/diff-release-steps.php $STATE/checklist.json`, write each uncovered one into +`$STATE/release-steps.md`, and prove the log with the comparison procedure, or record why it was not +proven. Each log row ends with its status: `verified`, `not needed`, `covered by recipe`, or +`to verify`. When the developer does not allow the proof, ask whether they accept shipping the +unproven steps, and record their reason in `dod.json` `release_steps_accepted`. + +## Phase 8 — Report + +1. Run `php $FI/check-dod.php $STATE`. Its first line is the run's status. +2. **NOT DONE:** the report opens with that line and the unmet items, each with what the + developer can do (fix, waive with a reason, accept). Then stop and ask. Do not describe the run + as installed, working, done or ready. +3. **DONE:** write `$STATE/report.md` with the template and rules in + [references/report.md](references/report.md). Problems found in the project that this install + did not cause go to the developer as ticket candidates, not into the report. +4. Leave uncommitted changes unstaged for review. Stage only the files you changed, by path, and + commit or push only on the developer's yes. + +## Hard rules + +- All state lives in `$STATE`. Never commit `$STATE/sources/` or the baselines. +- Offline, or a source not found → say so, record it in `state.md`, and stop for that source. Never + write a step from memory. +- A step is applied once. A row marked `already-present` is checked, not applied again. +- Never mark a row done without evidence, and never drop a failing row silently. +- Never claim "verified" for a row whose verdict is not PASS; an accepted row is reported as + accepted, with its note. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/apply-steps.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/apply-steps.md new file mode 100644 index 0000000..e63088c --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/apply-steps.md @@ -0,0 +1,55 @@ +# Applying checklist rows + +Apply each row by its decision, **in the project layer only**: the project's namespace directories +in `src/` (from `composer.json` `autoload.psr-4`; when a custom namespace comes before `Pyz` in +`KernelConstants::PROJECT_NAMESPACES`, new and overriding code goes there, and extends the `Pyz` +counterpart when one exists), plus `config/`, `data/import/` and the deploy files. Never `vendor/`, +`src/Generated/` or `src/Orm/`. The `spryker-customization` project-layer rules apply; its `rules/` +files (plugins, dependency providers, transfers) define the conventions. + +## Per row kind + +| Kind | How | +|---|---| +| `config` | Read the existing file first. Add the keys in the surrounding style; merge into an existing value (reconcile rule 2). No real secrets. | +| `plugin`, `route`, `widget`, `queue` | **Read the current plugin stack first.** Insert at the position the decision names (the reference order, else the guide's). Follow the project's own pattern for stack overrides: `parent::` plus a positional insert anchored on a named neighbour class, never a numeric index. A plugin the project already registers is `already-present`. | +| `plugin` with a `@deprecated` vendor class | Check every plugin class in `vendor/` for `@deprecated`. Use the named replacement; skip a deprecated plugin that has none. Record either case in the row's `note`. | +| `widget` | Register the widgets in `ShopApplicationDependencyProvider::getGlobalWidgets()`. Registration alone renders nothing in templates the project overrides: placing them is the storefront step. | +| `transfer` | Project layer; check fields with `getTransferStructureByName`. | +| `schema`, `event` | Project layer; follow the `propel-schema` conventions. | +| `navigation`, `route` | Add the entry; do not reorder existing ones. | +| `glossary` | Add the keys for every configured locale (through the `project-data` hand-off). Guides often have no glossary step, so also run `php $FI/glossary-key-check.php --package= --locales=`: it lists the keys the feature uses (Twig, PHP mail subjects and messages) or ships that no glossary row of the project defines, per locale. Add a `glossary` row with `data_class: feature-data` for each missing key; a missing key renders raw on the page. | +| `data-row`, `data-import` | Through the `project-data` hand-off ([data-classes.md](data-classes.md)). The importer plugin and console command registration stays here. | +| `deploy` | A new service or environment variable in a deploy file usually needs `docker/sdk up`, which is a rebuild: ask the developer. Never `docker/sdk reset` or `clean-data`. | +| `console` | Through `spryker-refresher` and the guide's own setup commands (below). | + +When a row conflicts with something the project already built (a plugin already registered, a field +already present, a value the project set differently), stop on that row, show the conflict and let +the developer choose. Do not overwrite. + +## Storefront API resources (API Platform) + +When a module ships `resources/api/storefront/*.resource.yml` and the project generates API Platform +resources (`src/Generated/Api/Storefront` exists; `config/GlueStorefront` alone is no proof), the +guide's `GlueApplicationDependencyProvider` route and relationship plugin rows do not apply: set +`skip:API Platform resource`. Keep the attribute-mapper and strategy plugin stacks: the resource +mapper reads them through `#[Plugins(dependencyProviderMethod: ...)]`. Code generation creates the +resource. + +## Codegen and setup after each section + +Invoke `spryker-refresher` with the files the section changed. It owns the file-pattern to command +mapping. Then: + +- **Glue applications are resolved, not assumed.** List `public/Glue*/index.php` and cross-check + the `entry-point: Glue*` values in the active deploy file. Run `vendor/bin/glue ` for + `public/Glue` and `GLUE_APPLICATION=GLUE_BACKEND vendor/bin/glue ` for + `public/GlueBackend`. Use `GLUE_APPLICATION=GLUE_STOREFRONT` only when + `public/GlueStorefront/index.php` exists and an entry point uses it. A recipe step for an + application that does not exist is `skip:no such Glue application`. +- Run the section's other `console` rows (a search setup, a feature importer) after you check that + each command exists: `docker/sdk console list`. +- Run the Yves and Zed frontend builds only when the section touched the frontend. + +A failing command: show its output and hand it to the `spryker-issue-diagnoser` agent before a +retry. Never skip a failing row to look green. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/data-classes.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/data-classes.md new file mode 100644 index 0000000..155e715 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/data-classes.md @@ -0,0 +1,51 @@ +# Data classes and the hand-off to project-data + +Every data row (`glossary`, `data-row`, `data-import`) gets a `data_class` before the install. The +parser sets it for translations and import configuration (`feature-data`) and for rows in a demo +data section (`demo-data`). Set the others by this test: + +| `data_class` | Test | Examples | What happens | +|---|---|---|---| +| `feature-data` | The feature fails, or shows raw glossary keys, with zero rows. | Glossary keys, permissions, ACL rules, type or status rows that have no Back Office create page, the entries in `data/import/*.yml`. | Always installed. | +| `project-content` | The feature needs at least one row, but the values are a project decision. | Service types, asset types, CMS slots for the feature. | Ask the developer for the values, or use the reference values as placeholders and list them for `curate-golive-data`. | +| `demo-data` | The feature works without the rows. | Sample assets, inquiries, orders. | Only when the developer chose demo data at gate #1. Otherwise `skip:demo data declined`. | + +When a row could be two classes, take the stricter one (`feature-data` before `project-content` +before `demo-data`) and write the reason in `note`. + +## What this skill writes, and what project-data writes + +| Part | Owner | +|---|---| +| Rows in `data/import/**` CSV files | `project-data` | +| Entries in the data import configuration (`data/import/**/*.yml`) | `project-data` | +| The importer plugin registration (`DataImportDependencyProvider`) and console commands (`ConsoleDependencyProvider`) | this skill | +| A new importer module | `data-import` skill | +| The check that the rows arrived | this skill | + +## The hand-off + +Write one file per guide section, `$STATE/data-handoff-.md`, and give it to +`project-data` (`/project-data`, or `/spryker-ai-dev-sdk:project-data` on a plugin install): + +```markdown +# Data hand-off: — + +Fixed row list. Add exactly these rows; change no other row. + +| Row | File | data_class | Rows to add | Source | Importer | +|---|---|---|---|---|---| +| R018 | data/import/common/common/glossary.csv | feature-data | keys, per project locale | guide lines – | data:import glossary | +| R041 | data/import/common/common/ssp_asset.csv | demo-data | rows | reference data/import/common/common/ssp_asset.csv | data:import:ssp-asset | + +Import config entries: . +Locales and stores: . +``` + +- `Rows to add` copies from the guide snippet or from the reference file. A `project-content` row + carries the values the developer gave, or says `placeholder` for each one. +- `project-data` writes and applies the rows with its apply ladder. Then check the result: the rows + are in the database and the feature shows them. Set the checklist rows to `done` only after that + check. +- Every `feature-data` and `project-content` row is also a release-step candidate: existing + environments do not import it on deploy ([release-steps.md](release-steps.md)). diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/environment-preflight.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/environment-preflight.md new file mode 100644 index 0000000..8a2167f --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/environment-preflight.md @@ -0,0 +1,28 @@ +# Environment preflight + +Shared by `spryker-feature-install` (Phase 0) and `spryker-upgrade`. Run it before the first `composer require` or `composer update`, and before any step that needs the stack (codegen, `propel:install`, imports, verification). Reading a guide or planning a checklist needs no stack: skip the preflight for a plan-only run. Everything here is read-only except the bootstrap, which the user confirms first. + +Report a failure as a **pre-existing environment issue**, before the confirmation block, and not as a feature or upgrade failure. + +## 1. Is the stack needed, and is it up + +`composer` runs in the project's PHP container (`docker/sdk cli composer ...`); `--ignore-platform-reqs` is not an option. Check `docker info` and the running containers of the project (`docker ps`). `docker/` is usually a submodule: `git submodule status` before calling it absent (see `../../spryker-upgrade/references/environment.md`). + +When the stack is down or was never booted, **suggest the bootstrap in the confirmation block** instead of failing at `composer require`: + +- name the deploy file: the project's `deploy.*.yml` files, with the one the user named or the last-booted one first; +- check for port clashes with other running stacks (`docker ps` published ports, the deploy file's hosts); +- offer `docker/sdk boot ` plus `docker/sdk start` when containers exist, `docker/sdk up` when they do not (that is a build and takes a while, say so); +- never `docker/sdk reset` or `clean-data`. + +## 2. Does the container see the host files + +Compare a checksum of `composer.json` and `composer.lock` on the host and in the container (`docker/sdk cli sha1sum composer.json composer.lock`). On a mutagen-synced project a mismatch means the sync is behind: run `mutagen sync flush` (the project's sync session, `mutagen sync list`), re-compare, and report sync conflicts (for example from deleted `vendor/` folders) without resolving them silently. + +## 3. Is `vendor/` in line with `composer.lock` + +`docker/sdk cli composer install --dry-run`: expect no operations. Operations listed mean `vendor/` is behind the lock (a dry run of one new package would then show every pending package); report the count, and offer `composer install` as the first step of the run, not as part of the feature. + +## 4. Do the frontend dependencies resolve + +For every `vendor/**/package.json` the Yves build uses (`spryker-shop/*`, `spryker/*`), check that each dependency appears in the project's `package-lock.json`. A package that requires a dependency the lock lacks (for example `style-dictionary` required by `spryker-shop/shop-ui`) fails the frontend build with `ERR_MODULE_NOT_FOUND`. Report it before the install; the fix is `frontend:project:install-dependencies` or a lock update, offered to the user. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/reconcile.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/reconcile.md new file mode 100644 index 0000000..e67d214 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/reconcile.md @@ -0,0 +1,70 @@ +# Reconcile rules + +Compare each checklist row with the reference demo shop at the same release. Write the result into +the row: + +- `reference`: `same`, `differs` or `absent`, with the reference path — for example + `differs: src/Pyz/Zed/Checkout/CheckoutDependencyProvider.php`. +- `decision`: one value from the table below. +- `note`: the reason, when the decision is not `apply-guide`. + +| Decision | When | +|---|---| +| `apply-guide` | The reference is `same`, or the reference has no such file and the step is needed. | +| `apply-reference` | The reference differs and the reference is right for this project (rules 1 and 4). | +| `merge` | The project has the file and its own values: apply only what the feature adds (rules 2 and 3). | +| `already-present` | The project has it. `check-feature-installed.php --mark` sets it for complete wiring. | +| `skip:` | A scenario the developer did not choose, a plugin the reference does not wire and the developer declined, demo data declined. | + +## The rules + +1. **Plugin subset and order: the reference decides.** The guide lists plugins for every scenario + and every product type. Take the plugins the reference wires for the feature, in the reference's + order. A guide plugin that the reference does not wire → ask the developer, and record the answer + in `note`. + + The reference is `b2b-demo-marketplace`; the project can be another type (`state.md`). A plugin + the reference wires for a capability the project does not have — merchants, product offers, + company accounts, business units — is `skip: not in the project`. After the composer + step, `check-feature-installed.php` reports such plugins as `not in vendor/ (module not + installed)`: their module is not part of the project, so they cannot be wired. Do not add a module + to make a plugin wireable; ask the developer when the feature itself needs it. +2. **Existing config: the project decides.** Merge the feature's part into the project's value: + add the array element, add the regex alternative, add the plugin to the stack. Never replace + the value with the guide's. A `...` in a guide snippet always means merge. +3. **Example values take the project's values.** Store codes, locales, the `/en|/de` part of a URL + regex, region names and hosts in a guide snippet are examples. +4. **Files the guide does not name.** `find-feature-change.php --add-rows` adds a row with + `source: reference-only` for each file of the reference change that no row names: templates, + DependencyProviders of neighbouring modules, OMS processes, data, deploy and recipe files. Its + decision follows the same table. A guide data path is an example (`data/import/glossary.csv`): + when a `reference-only` row names the real file for the same data, decide the two rows together + and skip one of them with the reason. +5. **Integrator manifests check, never apply.** A manifest that wires a plugin no row names is a + finding: add a row, or record why it is not needed. +6. **`already-present` is checked, not applied again.** A second copy of a plugin in a stack runs it + twice. + +## Example: a guide value that replaces the project's value + +The Order Amendment guide sets the secured URL pattern to one regex: + +```php +$config[CustomerConstants::CUSTOMER_SECURED_PATTERN] = '(^(/en|/de)?/order-amendment($|/))'; +``` + +The project already protects many customer pages with that constant. A literal copy removes the +login protection from all of them. The reference adds the new path as one more alternative: + +```php +$config[CustomerConstants::CUSTOMER_SECURED_PATTERN] = '(...existing alternatives...|^(/en|/de)?/order-amendment($|/))'; +``` + +The row's decision is `merge`, the locales are the project's (rule 3), and `note` names the +constant. + +## Example: plugins the reference leaves out + +A guide's checkout plugin stack can include gift-card plugins. A marketplace reference does not wire +them, because the marketplace shop does not use gift cards. The plugins are not a step for a +marketplace project unless the developer says the project uses gift cards. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md new file mode 100644 index 0000000..38a8172 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md @@ -0,0 +1,105 @@ +# Release steps + +**Goal:** find the commands that staging and production must run, once or on every deploy, so that +an existing environment gets the feature that the local install got. + +A guide is written for a local install. It runs imports, installers and republishes by hand. An +existing environment gets only what its deploy recipe runs, and it already has data: a new publisher +does not publish the rows that exist, and a glossary import that the deploy does not run never +happens. + +## 1. List the candidates + +```bash +php $FI/diff-release-steps.php $STATE/checklist.json +``` + +It compares the checklist with `config/install/production.yml` (all sections) and the `build` and +`build-static` sections of `config/install/docker.yml`. Check those defaults against the project: + +- Which recipe does each deploy file name (`pipeline:` in `deploy.*.yml`, the Docker SDK default + otherwise)? +- Which sections run on the image build, and which on the deploy? Read the pipeline in the + repository if it is there. + +Pass the real ones with `--recipe [:
,
]`. + +| Candidate | Comes from | +|---|---| +| A console command | A `console` row the guide runs | +| `data:import ...` | A `feature-data` or `project-content` row | +| `publish:trigger-events -r ` | A new publisher plugin: existing rows are not published | +| `queue:setup` | A new queue | +| `propel:migrate` | A schema row | +| `env ` | A config snippet that reads an environment variable | + +Write every candidate that is not `covered` into `$STATE/release-steps.md`: + +``` +| | | rows | to verify / verified / not needed | +``` + +Replace each `` placeholder with the resource name: the publisher plugin's +`getSubscribedEvents()` events, and the resource names that `publish:trigger-events --help` lists. + +## 2. Prove the steps + +**Ask the developer first:** + +- Which branch does production run? +- Which commands does the normal deployment run? Read them from the pipeline if it is in the + repository. +- May you run `docker/sdk reset` two times? It deletes the local data. + +**Then do these steps in this order.** Use the same deploy file in both parts. For a clean state, +use `docker/sdk reset`: it imports the project data, so load no other data. Wait until the queues +are empty after each reset and after the deployment. + +| # | Do | State | +|---|---|---| +| 1 | Commit all changes on the feature branch. Check out the production branch. | | +| 2 | `docker/sdk reset` | production today | +| 3 | Check out the feature branch. | | +| 4 | Build the images and assets as the pipeline does, without data: `docker/sdk up --build --assets`. Then run only the normal deployment commands. | | +| 5 | Copy `$FI/dump-state.php` into `$STATE/`, then `docker/sdk cli php $STATE/dump-state.php --dump deployed`: every table (row count and content, without ids and timestamps) and every search index (document count). | **deployed** | +| 6 | `docker/sdk reset` | | +| 7 | `docker/sdk cli php $STATE/dump-state.php --dump fresh` | **fresh** | +| 8 | `php $STATE/dump-state.php --compare deployed fresh`: `EQUAL`, or each table and index that differs. | | + +**For each difference:** + +- **A command fixes it** → find the smallest command, for example + `publish:trigger-events -r `. Do steps 1–5 again, run only that command, and compare + again. If the difference is gone, it is a release step: set the log row to `verified`. +- **No command fixes it** → write down what differs and what it changes. +- **Demo data you added on purpose** → the deployed state lacks it by design. Record it as `not + needed` for production, with that reason. + +**Never:** + +- `publish:trigger-events` without `-r`. +- A reset before the dump of the step before is saved. +- A command on the deployed state that the normal deployment does not run — ask first. +- Two Docker builds, resets or imports at the same time. +- Tests or page checks instead of the comparison. + +If the developer does not allow the resets, the log rows stay `to verify`, and the report says that +the release steps are not verified. + +## 3. Recipe or one-time job + +For each verified step, recommend one of these: + +| Recommend | When | Example | +|---|---|---| +| A recipe entry | Every deploy needs it | A new queue, an import of configuration data that changes with releases | +| A one-time job | Only the first deploy of the feature needs it | A republish of existing rows, a first import of `feature-data` | + +Environment variables: the team sets them in each environment before the deploy. Name the variable, +the file that reads it, and what it holds. + +## In the report + +The report ([report.md](report.md)) lists only `verified` steps, under "Steps after the deploy". +A run with steps still `to verify` is not DONE, unless the developer accepted them +(`dod.json` `release_steps_accepted`). diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/report.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/report.md new file mode 100644 index 0000000..fe105a6 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/report.md @@ -0,0 +1,167 @@ +# The install report + +Write `$STATE/report.md` only when `check-dod.php` says `DONE` (SKILL.md Phase 8), in exactly the +format below: the same sections, in the same order, with the same headings and fixed sentences. It +is the report the developer shares with colleagues. Offer to publish it as a shared document; working +detail (checklist, decisions per row, evidence, baselines) stays in `$STATE`. + +- Name the project and the feature by release number only (`202608.0`), never by a package's own + version tag. +- The guide link points to the guide that was followed: when the install release is older than the + release the docs site shows, the guide file in `spryker/spryker-docs` pinned to the commit used. +- A section with nothing in it keeps its heading and says so in one line ("None."). +- Leave out "Upgrading the project to release …" when the installed release is the latest. +- Problems in the project that this install did not cause are not in the report: list them for the + developer as ticket candidates. + +## Template + +```markdown +# — install report + + · + +The feature is installed in the project at release , the same release as the rest of the project. + +| Version | Release | +| --- | --- | +| Project (all Spryker features) | | +| feature, installed | | +| feature, latest available | | + +## What was done + + + +- +- +- + +## Branch and pull request + +Branch: ``. . | The change is not committed yet, so there is no pull request for it.> + +## Steps after the deploy + +On each existing environment, run once after the deploy (the deploy itself does not import data): + +1. `` + +## Integration guide + +[Install the feature, version used for this install]() (spryker-docs, state of , matching release ). + +## Not installed + +The install guide also contains steps that connect with other Spryker features. These steps are needed only when the project uses those features. This project does not use them, so the following steps were not installed: + +| Part of the guide | Reason | +| --- | --- | +| | is not in the project | + +## What was validated and how + +| What | How | Result | +| --- | --- | --- | +| All applicable checks of the guide | run on the local shop: | pass | +| | new | pass, twice in a row on a fresh install | +| Code quality | PHPStan level , code sniffer | no new findings | +| Existing behaviour | full Codecept suite (compared with a run before the install); crawl of Back Office pages | no new test failures | +| Steps after the deploy | local comparison of a deployed environment with a fresh install | equal after the imports | +| | not validated | need a review by | + +## Upgrading the project to release + +The project runs Spryker release . The latest available release is . Upgrading the project to makes the latest version of available, which adds these capabilities: + +| Capability | What it gives | +| --- | --- | +| | | + +Sources: [release notes ](), [module release notes](). +``` + +## Example + +The Recurring Orders report, as shared with the team: + +```markdown +# Recurring Orders — install report + +2026-11-18 · Veronika + +The Recurring Orders feature is installed in the project at release 202608.0, the same release as the rest of the project. + +| Version | Release | +| --- | --- | +| Project (all Spryker features) | 202608 | +| Recurring Orders feature, installed | 202608.0 | +| Recurring Orders feature, latest available | 202610.0 | + +## What was done + +A business customer can now turn an order into a schedule that the shop places again on a fixed rhythm. + +- Checkout option "Set up as recurring order" (weekly, every two weeks, monthly, every N weeks) +- Recurring Orders page in the customer account (details, history, pause, skip, cancel) +- Automatic placement and reminder e-mails through two Jenkins jobs +- Back Office overview of all recurring orders (Sales > Recurring Order Schedules) +- French translations added for all new storefront and e-mail texts +- All shop e-mails now sent with Symfony Mailer, so that e-mail subjects are translated +- `spryker/gui`, `spryker/cms`, `spryker/customer` and `spryker/mail` stay at their current versions, because their newer versions are not compatible with the project's Back Office build, customer override and e-mail setup + +## Branch and pull request + +Branch: `ai-dev-sdk-integration`. The change is not committed yet, so there is no pull request for it. + +## Steps after the deploy + +On each existing environment, run once after the deploy (the deploy itself does not import data): + +1. `vendor/bin/console data:import:glossary` +2. `vendor/bin/console data:import:cms-block` +3. `vendor/bin/console data:import:cms-block-store` + +## Integration guide + +[Install the Recurring Orders feature, version used for this install](https://github.com/spryker/spryker-docs/blob/693430ceea/docs/pbc/all/order-experience-management/latest/base-shop/install-and-upgrade/install-features/install-the-recurring-orders-feature.md) (spryker-docs, state of 17 August 2026, matching release 202608). + +## Not installed + +The install guide also contains steps that connect Recurring Orders with other Spryker features. These steps are needed only when the project uses those features. This project does not use them, so the following steps were not installed: + +| Part of the guide | Reason | +| --- | --- | +| Cost center and budget on recurring orders | Purchasing Control is not in the project | +| Restrictions for service products | Self-Service Portal is not in the project | +| Back Office setting "Schedule Grace Period" | the Configuration feature is not in the project; the default of 48 hours applies | +| Shipment copy for product bundles | the shop sells no product bundles | + +## What was validated and how + +| What | How | Result | +| --- | --- | --- | +| All 17 applicable checks of the guide | run on the local shop: checkout, customer account, Back Office, database, e-mails in the mail catcher, Jenkins jobs | pass | +| Checkout to customer account, and the Back Office list | 2 new Cypress journeys | pass, twice in a row on a fresh install | +| Code quality | PHPStan level 6, code sniffer | no new findings | +| Existing behaviour | full Codecept suite (compared with a run before the install); crawl of 77 Back Office pages | no new test failures; 1 crawl error, in a module this change did not touch | +| Steps after the deploy | local comparison of a deployed environment with a fresh install | equal after the 3 imports | +| French texts | not validated | need a review by a French speaker | + +## Upgrading the project to release 202610 + +The project runs Spryker release 202608. The latest available release is 202610. Upgrading the project to 202610 makes the latest version of Recurring Orders available, which adds these capabilities: + +| Capability | What it gives | +| --- | --- | +| Multi-day schedules | one recurring order can deliver on several days, for example every Tuesday and Thursday | +| Price tolerances | buyers set an accepted price increase for the order total and for single products; small price changes no longer stop the schedule for review | +| Price tolerances in the Back Office | tolerance column, filter and details on the schedules list and detail page | +| "Processing" status | a schedule shows "processing" while its order is being placed, and buyer actions are hidden during that time | +| Recovery of stuck schedules | a console command restarts schedules stuck in the state machine and reports the others | +| Orders Backend API | read, list and create orders, trigger order state transitions and add order comments, for example for an ERP integration | +| Fixes | schedules no longer get stuck in validation; a price accepted for "just this order" no longer replaces the regular price; a price change with a budget warning goes to review instead of being placed | +| Experience | a more consistent design across checkout, order review and the customer account | + +Sources: [release notes 202610.0](https://docs.spryker.com/docs/about/all/releases/release-notes-202610.0.html), [module release notes](https://github.com/spryker-feature/order-experience-management/releases). +``` diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/sources.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/sources.md new file mode 100644 index 0000000..4f0d739 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/sources.md @@ -0,0 +1,110 @@ +# Sources + +Every source goes into `$STATE/sources/`. A source that is not found is recorded in `state.md` as +not found, with the place you looked. Never write a step from memory. + +| Source | Use | Required | +|---|---|---| +| Integration guide (docs page + include) | The steps: the checklist rows | yes | +| Prerequisite and linked guides | Steps of features the project does not have yet | yes, when the checklist names them | +| `spryker-feature/` `composer.json` at the tag | Which modules the feature package requires | yes | +| Reference demo shop at the tag | The plugin subset and order, merged config | yes | +| Reference demo shop history | The change that brought the feature in: the files the guide does not name | yes | +| Integrator manifests of the new modules | A machine-readable wiring list | no — a cross-check | + +## The integration guide + +The guide on docs.spryker.com is a page that wraps one include. The steps are in the include. + +1. Find the page: the capability card's Install section (`getSprykerCapability`) names it. Without + a card, use `searchAlgoliaDocumentation` (its `github_api_url` is the markdown), the + `spryker-docs-research` skill, or a web search for `site:docs.spryker.com install the + feature`. Integration guides are under + `docs/pbc/all//latest/.../install-and-upgrade/install-features/` (Glue API guides under + `.../install-glue-api/`). +2. Map the page URL to its source in `spryker/spryker-docs`: drop the host, replace `.html` with + `.md`. Fetch the raw file into `$STATE/sources/docs/`: + ```bash + curl -fsSL --create-dirs -o $STATE/sources/docs/.md https://raw.githubusercontent.com/spryker/spryker-docs/master/.md + ``` +3. The page has one line `{% include pbc/all/install-features/latest/.md %}`. Fetch + `_includes/` into `$STATE/sources/docs/_includes/` the same way. +4. Fetch `_config.yml` into `$STATE/sources/docs/_config.yml`. Its `release_version` is the value of + `{{page.release_tag}}` in the guide: the docs describe the latest release only. When the install + release (Phase 1) is older, run the parser with `--release `. A guide step for + a module version the install release does not have shows as `not in vendor/` in + `check-feature-installed.php` after the composer step: skip it with that reason. +5. Run the parser with `--docs-root $STATE/sources/docs`. + +A `linked-guide` row is a page the guide sends you to for steps (translations, frontend templates, +a sub-feature). Fetch it the same way, and append it to the checklist, or skip the row with a reason. + +**No guide, or a guide that assumes a base feature that has none** (a marketplace guide that assumes +the base wiring; a card that says "no install guide found"): the reference demo shop's change for the +feature is then the main source (`find-feature-change.php`, Phase 4). Without one, take the +project-layer wiring from the module code in `vendor/` and the feature's other guides. Record the +source of every row in its `note`, and say in the report that no official guide was followed. + +**Identifiers.** The docs contradict themselves on exact names. Confirm every class, constant and +transfer name against the installed packages in `vendor/` (read-only) or `getSprykerModuleMap` +before you write it. + +## The `spryker-feature/` package + +```bash +gh api repos/spryker-feature//contents/composer.json?ref= --jq .content | base64 -d > $STATE/sources/feature-composer.json +``` + +Two package types exist: + +- **Metapackage** — `composer.json` only, `"type": "metapackage"`. Its `require` is the module list. +- **Code package** — `"type": "library"`, code in the `SprykerFeature\` namespace, often with its + own `data/import/*.csv` and translations. Some of these packages also carry module-style tags + next to the release tags. Use the release tag. + +The guide's module table also lists transitive modules. The `require` block is the authority for +what the feature package itself pulls in. + +## The reference demo shop + +The reference is `spryker-shop/b2b-demo-marketplace`, for every project type. It is the demo shop +that the plugin supports; for a project of another type, reconcile rule 1 says which of its +decisions do not apply. + +```bash +git clone --depth 1 --branch https://github.com/spryker-shop/b2b-demo-marketplace.git $STATE/sources/reference +``` + +The release tag is the branch. Use the default branch's content only; demo-only extras (a separate +demo namespace or branch) are not the reference for a project. + +## The reference demo shop history + +```bash +git clone --bare https://github.com/spryker-shop/b2b-demo-marketplace.git $STATE/sources/reference-history.git +``` + +A full bare clone: a shallow or blob-filtered clone cannot search the history. +`find-feature-change.php` uses it in Phase 4. It takes the first commit that added the feature +package to `composer.json`, and the merge that brought that commit into the default branch. That +merge is the reference change: every file it changed is named by a checklist row, added as a +`reference-only` row (its tests as `test` rows), or listed as not a step (generated code, lock files, CI). + +No label or link convention ties a pull request to a feature, so a title search can find nothing +or the wrong pull request. A feature that came through a long-lived branch is found at its merge +into the default branch. A feature that the default branch never required has no reference +change: the guide rows are then the only source. + +## The integrator manifests (optional) + +`spryker-sdk/integrator-manifests` has one `installer-manifest.json` per module version, under +`///`: + +```bash +gh api repos/spryker-sdk/integrator-manifests/contents// --jq '.[].name' +gh api repos/spryker-sdk/integrator-manifests/contents////installer-manifest.json --jq .content | base64 -d +``` + +Use a manifest to check that the wiring is complete. Never run the integrator to apply it: it +applies every manifest of every module when the project has no `integrator.lock`, and it covers +wiring only (no data import, OMS, Twig, schema or deploy recipe). diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-checklist.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-checklist.php new file mode 100644 index 0000000..53b2c95 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-checklist.php @@ -0,0 +1,149 @@ + [--phase decide|report] + * + * --phase decide after reconcile, before the install: every row has a valid decision, no row + * is `unknown`, every data row that is not skipped has a `data_class` + * --phase report (default) before the report: the decide checks, plus every row is `done` or + * `skipped`, every verified row has a passing verdict, and at least one `test` + * row is `done` + * + * A row's `decision` is one of apply-guide, apply-reference, merge, already-present or + * skip:. A `verification` row that is not skipped needs `verdict` PASS, or ACCEPTED with a + * `verdict_note` that names who accepted it and why. A feature without a passing test is only + * accepted when the checklist's `tests_waived` holds the developer's reason: the next upgrade has + * nothing else that notices the feature stopped working. + * + * Exit codes: 0 clean; 1 problems (listed by row); 2 usage or unreadable checklist. + */ + +declare(strict_types=1); + +require_once __DIR__ . '/lib.php'; + +/** + * @return list one line per problem + */ +function cc_problems(array $checklist, string $phase): array +{ + return array_merge(...array_values(cc_problems_by_item($checklist, $phase))); +} + +/** + * The problems grouped as the Definition of Done counts them: rows (decisions and status), + * verification (verdicts) and tests (coverage). + * + * @return array{rows: list, verification: list, tests: list} + */ +function cc_problems_by_item(array $checklist, string $phase): array +{ + $byItem = ['rows' => [], 'verification' => [], 'tests' => []]; + foreach ($checklist['rows'] as $row) { + $problems = []; + $id = (string)($row['id'] ?? '?'); + $where = sprintf('%s %s %s', $id, $row['kind'] ?? '?', $row['target'] ?? ''); + $decision = $row['decision'] ?? null; + $status = $row['status'] ?? null; + + if (($row['kind'] ?? '') === 'unknown') { + $problems[] = "$where: kind is unknown — read the guide at lines " . implode('-', $row['lines'] ?? []) . ' and set the kind'; + } + if (in_array($row['kind'] ?? '', FI_DATA_KINDS, true) && !fi_is_skip($decision) && !in_array($row['data_class'] ?? null, FI_DATA_CLASSES, true)) { + $problems[] = "$where: data row without a data class — set data_class to feature-data, project-content or demo-data"; + } + if ($decision === null || $decision === '') { + $problems[] = "$where: no decision"; + } elseif (fi_is_skip($decision)) { + if (trim(substr($decision, 5)) === '') { + $problems[] = "$where: skip without a reason — write skip:"; + } + } elseif (!in_array($decision, FI_DECISIONS, true)) { + $problems[] = "$where: unknown decision '$decision'"; + } elseif (in_array($decision, ['apply-reference', 'merge'], true) && empty($row['reference'])) { + $problems[] = "$where: decision $decision without the reference it is based on"; + } + if ($status !== null && !in_array($status, FI_STATUSES, true)) { + $problems[] = "$where: unknown status '$status'"; + } + + if ($phase !== 'report') { + $byItem['rows'] = array_merge($byItem['rows'], $problems); + continue; + } + if ($status === 'failed') { + $problems[] = "$where: failed"; + } elseif (!in_array($status, ['done', 'skipped'], true)) { + $problems[] = "$where: still $status"; + } elseif ($status === 'skipped' && !fi_is_skip($decision)) { + $problems[] = "$where: skipped, but the decision is not skip:"; + } + if (($row['kind'] ?? '') === 'verification' && !fi_is_skip($decision)) { + $verdict = $row['verdict'] ?? null; + if (!in_array($verdict, FI_VERDICTS_PASSING, true)) { + $problems[] = "$where: verdict " . ($verdict ?? 'missing') . ' — a verification row needs PASS, or ACCEPTED with a verdict_note'; + } elseif ($verdict === 'ACCEPTED' && trim((string)($row['verdict_note'] ?? '')) === '') { + $problems[] = "$where: ACCEPTED without a verdict_note"; + } + } + $item = match ($row['kind'] ?? '') { + 'verification' => 'verification', + 'test' => 'tests', + default => 'rows', + }; + $byItem[$item] = array_merge($byItem[$item], $problems); + } + + if ($phase === 'report') { + $coveringTests = array_filter($checklist['rows'], static fn (array $row): bool => ($row['kind'] ?? '') === 'test' && ($row['status'] ?? '') === 'done'); + if ($coveringTests === [] && trim((string)($checklist['tests_waived'] ?? '')) === '') { + $byItem['tests'][] = 'no test covers the feature: add `test` rows and make them pass (Phase 6b), or set `tests_waived` to the developer\'s reason'; + } + } + + return $byItem; +} + +function cc_main(array $argv): int +{ + $path = null; + $phase = 'report'; + for ($i = 1; $i < count($argv); $i++) { + if ($argv[$i] === '--phase') { + $phase = (string)($argv[++$i] ?? ''); + } else { + $path = $argv[$i]; + } + } + if ($path === null || !in_array($phase, ['decide', 'report'], true)) { + fwrite(STDERR, "usage: php check-checklist.php [--phase decide|report]\n"); + + return 2; + } + $checklist = fi_load_checklist($path); + if ($checklist === null) { + fwrite(STDERR, "$path is not a readable checklist\n"); + + return 2; + } + $problems = cc_problems($checklist, $phase); + if ($problems === []) { + fwrite(STDOUT, sprintf("OK: %d rows, phase %s.\n", count($checklist['rows']), $phase)); + + return 0; + } + fwrite(STDOUT, sprintf("%d problem(s), phase %s:\n", count($problems), $phase)); + foreach ($problems as $problem) { + fwrite(STDOUT, " $problem\n"); + } + + return 1; +} + +if (realpath($argv[0] ?? '') === __FILE__) { + exit(cc_main($argv)); +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-data-manifests.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-data-manifests.php new file mode 100644 index 0000000..f171aba --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-data-manifests.php @@ -0,0 +1,136 @@ +.yml` in `config/install/**`, with + * `${SPRYKER_REGION}` and similar variables matched against the files that exist. Each manifest's + * `source:` entries are the files it imports. + * + * Usage (from the project root, or set SPRYKER_PROJECT_ROOT): + * php check-data-manifests.php [...] + * + * without files: the CSV files under data/import that differ from HEAD (changed or new) + * + * Exit codes: 0 every file is imported by at least one recipe's manifest; 1 a file no recipe + * imports (listed); 2 usage, or no manifest found. + */ + +declare(strict_types=1); + +require_once __DIR__ . '/lib.php'; + +/** + * @return list manifest paths relative to the project root, from the install recipes + */ +function cdm_manifests(string $root): array +{ + $manifests = []; + $recipes = array_merge(glob($root . '/config/install/*.yml') ?: [], glob($root . '/config/install/*/*.yml') ?: []); + foreach ($recipes as $recipe) { + if (!preg_match_all('/--config[= ]([^\s\'"]+\.ya?ml)/', (string)file_get_contents($recipe), $m)) { + continue; + } + foreach ($m[1] as $config) { + $pattern = (string)preg_replace('/\$\{?[A-Z_]+\}?/', '*', $config); + foreach (glob($root . '/' . ltrim($pattern, '/')) ?: [] as $file) { + $manifests[] = substr($file, strlen($root) + 1); + } + } + } + $manifests = array_values(array_unique($manifests)); + sort($manifests); + + return $manifests; +} + +/** + * @return list the files a manifest imports, relative to the project root + */ +function cdm_sources(string $root, string $manifest): array +{ + $sources = []; + if (!preg_match_all('/^\s*-?\s*source:\s*[\'"]?([^\s\'"#]+)/m', (string)@file_get_contents($root . '/' . $manifest), $m)) { + return []; + } + foreach ($m[1] as $source) { + $source = ltrim((string)preg_replace('#^\./#', '', $source), '/'); + $sources[] = is_file($root . '/' . $source) || !is_file($root . '/' . dirname($manifest) . '/' . $source) + ? $source + : dirname($manifest) . '/' . $source; + } + + return $sources; +} + +/** + * @return list + */ +function cdm_changed_files(string $root): array +{ + $files = []; + foreach ([['diff', '--name-only', 'HEAD', '--', 'data/import'], ['ls-files', '--others', '--exclude-standard', '--', 'data/import']] as $args) { + $command = 'git -C ' . escapeshellarg($root) . ' ' . implode(' ', array_map('escapeshellarg', $args)) . ' 2>/dev/null'; + foreach (explode("\n", (string)shell_exec($command)) as $file) { + if (str_ends_with($file, '.csv') && is_file($root . '/' . $file)) { + $files[] = $file; + } + } + } + + return array_values(array_unique($files)); +} + +/** + * @return array> data file => manifests that import it (empty: none) + */ +function cdm_evaluate(string $root, array $files): array +{ + $byFile = array_fill_keys($files, []); + foreach (cdm_manifests($root) as $manifest) { + $sources = cdm_sources($root, $manifest); + foreach ($files as $file) { + if (in_array($file, $sources, true)) { + $byFile[$file][] = $manifest; + } + } + } + + return $byFile; +} + +function cdm_main(array $argv): int +{ + $root = fi_project_root(); + $files = array_slice($argv, 1); + if (array_filter($files, static fn (string $f): bool => str_starts_with($f, '-')) !== []) { + fwrite(STDERR, "usage: php check-data-manifests.php [...]\n"); + + return 2; + } + $manifests = cdm_manifests($root); + if ($manifests === []) { + fwrite(STDERR, "No import manifest found: no recipe in config/install runs data:import --config=.\n"); + + return 2; + } + $files = $files !== [] ? $files : cdm_changed_files($root); + $byFile = cdm_evaluate($root, $files); + $orphans = array_keys(array_filter($byFile, static fn (array $m): bool => $m === [])); + + fwrite(STDOUT, sprintf("%d data file(s) checked against %d manifest(s) the recipes run.\n", count($files), count($manifests))); + foreach ($byFile as $file => $importedBy) { + fwrite(STDOUT, sprintf(" %-4s %s%s\n", $importedBy === [] ? 'NONE' : 'ok', $file, $importedBy === [] ? ' imported by no manifest a recipe runs' : ' ' . implode(', ', $importedBy))); + } + + return $orphans === [] ? 0 : 1; +} + +if (realpath($argv[0] ?? '') === __FILE__) { + exit(cdm_main($argv)); +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-dod.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-dod.php new file mode 100644 index 0000000..145b4af --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-dod.php @@ -0,0 +1,231 @@ + e.g. .ai-dev/feature-install/recurring-orders + * + * Evidence it reads: + * baseline/, after/ the tool outputs compare-baselines.php reads (items 2, 6) + * composer.lock.before with composer.lock and composer.json: check-needed-moves.php (item 3) + * checklist.json rows, wiring, verdicts, `test` rows and their files, `tests_waived` + * (items 4, 5, 7, 8) + * release-steps.md the release-steps log (item 10): a row is met when its status starts + * with `verified`, `not needed` or `covered` + * dod.json what no file shows (items 1, 3, 9, 10, and waivers for 2 and 6): + * { + * "scope": {"feature": "...", "install_release": "...", "update_mode": "-w", "branch": "...", + * "confirmed": ""}, + * "accepted_moves": {"spryker/": ""}, + * "data_files": ["data/import/..."], + * "authored_content": [{"file": "...", "what": ""}], + * "release_steps_accepted": "", + * "waived": {"baseline:backoffice-crawl": "", "check:frontend-build": "..."} + * } + * + * Exit codes: 0 DONE; 1 NOT DONE (each unmet item listed); 2 usage or unreadable state. + */ + +declare(strict_types=1); + +require_once __DIR__ . '/lib.php'; +require_once __DIR__ . '/check-checklist.php'; +require_once __DIR__ . '/check-lock-diff.php'; +require_once __DIR__ . '/check-feature-installed.php'; +require_once __DIR__ . '/check-needed-moves.php'; +require_once __DIR__ . '/compare-baselines.php'; +require_once __DIR__ . '/check-data-manifests.php'; + +const DOD_ITEMS = [ + 1 => 'the developer confirmed the scope', + 2 => 'every baseline ran and is valid', + 3 => 'only modules the feature needs moved; every other move has a reason', + 4 => 'every checklist row is decided, and done or skipped with a reason', + 5 => 'the decided wiring is in place', + 6 => 'no regression against the baselines, and the frontend builds pass', + 7 => 'every verification passed', + 8 => 'passing tests cover the feature', + 9 => 'every data file reaches an environment, and every text the agent wrote is recorded for review', + 10 => 'the release steps are proven', +]; + +/** + * @return list unmet reasons of a measured group, minus the ones the developer waived + */ +function dod_unwaived(array $measured, array $waived, string $prefix): array +{ + $unmet = []; + foreach ($measured as $name => $problem) { + if ($problem !== null && trim((string)($waived["$prefix:$name"] ?? '')) === '') { + $unmet[] = "$name: $problem"; + } + } + + return $unmet; +} + +/** + * @return list release-steps log rows whose status is not verified, not needed or covered + */ +function dod_unproven_release_steps(string $file): array +{ + if (!is_file($file)) { + return ['release-steps.md is missing']; + } + $unproven = []; + $inTable = false; + foreach (file($file, FILE_IGNORE_NEW_LINES) ?: [] as $line) { + if (!preg_match('/^\s*\|/', $line)) { + $inTable = false; + continue; + } + $isHeader = !$inTable; + $inTable = true; + if ($isHeader || preg_match('/^\s*\|?[\s:\-|]+\|?\s*$/', $line)) { + continue; + } + $cells = array_map('trim', explode('|', trim(trim($line), '|'))); + $status = strtolower((string)end($cells)); + if (!preg_match('/^(verified|not needed|covered)\b/', $status)) { + $unproven[] = $cells[0] . ': ' . ($status !== '' ? $status : 'no status'); + } + } + + return $unproven; +} + +/** + * @return array> item number => unmet reasons (empty list = met) + */ +function dod_evaluate(string $root, string $stateDir): array +{ + $checklist = fi_load_checklist($stateDir . '/checklist.json'); + $dod = json_decode((string)@file_get_contents($stateDir . '/dod.json'), true); + $dod = is_array($dod) ? $dod : []; + $waived = (array)($dod['waived'] ?? []); + $result = array_fill_keys(array_keys(DOD_ITEMS), []); + + $scope = $dod['scope'] ?? []; + foreach (['feature', 'install_release', 'update_mode', 'branch', 'confirmed'] as $field) { + if (trim((string)($scope[$field] ?? '')) === '') { + $result[1][] = "scope.$field is not recorded"; + } + } + + $measured = cb_evaluate($stateDir); + $result[2] = dod_unwaived($measured['baselines'], $waived, 'baseline'); + $result[6] = dod_unwaived($measured['checks'], $waived, 'check'); + + $before = $stateDir . '/composer.lock.before'; + if (!is_file($before) || !is_file($root . '/composer.lock')) { + $result[3][] = 'cannot compare: composer.lock.before or composer.lock is missing'; + } else { + $composerJson = (array)json_decode((string)@file_get_contents($root . '/composer.json'), true); + $classified = cnm_classify(fi_lock_packages($before), fi_lock_packages($root . '/composer.lock'), $composerJson); + foreach (cnm_open($classified, (array)($dod['accepted_moves'] ?? [])) as $package => $move) { + $result[3][] = sprintf('%s %s -> %s: %s, and no reason recorded', $package, $move['before'], $move['after'], $move['verdict']); + } + $features = $checklist !== null ? array_map('strtolower', cld_features_from_checklist($checklist)) : []; + foreach (cld_dev_constraints($composerJson) as $package => $constraint) { + if (in_array(strtolower($package), $features, true)) { + $result[3][] = "$package has the dev constraint $constraint"; + } + } + } + + if ($checklist === null) { + foreach ([4, 5, 7, 8] as $item) { + $result[$item][] = 'checklist.json is missing or unreadable'; + } + } else { + $byItem = cc_problems_by_item($checklist, 'report'); + $result[4] = $byItem['rows']; + $result[7] = $byItem['verification']; + $result[8] = $byItem['tests']; + foreach ($checklist['rows'] as $row) { + if (($row['kind'] ?? '') === 'test' && ($row['status'] ?? '') === 'done' && !is_file($root . '/' . ltrim((string)($row['target'] ?? ''), '/'))) { + $result[8][] = sprintf('%s: the test file %s does not exist', $row['id'] ?? '?', $row['target'] ?? ''); + } + } + + $namespaces = cfi_project_namespaces($root); + $providers = cfi_dependency_providers($root, $namespaces); + foreach ($checklist['rows'] as $row) { + $decision = $row['decision'] ?? null; + if (!in_array($row['kind'] ?? '', CFI_WIRING_KINDS, true) || $decision === null || fi_is_skip($decision)) { + continue; + } + $state = cfi_wiring_state($root, $row, $namespaces, $providers); + if (!in_array($state['state'], ['present', 'file-present'], true)) { + $result[5][] = sprintf('%s %s: %s', $row['id'] ?? '?', $row['target'] ?? '', $state['state']); + } + } + + $dataRowsDone = array_filter($checklist['rows'], static fn (array $row): bool => in_array($row['kind'] ?? '', FI_DATA_KINDS, true) && ($row['status'] ?? '') === 'done'); + $dataFiles = array_values(array_filter((array)($dod['data_files'] ?? []), 'is_string')); + if ($dataRowsDone !== [] && $dataFiles === []) { + $result[9][] = 'data rows are done, but dod.json data_files does not list the files the hand-off wrote'; + } + if ($dataFiles !== []) { + foreach (cdm_evaluate($root, $dataFiles) as $file => $importedBy) { + if ($importedBy === []) { + $result[9][] = "$file is imported by no manifest a recipe runs"; + } + } + } + } + + foreach ($dod['authored_content'] ?? [] as $index => $content) { + $file = trim((string)($content['file'] ?? '')); + if ($file === '' || trim((string)($content['what'] ?? '')) === '') { + $result[9][] = sprintf('authored_content entry %d needs both `file` and `what`, so the report can list it for review', $index + 1); + } elseif (!is_file($root . '/' . ltrim($file, '/'))) { + $result[9][] = "authored_content names $file, which does not exist"; + } + } + + if (trim((string)($dod['release_steps_accepted'] ?? '')) === '') { + $result[10] = dod_unproven_release_steps($stateDir . '/release-steps.md'); + } + + return $result; +} + +function dod_main(array $argv): int +{ + $stateDir = $argv[1] ?? null; + if ($stateDir === null || !is_dir($stateDir)) { + fwrite(STDERR, "usage: php check-dod.php (for example .ai-dev/feature-install/)\n"); + + return 2; + } + $result = dod_evaluate(fi_project_root(), rtrim($stateDir, '/')); + $unmet = array_filter($result, static fn (array $reasons): bool => $reasons !== []); + + fwrite(STDOUT, $unmet === [] + ? "DONE — all 10 Definition of Done items are met.\n" + : sprintf("NOT DONE — %d of 10 Definition of Done items are not met: %s.\n", count($unmet), implode(', ', array_keys($unmet)))); + foreach (DOD_ITEMS as $number => $label) { + $reasons = $result[$number]; + fwrite(STDOUT, sprintf(" [%s] %2d %s\n", $reasons === [] ? 'x' : ' ', $number, $label)); + foreach (array_slice($reasons, 0, 8) as $reason) { + fwrite(STDOUT, ' - ' . (mb_strlen($reason) > 160 ? mb_substr($reason, 0, 120) . ' … ' . mb_substr($reason, -36) : $reason) . "\n"); + } + if (count($reasons) > 8) { + fwrite(STDOUT, sprintf(" - and %d more\n", count($reasons) - 8)); + } + } + + return $unmet === [] ? 0 : 1; +} + +if (realpath($argv[0] ?? '') === __FILE__) { + exit(dod_main($argv)); +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-feature-installed.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-feature-installed.php new file mode 100644 index 0000000..ebefeab --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-feature-installed.php @@ -0,0 +1,232 @@ + [--mark] + * php check-feature-installed.php --wiring + * + * (default) modules of each guide's module table: installed or missing; wiring rows: present, + * partial or absent in the project + * --mark also sets decision `already-present` on undecided wiring rows that are fully present + * --wiring gate after the install: every wiring row that is not skipped must be fully present + * + * The guide's `src/Pyz/` paths are matched against every project namespace in composer.json. A + * plugin whose class is not in `vendor/` is reported as not installed: its module is not part of + * the project, so the plugin is not a step (a marketplace plugin in a B2C project). + * + * Exit codes: 0 report (default, --mark) or all wiring present (--wiring); 1 --wiring found missing + * plugins; 2 usage or unreadable checklist. + */ + +declare(strict_types=1); + +require_once __DIR__ . '/lib.php'; + +const CFI_WIRING_KINDS = ['plugin', 'route', 'widget', 'queue']; + +/** + * @return list project namespaces, e.g. ['Pyz', 'Demo'] + */ +function cfi_project_namespaces(string $root): array +{ + $composer = json_decode((string)@file_get_contents($root . '/composer.json'), true); + $namespaces = []; + foreach ($composer['autoload']['psr-4'] ?? [] as $prefix => $dirs) { + foreach ((array)$dirs as $dir) { + if (preg_match('#^src/([A-Z]\w*)/?$#', rtrim((string)$dir, '/') . '/', $m) && !in_array($m[1], ['Generated', 'Orm'], true)) { + $namespaces[] = $m[1]; + } + } + if (preg_match('/^([A-Z]\w*)\\\\$/', (string)$prefix, $m) && is_dir($root . '/src/' . $m[1]) && !in_array($m[1], ['Generated', 'Orm'], true)) { + $namespaces[] = $m[1]; + } + } + if ($namespaces === [] && is_dir($root . '/src/Pyz')) { + $namespaces[] = 'Pyz'; + } + + return array_values(array_unique($namespaces)); +} + +/** + * @return list existing project files a guide path maps to + */ +function cfi_project_files(string $root, string $guidePath, array $namespaces): array +{ + $files = []; + foreach ($namespaces as $namespace) { + $candidate = (string)preg_replace('#^src/Pyz/#', 'src/' . $namespace . '/', $guidePath); + if (is_file($root . '/' . $candidate)) { + $files[] = $candidate; + } + } + + return array_values(array_unique($files)); +} + +/** + * @return list every DependencyProvider under the project namespaces + */ +function cfi_dependency_providers(string $root, array $namespaces): array +{ + $files = []; + foreach ($namespaces as $namespace) { + $base = $root . '/src/' . $namespace; + if (!is_dir($base)) { + continue; + } + $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($base, FilesystemIterator::SKIP_DOTS)); + foreach ($iterator as $file) { + if (str_ends_with($file->getFilename(), 'DependencyProvider.php')) { + $files[] = substr($file->getPathname(), strlen($root) + 1); + } + } + } + sort($files); + + return $files; +} + +/** + * The source wires the plugin: its short name is used, and no `use` statement imports a class of + * that name from another namespace. A deprecated class and its replacement often share the name. + */ +function cfi_mentions(string $source, string $plugin): bool +{ + $short = fi_short_name($plugin); + if (!preg_match('/\b' . preg_quote($short, '/') . '\b/', $source)) { + return false; + } + if (!str_contains($plugin, '\\') || str_contains($source, $plugin)) { + return true; + } + + return !preg_match('/^use\s+[A-Za-z0-9_\\\\]+\\\\' . preg_quote($short, '/') . '\s*;/m', $source); +} + +/** + * A vendor class is available when its file is in a package's `src/` under `vendor/`. A plugin of a + * module the project does not install (a marketplace or company-account plugin in a B2C project) + * cannot be wired. Without a `vendor/` directory nothing can be said, so every class counts as + * available. + */ +function cfi_class_available(string $root, string $class): bool +{ + if (!str_contains($class, '\\') || !is_dir($root . '/vendor')) { + return true; + } + + return glob($root . '/vendor/*/*/src/' . str_replace('\\', '/', $class) . '.php') !== []; +} + +/** + * @return array{state: string, files: list, missing: list, unavailable: list} + */ +function cfi_wiring_state(string $root, array $row, array $namespaces, array $providers): array +{ + $plugins = $row['plugins'] ?? []; + $target = (string)($row['target'] ?? ''); + $unavailable = array_values(array_filter($plugins, static fn (string $plugin): bool => !cfi_class_available($root, $plugin))); + $files = str_contains($target, '/') ? cfi_project_files($root, $target, $namespaces) : $providers; + if ($files === []) { + return ['state' => 'absent', 'files' => [], 'missing' => $plugins, 'unavailable' => $unavailable]; + } + $source = ''; + foreach ($files as $file) { + $source .= (string)file_get_contents($root . '/' . $file) . "\n"; + } + $missing = array_values(array_filter($plugins, static fn (string $plugin): bool => !cfi_mentions($source, $plugin))); + $state = match (true) { + $plugins === [] => 'file-present', + $missing === [] => 'present', + count($missing) === count($plugins) => 'absent', + default => 'partial', + }; + if (!str_contains($target, '/')) { + $files = array_values(array_filter($files, static fn (string $file): bool => cfi_mentions((string)file_get_contents($root . '/' . $file), $plugins[0] ?? ''))); + } + + return ['state' => $state, 'files' => $files, 'missing' => $missing, 'unavailable' => $unavailable]; +} + +function cfi_main(array $argv): int +{ + $path = null; + $mark = false; + $wiring = false; + for ($i = 1; $i < count($argv); $i++) { + match ($argv[$i]) { + '--mark' => $mark = true, + '--wiring' => $wiring = true, + default => $path = $argv[$i], + }; + } + $checklist = $path !== null ? fi_load_checklist($path) : null; + if ($checklist === null) { + fwrite(STDERR, "usage: php check-feature-installed.php [--mark | --wiring]\n"); + + return 2; + } + $root = fi_project_root(); + $namespaces = cfi_project_namespaces($root); + $providers = cfi_dependency_providers($root, $namespaces); + + if (!$wiring) { + foreach ($checklist['guides'] as $guide) { + $modules = $guide['modules'] ?? []; + $missing = array_filter($modules, static fn (array $m): bool => $m['directory'] === '' || !is_dir($root . '/' . trim($m['directory'], '/'))); + fwrite(STDOUT, sprintf("%s: %d of %d modules installed\n", $guide['file'], count($modules) - count($missing), count($modules))); + foreach ($missing as $module) { + fwrite(STDOUT, sprintf(" missing %-40s %s\n", $module['module'], $module['directory'])); + } + } + } + + $gaps = 0; + $marked = 0; + fwrite(STDOUT, sprintf("\nWiring rows (project namespaces: %s):\n", implode(', ', $namespaces))); + foreach ($checklist['rows'] as $index => $row) { + if (!in_array($row['kind'] ?? '', CFI_WIRING_KINDS, true)) { + continue; + } + $decision = $row['decision'] ?? null; + if ($wiring && ($decision === null || fi_is_skip($decision))) { + continue; + } + $state = cfi_wiring_state($root, $row, $namespaces, $providers); + if ($wiring && $state['state'] !== 'present' && $state['state'] !== 'file-present') { + $gaps++; + } + if ($mark && $decision === null && $state['state'] === 'present') { + $checklist['rows'][$index]['decision'] = 'already-present'; + $marked++; + } + fwrite(STDOUT, sprintf(" %-5s %-12s %s%s%s\n", $row['id'], $state['state'], $row['target'], $state['missing'] !== [] && $state['state'] === 'partial' + ? ' — missing: ' . implode(', ', array_map('fi_short_name', $state['missing'])) + : '', $state['unavailable'] !== [] + ? ' — not in vendor/ (module not installed): ' . implode(', ', array_map('fi_short_name', $state['unavailable'])) + : '')); + } + if ($mark) { + fi_save_checklist((string)$path, $checklist); + fwrite(STDOUT, "\n$marked row(s) marked already-present.\n"); + } + if ($wiring) { + fwrite(STDOUT, $gaps === 0 ? "\nOK: every decided wiring row is present.\n" : "\n$gaps decided wiring row(s) not fully present.\n"); + + return $gaps === 0 ? 0 : 1; + } + + return 0; +} + +if (realpath($argv[0] ?? '') === __FILE__) { + exit(cfi_main($argv)); +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-lock-diff.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-lock-diff.php new file mode 100644 index 0000000..61c9906 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-lock-diff.php @@ -0,0 +1,170 @@ + [--after composer.lock] + * [--composer composer.json] (--feature ... | --checklist ) + * + * --feature a package the install requires; repeatable + * --checklist read the packages from the composer rows that are not skipped + * + * Exit codes: 0 every move is inside the feature tree and no required package has a dev + * constraint; 1 moves outside the tree or such a dev constraint (listed); 2 usage or unreadable input. + */ + +declare(strict_types=1); + +require_once __DIR__ . '/lib.php'; + +/** + * @return array + */ +function cld_moved(array $before, array $after): array +{ + $moved = []; + foreach (array_unique(array_merge(array_keys($before), array_keys($after))) as $name) { + $old = $before[$name]['version'] ?? null; + $new = $after[$name]['version'] ?? null; + if ($old !== $new) { + $moved[$name] = ['before' => $old, 'after' => $new]; + } + } + ksort($moved); + + return $moved; +} + +/** + * @param list $roots + * + * @return array every package reachable from the roots through `require` + */ +function cld_tree(array $packages, array $roots): array +{ + $seen = []; + $queue = array_map('strtolower', $roots); + while ($queue !== []) { + $name = array_shift($queue); + if (isset($seen[$name])) { + continue; + } + $seen[$name] = true; + foreach (array_keys($packages[$name]['require'] ?? []) as $dependency) { + $dependency = strtolower($dependency); + if (isset($packages[$dependency]) && !isset($seen[$dependency])) { + $queue[] = $dependency; + } + } + } + + return $seen; +} + +/** + * @return array package => dev constraint, for Spryker packages + */ +function cld_dev_constraints(array $composerJson): array +{ + $dev = []; + foreach (['require', 'require-dev'] as $section) { + foreach ($composerJson[$section] ?? [] as $name => $constraint) { + if (preg_match('#^spryker[a-z\-]*/#', (string)$name) && preg_match('/(^|\s|\|)dev-/', (string)$constraint)) { + $dev[$name] = (string)$constraint; + } + } + } + + return $dev; +} + +/** + * @return list + */ +function cld_features_from_checklist(array $checklist): array +{ + $features = []; + foreach ($checklist['rows'] as $row) { + if (($row['kind'] ?? '') === 'composer' && !fi_is_skip($row['decision'] ?? null)) { + array_push($features, ...array_keys($row['packages'] ?? [])); + } + } + + return array_values(array_unique($features)); +} + +function cld_main(array $argv): int +{ + $root = fi_project_root(); + $options = ['before' => null, 'after' => $root . '/composer.lock', 'composer' => $root . '/composer.json', 'checklist' => null]; + $features = []; + for ($i = 1; $i < count($argv); $i++) { + $arg = $argv[$i]; + if ($arg === '--feature') { + $features[] = (string)($argv[++$i] ?? ''); + } elseif (in_array($arg, ['--before', '--after', '--composer', '--checklist'], true)) { + $options[substr($arg, 2)] = $argv[++$i] ?? null; + } else { + fwrite(STDERR, "unknown argument $arg\n"); + + return 2; + } + } + if ($options['checklist'] !== null) { + $checklist = fi_load_checklist($options['checklist']); + if ($checklist === null) { + fwrite(STDERR, "{$options['checklist']} is not a readable checklist\n"); + + return 2; + } + array_push($features, ...cld_features_from_checklist($checklist)); + } + if ($options['before'] === null || $features === [] || !is_file($options['before']) || !is_file($options['after'])) { + fwrite(STDERR, "usage: php check-lock-diff.php --before [--after composer.lock] [--composer composer.json] (--feature ... | --checklist )\n"); + + return 2; + } + + $after = fi_lock_packages($options['after']); + $moved = cld_moved(fi_lock_packages($options['before']), $after); + $tree = cld_tree($after, $features); + $outside = array_diff_key($moved, $tree); + $dev = cld_dev_constraints((array)json_decode((string)@file_get_contents($options['composer']), true)); + + fwrite(STDOUT, sprintf("%d package(s) moved; %d inside the tree of %s.\n", count($moved), count($moved) - count($outside), implode(', ', array_unique($features)))); + if ($outside !== []) { + fwrite(STDOUT, "\nMoved outside the feature tree — accept each, or narrow the update:\n"); + foreach ($outside as $name => $versions) { + fwrite(STDOUT, sprintf(" %-55s %s -> %s\n", $name, $versions['before'] ?? '(new)', $versions['after'] ?? '(removed)')); + } + } + $featureSet = array_map('strtolower', $features); + $devOnFeature = array_filter($dev, static fn (string $name): bool => in_array(strtolower($name), $featureSet, true), ARRAY_FILTER_USE_KEY); + if ($devOnFeature !== []) { + fwrite(STDOUT, "\nDev constraint on a package this install requires — set a released constraint (^):\n"); + foreach ($devOnFeature as $name => $constraint) { + fwrite(STDOUT, sprintf(" %-55s %s\n", $name, $constraint)); + } + } + $devOther = array_diff_key($dev, $devOnFeature); + if ($devOther !== []) { + fwrite(STDOUT, "\nnote: other dev constraints in composer.json (not part of this install):\n"); + foreach ($devOther as $name => $constraint) { + fwrite(STDOUT, sprintf(" %-55s %s\n", $name, $constraint)); + } + } + + return ($outside === [] && $devOnFeature === []) ? 0 : 1; +} + +if (realpath($argv[0] ?? '') === __FILE__) { + exit(cld_main($argv)); +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-needed-moves.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-needed-moves.php new file mode 100644 index 0000000..6ba4e1b --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-needed-moves.php @@ -0,0 +1,149 @@ + [--after composer.lock] + * [--composer composer.json] [--accepted ] + * + * --accepted moves listed with a reason in dod.json `accepted_moves` are not reported as open + * + * Per moved package: `needed` (a requirer or a conflict rules out the old version, named), + * `not needed` (the old version satisfies every requirer), or `unknown` (a constraint it cannot + * read, for example a branch). New and removed packages are listed, not judged. + * + * Exit codes: 0 every move is needed or accepted; 1 a move is not needed or unknown, and not + * accepted; 2 usage or unreadable input. + */ + +declare(strict_types=1); + +require_once __DIR__ . '/lib.php'; + +/** + * @return array}> + */ +function cnm_classify(array $before, array $after, array $composerJson): array +{ + $result = []; + $names = array_unique(array_merge(array_keys($before), array_keys($after))); + sort($names); + foreach ($names as $name) { + $old = $before[$name]['version'] ?? null; + $new = $after[$name]['version'] ?? null; + if ($old === $new) { + continue; + } + if ($old === null || $new === null) { + $result[$name] = ['before' => $old, 'after' => $new, 'verdict' => $old === null ? 'new' : 'removed', 'why' => []]; + continue; + } + $blockers = []; + $unknown = []; + $requirers = []; + foreach ($after as $requirer => $package) { + foreach (['require' => 'requires', 'conflict' => 'conflicts with'] as $section => $relation) { + foreach ($package[$section] ?? [] as $dependency => $constraint) { + if (strtolower($dependency) === $name) { + $requirers[] = [$requirer, $relation, (string)$constraint]; + } + } + } + } + foreach (['require', 'require-dev'] as $section) { + foreach ($composerJson[$section] ?? [] as $dependency => $constraint) { + if (strtolower((string)$dependency) === $name) { + $requirers[] = ['composer.json', 'requires', (string)$constraint]; + } + } + } + foreach ($requirers as [$requirer, $relation, $constraint]) { + $satisfied = fi_version_satisfies($old, $constraint); + if ($satisfied === null) { + $unknown[] = "$requirer $relation $constraint"; + } elseif ($relation === 'requires' && $satisfied === false) { + $blockers[] = "$requirer requires $constraint"; + } elseif ($relation === 'conflicts with' && $satisfied === true) { + $blockers[] = "$requirer conflicts with $constraint"; + } + } + $result[$name] = match (true) { + $blockers !== [] => ['before' => $old, 'after' => $new, 'verdict' => 'needed', 'why' => $blockers], + $unknown !== [] => ['before' => $old, 'after' => $new, 'verdict' => 'unknown', 'why' => $unknown], + default => ['before' => $old, 'after' => $new, 'verdict' => 'not needed', 'why' => ["$old satisfies every requirer"]], + }; + } + + return $result; +} + +/** + * @return array}> the + * not-needed and unknown moves that have no reason in `accepted_moves` + */ +function cnm_open(array $classified, array $acceptedMoves): array +{ + return array_filter( + $classified, + static fn (array $move, string $name): bool => in_array($move['verdict'], ['not needed', 'unknown'], true) + && trim((string)($acceptedMoves[$name] ?? '')) === '', + ARRAY_FILTER_USE_BOTH + ); +} + +function cnm_main(array $argv): int +{ + $root = fi_project_root(); + $options = ['before' => null, 'after' => $root . '/composer.lock', 'composer' => $root . '/composer.json', 'accepted' => null]; + for ($i = 1; $i < count($argv); $i++) { + $key = substr((string)$argv[$i], 2); + if (!array_key_exists($key, $options) || !str_starts_with((string)$argv[$i], '--')) { + fwrite(STDERR, "unknown argument {$argv[$i]}\n"); + + return 2; + } + $options[$key] = $argv[++$i] ?? null; + } + if ($options['before'] === null || !is_file($options['before']) || !is_file((string)$options['after'])) { + fwrite(STDERR, "usage: php check-needed-moves.php --before [--after composer.lock] [--composer composer.json] [--accepted ]\n"); + + return 2; + } + $composerJson = (array)json_decode((string)@file_get_contents((string)$options['composer']), true); + $classified = cnm_classify(fi_lock_packages($options['before']), fi_lock_packages((string)$options['after']), $composerJson); + $dod = $options['accepted'] !== null ? (array)json_decode((string)@file_get_contents($options['accepted']), true) : []; + $open = cnm_open($classified, (array)($dod['accepted_moves'] ?? [])); + + $counts = array_count_values(array_column($classified, 'verdict')); + fwrite(STDOUT, sprintf("%d package(s) moved: %s.\n", count($classified), implode(', ', array_map(static fn ($v, $n) => "$n $v", array_keys($counts), $counts)))); + foreach (['not needed', 'unknown', 'needed', 'new', 'removed'] as $verdict) { + foreach ($classified as $name => $move) { + if ($move['verdict'] !== $verdict) { + continue; + } + $accepted = trim((string)($dod['accepted_moves'][$name] ?? '')); + fwrite(STDOUT, sprintf(" %-11s %-50s %s -> %s%s\n", strtoupper($verdict), $name, $move['before'] ?? '(none)', $move['after'] ?? '(none)', $accepted !== '' ? ' accepted: ' . $accepted : '')); + if ($move['why'] !== [] && $verdict !== 'not needed') { + fwrite(STDOUT, ' ' . implode('; ', array_slice($move['why'], 0, 3)) . "\n"); + } + } + } + if ($open !== []) { + fwrite(STDOUT, sprintf("\n%d move(s) the feature does not need: move each back (composer require :), or record the developer's reason in dod.json accepted_moves.\n", count($open))); + } + + return $open === [] ? 0 : 1; +} + +if (realpath($argv[0] ?? '') === __FILE__) { + exit(cnm_main($argv)); +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/compare-baselines.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/compare-baselines.php new file mode 100644 index 0000000..f610a14 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/compare-baselines.php @@ -0,0 +1,207 @@ +`; code 0 passes. + * A build the project does not have: no file. + * + * Usage (from the project root): + * php compare-baselines.php + * + * Exit codes: 0 every baseline is valid and nothing regressed; 1 a baseline is not valid or a check + * regressed (each named); 2 usage. + */ + +declare(strict_types=1); + +require_once __DIR__ . '/lib.php'; +require_once __DIR__ . '/../../spryker-upgrade/scripts/check-baselines.php'; + +const CB_BASELINES = [ + 'phpstan' => 'phpstan-baseline-run.txt', + 'sniffer' => 'sniff-baseline.txt', + 'tests' => 'codecept-baseline.txt', + 'backoffice-crawl' => 'backoffice-smoke-baseline.json', + 'storage-counts' => 'storage-search-counts-before.json', +]; + +const CB_BUILDS = ['yves-build.txt', 'zed-build.txt', 'mp-build.txt']; + +function cb_text(string $file): ?string +{ + return is_file($file) ? bl_plain_text((string)file_get_contents($file)) : null; +} + +function cb_phpstan_errors(string $text): ?int +{ + if (preg_match('/Found (\d+) (?:\S+ )?errors?/', $text, $m)) { + return (int)$m[1]; + } + + return preg_match('/\[OK\] No errors/', $text) ? 0 : null; +} + +function cb_sniff_findings(string $text): ?int +{ + if (preg_match('/A TOTAL OF (\d+) ERRORS? AND (\d+) WARNINGS?/', $text, $m)) { + return (int)$m[1] + (int)$m[2]; + } + if (preg_match_all('/FOUND (\d+) ERRORS?(?: AND (\d+) WARNINGS?)?/', $text, $m, PREG_SET_ORDER)) { + return array_sum(array_map(static fn (array $hit): int => (int)$hit[1] + (int)($hit[2] ?? 0), $m)); + } + + return bl_content_problem('sniff-baseline.txt', $text) === null ? 0 : null; +} + +/** + * @return array{total: ?int, failing: list} + */ +function cb_codecept(string $text): array +{ + $failing = []; + if (preg_match_all('/^\s*\d+\) (\S.*?)\s*$/m', $text, $m)) { + $failing = array_values(array_unique(array_map('trim', $m[1]))); + } + $total = null; + if (preg_match_all('/Tests: \d+, Assertions: \d+(?:, Errors: (\d+))?(?:, Failures: (\d+))?/', $text, $m, PREG_SET_ORDER)) { + $total = array_sum(array_map(static fn (array $hit): int => (int)($hit[1] ?? 0) + (int)($hit[2] ?? 0), $m)); + } elseif (preg_match('/\bOK \(\d+ tests?/', $text)) { + $total = 0; + } + + return ['total' => $total, 'failing' => $failing]; +} + +/** + * @return array{baselines: array, checks: array} each name → null + * when met, else the reason + */ +function cb_evaluate(string $stateDir): array +{ + $baselineDir = $stateDir . '/baseline'; + $afterDir = $stateDir . '/after'; + $baselines = []; + foreach (CB_BASELINES as $name => $file) { + $contents = @file_get_contents($baselineDir . '/' . $file); + $baselines[$name] = $contents === false ? "missing baseline/$file" : bl_content_problem($file, $contents); + } + + $checks = []; + $before = cb_text($baselineDir . '/phpstan-baseline-run.txt'); + $after = cb_text($afterDir . '/phpstan-after.txt'); + $checks['phpstan'] = match (true) { + $after === null => 'missing after/phpstan-after.txt', + cb_phpstan_errors($after) === null => 'after/phpstan-after.txt has no PHPStan result line', + $before === null || cb_phpstan_errors($before) === null => 'no valid baseline to compare with', + cb_phpstan_errors($after) > cb_phpstan_errors($before) => sprintf('errors grew from %d to %d', cb_phpstan_errors($before), cb_phpstan_errors($after)), + default => null, + }; + + $before = cb_text($baselineDir . '/sniff-baseline.txt'); + $after = cb_text($afterDir . '/sniff-after.txt'); + $checks['sniffer'] = match (true) { + $after === null => 'missing after/sniff-after.txt', + cb_sniff_findings($after) === null => 'after/sniff-after.txt has no sniffer result', + $before === null || cb_sniff_findings($before) === null => 'no valid baseline to compare with', + cb_sniff_findings($after) > cb_sniff_findings($before) => sprintf('findings grew from %d to %d', cb_sniff_findings($before), cb_sniff_findings($after)), + default => null, + }; + + $before = cb_text($baselineDir . '/codecept-baseline.txt'); + $after = cb_text($afterDir . '/codecept-after.txt'); + if ($after === null) { + $checks['tests'] = 'missing after/codecept-after.txt'; + } elseif ($before === null) { + $checks['tests'] = 'no valid baseline to compare with'; + } else { + $old = cb_codecept($before); + $new = cb_codecept($after); + $newFailures = array_values(array_diff($new['failing'], $old['failing'])); + $checks['tests'] = match (true) { + $new['total'] === null => 'after/codecept-after.txt has no summary line', + $newFailures !== [] => sprintf('%d test(s) fail that passed before: %s', count($newFailures), implode('; ', array_slice($newFailures, 0, 3))), + $new['failing'] === [] && $old['total'] !== null && $new['total'] > $old['total'] => sprintf('failures grew from %d to %d', $old['total'], $new['total']), + default => null, + }; + } + + $report = json_decode((string)@file_get_contents($baselineDir . '/backoffice-smoke-report.json'), true); + if (!is_array($report) || !is_array($report['results'] ?? null)) { + $checks['backoffice-crawl'] = 'missing baseline/backoffice-smoke-report.json (run backoffice-smoke.php again after the install)'; + } else { + $new = array_filter($report['results'], static fn (array $r): bool => ($r['problem'] ?? null) !== null && empty($r['inBaseline'])); + $checks['backoffice-crawl'] = $new === [] ? null : sprintf('%d page(s) or endpoint(s) fail that did not before: %s', count($new), implode('; ', array_slice(array_column($new, 'url'), 0, 3))); + } + + $report = json_decode((string)@file_get_contents($baselineDir . '/storage-search-counts-report.json'), true); + if (!is_array($report) || !isset($report['rows'])) { + $checks['storage-counts'] = 'missing baseline/storage-search-counts-report.json (snapshot after, then --compare before after)'; + } else { + $failing = array_filter((array)$report['rows'], static fn (array $r): bool => !empty($r['failing'])); + $checks['storage-counts'] = $failing === [] ? null : sprintf('%d table(s) lost rows: %s', count($failing), implode(', ', array_slice(array_column($failing, 'table'), 0, 3))); + } + + $builds = []; + foreach (CB_BUILDS as $file) { + $text = cb_text($afterDir . '/' . $file); + if ($text === null) { + continue; + } + if (!preg_match_all('/^exit (\d+)\s*$/m', $text, $m)) { + $builds[] = "after/$file does not end with `exit `"; + } elseif ((int)end($m[1]) !== 0) { + $builds[] = sprintf('%s failed (exit %d)', basename($file, '.txt'), (int)end($m[1])); + } + } + $hasBuild = array_filter(CB_BUILDS, static fn (string $file): bool => is_file($afterDir . '/' . $file)) !== []; + $checks['frontend-build'] = match (true) { + !$hasBuild => 'no build output in after/ (yves-build.txt, zed-build.txt, mp-build.txt)', + $builds !== [] => implode('; ', $builds), + default => null, + }; + + return ['baselines' => $baselines, 'checks' => $checks]; +} + +function cb_main(array $argv): int +{ + $stateDir = $argv[1] ?? null; + if ($stateDir === null || !is_dir($stateDir)) { + fwrite(STDERR, "usage: php compare-baselines.php \n"); + + return 2; + } + $result = cb_evaluate(rtrim($stateDir, '/')); + $problems = 0; + foreach (['baselines' => 'Baselines', 'checks' => 'After the install'] as $group => $title) { + fwrite(STDOUT, "$title:\n"); + foreach ($result[$group] as $name => $problem) { + $problems += $problem === null ? 0 : 1; + fwrite(STDOUT, sprintf(" %-5s %-17s %s\n", $problem === null ? 'ok' : 'FAIL', $name, $problem ?? '')); + } + } + + return $problems === 0 ? 0 : 1; +} + +if (realpath($argv[0] ?? '') === __FILE__) { + exit(cb_main($argv)); +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/diff-release-steps.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/diff-release-steps.php new file mode 100644 index 0000000..dde186e --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/diff-release-steps.php @@ -0,0 +1,167 @@ + [--recipe [:
,
]]... + * + * --recipe an install recipe and, optionally, the sections of it that run on a deploy. + * Default: config/install/production.yml (all sections) and + * config/install/docker.yml:build,build-static. + * + * Candidates: console rows; imports of feature-data and project-content rows; a republish per new + * publisher plugin; queue:setup for new queues; new environment variables; propel:migrate for + * schema rows. Rows whose decision is skip: or already-present are not candidates. + * + * Exit codes: 0 every candidate is covered by a recipe; 1 candidates to prove (listed); 2 usage. + */ + +declare(strict_types=1); + +require_once __DIR__ . '/lib.php'; + +/** + * Commands that only prepare a local stack (code generation is part of the image build, which the + * recipes' build sections cover) or only read state. + */ +const DRS_LOCAL_ONLY = ['frontend:yves:build', 'frontend:zed:build', 'frontend:mp:build', 'frontend:project:install-dependencies', 'cache:empty-all', 'dev:ide-auto-completion:generate']; + +/** A local command and the command a deploy runs for the same effect. */ +const DRS_DEPLOY_EQUIVALENT = ['propel:install' => 'propel:migrate']; + +/** + * @return list command signatures a recipe runs, from `command:` lines of the chosen sections + */ +function drs_recipe_commands(string $file, ?array $sections): array +{ + if (!is_file($file)) { + return []; + } + $commands = []; + $current = null; + foreach (file($file, FILE_IGNORE_NEW_LINES) ?: [] as $line) { + if (preg_match('/^ ([A-Za-z0-9_\-]+):\s*$/', $line, $m)) { + $current = $m[1]; + continue; + } + if (preg_match("/^\s+command:\s*['\"]?(.+?)['\"]?\s*$/", $line, $m) && ($sections === null || in_array($current, $sections, true))) { + $commands[] = fi_command_signature($m[1]); + } + } + + return $commands; +} + +function drs_covered(string $signature, array $recipeCommands): bool +{ + foreach ($recipeCommands as $recipeCommand) { + if ($recipeCommand === $signature || str_starts_with($signature, $recipeCommand . ' ') || fi_command_name($recipeCommand) === $signature) { + return true; + } + } + + return false; +} + +/** + * @return list}> + */ +function drs_candidates(array $checklist): array +{ + $candidates = []; + $add = static function (string $step, string $why, string $rowId) use (&$candidates): void { + $step = DRS_DEPLOY_EQUIVALENT[$step] ?? $step; + $candidates[$step] ??= ['step' => $step, 'why' => $why, 'rows' => []]; + if (!in_array($rowId, $candidates[$step]['rows'], true)) { + $candidates[$step]['rows'][] = $rowId; + } + }; + foreach ($checklist['rows'] as $row) { + $decision = $row['decision'] ?? null; + if (fi_is_skip($decision) || $decision === 'already-present') { + continue; + } + $id = (string)$row['id']; + $kind = $row['kind'] ?? ''; + $target = (string)($row['target'] ?? ''); + if ($kind === 'console') { + $signature = fi_command_signature($target); + if (!in_array(fi_command_name($target), DRS_LOCAL_ONLY, true)) { + $add($signature, 'the guide runs it', $id); + } + } + if (in_array($kind, FI_DATA_KINDS, true) && in_array($row['data_class'] ?? null, ['feature-data', 'project-content'], true)) { + $add($kind === 'glossary' ? 'data:import glossary' : 'data:import ', ($row['data_class']) . ' rows the feature needs', $id); + } + if (in_array($kind, ['schema', 'event'], true)) { + $add('propel:migrate', 'schema change', $id); + } + if ($kind === 'queue') { + $add('queue:setup', 'new queue', $id); + } + foreach ($row['plugins'] ?? [] as $plugin) { + if (str_contains($plugin, '\\Plugin\\Publisher\\')) { + $add('publish:trigger-events -r ', 'new publisher: existing rows are not published', $id); + } + } + foreach ($row['env'] ?? [] as $variable) { + $add('env ' . $variable, 'environment variable the code reads', $id); + } + } + + return array_values($candidates); +} + +function drs_main(array $argv): int +{ + $path = null; + $recipes = []; + for ($i = 1; $i < count($argv); $i++) { + if ($argv[$i] === '--recipe') { + $recipes[] = (string)($argv[++$i] ?? ''); + } else { + $path = $argv[$i]; + } + } + $checklist = $path !== null ? fi_load_checklist($path) : null; + if ($checklist === null) { + fwrite(STDERR, "usage: php diff-release-steps.php [--recipe [:
,
]]...\n"); + + return 2; + } + $root = fi_project_root(); + if ($recipes === []) { + $recipes = ['config/install/production.yml', 'config/install/docker.yml:build,build-static']; + } + $recipeCommands = []; + foreach ($recipes as $recipe) { + [$file, $sectionList] = array_pad(explode(':', $recipe, 2), 2, null); + $file = str_starts_with((string)$file, '/') ? (string)$file : $root . '/' . $file; + if (!is_file($file)) { + fwrite(STDOUT, "note: recipe $recipe not found — its commands count as not covered\n"); + } + array_push($recipeCommands, ...drs_recipe_commands($file, $sectionList !== null ? explode(',', $sectionList) : null)); + } + + $open = 0; + fwrite(STDOUT, sprintf("| %-60s | %-9s | %-45s | %s |\n", 'step', 'recipe', 'why', 'rows')); + fwrite(STDOUT, '|' . str_repeat('-', 62) . '|' . str_repeat('-', 11) . '|' . str_repeat('-', 47) . "|------|\n"); + foreach (drs_candidates($checklist) as $candidate) { + $isEnv = str_starts_with($candidate['step'], 'env '); + $covered = !$isEnv && drs_covered($candidate['step'], $recipeCommands); + $open += $covered ? 0 : 1; + fwrite(STDOUT, sprintf("| %-60s | %-9s | %-45s | %s |\n", $candidate['step'], $covered ? 'covered' : ($isEnv ? 'set it' : 'to prove'), $candidate['why'], implode(' ', $candidate['rows']))); + } + fwrite(STDOUT, $open === 0 ? "\nOK: every candidate is covered by a recipe.\n" : "\n$open candidate(s) not covered: add each to the release-steps log and prove it.\n"); + + return $open === 0 ? 0 : 1; +} + +if (realpath($argv[0] ?? '') === __FILE__) { + exit(drs_main($argv)); +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/dump-state.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/dump-state.php new file mode 100644 index 0000000..eba3474 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/dump-state.php @@ -0,0 +1,233 @@ +] [--user ] [--password-env ] + * + * Connection: SPRYKER_DB_ENGINE (mysql|pgsql), SPRYKER_DB_HOST, SPRYKER_DB_PORT, SPRYKER_DB_DATABASE, + * SPRYKER_DB_USERNAME, SPRYKER_DB_PASSWORD as the Docker SDK sets them; SPRYKER_SEARCH_HOST and + * SPRYKER_SEARCH_PORT for the search engine (left out when not set). --dsn, --user and + * --password-env override the database settings. + * + * Exit: --dump 0 written, 2 usage or connection error. --compare 0 equal, 1 differences (listed), + * 2 usage. + */ + +declare(strict_types=1); + +const DS_SKIP_TABLES = '/^(propel_migration|spy_queue_process|spy_.*_lock|spy_oauth_(access|refresh)_token|spy_session.*|spy_event_behavior_entity_change|spy_.*_log|spy_customer_session|spy_.*_history_log)$/'; +const DS_SKIP_COLUMN = '/^(id_.*|fk_.*|.*_at|uuid|key|created|updated|reference)$/'; +const DS_SKIP_JSON_KEY = '/^(id|uuid|fk.*|id[A-Z_].*|.*Id|.*_id|.*At|.*_at|_timestamp|key)$/'; + +function ds_strip_json(mixed $value): mixed +{ + if (!is_array($value)) { + return $value; + } + $clean = []; + foreach ($value as $key => $item) { + if (is_string($key) && preg_match(DS_SKIP_JSON_KEY, $key)) { + continue; + } + $clean[$key] = ds_strip_json($item); + } + if (array_is_list($clean)) { + $encoded = array_map(static fn ($item) => json_encode($item), $clean); + sort($encoded); + + return $encoded; + } + ksort($clean); + + return $clean; +} + +/** + * The row as compared: identifier and timestamp columns removed, JSON values normalised the same way. + */ +function ds_normalise_row(array $row): string +{ + $clean = []; + foreach ($row as $column => $value) { + if (preg_match(DS_SKIP_COLUMN, (string)$column)) { + continue; + } + if (is_string($value) && $value !== '' && ($value[0] === '{' || $value[0] === '[')) { + $decoded = json_decode($value, true); + if (is_array($decoded)) { + $value = json_encode(ds_strip_json($decoded)); + } + } + $clean[$column] = $value; + } + ksort($clean); + + return json_encode($clean); +} + +/** + * @return array + */ +function ds_dump_tables(PDO $pdo, string $engine): array +{ + $tables = match ($engine) { + 'sqlite' => $pdo->query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'")->fetchAll(PDO::FETCH_COLUMN), + 'pgsql' => $pdo->query("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE'")->fetchAll(PDO::FETCH_COLUMN), + default => $pdo->query('SHOW TABLES')->fetchAll(PDO::FETCH_COLUMN), + }; + sort($tables); + $result = []; + foreach ($tables as $table) { + if (preg_match(DS_SKIP_TABLES, (string)$table)) { + continue; + } + $quoted = $engine === 'mysql' ? '`' . $table . '`' : '"' . $table . '"'; + $hashes = []; + $statement = $pdo->query('SELECT * FROM ' . $quoted); + while (($row = $statement->fetch(PDO::FETCH_ASSOC)) !== false) { + $hashes[] = md5(ds_normalise_row($row)); + } + sort($hashes); + $result[(string)$table] = ['rows' => count($hashes), 'hash' => md5(implode('', $hashes))]; + } + + return $result; +} + +/** + * @return array index => document count; empty when no search engine is configured + */ +function ds_dump_search(array $env): array +{ + $host = $env['SPRYKER_SEARCH_HOST'] ?? ''; + if ($host === '' || !function_exists('curl_init')) { + return []; + } + $handle = curl_init(sprintf('http://%s:%s/_cat/indices?format=json', $host, $env['SPRYKER_SEARCH_PORT'] ?? '9200')); + curl_setopt_array($handle, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 20]); + $indices = json_decode((string)curl_exec($handle), true); + $counts = []; + foreach (is_array($indices) ? $indices : [] as $index) { + if (isset($index['index']) && !str_starts_with((string)$index['index'], '.')) { + $counts[(string)$index['index']] = (int)($index['docs.count'] ?? 0); + } + } + ksort($counts); + + return $counts; +} + +/** + * @return list one line per difference + */ +function ds_compare(array $a, array $b): array +{ + $differences = []; + $tables = array_unique(array_merge(array_keys($a['tables'] ?? []), array_keys($b['tables'] ?? []))); + sort($tables); + foreach ($tables as $table) { + $left = $a['tables'][$table] ?? null; + $right = $b['tables'][$table] ?? null; + if ($left === null || $right === null) { + $differences[] = sprintf('table %s exists only in %s', $table, $left === null ? 'the second dump' : 'the first dump'); + } elseif ($left['rows'] !== $right['rows']) { + $differences[] = sprintf('table %s: %d rows vs %d rows', $table, $left['rows'], $right['rows']); + } elseif ($left['hash'] !== $right['hash']) { + $differences[] = sprintf('table %s: same row count (%d), different content', $table, $left['rows']); + } + } + $indices = array_unique(array_merge(array_keys($a['search'] ?? []), array_keys($b['search'] ?? []))); + sort($indices); + foreach ($indices as $index) { + $left = $a['search'][$index] ?? null; + $right = $b['search'][$index] ?? null; + if ($left !== $right) { + $differences[] = sprintf('search index %s: %s vs %s documents', $index, $left ?? 'none', $right ?? 'none'); + } + } + + return $differences; +} + +function ds_file(string $labelOrPath): string +{ + return is_file($labelOrPath) ? $labelOrPath : __DIR__ . '/state-' . $labelOrPath . '.json'; +} + +function ds_main(array $argv): int +{ + $usage = "usage: php dump-state.php --dump