---
name: apex
description: |
  SmartStack incremental development using APEX methodology (Analyze-Plan-Execute-eXamine).
  Use this skill when:
  - Adding a new section/resource to an existing module
  - Developing feature by feature without /business-analyse
  - Fixing or extending code generated by /business-analyse-develop
  - Any incremental SmartStack development task
argument-hint: "[-a] [-x] [-s] [-e] [-r] [-pr] <task description>"
---

<objective>
Execute incremental SmartStack development using the APEX methodology. This skill knows the SmartStack hierarchy (application/module/section/resource), delegates code creation to existing skills (/controller, /application, /ui-components, /efcore, /notification, /workflow) and MCP tools, and validates via MCP conventions.

**Key principle:** /apex ORCHESTRATES — it never generates SmartStack code directly. All generation goes through skills and MCP tools.
</objective>

<quick_start>

```bash
# Direct use (you know exactly what to build):
/apex add absence management to HR module           # Add section to module
/apex -a fix the leave request controller            # Auto fix
/apex -a -x -s -pr add PDF export to Orders           # Full workflow
/apex -e add status field to Project entity          # Economy (no agents)
/apex -r                                             # Resume previous

# From /sketch (vague idea → precise command):
/sketch une app RH avec employés et absences         # → generates /apex command

# From /business-analyse-develop (automated multi-module):
# /business-analyse-develop delegates to /apex -d automatically
```

</quick_start>

<parameters>

| Flag | Description |
|------|-------------|
| `-a` | Auto mode: skip confirmations |
| `-x` | Deep review: adversarial code review (beyond step-04 automated checks) |
| `-s` | Save mode: output to `.claude/output/apex/` |
| `-e` | Economy mode: no subagents |
| `-r` | Resume: continue from previous state |
| `-pr` | PR mode: create pull request at end |
| `-d {path}` | Delegate mode: read context from PRD file at `{path}`. Implies `-a -e`. Used by `/business-analyse-develop`. |
| `--foundation` | Foundation mode: generate ONLY entities + EF configs + migration. No services/controllers/frontend. Used by business-analyse-develop Phase 0. |

</parameters>

<state_variables>

| Variable | Type | Description |
|----------|------|-------------|
| `{task_description}` | string | What to implement (flags removed) |
| `{task_id}` | string | Kebab-case identifier |
| `{auto_mode}` | boolean | Skip confirmations |
| `{examine_mode}` | boolean | Adversarial review |
| `{save_mode}` | boolean | Save outputs to `.claude/output/apex/{task-id}/` |
| `{economy_mode}` | boolean | No subagents |
| `{pr_mode}` | boolean | Create PR at end |
| `{delegate_mode}` | boolean | Delegated by `/business-analyse-develop` via `-d` flag |
| `{delegate_prd_path}` | string? | Path to PRD file (`.ralph/prd.json` or `.ralph/prd-{module}.json`) |
| `{foundation_mode}` | boolean | Foundation mode: entities-only (no services/controllers/frontend). Used by business-analyse-develop Phase 0. |
| `{app_name}` | string | Application name |
| `{module_code}` | string | Module code |
| `{sections}` | object[] | Sections (required, min 1) with code/labels/icon/displayOrder |
| `{entities}` | string[] | Main entities to manage (from need-challenge) |
| `{module_complexity}` | string | "simple-crud", "crud-rules", "crud-workflow", "complex" |
| `{has_dependencies}` | string | "none", "references", "unknown" |
| `{key_properties}` | string[] | Key business properties mentioned by user |
| `{code_patterns}` | object[] | Per-entity code generation config [{entity, strategy, prefix, digits, includeTenantSlug, separator}] |
| `{prd_path}` | string? | `.ralph/prd-{module}.json` if exists |
| `{feature_path}` | string? | `docs/business/.../feature.json` if exists |
| `{needs_seed_data}` | boolean | Seed data creation required |
| `{needs_migration}` | boolean | EF Core migration required |
| `{needs_workflow}` | boolean | Workflow integration required |
| `{needs_notification}` | boolean | Notification integration required |
</state_variables>

<state_persistence>

**These variables exist only in the conversation context.** There is no file-based persistence between sessions.

- Variables are set in step-00 (init) and propagated through subsequent steps via conversation context
- If the conversation is interrupted, use `-r` (resume) — the model will re-derive state from existing files and git history
- The `save_mode` (`-s`) flag writes step outputs to `.claude/output/apex/` but this is documentation, not resumable state
- Delegate mode (`-d`) reads initial state from the PRD file, making it more resilient to interruptions

</state_persistence>

<entry_point>

**FIRST ACTION:** Load `steps/step-00-init.md`

</entry_point>

<step_files>
**Progressive loading — only load current step. Step 03 dispatches to layer sub-steps.**

