---
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 /ralph-loop
  - 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 (context/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
/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
```

</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 `/ralph-loop`. |

</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 `/ralph-loop` via `-d` flag |
| `{delegate_prd_path}` | string? | Path to PRD file (`.ralph/prd.json` or `.ralph/prd-{module}.json`) |
| `{context_code}` | string | "business", "platform", "personal" |
| `{app_name}` | string | Application name |
| `{module_code}` | string | Module code |
| `{sections}` | object[] | Sections (MANDATORY, 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 |
| `{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>

<entry_point>

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

</entry_point>

<step_files>
**Progressive loading - only load current step:**

| Step | File | Model | Purpose |
|------|------|-------|---------|
| 00 | `steps/step-00-init.md` | Sonnet | Parse flags, detect context, verify MCP, define hierarchy (5 levels), challenge need |
| 01 | `steps/step-01-analyze.md` | Opus | Explore existing code (Agent Teams or direct) |
| 02 | `steps/step-02-plan.md` | Opus | Layer-by-layer plan with skill/MCP mapping |
| 03 | `steps/step-03-execute.md` | Opus | Orchestrate execution via skills and MCP |
| 04 | `steps/step-04-examine.md` | Opus | eXamine: MCP validation, build, 21 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 | Scaffold tests via MCP |
| 08 | `steps/step-08-run-tests.md` | Opus | Run tests until 100% pass |
</step_files>

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

| Phase | Step | Obligatory | Description |
|-------|------|------------|-------------|
| *Init* | 00 | Yes | Setup, hierarchy, challenge the need (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 |
| **X** — eXamine | 04 | Yes | 30 POST-CHECKs, MCP validation, build, acceptance criteria |
| *Deep Review* | 05 (if -x) | No | Adversarial code review beyond automated checks |
| *Resolve* | 06 (if BLOCKING) | No | Fix BLOCKING findings |
| *Tests* | 07-08 | **Yes** | Scaffold and run tests |
</apex_phases>

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

| File | Purpose | Loaded by |
|------|---------|-----------|
| `references/smartstack-api.md` | BaseEntity, interfaces, entity/config/controller patterns | step-01, step-03 |
| `references/smartstack-layers.md` | Layer execution rules, skill/MCP mapping, seed data | step-02, step-03 |
| `references/core-seed-data.md` | Comprehensive seed data templates (navigation, permissions, roles) | step-03 (delegate mode + seedData tasks) |
| `references/error-classification.md` | Build error diagnosis categories A-F | step-03 (build failure), step-04 |
| `references/agent-teams-protocol.md` | TeamCreate, coordination, shutdown protocol | step-01, step-03 |
</reference_files>

<execution_rules>

- **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** - domain -> infra -> migration(BLOCKING) -> app -> api -> frontend -> i18n -> tests
- **Agent Teams** - Parallel execution for scan (step-01) and Layer 1 (step-03), unless 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 `/ralph-loop` delegates code generation to `/apex`.

</execution_rules>

<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 context detected (context/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 (navigation, permissions, roles, provider) if required
- Tests: 100% pass, >= 80% coverage
- Commits atomic per layer
</success_criteria>
