> ## 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.

# Step 7: Process Repurchases

> Execute share repurchases, distribution schedules, and regulatory compliance

## Overview

Step 7 is the **most complex step** in the ESOP projection engine, handling the full lifecycle of repurchase obligations from termination through final distribution.

<Warning>
  This step processes **9 distinct phases** including QDRO processing, distribution schedules, RMD enforcement, and multi-strategy repurchase execution.
</Warning>

## Why This Matters

When employees terminate, the ESOP must:

1. Calculate what they're owed (vested shares + cash)
2. Create a payment schedule (deferred installments or lump sum)
3. Execute repurchases using available cash
4. Apply the company's chosen repurchase strategy

This step determines the **cash flow impact** on the company and trust.

***

## Processing Phases

Step 7 executes in strict sequential order:

<Steps>
  <Step title="Phase 1: QDRO Processing">
    Handle divorce settlements and court orders
  </Step>

  <Step title="Phase 2: Forfeiture Recording">
    Track non-vested share and cash forfeitures
  </Step>

  <Step title="Phase 3: Distribution Schedule Creation">
    Build payment timelines for new terminations
  </Step>

  <Step title="Phase 4: RMD Enforcement">
    Force distributions for participants age 73+
  </Step>

  <Step title="Phase 5: Execute Due Payments">
    Process scheduled distributions for current year
  </Step>

  <Step title="Phase 6: Distribution Form Conversion">
    Convert stock to cash if required by plan rules
  </Step>

  <Step title="Phase 7: (Deprecated) Segregation Policy">
    Removed in v0.3 to focus on core ESOP mechanics
  </Step>

  <Step title="Phase 8: Execute Repurchase Strategy">
    Apply recycle/redeem/releverage strategy
  </Step>

  <Step title="Phase 9: Funding Reconciliation">
    Reconcile TrustCashLedger draws and balances
  </Step>
</Steps>

***

## Detailed Phase Breakdown

### Phase 1: QDRO Processing

**QDRO** = Qualified Domestic Relations Order (divorce/separation settlements)

<AccordionGroup>
  <Accordion title="What Happens" icon="gavel">
    When a divorce decree requires splitting an ESOP account:

    1. **Apply Split Percentage** (typically 50%)
    2. **Respect Vesting** - Only vested amounts are split
    3. **Pro-Rata Across Securities** - In multi-class mode, split proportionally
    4. **Reduce Participant Balance** - Deduct from employee account
    5. **Create Immediate Repurchase** - Alternate payee is paid immediately
    6. **Mark as Processed** - Prevent reprocessing in future years

    ```python theme={null}
    # Example QDRO processing
    for employee in active_employees:
        if employee.qdro_orders:
            for order in employee.qdro_orders:
                if not order.processed_this_year:
                    # Determine vesting
                    vesting_pct = vesting_schedule[employee.service_years]
                    
                    # Apply split (e.g., 50%)
                    split_pct = order.percent  # 0.50 for 50%
                    
                    # For each security holding
                    for security_id, holding in employee.holdings:
                        vested_shares = holding.shares * vesting_pct
                        split_shares = vested_shares * split_pct
                        
                        # Reduce employee, add to repurchase
                        holding.shares -= split_shares
                        repurchase_queue[security_id] += split_shares
                    
                    # Mark processed
                    order.processed_year = current_year
    ```
  </Accordion>

  <Accordion title="Multi-Class Behavior" icon="shapes">
    In multi-class mode, QDROs split proportionally across all securities:

    **Example:**

    * Employee holds: 100 Class A shares, 200 Class B shares
    * Vesting: 80%
    * QDRO: 50% split

    **Calculation:**

    * Class A vested: 100 \* 0.80 = 80 shares
    * Class A split: 80 \* 0.50 = 40 shares → to alternate payee
    * Class B vested: 200 \* 0.80 = 160 shares
    * Class B split: 160 \* 0.50 = 80 shares → to alternate payee
  </Accordion>

  <Accordion title="Compliance Logging" icon="file-lines">
    Every QDRO generates compliance events:

    ```json theme={null}
    {
      "event": "qdro_processed",
      "employee_id": "EMP042",
      "percent": 0.50,
      "shares_by_security": {
        "CLASS_A": 40.0,
        "CLASS_B": 80.0
      },
      "cash_paid": 2500.00
    }
    ```
  </Accordion>
</AccordionGroup>

***

### Phase 2: Forfeiture Recording

When participants terminate **before fully vested**, non-vested amounts are forfeited.

