# APEX Shared — SmartStack Detection & MCP References

> **Loaded by:** step-00-init (always), other steps as needed

---

## SmartStack Project Detection

### Scan Pattern

1. `*.sln` → .NET backend confirmed
2. `docs/business/` → BA artifacts exist
3. `.ralph/prd-*.json` → PRDs exist
4. `src/pages/` → React frontend exists

---

## Delegate Mode Context

> **Active when:** `-d {path}` flag is set. Implies `-a` (auto) + `-e` (economy).

When `/business-analyse-develop` invokes `/apex -d {prd_path}`:

1. **Read PRD** from `{delegate_prd_path}` (`.ralph/prd.json` or `.ralph/prd-{module}.json`)
2. **Extract context:**
   - `app_name` = `prd.project.application` (e.g., "HumanResources")
   - `module_code` = `prd.project.module` (e.g., "EmployeeManagement")
   - `sections` = from `_seedDataMeta.coreSeedData.navigationSections` in infrastructure tasks
   - `entities` = from `prd.tasks` filtered by `category == 'domain'` (entity names from description)
   - `feature_path` = `prd.source.feature_json_path`
3. **Read task metadata** per category:
   - `_seedDataMeta` → seed data scope (coreSeedData, navRoute, appLabels)
   - `_frontendMeta` → wireframes, filesToCreate, fkFields
   - `_migrationMeta` → entities[], moduleCode
4. **Skip:** challenge questions (step-00 §5), user checkpoints (step-01 §6, step-02 §6)
5. **No nested teams:** `-e` implied, all execution sequential on agent principal

### PRD State Update Protocol (delegate mode only)

After completing each layer in step-03, update the PRD file:
```
Read {delegate_prd_path}
For each task executed in this layer:
  task.status = 'completed' (or 'failed')
  task.completed_at = ISO timestamp
  task.commit_hash = git rev-parse --short HEAD
  task.files_changed = { created: [...], modified: [...] }
Write back to {delegate_prd_path}
```

---

## MCP Tools Reference

### Required (every execution)

| Tool | Purpose | Step |
|------|---------|------|
| `validate_conventions` | Validate SmartStack conventions | 00 (check), 04 (examine) |

### Permission Path Format

> **NOTE:** Permission paths use the navigation hierarchy as base (2+ segments).
> Controller `[NavRoute]` attributes use the same segments: minimum 2 (`app.module`) for module-level, 3 (`app.module.section`) for section-level.

| Level | Permission format | Segments |
|-------|------------------|----------|
| Module | `{app}.{module}.{action}` | 2+1 segments |
| Section | `{app}.{module}.{section}.{action}` | 3+1 segments |
| Resource | `{app}.{module}.{section}.{resource}.{action}` | 4+1 segments |

**Examples:**
- Module: `human-resources.employees.read` (2+1)
- Section: `human-resources.employees.departments.read` (3+1)
- Resource: `human-resources.employees.departments.export.execute` (4+1)

> Permission codes use the SAME kebab-case segments as NavRoute codes.
> Every dot-separated segment in a permission path is a navigation entity code.
> Multi-word codes must use kebab-case: `human-resources`, NOT `humanresources`.
>
> SmartStack.app reference: `support-client.my-tickets.read`, `administration.email-templates.read`
>
> Do not use: `humanresources.employees.read` (concatenated — no kebab-case)
> Correct: `human-resources.employees.read` (kebab-case — matches NavRoute)

### Generation (step-03)

| Tool | Purpose | Condition |
|------|---------|-----------|
| `scaffold_extension` | Generate entities, services, controllers | New code creation |
| `suggest_migration` | Get standardized migration name | EF Core changes |
| `generate_permissions` | Generate RBAC permissions + seed data | New module/section |
| `scaffold_api_client` | Generate TypeScript API client | Frontend changes |
| `scaffold_routes` | Generate React Router routes | Frontend changes |

### eXamine (step-04) — POST-CHECKs (see post-checks.md)

| Tool | Purpose | Condition |
|------|---------|-----------|
| `check_migrations` | Validate EF Core migrations | Migration created |
| `validate_frontend_routes` | Validate route/layout alignment | Frontend changes |
| `validate_security` | Check security patterns | API changes |

