# Quickstart: FMEA & Poka-Yoke for Enterprise Packages

**Time to complete**: 10 minutes
**Prerequisites**: ggen installed, existing marketplace package

## Overview

This guide shows how to add enterprise-grade FMEA (Failure Mode and Effects Analysis) and Poka-Yoke (error-proofing) controls to your ggen marketplace package.

## Step 1: Add Enterprise Configuration

Edit your `package.toml` to add enterprise sections:

```toml
# package.toml

[package]
name = "my-enterprise-cli"
version = "1.0.0"

# Enable enterprise features
[enterprise]
fortune_500_ready = true
fmea_controls = true
poka_yoke_enabled = true
domain_protection = "trait-boundary"
```

## Step 2: Configure Path Protection

Define which paths are protected (domain logic) and which can be regenerated:

```toml
# package.toml (continued)

[generation]
# These paths will NEVER be overwritten
protected_paths = [
    "src/domain/**",
    "src/main.rs",
    "Cargo.toml",
]

# These paths CAN be regenerated freely
regenerate_paths = [
    "src/generated/**",
]
```

**Key principle**: Your business logic goes in `src/domain/`. Generated scaffolding goes in `src/generated/`. Running `ggen generate` will ONLY touch `src/generated/`.

## Step 3: Configure Poka-Yoke Controls

Add error-proofing to prevent accidental edits:

```toml
# package.toml (continued)

[poka_yoke]
# Warning header for generated files
generated_file_header = """
// ⚠️ DO NOT EDIT - This file is auto-generated
// @generated by ggen from RDF ontology
//
// Regenerate with:
//   ggen generate --template my-template --domain my-cli.rdf
//
// Place your code in src/domain/ instead.
"""

# Prevent staging generated files
gitignore_patterns = ["src/generated/"]

# Mark as generated in GitHub
gitattributes_patterns = ["src/generated/** linguist-generated=true"]
```

## Step 4: Document Failure Modes (FMEA)

List potential failure modes with severity ratings and mitigation controls:

```toml
# package.toml (continued)

[fmea]
enabled = true
min_coverage = 100  # All critical modes must have controls

# Failure Mode 1: Developer edits generated file
[[fmea.controls]]
id = "F1"
mode = "Developer edits generated file directly"
severity = 9      # High impact (work lost on regeneration)
occurrence = 6    # Moderate likelihood (common mistake)
detection = 4     # Somewhat detectable (code review)
control = "⚠️ DO NOT EDIT header + .gitignore + pre-commit hook"

# Failure Mode 2: Regeneration overwrites domain logic
[[fmea.controls]]
id = "F2"
mode = "ggen generate overwrites domain implementations"
severity = 10     # Critical (months of work lost)
occurrence = 7    # Likely without protection
detection = 2     # Easy to detect (compilation fails)
control = "Trait boundary separation - protected_paths config"

# Failure Mode 3: Merge conflicts in ontology
[[fmea.controls]]
id = "F3"
mode = "Merge conflict when two devs modify same ontology file"
severity = 4      # Low-moderate (resolvable)
occurrence = 5    # Moderate at scale
detection = 4     # Detectable in PR
control = "One-file-per-verb pattern - each verb in separate .ttl"

# Failure Mode 4: Wrong team modifies noun
[[fmea.controls]]
id = "F4"
mode = "Developer from wrong team modifies noun they don't own"
severity = 6      # Moderate (potential bugs)
occurrence = 4    # Less likely with awareness
detection = 3     # Detectable with CODEOWNERS
control = "CODEOWNERS per noun directory"
```

### Understanding RPN Scores

**RPN = Severity × Occurrence × Detection**

| RPN Range | Level | Action Required |
|-----------|-------|-----------------|
| 201-1000 | **Critical** | MUST have control (validation fails without) |
| 100-200 | **High** | SHOULD have control (warning if missing) |
| 1-99 | **Medium** | MAY have control (informational) |

## Step 5: Validate Your Package

Run validation to ensure compliance:

```bash
# Basic validation
ggen marketplace validate

# Strict mode (warnings = errors)
ggen marketplace validate --strict

# Generate FMEA report
ggen marketplace validate --fmea-report fmea-report.json --format json
```

**Expected output**:

```
✅ Package validation passed

FMEA Summary:
  Total failure modes: 4
  Critical (RPN >200): 1 - all mitigated
  High (RPN 100-200): 1 - all mitigated
  Medium (RPN <100): 2
  Coverage: 100%

Poka-Yoke Controls:
  Generated file header: ✅ configured
  Gitignore patterns: 1 patterns
  Gitattributes patterns: 1 patterns

Path Protection:
  Protected paths: 3 patterns
  Regenerate paths: 1 patterns
  Overlap check: ✅ no conflicts
```

## Step 6: Set Up Team Ownership (Optional)

For multi-team projects, create OWNERS files per noun:

```bash
# Create OWNERS file for user noun
mkdir -p ontology/user
cat > ontology/user/OWNERS << 'EOF'
# Identity Team owns user noun
@company/identity-team
@john.smith
@jane.doe

# Breaking changes require Platform Team
*.breaking.ttl @company/platform-team
EOF
```

Generate aggregated CODEOWNERS:

```bash
ggen generate --codeowners
# Creates .github/CODEOWNERS from all noun OWNERS files
```

## Step 7: First Generation

Run initial generation with stub creation:

```bash
# First generation creates domain stubs
ggen generate \
  --template my-template \
  --domain my-cli.rdf \
  --output ./ \
  --first-generation
```

This creates:
- `src/generated/*.rs` - Generated traits (regeneratable)
- `src/domain/*.rs` - Domain stubs with `unimplemented!()` (protected)
- `.gitignore` - Updated with generated patterns
- `.gitattributes` - Marks generated files

## Step 8: Implement Domain Logic

Edit files in `src/domain/` to implement your business logic:

```rust
// src/domain/user.rs (PROTECTED - your code here)
use crate::generated::UserTrait;
use crate::error::DomainError;

pub struct UserDomain;

impl UserTrait for UserDomain {
    fn create(&self, name: String, email: String) -> Result<User, DomainError> {
        // YOUR IMPLEMENTATION HERE
        // This code will NEVER be overwritten by ggen generate
        validate_email(&email)?;
        let user = User::new(name, email);
        self.repository.save(&user)?;
        Ok(user)
    }
}
```

## Step 9: Regenerate Safely

When ontology changes, regenerate without fear:

```bash
# Safe regeneration - domain logic untouched
ggen generate \
  --template my-template \
  --domain my-cli.rdf \
  --output ./ \
  --force  # Overwrites src/generated/ ONLY
```

**What happens**:
- ✅ `src/generated/*.rs` - Updated with new traits
- ✅ `src/domain/*.rs` - UNTOUCHED (your 500 LOC of business logic safe)
- ✅ Compilation fails if trait signatures changed (expected, fix domain)

## Complete Example package.toml

```toml
[package]
name = "enterprise-ops"
version = "1.0.0"
description = "Enterprise operations CLI with FMEA/Poka-Yoke"

[enterprise]
fortune_500_ready = true
fmea_controls = true
poka_yoke_enabled = true
domain_protection = "trait-boundary"

[generation]
protected_paths = ["src/domain/**", "src/main.rs", "Cargo.toml"]
regenerate_paths = ["src/generated/**"]

[poka_yoke]
generated_file_header = """
// ⚠️ DO NOT EDIT - This file is auto-generated
// @generated by ggen
// Place your code in src/domain/ instead.
"""
gitignore_patterns = ["src/generated/"]
gitattributes_patterns = ["src/generated/** linguist-generated=true"]

[fmea]
enabled = true
min_coverage = 100

[[fmea.controls]]
id = "F1"
mode = "Developer edits generated file"
severity = 9
occurrence = 6
detection = 4
control = "DO NOT EDIT header + .gitignore"

[[fmea.controls]]
id = "F2"
mode = "Regenerate overwrites domain logic"
severity = 10
occurrence = 7
detection = 2
control = "protected_paths configuration"
```

## Next Steps

1. **Add more failure modes**: Think about what could go wrong in your specific domain
2. **Set up CI validation**: Add `ggen marketplace validate --strict` to your CI pipeline
3. **Create OWNERS files**: For multi-team projects, define ownership per noun
4. **Review RPN scores**: Prioritize controls by RPN (highest first)

## Troubleshooting

### "Missing [fmea] section"
Add `[fmea]` with at least one control to package.toml.

### "Unmitigated critical failure mode"
Add a `control` field to failure modes with RPN >200.

### "Path overlap detected"
A path cannot be both protected and regeneratable. Remove from one list.

### "Cannot write to protected path"
You're trying to generate into a protected path. Use `--output src/generated/` instead.