<Tabs>
  <Tab title="Forfeiture Policies">
    **Two policy options:**

    1. **`reallocate_next_year`** (Most Common)
       * Add forfeitures to next year's share pool
       * Used to fund next year's allocations
       * Reduces company cash contribution need

    2. **`reallocate_on_payout`** (Less Common)
       * Hold forfeitures until employee fully paid out
       * Then reallocate to remaining participants
       * Used when plan wants to delay forfeiture recognition

    ```python theme={null}
    if forfeiture_policy == "reallocate_next_year":
        carry_over_state.forfeited_shares_for_next_year += forfeited_amount
        carry_over_state.forfeited_cash_for_next_year += forfeited_cash

    elif forfeiture_policy == "reallocate_on_payout":
        carry_over_state.forfeited_shares_from_payout[employee_id] = forfeited_amount
        carry_over_state.forfeited_cash_from_payout[employee_id] = forfeited_cash
    ```
  </Tab>

  <Tab title="Calculation Example">
    **Scenario:**

    * Employee termination: Service years = 1.0
    * Vesting schedule: Year 1 = 20%, Year 5 = 100%
    * Employee has: 1,000 allocated shares, \$5,000 cash

    **Vesting:**

    * Vested: 1,000 × 20% = 200 shares, \$1,000 cash
    * Forfeited: 1,000 × 80% = 800 shares, \$4,000 cash

    **If `reallocate_next_year`:**

    ```
    carry_over_state.forfeited_shares_for_next_year += 800
    carry_over_state.forfeited_cash_for_next_year += 4000
    ```

    In Step 2 of next year, these 800 shares will be added to the share pool for allocation.
  </Tab>

  <Tab title="Cash Forfeitures">
    <Info>
      **New in v0.2:** Cash forfeitures mirror share forfeiture policy.
    </Info>

    Participants may have cash balances from:

    * Previous diversification elections
    * Cash contributions from the company
    * Dividends or interest

    **Non-vested cash is forfeited using the same policy:**

    * `reallocate_next_year`: Cash added to next year's contribution
    * `reallocate_on_payout`: Cash held until final payout
  </Tab>
</Tabs>

***

### Phase 3: Distribution Schedule Creation

When an employee terminates, the engine creates a **multi-year payment schedule**.

<Tabs>
  <Tab title="Schedule Parameters">
    From `DistributionRule` matched to termination trigger:

    ```python theme={null}
    {
      "trigger": "retirement",           # or "death", "disability", "termination"
      "payment_years": 5,                # Installment period
      "defer_years": 1,                  # Wait period before first payment
      "lump_sum_threshold": 5000,        # Force lump sum if account < this
      "installment_frequency": "annual", # or "quarterly", "monthly"
      "distribution_form": "cash"        # or "stock", "stock_with_mandatory_put"
    }
    ```
  </Tab>

  <Tab title="Timing Rules">
    **Regulatory Timing Caps:**

    | Termination Type    | Max Deferral | IRS Rule        |
    | ------------------- | ------------ | --------------- |
    | Retirement          | 1 year       | IRC §409(o)     |
    | Death               | 1 year       | IRC §409(o)     |
    | Disability          | 1 year       | IRC §409(o)     |
    | Other Termination   | 5 years      | IRC §409(o)     |
    | Age 65+ & 10+ years | 1 year       | IRC §401(a)(14) |

    **Leveraged ESOP Deferral (Optional):**

    * IF policy enabled AND loan outstanding
    * THEN defer start\_year to loan maturity
    * Protects company cash flow during debt service

    ```python theme={null}
    if leveraged_deferral_enabled:
        latest_loan_maturity = max(loan.maturity_year for loan in loans)
        if latest_loan_maturity > start_year:
            start_year = latest_loan_maturity  # Push out payment
    ```
  </Tab>

  <Tab title="Special Cases">
    **Small Balance Cashout:**

    * If vested value ≤ lump\_sum\_threshold (e.g., \$5,000)
    * Force immediate lump sum payment
    * Reduces administrative burden

    ```python theme={null}
    vested_value = (vested_shares * share_price) + vested_cash
    if vested_value <= lump_sum_threshold:
        payment_years = 1
        defer_years = 0
        start_year = current_year  # Immediate
    ```

    **Large Balance Extension:**

    * If vested value > large\_balance\_threshold (e.g., \$1M)
    * Add extra installment years
    * Each increment adds 1 year (up to max)

    ```python theme={null}
    if vested_value > large_balance_threshold:
        increments = (vested_value - threshold) // increment
        payment_years = min(payment_years + increments, max_installment_years)
    ```
  </Tab>

  <Tab title="Example Schedule">
    **Scenario:** Retirement in 2025, \$250,000 vested value

    ```json theme={null}
    {
      "trigger": "retirement",
      "start_year": 2026,               // Year after termination (1-year defer)
      "years_total": 5,                 // 5 annual payments
      "years_paid": 0,                  // None paid yet
      "annual_shares": 100,             // 100 shares/year
      "annual_cash": 10000,             // $10K cash/year
      "remaining_shares": 500,          // Total to pay
      "remaining_cash": 50000,          // Total to pay
      "installment_frequency": "annual"
    }
    ```

    **Payment Timeline:**

    * 2026: 100 shares + \$10K
    * 2027: 100 shares + \$10K
    * 2028: 100 shares + \$10K
    * 2029: 100 shares + \$10K
    * 2030: 100 shares + \$10K
  </Tab>
</Tabs>

***

### Phase 4: RMD Enforcement

**RMD** = Required Minimum Distribution (IRS tax rule)

<Warning>
  Participants **age 73+** must begin receiving distributions, regardless of employment status or deferral preferences.
