<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of Contents**

- [HOWTO: Path Protection & Poka-Yoke in ggen](#howto-path-protection--poka-yoke-in-ggen)
  - [Overview](#overview)
  - [What is FMEA?](#what-is-fmea)
  - [Configuration Location](#configuration-location)
  - [1. Generation Configuration (`[generation]`)](#1-generation-configuration-generation)
    - [In ggen.toml](#in-ggentoml)
    - [Path Protection Rules](#path-protection-rules)
    - [Example: Safe Regeneration](#example-safe-regeneration)
  - [2. Poka-Yoke Configuration (`[generation.poka_yoke]`)](#2-poka-yoke-configuration-generationpoka_yoke)
    - [In ggen.toml](#in-ggentoml-1)
    - [Poka-Yoke Effects](#poka-yoke-effects)
  - [3. CODEOWNERS Configuration (`[codeowners]`)](#3-codeowners-configuration-codeowners)
    - [In ggen.toml](#in-ggentoml-2)
    - [Creating OWNERS Files](#creating-owners-files)
    - [Generate Aggregated CODEOWNERS](#generate-aggregated-codeowners)
  - [4. Package-Level FMEA (Design Documentation)](#4-package-level-fmea-design-documentation)
    - [Example: marketplace/packages/my-cli/package.toml](#example-marketplacepackagesmy-clipackagetoml)
    - [RPN Calculation (Design-Time Analysis)](#rpn-calculation-design-time-analysis)
  - [5. Complete Example: ggen.toml](#5-complete-example-ggentoml)
  - [6. Troubleshooting](#6-troubleshooting)
    - ["Path overlap detected"](#path-overlap-detected)
    - ["Cannot write to protected path"](#cannot-write-to-protected-path)
  - [7. Key Concepts Summary](#7-key-concepts-summary)
  - [8. The Core Principle](#8-the-core-principle)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

# HOWTO: Path Protection & Poka-Yoke in ggen

**Document**: Generation Safety Configuration Guide
**Branch**: `006-marketplace-fmea-poka-yoke`
**Last Updated**: 2025-12-14

---

## Overview

This guide explains how to configure **path protection** and **Poka-Yoke** (error-proofing) controls in ggen. These features ensure AI coding agents can regenerate code safely without overwriting domain logic.

**Key Insight**: ggen is used by AI agents, not human developers. The controls ensure an agent can run `ggen generate` repeatedly without overwriting code it authored in previous sessions.

---

## What is FMEA?

**FMEA (Failure Mode and Effects Analysis)** is a **design-time analysis methodology**, NOT a runtime configuration. It's used during package development to:

1. **Identify** potential failure modes (what could go wrong)
2. **Assess** risk using Severity × Occurrence × Detection = RPN
3. **Document** mitigations in package.toml as evidence of analysis

FMEA belongs in **package.toml** as documentation of analysis performed, not in **ggen.toml** as runtime configuration.

---

## Configuration Location

| What | Where | Purpose |
|------|-------|---------|
| Path protection | `ggen.toml [generation]` | Runtime safety during code generation |
| FMEA analysis | `package.toml [fmea]` | Design-time risk documentation |

---

## 1. Generation Configuration (`[generation]`)

Controls path protection during code generation.

### In ggen.toml

```toml
[generation]
# Enable generation safety checks
enabled = true

# Protected paths (glob patterns) - NEVER overwrite
# These contain domain logic implemented by developers/agents
protected_paths = [
    "src/domain/**",
    "crates/*/src/domain/**",
    "**/src/main.rs",
]

# Regeneratable paths (glob patterns) - safe to overwrite
# These contain generated scaffolding from templates
regenerate_paths = [
    "src/generated/**",
    "crates/*/src/generated/**",
]

# Header to inject into generated files
generated_header = """
// ============================================================
// DO NOT EDIT THIS FILE
//
// This file is auto-generated by ggen from RDF ontology.
// Any manual changes will be OVERWRITTEN on regeneration.
//
// Regenerate with: ggen generate
// ============================================================
"""

# Require confirmation before overwriting any file
require_confirmation = false

# Create backup before overwriting
backup_before_write = true
```

### Path Protection Rules

| Rule | Check | Action |
|------|-------|--------|
| No Overlap | `protected_paths ∩ regenerate_paths = ∅` | ERROR if paths overlap |
| Protected Write | Attempt to write to protected path | ERROR, write blocked |
| Regenerate Safe | Write to regenerate path | ALLOWED |

### Example: Safe Regeneration

```bash
# Agent runs this multiple times - domain logic is NEVER touched
ggen generate \
  --template clap-noun-verb \
  --domain ontology/cli.ttl \
  --output src/generated/ \
  --force

# Result:
# ✅ src/generated/*.rs - Regenerated with new traits
# ✅ src/domain/*.rs    - UNTOUCHED (protected)
```

---

## 2. Poka-Yoke Configuration (`[generation.poka_yoke]`)

Additional error-proofing controls.

### In ggen.toml

```toml
[generation.poka_yoke]
# Add warning headers to generated files
warning_headers = true

# Add generated files to .gitignore
gitignore_generated = false

# Add generated files to .gitattributes (linguist-generated)
gitattributes_generated = true

# Validate imports don't cross boundaries
validate_imports = false
```

### Poka-Yoke Effects

| Setting | Effect |
|---------|--------|
| `warning_headers = true` | Injects `// DO NOT EDIT` header into generated files |
| `gitignore_generated = true` | Adds `src/generated/` to `.gitignore` |
| `gitattributes_generated = true` | Marks generated files as `linguist-generated` in GitHub |
| `validate_imports = true` | ERROR if domain imports from generated (circular) |

---

## 3. CODEOWNERS Configuration (`[codeowners]`)

Aggregates team ownership from distributed OWNERS files.

### In ggen.toml

```toml
[codeowners]
# Enable CODEOWNERS generation
enabled = true

# Source directories to scan for OWNERS files
source_dirs = ["ontology", "ontologies"]

# Base directories to generate entries for
base_dirs = [
    "ontology",
    "ontologies",
    "src/generated",
    "src/domain",
    "crates/*/src/generated",
    "crates/*/src/domain",
]

# Output path (defaults to .github/CODEOWNERS)
output_path = ".github/CODEOWNERS"

# Auto-regenerate on noun changes
auto_regenerate = false
```

### Creating OWNERS Files

```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
EOF
```

### Generate Aggregated CODEOWNERS

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

---

## 4. Package-Level FMEA (Design Documentation)

FMEA in package.toml documents the **analysis performed** during package design. It's evidence that failure modes were considered, not runtime configuration.

### Example: marketplace/packages/my-cli/package.toml

```toml
[package]
name = "my-cli"
version = "1.0.0"

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

# FMEA section documents design-time risk analysis
# This is EVIDENCE of analysis, not runtime configuration
[fmea]
controls = [
    { id = "F1", mode = "Edit generated file", severity = 8, occurrence = 6, detection = 5, control = "File header warning + gitignore" },
    { id = "F2", mode = "Overwrite domain logic", severity = 10, occurrence = 4, detection = 4, control = "Trait boundary - domain in separate files" },
]
```

### RPN Calculation (Design-Time Analysis)

```
RPN = Severity × Occurrence × Detection

Example F1: RPN = 8 × 6 × 5 = 240 (CRITICAL - must have control documented)
Example F2: RPN = 10 × 4 × 4 = 160 (HIGH - should have control documented)
```

| RPN Range | Level | Documentation Requirement |
|-----------|-------|---------------------------|
| 201-1000 | **Critical** | MUST document control |
| 100-200 | **High** | SHOULD document control |
| 1-99 | **Medium** | MAY document control |

---

## 5. Complete Example: ggen.toml

```toml
# ggen.toml - Runtime Configuration

[project]
name = "my-project"
version = "1.0.0"

# ============================================================================
# Marketplace Configuration
# ============================================================================
[marketplace]
registry_url = "https://marketplace.ggen.dev"
cache_packages = true
verify_signatures = true

# ============================================================================
# Generation Configuration (Path Protection)
# ============================================================================
[generation]
enabled = true

protected_paths = [
    "src/domain/**",
    "crates/*/src/domain/**",
    "**/src/main.rs",
]

regenerate_paths = [
    "src/generated/**",
    "crates/*/src/generated/**",
]

generated_header = """
// ============================================================
// DO NOT EDIT THIS FILE
//
// This file is auto-generated by ggen from RDF ontology.
// Any manual changes will be OVERWRITTEN on regeneration.
//
// Regenerate with: ggen generate
// ============================================================
"""

require_confirmation = false
backup_before_write = true

[generation.poka_yoke]
warning_headers = true
gitignore_generated = false
gitattributes_generated = true
validate_imports = false

# ============================================================================
# CODEOWNERS Configuration
# ============================================================================
[codeowners]
enabled = true
source_dirs = ["ontology", "ontologies"]
base_dirs = ["ontology", "src/generated", "src/domain"]
output_path = ".github/CODEOWNERS"
auto_regenerate = false
```

---

## 6. Troubleshooting

### "Path overlap detected"

**Problem**: A path appears in both `protected_paths` and `regenerate_paths`.

**Fix**: Remove the path from one list. Paths cannot be both protected and regeneratable.

### "Cannot write to protected path"

**Problem**: Attempting to generate into a protected directory.

**Fix**: Use `--output src/generated/` to write to regeneratable paths only.

---

## 7. Key Concepts Summary

| Concept | Type | Purpose |
|---------|------|---------|
| **FMEA** | Design-time analysis | Identify and document failure modes |
| **Protected Paths** | Runtime config | Paths NEVER overwritten by ggen |
| **Regenerate Paths** | Runtime config | Paths safely overwritten by ggen |
| **Poka-Yoke** | Runtime config | Error-proofing controls |
| **CODEOWNERS** | Runtime config | Team ownership boundaries |

---

## 8. The Core Principle

**"ggen is for AI Coding Agents"**

The path protection system exists to solve one problem:

> How does an AI agent regenerate code freely without losing domain logic it authored in a previous session?

**Answer**:
1. `src/generated/` contains **traits** (the contract) → regenerate freely
2. `src/domain/` contains **implementations** (the logic) → NEVER touched
3. Rust compiler ensures domain implements the traits
4. Warning headers prevent accidental edits
5. ggen.toml defines the boundaries

**Result**: Run `ggen generate` as often as needed. Domain logic is always safe.