| Step | File | Model | Purpose |
|------|------|-------|---------|
| 00 | `steps/step-00-init.md` | Sonnet | Parse flags, detect application, verify MCP, define hierarchy (4 levels), scope validation |
| 01 | `steps/step-01-analyze.md` | Opus | Explore existing code (parallel Agent tool or sequential) |
| 02 | `steps/step-02-plan.md` | Opus | Layer-by-layer plan with skill/MCP mapping |
| 03 | `steps/step-03-execute.md` | Opus | **Orchestrator** — dispatches to layer sub-steps below |
| 03a | `steps/step-03a-layer0-domain.md` | Opus | Layer 0: Domain entities, EF configs, migration |
| 03b | `steps/step-03b-layer1-seed.md` | Opus | Layer 1: Seed data (navigation, permissions, roles) |
| 03c | `steps/step-03c-layer2-backend.md` | Opus | Layer 2: Services, controllers, backend tests |
| 03d | `steps/step-03d-layer3-frontend.md` | Opus | Layer 3: Pages, i18n, routes, frontend tests |
| 03e | `steps/step-03e-layer4-devdata.md` | Opus | Layer 4: Development test data (optional) |
| 04 | `steps/step-04-examine.md` | Opus | eXamine: MCP validation, build, POST-CHECKs, acceptance criteria |
| 05 | `steps/step-05-deep-review.md` | Opus | Deep Review: adversarial code review (if -x) |
| 06 | `steps/step-06-resolve.md` | Opus | Fix BLOCKING findings (if any) |
| 07 | `steps/step-07-tests.md` | Opus | Final Test Sweep: security tests, coverage, remaining failures |
| 08 | `steps/step-08-run-tests.md` | Opus | Run Final Test Sweep until 100% pass |
</step_files>

<apex_phases>
**APEX = Analyze → Plan → Execute → eXamine**

| Phase | Step | Required | Description |
|-------|------|----------|-------------|
| *Init* | 00 | Yes | Setup, hierarchy, scope validation, **scope guard** (skipped in `-d` delegate mode) |
| **A** — Analyze | 01 | Yes | Explore existing code |
| **P** — Plan | 02 | Yes | File-by-file plan with skill/MCP mapping |
| **E** — Execute | 03 | Yes | Orchestrate creation via skills and MCP (5 layers: domain, seed, backend, frontend, devdata) |
| **X** — eXamine | 04 | Yes | 3 MCP tools + POST-CHECKs (security + convention + architecture, see post-checks.md), build, acceptance criteria |
| *Deep Review* | 05 (if -x) | No | Adversarial code review beyond automated checks |
| *Resolve* | 06 (if BLOCKING) | No | Fix BLOCKING findings |
| *Final Test Sweep* | 07-08 | **Yes** | Security tests, coverage sweep, remaining failures |
</apex_phases>

<reference_files>
**Loaded conditionally by steps that need them:**

| File | Purpose | Loaded by | Stays in context for |
|------|---------|-----------|---------------------|
| `references/smartstack-api.md` | BaseEntity, interfaces, entity/config/controller patterns | step-01 | step-03a/03b/03c (released after L2) |
| `references/smartstack-layers.md` | Layer rules, skill/MCP mapping, planning templates, delegate fast path | step-02 | step-03a/03b/03c (released after L2) |
| `references/core-seed-data.md` | Comprehensive seed data templates (navigation, permissions, roles) | step-03b (Layer 1) | released after Layer 1 |
| `references/smartstack-frontend.md` | Frontend patterns, EntityLookup, i18n (sections 1-6) | step-03d (Layer 3, deferred) | step-04 |
| `references/smartstack-frontend-compliance.md` | Documentation, form testing, compliance gates (sections 7-9) | step-03d (Layer 3, deferred) | step-04 |
| `references/challenge-questions.md` | Hierarchy rules, challenge questions, delegate mode skip | step-00 | — |
| `references/error-classification.md` | Build error diagnosis categories A-F | step-03 (build failure), step-04 | — |
| `references/parallel-execution.md` | Agent tool launch patterns, task coordination, decision matrix | step-01, step-03c/03d (if NOT economy_mode) | — |
| `references/post-checks.md` | Compact checklist — indexes checks in `references/checks/*.sh` | step-04 | — |
| `references/checks/*.sh` | Bash check scripts (security, backend, frontend, seed, architecture, infrastructure) | step-04 (executed via bash) | — |

**Context propagation rule:** Files loaded in step N remain in conversation context for step N+1. Steps mark "do NOT re-read" to avoid duplicate reads.
</reference_files>

<execution_rules>

