**Module ID:** `mime-enums`  
**Module name:** MIME Enumerations  
**Lifecycle phase:** formation  
**Status:** INTENT ONLY. No code yet.  
**Date:** 2026-07-21  

---

## 1. Intent (the "why")
- **Problem**: FreshCloud needs standardized MIME type identifiers and metadata flags for email processing (IMAP/SMTP), with clear UI mapping for end-users.  
- **Role**: Provides immutable constants for content types, priorities, and header flags to prevent runtime ambiguities. Enables consistent rendering ("Text" vs. "HTML") and priority indicators ("!" / "!!") in the UI layer.  
- **Impact**: Replaces MailSo's scattered constants with a centralized, versioned enum system that eliminates magic strings and enforces IANA compliance.  

## 2. User-facing behaviour
- **ContentType**: Maps `text/plain` to "Text", `text/html` to "HTML", `multipart/alternative` to "Formatted" in the UI.  
- **MessagePriority**: Translates `HIGH` to "!!", `NORMAL` to "!", `LOW` to "-".  
- **Header Flags**: Exposes boolean states for `PGP_SIGNATURE`, `DKIM_VERIFIED` for trust indicators.  
- **Validation**: Rejects unknown content types with clear error messages.  

## 3. Public contract (data shapes + signatures)
```typescript
namespace FreshCloud\Mail\MimeEnumerations {
  enum ContentType {
    PLAIN = 'text/plain',
    HTML = 'text/html',
    MULTIPART_ALTERNATIVE = 'multipart/alternative'
  }

  enum MessagePriority {
    HIGH = 'HIGH',
    NORMAL = 'NORMAL',
    LOW = 'LOW'
  }

  enum HeaderFlag {
    PGP_SIGNATURE = 'PGP_SIGNATURE',
    DKIM_VERIFIED = 'DKIM_VERIFIED'
  }

  interface EnumValidator {
    validateContentType(value: string): ContentType;
    validatePriority(value: string): MessagePriority;
    validateHeaderFlag(value: string): HeaderFlag;
  }

  class EnumConstants implements EnumValidator {
    public static readonly CONTENT_TYPES: ContentType[];
    public static readonly PRIORITIES: MessagePriority[];
    public static readonly HEADER_FLAGS: HeaderFlag[];
  }
}
```

## 4. Persistence (what gets stored where)
- **No persistence needed**: Constants are in-memory only. No PocketBase tables or files.  
- **Audit Trail**: If ContentType/Priority usage appears in future audit logs, leverage existing `email_audit` table.  

## 5. Dependencies (what this module uses, what uses this)
- **Dependencies**:  
  - `FreshCloud\Mail\Uid` (UID generation for constants)  
  - `FreshCloud\Mail\Logger` (error logging)  
- **Dependents**:  
  - `mime-parser` (consumes ContentType)  
  - `mime-content` (consumes MessagePriority)  
  - `ui-bridge` (consumes UI-mapped enum values)  

## 6. Behaviour inventory (the N public methods)
| Method | Signature | Purpose | Side Effects | Errors |
|--------|-----------|---------|--------------|--------|
| `validateContentType` | `(string): ContentType` | Normalizes input to IANA-approved content type | None | `InvalidEnumException` on unknown value |
| `validatePriority` | `(string): MessagePriority` | Ensures priority is HIGH/NORMAL/LOW | None | `InvalidEnumException` on unknown value |
| `validateHeaderFlag` | `(`string`): HeaderFlag` | Confirms flag is PGP_SIGNATURE/DKIM_VERIFIED | None | `InvalidEnumException` on unknown value |

## 7. State machine
- **States**:  
  - `Uninitialized`: Constants loaded but not validated.  
  - `Validated`: Enum values verified against IANA registry.  
- **Transitions**:  
  - `Uninitialized` → `Validated`: On first method call.  
  - **Trigger**: Lazy initialization via static property access.  

## 8. Side effects
- **Writes**: None (constants are read-only).  
- **Reads**: Static property access loads IANA registry once.  
- **Emits**: Errors via `Logger::error()` for invalid enum values.  
- **Metrics**: `freshcloud_mime_enum_hits_total` (count per validation).  

## 9. Input validation
- **ContentType**: Must match `^text/.*$` or `multipart/.*$` per RFC 2045.  
- **MessagePriority**: Must be `HIGH`, `NORMAL`, or `LOW`.  
- **HeaderFlag**: Must be `PGP_SIGNATURE` or `DKIM_VERIFIED`.  
- **Case Sensitivity**: Inputs normalized to uppercase before validation.  

## 10. Failure modes
| Failure | Handling | Caller sees |
|---------|----------|-------------|
| Unknown ContentType | Throws `InvalidEnumException` with RFC 2045 reference | UI error: "Unsupported content type" |
| Invalid Priority | Throws `InvalidEnumException` with valid options | UI error: "Priority must be HIGH/NORMAL/LOW" |
| Memory exhaustion | Fails fast (no fallback) | `RuntimeException` from Logger |

