Skip to main content

FORGERY: Domain Model Integration with Manuscript

Document ID: FORGERY-DOMAIN-SYNC-001
Version: 1.0
Date: December 16, 2025
Status: Technical Integration Specification

Executive Summary

This document specifies how Forgery integrates with Manuscript (MSX) to automatically discover, validate, and forge domain models. It ensures that as domain models evolve in Manuscript, Forgery automatically generates relevant testing quests and maintains synchronization.

1. MANUSCRIPT INTEGRATION OVERVIEW

1.1 Domain Model Discovery

Forgery automatically scans Manuscript for domains:
Manuscript Structure (.msx)
├─ domains/
│   ├─ user/v1.proto
│   ├─ document/v1.proto
│   ├─ collaboration/v1.proto
│   ├─ workspace/v1.proto
│   ├─ aria/v1.proto
│   ├─ notification/v1.proto
│   ├─ audit/v1.proto
│   └─ envelope/v1.proto
└─ shared/v1.proto

Forgery Discovery Process
├─ Scan .msx/domains/*/v1.proto
├─ Parse proto definitions
├─ Extract domain metadata:
│   ├─ Domain name
│   ├─ Event types (messages)
│   ├─ Complexity (field count)
│   ├─ Dependencies (imports)
│   └─ Custom options (metadata)
├─ Auto-generate quests per domain
└─ Cache for quest generation

1.2 Domain Metadata Extraction

Proto File Parsing:
// Example: user/v1.proto
syntax = "proto3";
package materi.v1.user;

import "shared/v1.proto";

// Custom option to mark domains
option (materi.domain_options).name = "User";
option (materi.domain_options).description = "User identity and profile management";
option (materi.domain_options).tier = 1;

message UserCreated {
  string user_id = 1;
  string email = 2;
  string name = 3;
  int64 created_at = 4;
  // ... 10 more fields
}

message UserUpdated {
  string user_id = 1;
  string email = 2 [optional = true];
  string name = 3 [optional = true];
  // ... 8 more fields
}

// ... 6 more message types
Forgery Extraction:
type DomainMetadata struct {
  Name         string    // "User"
  PackageName  string    // "materi.v1.user"
  Description  string    // "User identity and profile management"
  ProtoFile    string    // "user/v1.proto"
  Tier         int       // 1 (Apprentice - foundational)

  Events       []Message // [UserCreated, UserUpdated, ...]
  Dependencies []string  // ["shared"]
  Complexity   float64   // 1.0-3.0 scale
  TestSuites   []string  // auto-generated
}

type Message struct {
  Name      string
  FieldCount int
  IsEvent   bool
}

func (d DomainMetadata) CalculateComplexity() float64 {
  baseComplexity := 1.0

  // Event count factor
  baseComplexity *= (1.0 + float64(len(d.Events)) * 0.1)

  // Field complexity
  avgFields := 0.0
  for _, e := range d.Events {
    avgFields += float64(e.FieldCount)
  }
  avgFields /= float64(len(d.Events))
  baseComplexity *= (1.0 + (avgFields / 10.0))

  // Dependency factor
  baseComplexity *= (1.0 + float64(len(d.Dependencies)) * 0.2)

  return baseComplexity
}

2. AUTOMATIC QUEST GENERATION

2.1 Quest Generation Pipeline

For each discovered domain, Forgery generates 4 quest tiers:
Domain: "User" (Complexity: 1.5)

Tier 1: Smoke Test
  ├─ ID: quest_user_smoke_v1
  ├─ Name: "Forge the User Domain"
  ├─ Tests:
  │   ├─ Proto compilation
  │   ├─ Import validation
  │   └─ Schema export verification
  ├─ XP: 100
  └─ Duration: 5 min

Tier 2: Integration Test
  ├─ ID: quest_user_integration_v1
  ├─ Name: "User Domain Integration"
  ├─ Tests:
  │   ├─ Cross-message validation
  │   ├─ Dependency imports
  │   ├─ Event serialization
  │   └─ Message round-trip (protobuf)
  ├─ XP: 375 (250 base × 1.5 complexity)
  └─ Duration: 20 min

Tier 3: Network Trial
  ├─ ID: quest_user_network_v1
  ├─ Name: "User Domain Under Fire"
  ├─ Tests:
  │   ├─ 1000 concurrent UserCreated events
  │   ├─ 50% latency injection
  │   ├─ Timeout handling
  │   └─ Event ordering guarantees
  ├─ XP: 1875 (1250 base × 1.5 complexity)
  └─ Duration: 1 hour

Tier 4: Transmutation Ritual
  ├─ ID: quest_user_transmutation_v1
  ├─ Name: "The User Ascension"
  ├─ Tests:
  │   ├─ Full system integration
  │   ├─ Cross-domain user events
  │   ├─ Collaborative domain sync
  │   └─ Production readiness checks
  ├─ XP: 7500 (5000 base × 1.5 complexity)
  └─ Duration: 2-4 hours

2.2 Quest Customization by Domain Type

Detected Domain Patterns:
Pattern: Identity Domain (user, workspace)
├─ Focuses on: CRUD operations, permissions
├─ Additional tests: Auth flows, role-based access
└─ Tier bonus: 1.1x XP

Pattern: Event/Communication Domain (notification, audit)
├─ Focuses on: Async messaging, ordering guarantees
├─ Additional tests: Event deduplication, ordering
└─ Tier bonus: 1.2x XP (harder to test)

Pattern: Collaborative Domain (collaboration, document)
├─ Focuses on: Conflict resolution, consistency
├─ Additional tests: Concurrent modifications, CRDT simulation
└─ Tier bonus: 1.3x XP (highly complex)

Pattern: Derived Domain (aria - AI)
├─ Focuses on: Async processing, state management
├─ Additional tests: State transitions, error recovery
└─ Tier bonus: 1.25x XP (specialized)

3. SCRIBE INTEGRATION (Domain Sync)

3.1 Synchronization Flow

Forgery monitors Manuscript changes via Scribe:
Developer Action: "git push" to manuscript

GitHub Action (manuscript/.github/workflows/*)
  ├─ Run: scribe sync msx
  ├─ Run: scribe sync service:*
  └─ Webhook: POST to Forgery

Forgery Webhook: /api/manuscript/sync
  ├─ Payload: {
  │   "event": "manuscript.updated",
  │   "timestamp": "2025-12-16T10:30:00Z",
  │   "changed_files": ["user/v1.proto", "shared/v1.proto"],
  │   "commit": "abc123...",
  │   "branch": "main"
  │ }
  ├─ Verify signature (GitHub)
  └─ Process changes

Forgery Processing
  ├─ Re-scan affected domains
  ├─ Detect schema changes
  ├─ Update quest definitions
  ├─ Notify players: "New challenges available!"
  └─ Update checksums

3.2 Change Detection

Forgery detects and responds to domain changes:
type DomainChange struct {
  Domain       string
  ChangeType   string // "schema", "event", "dependency"
  Severity     string // "minor", "major", "breaking"

  Before       DomainMetadata
  After        DomainMetadata

  ImpactedQuests []string // Which quests are affected
  RecommendedAction string
}

func DetectDomainChanges(before, after DomainMetadata) []DomainChange {
  changes := []DomainChange{}

  // Schema changes (added/removed fields)
  for _, eventBefore := range before.Events {
    eventAfter := findEvent(after, eventBefore.Name)
    if eventAfter == nil {
      changes = append(changes, DomainChange{
        Domain:      before.Name,
        ChangeType:  "event_removed",
        Severity:    "major",
        Before:      before,
        After:       after,
      })
    } else if eventAfter.FieldCount > eventBefore.FieldCount {
      changes = append(changes, DomainChange{
        Domain:      before.Name,
        ChangeType:  "event_expanded",
        Severity:    "minor",
      })
    }
  }

  // Dependency changes
  if len(after.Dependencies) != len(before.Dependencies) {
    changes = append(changes, DomainChange{
      Domain:      before.Name,
      ChangeType:  "dependency_changed",
      Severity:    "major",
    })
  }

  return changes
}

3.3 Quest Update Strategy

When a domain changes, Forgery intelligently updates quests:
scenario:
    change: "User domain adds new 'verification_status' field to UserCreated"
    severity: 'minor'
    impact: 'All UserCreated-related tests affected'

actions:
    1. Detect Change: └─ UserCreated.fields increased from 4 to 5

    2. Update Quests:
        ├─ Tier 1 (Smoke): Add field to compilation test
        ├─ Tier 2 (Integration): Add field to serialization test
        ├─ Tier 3 (Network): Update load test fixtures
        └─ Tier 4 (Transmutation): Regenerate full test suite

    3. Notify Players:
        ├─ In-app notification: 'User domain updated!'
        ├─ Email: 'New challenges in User domain'
        └─ Leaderboard update: 'User domain refreshed - 0 points carried over'

    4. Reset Progress:
        ├─ User tier 1-3 quests: Reset to available
        ├─ User tier 4 quest: Mark as needs-retry
        └─ Achievement tracking: Track "upgrader" achievement

    5. Database Updates:
        ├─ quest_definitions: Update test specs
        ├─ quest_instances: Reset user progress
        ├─ domain_checksums: Update hash
        └─ quest_history: Log change event

4. DOMAIN COVERAGE MATRIX

4.1 Current Domains (8 Total)

DomainEventsComplexityTierStatus
user41.0Apprentice✓ Ready
document61.8Journeyman✓ Ready
collaboration52.0Master✓ Ready
workspace41.3Journeyman✓ Ready
aria (AI)31.5Journeyman✓ Ready
notification51.2Apprentice✓ Ready
audit41.1Apprentice✓ Ready
envelope20.9Apprentice✓ Ready
Total Quests Available:
8 domains × 4 tiers = 32 unique quests
+ Cross-domain quests (collaboration)
+ Rituals (recurring)
─────────────────────────────────
~50 total challenging experiences

4.2 Quest Discovery Roadmap

Current State (Month 1):
  ├─ 32 domain-specific quests
  ├─ 8 single-domain rituals
  └─ 0 cross-domain quests

Enhancement (Month 2):
  ├─ Cross-domain quests:
  │   ├─ "Document Collaboration Tango" (document × collaboration)
  │   ├─ "Workspace Guardian" (workspace × audit)
  │   └─ "Notification Storm" (notification × envelope)
  ├─ Multi-tier rituals (weekly)
  └─ +15 quests total

Expansion (Month 3+):
  ├─ Custom domain support (enterprise)
  ├─ Community-contributed quests
  ├─ AI-generated quests (Pro+)
  └─ Potentially 100+ quests

5. QUALITY ASSURANCE

5.1 Quest Validation Pipeline

Every auto-generated quest goes through validation:
Step 1: Schema Parsing
  ├─ Parse proto file
  ├─ Extract messages
  ├─ Validate syntax
  └─ Assert: No errors

Step 2: Test Generation
  ├─ Create compilation test
  ├─ Create import test
  ├─ Create serialization test
  ├─ Create load test
  └─ Assert: All tests run locally

Step 3: Local Test Run
  ├─ Spin up test environment
  ├─ Run quest in isolation
  ├─ Measure timing
  ├─ Calculate expected XP
  └─ Assert: Timing is reasonable

Step 4: Integration Test
  ├─ Cross-domain imports
  ├─ Dependency validation
  ├─ Event ordering
  └─ Assert: No conflicts

Step 5: Human Review (First 10)
  ├─ QA engineer plays quest
  ├─ Verifies difficulty rating
  ├─ Checks XP balance
  ├─ Reviews narrative
  └─ Assert: Quality standards met

Step 6: Community Beta (Pro users)
  ├─ Release as "Beta" quest
  ├─ Collect feedback
  ├─ Monitor completion rate
  ├─ Adjust difficulty if needed
  └─ Assert: Community approval

Step 7: Launch
  ├─ Mark quest as "Live"
  ├─ Announce in-app
  ├─ Add to leaderboards
  └─ Enable achievements

5.2 Quality Metrics

Quest Quality Scorecard:
quest_quality:
    difficulty_accuracy:
        target: '±10% of estimated duration'
        measurement: 'avg_actual_time / estimated_time'
        threshold: 0.9-1.1

    completion_rate:
        target: '60-80% attempt-to-completion'
        measurement: 'completed / attempted'
        threshold: '> 60%'
        comment: 'Too easy if > 90%, too hard if < 40%'

    player_satisfaction:
        target: '4.0+ / 5.0 stars'
        measurement: 'optional player rating after quest'
        threshold: '> 4.0'

    pass_rate:
        target: '95%+ of players pass on attempt'
        measurement: 'success / total_attempts'
        threshold: '> 90%'
        comment: 'Very hard quests (tier 3-4) may be 70-80%'

6. SCALABILITY CONSIDERATIONS

6.1 Handling Large Domain Models

For domains with 20+ events (edge case):
Challenge: Too many generated quests (5+ per tier)
Solution: Grouping by subdomain

Example: (Hypothetical) "Order Management" domain
  ├─ 8 events: Order lifecycle
  ├─ 7 events: Payment processing
  ├─ 6 events: Fulfillment
  └─ 5 events: Returns/Refunds

Instead of: 4 quests × 26 messages = 104 tests
Generate: 4 quest groups × 4 sub-domains = 16 quests

Tier 1: "Master Orders" (order lifecycle)
Tier 1: "Master Payments" (payment sub-domain)
Tier 2: "Fulfillment Flow"
Tier 3: "Returns & Edge Cases"
Tier 4: "Order System Mastery"

6.2 Performance Optimization

Caching and checksums:
Domain Checksum = SHA256(proto_file_content + dependencies)

Cache:
  ├─ Store checksums of all domains
  ├─ On manifest scan: compare checksums
  ├─ If unchanged: use cached quest definitions
  ├─ If changed: regenerate affected quests only
  └─ Reduces scan time from 30s → 5s (for unchanged domains)

Example:
  ├─ Scan user domain: checksum matches cache → skip
  ├─ Scan document domain: checksum changed → regenerate
  └─ Scan 6 others: all match cache → skip
  └─ Total time: 2 seconds (vs 30 without cache)

7. IMPLEMENTATION PLAN

Phase 1: Foundation (Weeks 1-2)

  • Domain scanner (parse protos)
  • Metadata extractor
  • Quest template generator
  • Basic Manuscript integration

Phase 2: Validation (Weeks 3-4)

  • Quest validation pipeline
  • Local test runner
  • Quality metrics
  • Scribe webhook integration

Phase 3: Automation (Weeks 5-6)

  • Change detection
  • Automated quest updates
  • Player notifications
  • Caching system

Phase 4: Scale (Weeks 7+)

  • Performance optimization
  • Multi-domain quests
  • Community quest support
  • AI quest generation (Pro+)

8. API CONTRACTS

8.1 Domain Scanner API

// Get all discovered domains
GET /api/domains
Response:
  {
    "domains": [
      {
        "name": "User",
        "package": "materi.v1.user",
        "events": 4,
        "complexity": 1.0,
        "quests": ["quest_user_smoke_v1", "quest_user_integration_v1", ...]
      },
      ...
    ]
  }

// Get specific domain
GET /api/domains/{domain_name}
Response:
  {
    "name": "User",
    "description": "User identity and profile management",
    "proto_file": "user/v1.proto",
    "events": [...],
    "dependencies": ["shared"],
    "quests": [...],
    "last_updated": "2025-12-16T10:30:00Z"
  }

// Sync with Manuscript
POST /api/domains/sync
Body: { "force_refresh": false }
Response:
  {
    "status": "synced",
    "domains_scanned": 8,
    "quests_generated": 32,
    "changes_detected": 2,
    "timestamp": "2025-12-16T10:30:00Z"
  }

8.2 Quest Generation API

// Get quest for domain
GET /api/quests/domain/{domain_name}/{tier}
Response:
  {
    "id": "quest_user_integration_v1",
    "name": "User Domain Integration",
    "tier": 2,
    "difficulty": "medium",
    "estimated_duration": "20m",
    "xp_reward": 375,
    "tests": [...],
    "description": "..."
  }

// Regenerate quests for domain
POST /api/quests/domain/{domain_name}/regenerate
Response:
  {
    "status": "regenerated",
    "quests_updated": 4,
    "affected_players": 150,
    "notifications_sent": true
  }

9. FUTURE ENHANCEMENTS

Post-MVP:
1. AI Quest Generation (Pro+)
   └─ Use domain complexity to generate novel tests

2. Custom Domains (Enterprise)
   └─ Allow enterprise customers to add their own proto files

3. Cross-Domain Quests (Community)
   └─ Multi-domain storylines

4. Community Quest Contributions
   └─ Players create quests for domains

5. Domain Lore (Tie to Narrative)
   └─ Each domain gets a "smithing legend"
   └─ Lore fragments unlock as quests complete

Document Status: Ready for Technical Design Review Next Step: Domain Scanner Implementation (Weeks 1-2)