</Warning>

<Tabs>
  <Tab title="How It Works">
    ```python theme={null}
    RMD_AGE = 73  # As of 2025 (was 72 pre-SECURE Act 2.0)

    for employee in active_employees:
        if employee.age >= RMD_AGE:
            # Check if already has active schedule
            has_due_schedule = any(
                sched for sched in employee.pending_distributions
                if sched.start_year <= current_year
            )
            
            # If no schedule and has balance, force immediate distribution
            if not has_due_schedule and (employee.vested_shares > 0 or employee.vested_cash > 0):
                # Create immediate schedule
                employee.pending_distributions.append({
                    "trigger": "rmd",
                    "start_year": current_year,  # Immediate
                    "years_total": 1,
                    "annual_shares": employee.vested_shares,
                    "annual_cash": employee.vested_cash,
                    "remaining_shares": employee.vested_shares,
                    "remaining_cash": employee.vested_cash
                })
    ```
  </Tab>

  <Tab title="RMD Scenarios">
    **Scenario 1: Active Employee, Age 73**

    * Still working, no termination
    * RMD forces distribution of vested balance
    * Employee remains active, continues accruing

    **Scenario 2: Terminated with Deferred Schedule**

    * Terminated at age 65, distribution deferred to 2028
    * Reaches age 73 in 2026
    * RMD **overrides** deferral, forces payment in 2026

    **Scenario 3: Already Receiving Distributions**

    * RMD check passes (already compliant)
    * No additional action needed
  </Tab>

  <Tab title="Compliance Logging">
    ```json theme={null}
    {
      "event": "rmd_schedule_created",
      "employee_id": "EMP105",
      "age": 73,
      "start_year": 2025,
      "reason": "Regulatory requirement - age 73 reached"
    }
    ```
  </Tab>
</Tabs>

***

### Phase 5: Execute Due Payments

Process all distribution schedules where `current_year >= start_year`.

<Tabs>
  <Tab title="Payment Calculation">
    ```python theme={null}
    for employee in active_employees:
        for schedule in employee.pending_distributions:
            # Check if payment due
            if current_year >= schedule.start_year or employee.age >= RMD_AGE:
                if schedule.years_paid < schedule.years_total:
                    # Calculate this year's payment
                    payment_shares = min(
                        schedule.annual_shares, 
                        schedule.remaining_shares
                    )
                    payment_cash = min(
                        schedule.annual_cash, 
                        schedule.remaining_cash
                    )
                    
                    # Update schedule
                    schedule.remaining_shares -= payment_shares
                    schedule.remaining_cash -= payment_cash
                    schedule.years_paid += 1
                    
                    # Add to repurchase queue
                    total_shares_to_repurchase += payment_shares
                    total_payment_value += (payment_shares * share_price) + payment_cash
    ```
  </Tab>

  <Tab title="Multi-Class Distribution">
    In multi-class mode, payments are distributed **pro-rata across securities**:

    **Example:**

    * Employee holds: 80 Class A, 120 Class B (total 200 shares)
    * Payment due: 50 shares

    **Pro-Rata Calculation:**

    * Class A weight: 80 / 200 = 40%
    * Class B weight: 120 / 200 = 60%

    **Distribution:**

    * Class A: 50 × 40% = 20 shares
    * Class B: 50 × 60% = 30 shares

    ```python theme={null}
    total_shares = sum(holding.shares for holding in employee.holdings)
    for security_id, holding in employee.holdings.items():
        weight = holding.shares / total_shares
        quantity = payment_shares * weight
        quantity = round(quantity, 4)  # Precision rounding
        
        # Deduct from employee, add to repurchase
        holding.shares -= quantity
        repurchase_by_security[security_id] += quantity
    ```
  </Tab>

  <Tab title="TrustCashLedger Draws">
    Cash payments are funded via the Funding Waterfall using the `TrustCashLedger`:

    ```python theme={null}
    if payment_cash > 0:
        result = trust.cash_ledger.draw_cash(
            amount=payment_cash,
            sources=plan_rules.cash_usage_policy
        )
        # result.transactions lists per-source draws; result.shortfall if any
    ```

    <Note>
      See [TrustCashLedger](/models/trust-cash-ledger) for ledger structure and draw behavior.
    </Note>
  </Tab>
</Tabs>

***

### Phase 6: Distribution Form Conversion

If the plan requires **cash-only distributions**, convert remaining stock to cash.

<Tabs>
  <Tab title="Distribution Forms">
    Three options per plan rules:

    1. **`stock`** - Distribute shares as shares
    2. **`cash`** - Convert all shares to cash at current price
    3. **`stock_with_mandatory_put`** - Distribute shares with put option (treated as cash in modeling)

    ```python theme={null}
    distribution_rule = get_distribution_rule(employee.termination_reason)

    if distribution_rule.distribution_form == "cash":
        if employee.remaining_payout_shares > 0:
            # Convert shares to cash value
            cash_value = employee.remaining_payout_shares * current_share_price
            
            # Update employee account
            employee.remaining_payout_cash += cash_value
            employee.remaining_payout_shares = 0
            
            # Add shares to repurchase queue
            total_shares_to_repurchase += employee.remaining_payout_shares
    ```
  </Tab>

  <Tab title="Multi-Class Conversion">
    In multi-class mode, convert each security holding:

    ```python theme={null}
    for security_id, holding in employee.holdings.items():
        security_price = securities[security_id].current_share_price
        cash_value = holding.shares * security_price
        
        employee.vested_cash += cash_value
        repurchase_by_security[security_id] += holding.shares
        holding.shares = 0  # Fully converted
    ```
  </Tab>