**Key POST-CHECKs (most common failures):**
- **#8:** Forms must be full pages — no modals/dialogs
- **#13:** No hardcoded Tailwind colors — use CSS variables only
- **#6+27:** i18n in separate `locales/{lang}/{module}.json` — not embedded in .ts
- **#10:** Form pages must have `.test.tsx` companion files
- **#28:** Pages must use `useTranslation` — no hardcoded strings

### Analysis (step-01)

| Tool | Purpose |
|------|---------|
| `api_docs` | Existing API documentation |
| `analyze_extension_points` | React extension points |

### Tests (step-07)

| Tool | Purpose |
|------|---------|
| `scaffold_tests` | Generate tests (domain, app, api, security) |
| `suggest_test_scenarios` | Suggest test scenarios |
| `analyze_test_coverage` | Check coverage percentage |

### Deep Review (step-05, if -x)

| Tool | Purpose |
|------|---------|
| `review_code` | Adversarial code review |
| `analyze_code_quality` | Code quality metrics |

---

## Severity Labels

| Label | Meaning | When to use |
|-------|---------|-------------|
| **BLOCKING** | Build fails or security vulnerability. Cannot proceed. | `dotnet build` / `npm typecheck` failure, OWASP violation, tenant isolation bypass |
| **CRITICAL** | Functionally broken at runtime but compiles. | Missing DI registration, wrong route, empty translations at runtime |
| **WARNING** | Suboptimal but works. Should fix before merge. | Missing tests, non-canonical naming, cosmetic issues |
| **INFO** | Suggestion or best practice. Non-blocking. | Performance tips, alternative patterns |

> **Rule:** Only use BLOCKING for issues that prevent compilation or create security vulnerabilities.
> CRITICAL is for runtime failures. Everything else is WARNING or INFO.

---

## MCP Degraded Mode

> When MCP is unavailable, fall back to manual patterns from reference files.

| MCP Tool | Fallback |
|----------|----------|
| `validate_conventions` | Manual review against `smartstack-api.md` patterns |
| `scaffold_extension` | Create files manually following `smartstack-api.md` entity/service/controller patterns |
| `suggest_migration` | Name format: `{context}_v{version}_{sequence}_{Description}` (see existing migrations for version) |
| `generate_permissions` | Write `HasData()` code manually following `core-seed-data.md` permission section |
| `scaffold_routes` | Create `componentRegistry.generated.ts` with `PageRegistry.register()` calls manually following `smartstack-frontend.md` §1 (or legacy `applicationRoutes` array for pre-v3.7 projects) |
| `validate_frontend_routes` | Run POST-CHECK bash scripts from `post-checks.md` |
| `validate_security` | Run security POST-CHECKs S1-S6 from `post-checks.md` |
| `check_migrations` | Run `dotnet ef migrations has-pending-model-changes` manually |
| `scaffold_tests` | Create test files manually following `smartstack-frontend-compliance.md` §8 patterns |

---

## Context Bridge for Skill Delegation

> When delegating to `/controller`, `/ui-components`, `/application`, etc., pass this context block to ensure the skill has enough information.

```
Context for {skill_name}:
- Application: {app_name}
- Module: {module_code}
- NavRoute: {navRoute} (e.g., "human-resources.employees")
- Entity: {entity_name} with properties: {key_properties}
- Tenant mode: {strict|optional|scoped|none}
- CSS: Use CSS variables ONLY (see smartstack-frontend.md §4)
- I18n: 4 languages (fr, en, it, de), namespace: {module-kebab}
- Forms: Full pages with own routes, ZERO modals/drawers
- FK fields: Use EntityLookup component (see smartstack-frontend.md §6)
```

> Adjust the template based on the skill: backend skills don't need CSS/i18n context, frontend skills don't need tenant mode details.

---

## Existing Skills Delegation

| Skill | When to delegate |
|-------|-----------------|
| `/controller` | Complex controller with custom routes |
| `/application` | New application/module structure |
| `/ui-components` | Complex React pages (tables, grids, dashboards) |
| `/efcore` | Complex EF Core configurations |
| `/notification` | In-app or email notifications |
| `/workflow` | Automated workflow triggers |
