> ## Documentation Index
> Fetch the complete documentation index at: https://village-docs.villagelabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# System Overview

> An overview of our enterprise-grade ESOP financial modeling architecture.

## System Philosophy

At Village Labs, we designed the Repurchase Engine for **transparency, fidelity, and scalability**. Our architecture separates the core simulation logic from data intake and reporting, allowing for maximum flexibility. This modular design is a key principle of our **Village Operating System**, ensuring that each component is specialized and highly effective.

<Info>
  The architecture is grounded in the legal and financial first principles of ESOPs. This ensures that the outputs from our engine are not only predictive but also robust, auditable, and defensible.
</Info>

## Core Capability

The engine's core capability is to **process a company's census data and financial state through a discrete, step-by-step annual simulation cycle**, producing a detailed year-over-year forecast of all ESOP activities.

<Frame>
  ```mermaid theme={null}
  graph LR
    A[Input Data] --> B[Simulation Engine]
    B --> C[Year 1 Processing]
    C --> D[Year 2 Processing]
    D --> E[...]
    E --> F[Year N Processing]
    F --> G[Complete Forecast]
    
    style B fill:#29371F,color:#fff
    style G fill:#3D5030,color:#fff
  ```
</Frame>

## System Architecture

<CardGroup cols={2}>
  <Card title="Simulation Core" icon="gears" href="/architecture/simulation-core">
    Discrete annual processing pipeline
  </Card>

  <Card title="Data Layer" icon="database" href="/architecture/data-layer">
    Immutable, versioned system of record
  </Card>

  <Card title="Design Principles" icon="compass" href="/architecture/design-principles">
    Foundational architectural concepts
  </Card>

  <Card title="Input Framework" icon="file-import">
    PlanRules, OperatingAssumptions, and more
  </Card>
</CardGroup>

## High-Level Flow

<Steps>
  <Step title="Input Configuration">
    Provide four structured inputs:

    * **PlanRules**: Legal framework
    * **OperatingAssumptions**: Annual strategy
    * **InitialState**: Current ESOP state
    * **SystemConfiguration**: Simulation settings
  </Step>

  <Step title="Annual Processing Cycle">
    For each projection year, execute ordered processing steps:

    * Turnover projection
    * Share pool calculation
    * Contribution determination
    * Diversification processing
    * Repurchase events
  </Step>

  <Step title="State Capture">
    Record complete snapshots:

    * Company financial state
    * Trust cash and shares
    * Individual participant accounts
    * All transactions and events
  </Step>

  <Step title="Output Generation">
    Generate comprehensive results:

    * Annual projections
    * Repurchase obligations
    * Cash flow analysis
    * Participant snapshots
  </Step>
</Steps>

## Key Components

### 1. Simulation Core

The heart of the system is a **discrete, step-by-step annual processing pipeline**. For each year of a projection, the engine executes a sequence of modules, each responsible for a specific aspect of ESOP administration.

```python theme={null}
# Conceptual annual processing flow
for year in range(start_year, end_year):
    # Step 0: Project employee turnover (optional)
    turnover_events = project_turnover(participants, year)
    
    # Step 1: Initialize year - calculate share price
    share_price = calculate_share_price(company_equity, outstanding_shares)
    
    # Step 2: Determine share pool for allocation
    share_pool = calculate_share_pool(esop_loans, contributions)
    
    # Step 3: Allocate shares to participants
    allocations = allocate_shares(share_pool, eligible_participants)
    
    # Step 4: Calculate company contribution
    contribution = determine_contribution(policy, financial_state)
    
    # Step 5: Update vesting status
    vesting_updates = update_vesting(participants, vesting_schedule)
    
    # Step 6: Process diversification elections
    diversifications = process_diversifications(eligible_participants)
    
    # Step 7: Process repurchase events
    repurchases = process_repurchases(terminated_participants, funding_waterfall)
    
    # Step 8: Year-end closing - roll forward and evolve
    year_end_closing(participants, company_state, trust_state)
    
    # Capture year-end state
    save_annual_snapshot(year, company_state, trust_state, participants)
```

<Note>
  **Critical Design Choice:** This strict order of operations ensures that legal obligations are met before discretionary actions are taken.
</Note>

### 2. Data Layer

All inputs and outputs are managed in a **versioned, relational database** that serves as the immutable system of record for all modeling activities.

<Tabs>
  <Tab title="Input Tables">
    * `Scenarios`: Versioned scenario configurations
    * `Censuses`: Versioned participant data
    * `PlanRules`: Legal framework definitions
    * `OperatingAssumptions`: Annual strategy settings
  </Tab>

  <Tab title="Processing Tables">
    * `SimulationRuns`: Execution metadata
    * `ProcessingLogs`: Step-by-step audit trail
    * `Events`: All modeled transactions
  </Tab>

  <Tab title="Output Tables">
    * `AnnualCompanyStates`: Company financials per year
    * `AnnualTrustStates`: Trust assets per year
    * `AnnualParticipantSnapshots`: Individual accounts per year
  </Tab>
</Tabs>

### 3. Input Framework

The engine requires structured input organized into four distinct categories:

<CardGroup cols={2}>
  <Card title="PlanRules" icon="scale-balanced">
    **The "Constitution"**

    Stable legal framework:

    * Vesting schedule
    * Distribution policy
    * Cash usage policy
    * Diversification rules
  </Card>

  <Card title="OperatingAssumptions" icon="chart-mixed">
    **The "Annual Strategy"**

    Variable financial decisions:

    * Contribution amounts
    * Repurchase strategy
    * Share valuations
    * Growth projections
  </Card>

  <Card title="InitialState" icon="flag">
    **Starting Point**

    Current ESOP status:

    * Participant census
    * Trust cash balances
    * ESOP loan details
    * Share allocations
  </Card>

  <Card title="SystemConfiguration" icon="gears">
    **Simulation Settings**

    Runtime parameters:

    * Projection years
    * Turnover models
    * Sensitivity analysis
    * Output preferences
  </Card>
</CardGroup>

## Processing Pipeline

The annual simulation cycle executes a precise sequence of operations:

```mermaid theme={null}
graph TD
    A[Start Year N] --> B[Step 0: Turnover Projection]
    B --> C[Step 1: Initialization]
    C --> D[Step 2: Determine Share Pool]
    D --> E[Step 3: Allocate Shares]
    E --> F[Step 4: Calculate Contribution]
    F --> G[Step 5: Update Vesting]
    G --> H[Step 6: Process Diversification]
    H --> I[Step 7: Process Repurchases]
    I --> J[Step 8: Year-End Closing]
    J --> K[Capture Year-End State]
    K --> L[End Year N]
    
    style A fill:#29371F,color:#fff
    style L fill:#29371F,color:#fff
```

<Warning>
  The order of operations is **legally significant**. For example, vesting must be updated before repurchases are processed to determine what employees are entitled to receive.
</Warning>

## Data Flow Architecture

```
┌─────────────────────────────────────────────────────────┐
│ Input Layer                                             │
│ ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  │
│ │  PlanRules   │  │ Operating    │  │ InitialState │  │
│ │              │  │ Assumptions  │  │              │  │
│ └──────────────┘  └──────────────┘  └──────────────┘  │
└────────────────────────┬────────────────────────────────┘
                         │
                         ↓
┌─────────────────────────────────────────────────────────┐
│ Simulation Engine                                       │
│ ┌──────────────────────────────────────────────────┐   │
│ │  Annual Processing Pipeline                      │   │
│ │  → Turnover → Share Pool → Contributions →       │   │
│ │  → Diversification → Repurchases                 │   │
│ └──────────────────────────────────────────────────┘   │
└────────────────────────┬────────────────────────────────┘
                         │
                         ↓
┌─────────────────────────────────────────────────────────┐
│ Data Layer (Immutable Database)                         │
│ ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  │
│ │ Company      │  │ Trust        │  │ Participant  │  │
│ │ Snapshots    │  │ Snapshots    │  │ Snapshots    │  │
│ └──────────────┘  └──────────────┘  └──────────────┘  │
└────────────────────────┬────────────────────────────────┘
                         │
                         ↓
┌─────────────────────────────────────────────────────────┐
│ Output Layer                                            │
│ ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  │
│ │ Forecast     │  │ Analytics    │  │ Exports      │  │
│ │ Results      │  │ & Insights   │  │ & Reports    │  │
│ └──────────────┘  └──────────────┘  └──────────────┘  │
└─────────────────────────────────────────────────────────┘
```

## Key Architectural Features

<AccordionGroup>
  <Accordion title="Loan-by-Loan Share Release" icon="link">
    Leveraged ESOPs with multiple debt tranches are modeled with precision. Each `ESOPLoan` object owns its specific suspense shares, and the engine iterates through each loan independently to calculate share releases.

    **Why It Matters:** Prevents cross-contamination of suspense accounts and ensures accurate modeling of complex debt structures.
  </Accordion>

  <Accordion title="Funding Waterfall" icon="water">
    The repurchase processing module implements a strict, rules-based sequence for drawing funds from the trust's cash accounts, following the `PlanRules.cash_usage_policy`.

    **Why It Matters:** Ensures legal compliance and prevents improper use of restricted cash sources (e.g., forfeitures).
  </Accordion>

  <Accordion title="Temporal State Management" icon="clock">
    Every simulation run creates a complete, timestamped snapshot of all system state. Nothing is ever overwritten.

    **Why It Matters:** Perfect reproducibility and the ability to perform temporal analysis (e.g., "How did our June forecast compare to September?").
  </Accordion>

  <Accordion title="Agent-Ready Toolkit" icon="robot">
    The engine exposes high-level user intent functions designed for AI agent integration.

    **Why It Matters:** Stable API for conversational interfaces, allowing internal refactoring without breaking agent capabilities.
  </Accordion>
</AccordionGroup>

## Performance Characteristics

<CardGroup cols={3}>
  <Card title="Speed" icon="gauge-high">
    20-year projection: **\< 2 seconds**

    100-participant census
  </Card>

  <Card title="Scale" icon="chart-line">
    Tested up to **10,000 participants**

    50-year projections
  </Card>

  <Card title="Accuracy" icon="bullseye">
    **Deterministic** results

    Bit-for-bit reproducible
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Design Principles" icon="compass" href="/architecture/design-principles">
    Understand the foundational concepts
  </Card>

  <Card title="Simulation Core" icon="gears" href="/architecture/simulation-core">
    Dive into the processing pipeline
  </Card>

  <Card title="Data Layer" icon="database" href="/architecture/data-layer">
    Explore the database structure
  </Card>

  <Card title="Data Models" icon="shapes" href="/models/overview">
    Learn the core data structures
  </Card>
</CardGroup>