</Tabs>

***

### Phase 7: (Deprecated) Segregation Policy

<Info>
  Segregation is removed in v0.3 to focus on core, high-fidelity ESOP mechanics. The model no longer documents or enforces `segregation_policy`.
</Info>

***

### Phase 8: Execute Repurchase Strategy

The company's **strategic choice** for handling repurchased shares.

<Tabs>
  <Tab title="Three Strategies">
    <CardGroup cols={3}>
      <Card title="Recycle" icon="recycle">
        **Keep shares in the plan**

        * Add to next year's allocation pool
        * Shares remain outstanding
        * Use OIA cash if available
        * Most cash-efficient
      </Card>

      <Card title="Redeem" icon="trash">
        **Retire shares permanently**

        * Reduce outstanding shares
        * Increases ownership % for remaining participants
        * Shares cannot be reissued
      </Card>

      <Card title="Releverage" icon="hand-holding-dollar">
        **Create new ESOP loan**

        * Borrow to fund repurchase
        * Default term: 10 years
        * Shares held in suspense
        * Released as loan paid down
      </Card>
    </CardGroup>
  </Tab>

  <Tab title="Strategy Configuration">
    **Single Strategy per Year:**

    ```python theme={null}
    repurchase_strategy = {
        2025: "recycle",
        2026: "redeem",
        2027: "releverage"
    }
    ```

    **Weighted Combination:**

    ```python theme={null}
    repurchase_strategy = {
        2025: {
            "recycle": 0.60,    # 60% recycled
            "redeem": 0.30,     # 30% redeemed
            "releverage": 0.10  # 10% refinanced
        }
    }
    ```

    Weights are normalized if they don't sum to 1.0.
  </Tab>

  <Tab title="Execution Logic">
    **For Weighted Strategy:**

    ```python theme={null}
    if isinstance(strategy, dict):
        # Normalize weights
        total_weight = sum(strategy.values())
        weights = {k: v / total_weight for k, v in strategy.items()}
        
        # Apply each strategy
        for strategy_name, weight in weights.items():
            quantity = total_shares_to_repurchase * weight
            
            if strategy_name == "recycle":
                carry_over_state.recycled_shares += quantity
                # Funding is handled via TrustCashLedger waterfall
            
            elif strategy_name == "redeem":
                company_state.total_outstanding_shares -= quantity
            
            elif strategy_name == "releverage":
                loan_amount = quantity * share_price
                new_loan = ESOPLoan(
                    loan_id=f"LOAN_{current_year}",
                    original_amount=loan_amount,
                    remaining_balance=loan_amount,
                    annual_payment=loan_amount / 10,  # 10-year term
                    shares_released_per_payment=quantity / 10,
                    maturity_year=current_year + 10
                )
                company_state.loans.append(new_loan)
    ```
  </Tab>

  <Tab title="Multi-Class Execution">
    In multi-class mode, strategy is applied **per security**:

    ```python theme={null}
    # Example: 60% recycle, 40% redeem
    for security_id, shares_to_repurchase in repurchase_by_security.items():
        # Recycle 60%
        recycle_qty = shares_to_repurchase * 0.60
        carry_over_state.recycled_shares_by_security[security_id] += recycle_qty
        
        # Redeem 40%
        redeem_qty = shares_to_repurchase * 0.40
        securities[security_id].total_outstanding_shares -= redeem_qty
    ```

    Each security maintains its own:

    * Outstanding share count
    * Recycled share pool
    * Releverage loans (tagged to security)
  </Tab>

  <Tab title="Example Scenarios">
    **Scenario 1: Pure Recycle**

    * Shares to repurchase: 1,000
    * Strategy: `"recycle"`
    * Result: 1,000 shares added to next year's pool
    * Outstanding shares: No change

    **Scenario 2: Pure Redeem**

    * Shares to repurchase: 1,000
    * Strategy: `"redeem"`
    * Result: Total outstanding shares reduced by 1,000
    * Remaining participants' ownership % increases

    **Scenario 3: Weighted Mix**

    * Shares to repurchase: 1,000
    * Strategy: `{"recycle": 0.7, "redeem": 0.3}`
    * Result: 700 shares recycled, 300 shares redeemed
  </Tab>
</Tabs>

***

### Phase 9: Funding Reconciliation

Final accounting for the year's cash flows.