- **ULTRA THINK at each step transition** — Deep reasoning about scope, existing code, and whether elements need to be CREATED or MODIFIED before acting. This is critical when updating an existing module (adding sections/resources to existing seed data, permissions, roles).
- **Load one step at a time** - Progressive loading to manage context
- **ORCHESTRATE, never generate** - All SmartStack code via skills (/controller, /application, etc.) or MCP tools
- **MCP-first** - Use MCP scaffold/validate tools before manual approaches
- **Verify MCP at startup** - step-00 checks MCP availability
- **Layer order** - Layer 0 (domain+infra+migration) → Layer 1 (seed data) → Layer 2 (backend+tests) → Layer 3 (frontend+tests) → Layer 4 (devdata)
- **Parallel Agent tool** - Parallel execution for scan (step-01) and within Layer 2/3 (step-03) for multi-entity, unless economy_mode
- **Tests inline** - Backend tests run after Layer 2, frontend tests run after Layer 3 (max 3 fix iterations each). Step-07 = final sweep (security + coverage).
- **Exception: seed data** — The templates in core-seed-data.md and person-extension-pattern.md are generated directly because no MCP tool covers seed data creation yet. This is a documented exception to the "orchestrate, never generate" rule. <!-- TODO: Remove exception when MCP scaffold_seed_data (B1) is ready -->
- **Frontend pages: ALWAYS via Skill("ui-components")** — economy_mode affects parallelization only, NOT whether /ui-components is called. NEVER generate .tsx pages directly, even in delegate or economy mode.
- **Save outputs** if `{save_mode}` = true
- **Commits per layer** - Atomic commits after each execution layer
- **Delegate mode** (`-d`): Read PRD context, skip challenge questions, auto+economy mode implied. Used when `/business-analyse-develop` delegates code generation to `/apex`.
- **Foundation mode** (`--foundation`): Generate ONLY entities + EF configs + migration (domain + infrastructure layers). Skip application/api/frontend/tests. Used by business-analyse-develop Phase 0 to create database foundation before spawning parallel teammates.

</execution_rules>

<execution_guarantee>

## Execution Guarantee (CRITICAL — read before ANY step)

> **The user is NOT watching. There is NOBODY to answer your questions. Stopping is a FAILURE.**

When APEX runs (especially in `-d` delegate mode or `-a` auto mode), the execution is **fully autonomous**. The user has launched the command and walked away. Any pause, question, or numbered option list is a **dead end** — nobody will respond.

**YOU MUST NOT:**
- Stop to ask the user a question between layers
- Present numbered options ("Would you like to: 1. Continue... 2. Generate... 3. Stop...")
- Pause between layers to summarize progress and wait for confirmation
- Stop because the work seems "large" or "complex" — that is expected
- Add "Let me know if you want me to continue" at any point

**YOU MUST:**
- After Layer N completes, **IMMEDIATELY** load the next sub-step file. No pause, no summary, no question.
- Execute the full pipeline: Layer 0 → Layer 1 → Layer 2 → Layer 3 → Layer 4 → step-04, with **ZERO pauses** between layers
- Treat each "Load `steps/step-03X-...md`" instruction as a **mandatory immediate action**, not a suggestion
- Continue even if a layer produced warnings (only a build gate failure after max retries is a valid stop)

**The ONLY valid reasons to stop:**
1. A build gate fails after maximum retries (3 attempts)
2. ALL layers are completed and step-04 (eXamine) is done
3. The user presses Ctrl+C

**Anything else — including "being helpful" by asking — is a VIOLATION of the execution guarantee.**

</execution_guarantee>

<error_handling>

## Error Handling Strategy

| Error | Action | Max Retries |
|-------|--------|-------------|
| `dotnet build` fails | Identify error, fix via skill/MCP, rebuild | 3 |
| `npm run typecheck` fails | Fix TypeScript error, retry | 3 |
| MCP unavailable | Degraded mode: use `smartstack-api.md` as sole reference, no MCP validation | — |
| File lock (MSB3021) | Auto-use `--output /tmp/{project}_build` for build verification | — |
| NuGet restore required | Run `dotnet restore` before first `dotnet build` | 1 |
| Migration fails | Rollback migration (`dotnet ef migrations remove`), fix entity/config, retry | 2 |
| MCP scaffold output wrong | Verify against `smartstack-api.md` patterns, fix manually | — |
| POST-CHECK fails | Return to step-03, fix the issue, re-validate | 2 |
| Stuck after max retries | AskUserQuestion with options: "Try alternative", "Skip", "Discuss" | — |

**Principle:** Always fix CODE, never bypass checks. If stuck, escalate to user.

</error_handling>

<success_criteria>
- SmartStack hierarchy detected (app/module)
- Plan validated with skill/MCP mapped for each file
- Code created/corrected via existing skills and MCP (no direct generation)
- MCP validate_conventions: 0 errors
- Build: dotnet build PASS + npm run typecheck PASS (if frontend)
- Seed data complete as dedicated Layer 1 (navigation, permissions, roles, provider) — impossible to skip
- Tests inline: backend tests after Layer 2, frontend tests after Layer 3
- Final test sweep: security tests + coverage >= 80% + target 100% pass rate (acceptable fallback: skip with TODO after max retries)
- Commits atomic per layer
</success_criteria>