## 11. User simulation
**Scenario 1: Plain Text Rendering**  
Given a MIME part with `Content-Type: text/plain`  
When UI requests ContentType mapping  
Then display "Text"  

**Scenario 2: PGP Signature Detected**  
Given an email with `PGP_SIGNATURE` header flag  
When validating HeaderFlag  
Then return `PGP_SIGNATURE` for UI trust indicator  

**Scenario 3: Unknown Content Type**  
Given `Content-Type: application/unknown`  
When validating ContentType  
Then throw `InvalidEnumException`  

## 12. Reproducibility test
1. Create fresh `FreshCloud\Mail\MimeEnumerations` namespace.  
2. Define ContentType, MessagePriority, HeaderFlag enums.  
3. Implement `EnumConstants` class with static arrays.  
4. Add `validate*` methods with strict input checks.  
5. Include IANA registry in unit tests.  
6. Mock `Logger::error()` for invalid inputs.  
7. Verify UI mappings in ui-bridge module.  
8. Test multi-threaded access (static property safety).  
9. Run RFC 2045 compliance test suite.  

## 13. Substitutability (FvW v8 §37.4)
An alternative must:  
- Provide identical enum values (e.g., `ContentType::PLAIN` must resolve to `'text/plain'`).  
- Implement all `validate*` methods with identical signatures.  
- Support lazy loading of IANA registry.  
- Emit equivalent errors with standardized messages.  
- Expose `freshcloud_mime_enum_hits_total` metric.  

## 14. Invariants (the 5 things that must always hold)
1. **Constant Immutability**: All public properties are read-only after initialization.  
2. **IANA Compliance**: Content types MUST match RFC 2045 registry.  
3. **UI Binding**: ContentType values MUST map to "Text"/"HTML"/"Formatted".  
4. **Error Consistency**: All invalid enum inputs throw `InvalidEnumException`.  
5. **No AGPL Lineage**: Clean-room implementation (no MailSo code fragments).  

## 15. Sweep fields applied (the 14 design intent fields)
### Sweep 1: Multi-user + PocketBase  
| Field | Design Intent | PHP Implementation |
|-------|--------------|-------------------|
| user_scoping | Pure constants; no user data | Static class, no user parameters in methods |
| pb_integration | No PB interaction; constants only | Zero references to PocketBase SDK |
| auth_boundary | No auth needed; immutable data | No auth middleware in methods |
| state_isolation | No shared state | Static properties only, no instance state |
| logout_behaviour | No action required | No cleanup methods |
| multi_account | No account-specific logic | Constants are universal across accounts |

### Sweep 2: World-class Abilities  
| Field | Design Intent | PHP Implementation |
|-------|--------------|-------------------|
| connection_pool | Not applicable | No database/connection code |
| offline_cache | Not applicable | No file/DB writes |
| sieve_integration | Not applicable | No Sieve script parsing |
| audit_logging | Minimal logs for invalid inputs | `Logger::error()` only on validation failure |
| ux_primitives | UI enum mappings | `ContentType` maps to "Text"/"HTML" in UI bridge |

### Sweep 3: Migration + Observability + Tests  
| Field | Design Intent | PHP Implementation |
|-------|--------------|-------------------|
| migration | No migration; constants only | Zero DB schema changes |
| observability | Validation metrics | `freshcloud_mime_enum_hits_total` Prometheus counter |
| tests | IANA compliance tests | PHPUnit data providers with RFC 2045 test vectors |

## 16. Cross-references
- **§11**: Rules for module structure (see `rules.md`).  
- **§37**: Public contract requirements (see `fragment.md`).  
- **§38**: Formation-phase intent (this document).  
- **§19**: Clean-room extraction from MailSo (historical reference).  
- **Dependent modules**: `mime-parser`, `mime-content`, `ui-bridge`.  

## 17. What we are intentionally NOT doing (deferred to future)
1. Supporting MIME types outside IANA registry (future RFC expansions).  
2. Custom header flags beyond PGP/DKIM (extensible via follow-up module).  
3. Compression/encoding flags (defer to `mime-encoding` module).  
4. Priority variants (e.g., "URGENT").  
5. Content disposition flags (e.g., `ATTACHMENT`).  
6. Real-time validation of live streams (static validation only).  
7. Performance optimization for high-volume parsing.  
8. Locale-aware UI mappings (default English only).  
9. Version-specific MIME features (e.g., RFC 6532 future-proofing).  
10. Custom enum extensibility plugins (strict predefined set).  
*Note: MailSo had 5 PHP files; we use 4 (ContentType, MessagePriority, Header, EnumConstants) for simplicity.*