<Tabs>
  <Tab title="Ledger Reconciliation">
    Reconcile TrustCashLedger movements for the year (no investment earnings in v0.3):

    ```python theme={null}
    ledger_summary = {
        "boy": trust.cash_ledger_snapshot_boy,
        "draws": result.transactions,  # from distributions and repurchases
        "deposits": company_contributions,
        "transfers": internal_transfers,
        "eoy": trust.cash_ledger_snapshot_eoy
    }
    ```
  </Tab>

  <Tab title="Loan Payment Reconciliation">
    Aggregate all loan payments made during the year:

    ```python theme={null}
    # Scan compliance events for loan payments
    principal_paid = 0
    interest_paid = 0

    for event in compliance_log:
        if event.event == "loan_payment_made" and event.year == current_year:
            principal_paid += event.outputs["principal"]
            interest_paid += event.outputs["interest"]

    # Track OIA usage
    total_debt_service = principal_paid + interest_paid
    carry_over_state.oia_uses_loan_payments += total_debt_service

    # Deduct from OIA if available
    if oia_balance >= total_debt_service:
        oia_balance -= total_debt_service
    ```
  </Tab>

  <Tab title="Funding Summary Event">
    At the end of Step 7, emit comprehensive funding summary:

    ```json theme={null}
    {
      "phase": "repurchase",
      "event": "repurchase_funding_summary",
      "inputs": {
        "shares_to_repurchase": 850.0,
        "payment_value": 425000.00,
        "share_price": 500.00
      },
      "outputs": {
        "recycled_shares": 510.0,
        "outstanding_shares": 99150.0,
        "ledger": {
          "participant_cash_accounts": 125000.00,
          "unallocated_company_contributions": 200000.00,
          "unallocated_forfeiture_cash": 50000.00
        }
      }
    }
    ```

    This summary provides complete audit trail for cash flow analysis.
  </Tab>
</Tabs>

***

## Multi-Class Security Support

<Info>
  **New in v0.2:** Full multi-class security support with per-security tracking.
</Info>

When `multi_class_mode=True` and `securities` exist:

### Key Differences

| Aspect               | Single-Class    | Multi-Class              |
| -------------------- | --------------- | ------------------------ |
| **Share Tracking**   | Aggregate total | Per-security holdings    |
| **Pricing**          | Single price    | Security-specific prices |
| **Pro-Rata Logic**   | N/A             | Weighted by holdings     |
| **Repurchase**       | Single queue    | Per-security queues      |
| **Recycled Pool**    | Single pool     | Per-security pools       |
| **Releverage Loans** | Generic loan    | Security-tagged loans    |

### Example: Pro-Rata Distribution

```python theme={null}
# Employee has mixed holdings
employee.holdings = {
    "CLASS_A": Holding(shares=100, vested=True),
    "CLASS_B": Holding(shares=200, vested=True)
}

# Total: 300 shares
# Payment due: 75 shares

# Pro-rata calculation
total_shares = 300
weight_A = 100 / 300 = 0.333
weight_B = 200 / 300 = 0.667

# Distribute
payment_A = 75 * 0.333 = 25 shares
payment_B = 75 * 0.667 = 50 shares

# Value calculation (different prices)
price_A = 500.00
price_B = 450.00

value_A = 25 * 500 = $12,500
value_B = 50 * 450 = $22,500
total_value = $35,000
```

### Security-Specific Repurchase

```python theme={null}
# Repurchase tracking by security
repurchase_by_security = {
    "CLASS_A": 125.0,
    "CLASS_B": 250.0
}

# Strategy: 60% recycle, 40% redeem
for security_id, quantity in repurchase_by_security.items():
    recycle_qty = quantity * 0.60
    redeem_qty = quantity * 0.40
    
    # Update security-specific pools
    carry_over_state.recycled_shares_by_security[security_id] += recycle_qty
    securities[security_id].total_outstanding_shares -= redeem_qty
```

***

## Configuration Reference

Key configuration parameters used in Step 7:

<AccordionGroup>
  <Accordion title="Regulatory Limits" icon="gavel">
    ```python theme={null}
    regulatory_limits = {
        "rmd_age": 73  # Age when distributions must begin (IRS requirement)
    }
    ```
  </Accordion>

  <Accordion title="Distribution Timing Rules" icon="clock">
    ```python theme={null}
    distribution_timing_rules = {
        "retirement_death_disability": {
            "termination_types": ["retirement", "death", "disability"],
            "max_deferral_years": 1  # Must start within 1 year
        },
        "termination": {
            "termination_types": ["termination"],
            "max_deferral_years": 5  # Can defer up to 5 years
        },
        "latest_commencement": {
            "min_age": 65,
            "min_service_years": 10,
            "max_deferral_years": 1  # Age 65+ with 10+ years: max 1 year defer
        }
    }
    ```
  </Accordion>

  <Accordion title="Default Loan Terms" icon="hand-holding-dollar">
    ```python theme={null}
    default_loan_terms = {
        "releverage_years": 10  # Default term for releverage loans
    }
    ```
  </Accordion>

  <Accordion title="Default Rates" icon="percent">
    ```python theme={null}
    default_rates = {
        "oia_yield_rate": 0.03  # 3% annual yield on OIA balance
    }
    ```
  </Accordion>

  <Accordion title="Calculation Precision" icon="calculator">
    ```python theme={null}
    calculation_precision = {
        "precision_string": "0.0001"  # Round to 4 decimal places
    }
    ```
  </Accordion>

  <Accordion title="Account Thresholds" icon="gauge">
    ```python theme={null}
    account_thresholds = {
        "division_by_zero_default": 1  # Denominator default when total_shares = 0
    }
    ```
  </Accordion>
</AccordionGroup>

***

## The Funding Waterfall

See [Simulation Core](/architecture/simulation-core#funding-waterfall) for complete waterfall explanation.

**Quick Summary:**

```python theme={null}
cash_usage_policy = [
    "unallocated_company_contributions",  # 1st priority
    "unallocated_forfeiture_cash",        # 2nd priority
    "participant_cash_accounts"           # 3rd priority
]

# Draw cash in specified order
for source in cash_usage_policy:
    if remaining_need > 0:
        available = trust_cash_ledger[source]
        amount_to_use = min(available, remaining_need)
        trust_cash_ledger[source] -= amount_to_use
        remaining_need -= amount_to_use
```

***

## Common Scenarios

<AccordionGroup>
  <Accordion title="Scenario 1: Simple Retirement" icon="user-tie">
    **Setup:**

    * Employee retires, age 65, 15 years service
    * Vested: 2,000 shares at $500/share = $1M
    * Distribution rule: 5-year installment, 1-year defer
    * Repurchase strategy: 100% recycle

    **Processing:**

    1. **Phase 3:** Create schedule starting 2026, 5 annual payments of 400 shares each
    2. **Phase 5:** In 2026, pay first installment of 400 shares
    3. **Phase 8:** Recycle 400 shares → added to 2027 allocation pool

    **Result:**

    * Employee receives 400 shares in 2026 (valued at current price)
    * Trust repurchases and recycles shares
    * Company has 400 shares for next year's allocation
  </Accordion>

  <Accordion title="Scenario 2: Divorce QDRO" icon="gavel">
    **Setup:**

    * Active employee, age 42, divorce decree
    * QDRO: 50% split to ex-spouse
    * Account: 1,500 vested shares, \$25K cash
    * Repurchase strategy: 100% redeem

    **Processing:**

    1. **Phase 1:** Process QDRO
       * Split: 750 shares + \$12,500 to ex-spouse
       * Employee retains: 750 shares + \$12,500
       * Immediate payout to ex-spouse
    2. **Phase 8:** Redeem 750 shares
       * Outstanding shares reduced by 750

    **Result:**

    * Ex-spouse paid immediately
    * Employee continues with reduced account
    * Company ownership percentages recalculated
  </Accordion>

  <Accordion title="Scenario 3: RMD Override" icon="clock-rotate-left">
    **Setup:**

    * Employee terminated at age 68 in 2020
    * Distribution deferred to 2025 (5-year max)
    * Employee reaches age 73 in 2023
    * Vested balance: 1,200 shares

    **Processing:**

    1. **Phase 4:** In 2023, RMD check triggers
       * Age 73 reached, no active distribution
       * Create immediate RMD schedule
    2. **Phase 5:** Force distribution in 2023 (overrides 2025 deferral)

    **Result:**

    * Distribution starts in 2023 instead of 2025
    * Ensures IRS compliance
    * Prevents tax penalties
  </Accordion>

  <Accordion title="Scenario 4: Weighted Repurchase" icon="scale-balanced">
    **Setup:**

    * Total repurchase: 3,000 shares
    * Strategy: 60% recycle, 30% redeem, 10% releverage
    * Share price: \$500

    **Processing:**

    1. **Phase 8:** Apply weighted strategy
       * Recycle: 3,000 × 60% = 1,800 shares
       * Redeem: 3,000 × 30% = 900 shares
       * Releverage: 3,000 × 10% = 300 shares

    **Recycle:**

    * Add 1,800 shares to next year's pool
    * Use OIA: \$900K if available

    **Redeem:**

    * Reduce outstanding shares by 900

    **Releverage:**

    * Create loan: $150K (300 shares × $500)
    * Term: 10 years
    * Annual release: 30 shares/year

    **Result:**

    * Mixed strategy provides flexibility
    * 1,800 shares available for reallocation
    * 900 shares permanently retired
    * 300 shares financed via new loan
  </Accordion>

  <Accordion title="Scenario 5: Multi-Class Distribution" icon="shapes">
    **Setup:**

    * Employee holds: 500 Class A ($600/share), 1,000 Class B ($400/share)
    * Payment due: 300 shares total
    * Strategy: 100% recycle

    **Processing:**

    1. **Phase 5:** Pro-rata distribution
       * Total shares: 1,500
       * Class A weight: 500 / 1,500 = 33.3%
       * Class B weight: 1,000 / 1,500 = 66.7%
         **Payment:**
       * Class A: 300 × 33.3% = 100 shares → value \$60K
       * Class B: 300 × 66.7% = 200 shares → value \$80K
       * Total value: \$140K
    2. **Phase 8:** Security-specific recycle
       * Class A: Add 100 to recycled\_shares\_by\_security\["CLASS\_A"]
       * Class B: Add 200 to recycled\_shares\_by\_security\["CLASS\_B"]

    **Result:**

    * Each security maintains separate recycled pools
    * Next year's allocation can draw from both pools
    * Preserves security mix in the plan
  </Accordion>
</AccordionGroup>

***

## Data Dependencies

### Inputs Required

<Tabs>
  <Tab title="Employee Data">
    ```python theme={null}
    {
      "employee_id": "EMP042",
      "age": 65,
      "service_years": 15.5,
      "termination_date": "2025-06-30",
      "termination_reason": "retirement",
      "vested_shares": 2000.0,
      "vested_cash": 50000.0,
      "potential_forfeitures": 0.0,
      "holdings": {  # Multi-class mode
        "CLASS_A": {"shares": 1200, "vested": True},
        "CLASS_B": {"shares": 800, "vested": True}
      },
      "qdro_orders": [
        {"percent": 0.50, "processed_year": null}
      ],
      "pending_distributions": []  # Schedules created in Phase 3
    }
    ```
  </Tab>

  <Tab title="Company State">
    ```python theme={null}
    {
      "current_share_price": 500.00,
      "total_outstanding_shares": 100000.0,
      "oia_balance": 250000.0,
      "loans": [
        {
          "loan_id": "LOAN_2020",
          "principal_balance": 2000000.0,
          "maturity_year": 2028,
          ...
        }
      ],
      "securities": {  # Multi-class mode
        "CLASS_A": {
          "security_id": "CLASS_A",
          "current_share_price": 600.00,
          "total_outstanding_shares": 60000.0
        },
        "CLASS_B": {
          "security_id": "CLASS_B",
          "current_share_price": 400.00,
          "total_outstanding_shares": 40000.0
        }
      }
    }
    ```
  </Tab>

  <Tab title="Plan Rules">
    ```python theme={null}
    {
      "vesting_schedule": {
        1: 0.20,
        2: 0.40,
        3: 0.60,
        4: 0.80,
        5: 1.00
      },
      "distribution_rules": [
        {
          "trigger": "retirement",
          "payment_years": 5,
          "defer_years": 1,
          "lump_sum_threshold": 5000,
          "large_balance_threshold": 1000000,
          "large_balance_increment": 250000,
          "max_installment_years": 10,
          "installment_frequency": "annual",
          "distribution_form": "cash"
        }
      ]
    }
    ```
  </Tab>

  <Tab title="Policies">
    ```python theme={null}
    {
      "forfeiture_policy": "reallocate_next_year",
      "repurchase_strategy": {
        2025: {"recycle": 0.60, "redeem": 0.40}
      },
      "segregation_policy": "on_termination",
      "distribution_policy": {
        "leveraged_deferral": True  # Defer to loan maturity
      },
      "releverage_years": 10  # Term for releverage loans
    }
    ```
  </Tab>
</Tabs>

### Outputs Generated

<Tabs>
  <Tab title="Employee Updates">
    ```python theme={null}
    {
      "pending_distributions": [
        {
          "trigger": "retirement",
          "start_year": 2026,
          "years_total": 5,
          "years_paid": 1,
          "annual_shares": 400.0,
          "remaining_shares": 1600.0,
          ...
        }
      ],
      "remaining_payout_shares": 1600.0,
      "remaining_payout_cash": 40000.0,
      "forfeited_shares": 0.0,
      "holdings": {  # Updated after payment
        "CLASS_A": {"shares": 1120},  # Reduced by 80
        "CLASS_B": {"shares": 680}    # Reduced by 120
      }
    }
    ```
  </Tab>

  <Tab title="Company Updates">
    ```python theme={null}
    {
      "total_outstanding_shares": 99600.0,  # After redemptions
      "oia_balance": 175000.0,  # After uses and earnings
      "loans": [
        ... existing loans ...,
        {  # New releverage loan
          "loan_id": "LOAN_2025_CLASS_A",
          "original_amount": 60000.0,
          "remaining_balance": 60000.0,
          "annual_payment": 6000.0,
          "shares_released_per_payment": 10.0,
          "maturity_year": 2035,
          "security_id": "CLASS_A"
        }
      ],
      "securities": {
        "CLASS_A": {
          "total_outstanding_shares": 59800.0  # After redemptions
        }
      }
    }
    ```
  </Tab>

  <Tab title="Carry-Over State">
    ```python theme={null}
    {
      "recycled_shares": 1200.0,
      "recycled_shares_by_security": {
        "CLASS_A": 720.0,
        "CLASS_B": 480.0
      },
      "forfeited_shares_for_next_year": 150.0,
      "forfeited_cash_for_next_year": 7500.0,
      "oia_uses_distributions": 50000.0,
      "oia_uses_repurchase": 360000.0,
      "oia_uses_loan_payments": 120000.0,
      "oia_earnings": 5250.0
    }
    ```
  </Tab>

  <Tab title="Compliance Events">
    ```json theme={null}
    [
      {
        "year": 2025,
        "phase": "distribution",
        "event": "distribution_schedule_created",
        "entity_type": "employee",
        "entity_id": "EMP042",
        "inputs": {
          "vested_shares": 2000.0,
          "payment_years": 5,
          "defer_years": 1,
          "trigger": "retirement"
        },
        "outputs": {
          "start_year": 2026,
          "annual_shares": 400.0,
          "annual_cash": 10000.0
        }
      },
      {
        "year": 2025,
        "phase": "repurchase",
        "event": "repurchase_executed_weighted",
        "entity_type": "company",
        "inputs": {
          "strategy_weights": {"recycle": 0.60, "redeem": 0.40},
          "shares_to_repurchase_by_security": {
            "CLASS_A": 200.0,
            "CLASS_B": 200.0
          }
        },
        "outputs": {
          "recycled_by_security": {
            "CLASS_A": 120.0,
            "CLASS_B": 120.0
          },
          "outstanding_shares_after": 99600.0,
          "oia_balance": 175000.0
        }
      }
    ]
    ```
  </Tab>
</Tabs>

***

## Performance Considerations

<Warning>
  Step 7 is **computationally intensive** due to multiple passes over employee list and complex pro-rata calculations.
</Warning>

**Optimization Strategies:**

1. **Index by Termination Status**
   * Pre-filter terminated employees
   * Avoid scanning full census each phase

2. **Cache Vesting Calculations**
   * Vesting percentages calculated multiple times
   * Cache lookups by service year

3. **Precision Rounding**
   * Apply rounding at calculation boundaries
   * Use `Decimal` for financial amounts
   * Avoid floating-point arithmetic

4. **Multi-Class Overhead**
   * Pro-rata calculations scale with # securities
   * Consider performance impact with 5+ securities

***

## Testing Scenarios

From `tests/engine/test_engine_step7.py`:

<Tabs>
  <Tab title="Basic Scenarios">
    1. **Recycle accumulates recycled shares**
       * Strategy: `"recycle"`
       * Verify: `carry_over_state.recycled_shares > 0`

    2. **Redeem reduces outstanding shares**
       * Strategy: `"redeem"`
       * Verify: `total_outstanding_shares` decreased

    3. **Cash forfeitures tracked**
       * Service: 1 year (20% vested)
       * Opening cash: \$1,000
       * Verify: 80% forfeited to carryover

    4. **Reallocate on payout defers forfeiture**
       * Policy: `"reallocate_on_payout"`
       * Verify: Forfeitures held until payout complete
  </Tab>

  <Tab title="Multi-Year Scenarios">
    5. **Multi-year distribution schedule**
       * Payment years: 3
       * Verify: Payments spread across years

    6. **RMD enforcement**
       * Age: 73
       * Verify: Immediate distribution created

    7. **Leveraged deferral**
       * Loan maturity: 2030
       * Termination: 2025
       * Verify: Start year pushed to 2030
  </Tab>

  <Tab title="Edge Cases">
    8. **Zero balance protection**
       * Total shares = 0
       * Verify: No divide-by-zero errors

    9. **Small balance cashout**
       * Vested value: \$4,000
       * Threshold: \$5,000
       * Verify: Lump sum forced

    10. **Missing configuration fallbacks**
        * No RMD age specified
        * Verify: Defaults to 73
  </Tab>
</Tabs>

***

## Related Documentation

<CardGroup cols={2}>
  <Card title="TrustCashLedger" icon="wallet" href="/models/trust-cash-ledger">
    Ledger structure and cash flow management
  </Card>

  <Card title="Design Principles" icon="compass" href="/architecture/design-principles">
    Why Step 7 is structured this way
  </Card>

  <Card title="Simulation Core" icon="gears" href="/architecture/simulation-core">
    How Step 7 fits into the annual cycle
  </Card>

  <Card title="ESOP Loan Model" icon="hand-holding-dollar" href="/models/esop-loan">
    Releverage loan creation and tracking
  </Card>
</CardGroup>

***

## Summary

Step 7 is the **most complex and critical** step in the ESOP projection engine:

**Key Responsibilities:**

* ✅ QDRO processing (divorce settlements)
* ✅ Forfeiture tracking (non-vested amounts)
* ✅ Distribution schedule creation (multi-year installments)
* ✅ RMD enforcement (age 73+ compliance)
* ✅ Payment execution (scheduled distributions)
* ✅ Distribution form conversion (stock → cash)
* ❌ Segregation policy (removed in v0.3)
* ✅ Repurchase strategy execution (recycle/redeem/releverage)
* ✅ Funding reconciliation (TrustCashLedger balances)

**Complexity Factors:**

* 9 sequential phases
* Multi-class security support
* Pro-rata calculations across securities
* Regulatory compliance checks
* Multi-year distribution schedules
* Weighted strategy execution
* Comprehensive event logging

**Performance Profile:**

* Most expensive step (1,130 lines of code)
* Multiple passes over employee list
* Pro-rata calculations scale with # securities
* Precision rounding for financial accuracy

<Note>
  **For Developers:** Step 7 processes are highly interdependent. Changing one phase may affect downstream phases. Always run full test suite after modifications.
</Note>
