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

# Type System

> AXON's epistemic type system based on a partial order lattice

AXON's type system is fundamentally different from traditional programming languages. Instead of representing **memory layouts** or **data structures**, AXON types represent **epistemic states** — the nature, reliability, and provenance of information.

## Core Principle

<Info>
  **Epistemic Types = Meaning Types**

  Types in AXON track *what information means* and *how reliable it is*, not how many bytes it occupies in memory.
</Info>

This enables the compiler and runtime to enforce semantic correctness: for example, preventing an `Opinion` from being used where a `FactualClaim` is required, or propagating `Uncertainty` through computations to maintain epistemic honesty.

***

## The Partial Order Lattice

AXON's type system is formalized as a **partial order lattice** `(T, ≤)`, where `≤` represents the **subsumption relationship** between types.

### Lattice Structure

```text theme={null}
            ⊤ (Any)
              │
    ┌─────────┼─────────────┐
    │         │             │
FactualClaim  Opinion  Speculation
    │                       │
 CitedFact            Uncertainty
    │
HighConfidenceFact
    │
    ⊥ (Never)
```

### Subsumption Rule

<Tip>
  **Type Subsumption:** If `T₁ ≤ T₂`, then `T₁` can be used wherever `T₂` is expected.
</Tip>

**Examples:**

* `CitedFact ≤ FactualClaim` — A cited fact **is a** factual claim
* `HighConfidenceFact ≤ CitedFact` — A high-confidence fact **is a** cited fact
* `Opinion ≤ Any` — An opinion **is** some form of information
* `Opinion ≰ FactualClaim` — An opinion **cannot** satisfy a factual claim requirement

***

## Type Categories

### 1. Epistemic Types (Reliability)

Track the **epistemic status** of information — how certain, verifiable, or grounded it is.

<AccordionGroup>
  <Accordion title="FactualClaim" icon="check">
    Information presented as objectively verifiable fact.

    ```axon theme={null}
    type Party {
      name: FactualClaim,
      role: FactualClaim
    }
    ```

    **Subsumption:** `FactualClaim ≤ Any`\
    **Cannot contain:** `Opinion`, `Speculation`
  </Accordion>

  <Accordion title="CitedFact" icon="quote-left">
    A factual claim with **explicit source attribution**.

    ```axon theme={null}
    anchor RequiresCitation {
      require: CitedFact
      on_violation: raise AnchorBreachError
    }
    ```

    **Subsumption:** `CitedFact ≤ FactualClaim ≤ Any`
  </Accordion>

  <Accordion title="HighConfidenceFact" icon="certificate">
    A cited fact with confidence score ≥ 0.85 (configurable).

    **Subsumption:** `HighConfidenceFact ≤ CitedFact ≤ FactualClaim ≤ Any`\
    **Use case:** Medical, legal, or financial domains requiring high certainty.
  </Accordion>

  <Accordion title="Opinion" icon="comment">
    Subjective judgment or interpretation.

    ```axon theme={null}
    type Risk {
      score: RiskScore,          // objective
      mitigation: Opinion?       // subjective
    }
    ```

    **Critical:** `Opinion ≰ FactualClaim` — opinions **never** satisfy factual requirements.
  </Accordion>

  <Accordion title="Uncertainty" icon="question">
    Lack of sufficient information to make a determination.

    <Warning>
      **Taint Propagation:** Any computation involving `Uncertainty` produces `Uncertainty`. This is enforced at compile time.
    </Warning>

    ```axon theme={null}
    let fact: FactualClaim = "The contract was signed in 2020"
    let unknown: Uncertainty = recall("signer_address")
    let result = weave [fact, unknown]  // result: Uncertainty
    ```
  </Accordion>

  <Accordion title="Speculation" icon="crystal-ball">
    Conjecture without evidence.

    ```axon theme={null}
    anchor AgnosticFallback {
      forbid: Speculation
      on_detection: raise AnchorBreachError
    }
    ```

    **Subsumption:** `Speculation ≤ Any` but incompatible with most epistemic types.
  </Accordion>
</AccordionGroup>

***

### 2. Content Types (Data)

Represent **structured or unstructured information** that flows through pipelines.

| Type          | Description                     | Example Use                 |
| ------------- | ------------------------------- | --------------------------- |
| `Document`    | Raw text document               | Contract PDFs, emails       |
| `Chunk`       | Segmented portion of a document | Paragraph, section          |
| `EntityMap`   | Extracted structured entities   | Parties, dates, obligations |
| `Summary`     | Condensed representation        | Executive summary           |
| `Translation` | Language-translated content     | EN → ES                     |

```axon Example: Content pipeline theme={null}
flow ProcessDocument(doc: Document) -> Summary {
  step Segment {
    given: doc
    ask: "Split into logical sections"
    output: List<Chunk>
  }
  
  step Extract {
    probe Segment.output for [entities, dates, amounts]
    output: EntityMap
  }
  
  step Summarize {
    given: Extract.output
    ask: "Generate executive summary"
    output: Summary
  }
}
```

***

### 3. Analysis Types (Metrics)

Quantitative or qualitative **assessments** with bounded ranges.

<CodeGroup>
  ```axon RiskScore (0.0..1.0) theme={null}
  type RiskScore(0.0..1.0)

  type Risk {
    score: RiskScore,
    description: FactualClaim
  }
  ```

  ```axon ConfidenceScore (0.0..1.0) theme={null}
  type ConfidenceScore(0.0..1.0)

  persona Expert {
    confidence_threshold: 0.85
    output_type: ConfidenceScore
  }
  ```

  ```axon SentimentScore (-1.0..1.0) theme={null}
  type SentimentScore(-1.0..1.0)

  step AnalyzeSentiment {
    given: customerReview
    ask: "Rate sentiment from negative to positive"
    output: SentimentScore
  }
  ```
</CodeGroup>

<Info>
  **Range Constraints:** Analysis types have built-in validation. Values outside the declared range raise `ValidationError`.
</Info>

***

### 4. Structural Types (User-Defined)

Custom types for domain-specific entities.

```axon contract_analyzer.axon theme={null}
type Party {
  name: FactualClaim,
  role: FactualClaim
}

type Risk {
  score: RiskScore,
  mitigation: Opinion?
}

type ContractAnalysis {
  parties: List<Party>,
  obligations: List<FactualClaim>,
  risks: List<Risk>,
  overall_confidence: ConfidenceScore
}
```

<Tip>
  **Compositional Types:** User types can embed epistemic types, enforcing semantic constraints at every level.
</Tip>

***

## Type Checking

AXON performs **semantic type checking** at compile time via the `TypeChecker` module.

### Compatibility Matrix

The type checker uses an `EpistemicLattice` class to determine type compatibility:

```python type_checker.py theme={null}
class EpistemicLattice:
    """Partial Order Lattice for AXON epistemic types."""
    
    _parents = {
        "HighConfidenceFact": "CitedFact",
        "CitedFact": "FactualClaim",
        "FactualClaim": "Any",
        "Opinion": "Any",
        "Speculation": "Any",
        "Uncertainty": "Any",
        "Any": None,
        "Never": None,
    }
    
    @classmethod
    def subsumes(cls, subtype: str, supertype: str) -> bool:
        """Check if subtype ≤ supertype in the lattice."""
        # Walk up the parent chain
        current = subtype
        while current is not None:
            if current == supertype:
                return True
            current = cls._parents.get(current)
        return False
```

### Validation Rules

<Steps>
  <Step title="Assignment Compatibility">
    Can `source_type` be assigned to `target_type`?

    ```axon theme={null}
    let claim: FactualClaim = get_cited_fact()  // ✅ CitedFact ≤ FactualClaim
    let claim: FactualClaim = get_opinion()     // ❌ Opinion ≰ FactualClaim
    ```
  </Step>

  <Step title="Parameter Passing">
    Can `argument_type` satisfy `parameter_type`?

    ```axon theme={null}
    flow Verify(input: FactualClaim) -> Boolean { ... }

    run Verify(cited_fact)   // ✅
    run Verify(opinion)      // ❌ Type error
    ```
  </Step>

  <Step title="Return Type Checking">
    Does step output match declared type?

    ```axon theme={null}
    step Extract {
      ask: "What is the contract date?"
      output: FactualClaim  // Checked at runtime
    }
    ```
  </Step>

  <Step title="Uncertainty Propagation">
    Any operation on `Uncertainty` yields `Uncertainty`.

    ```axon theme={null}
    let a: FactualClaim = "Known fact"
    let b: Uncertainty = recall("unknown_key")
    let c = weave [a, b]  // c: Uncertainty (taint)
    ```
  </Step>
</Steps>

***

## Runtime Validation

While the `TypeChecker` catches structural issues at compile time, **semantic validation** happens at runtime via the `SemanticValidator`.

### How It Works

1. **Step Execution** — Model produces output
2. **Semantic Classification** — Runtime determines epistemic type
3. **Lattice Check** — Validator checks `actual_type ≤ declared_type`
4. **Action** — Pass, raise `ValidationError`, or trigger `refine`

```python semantic_validator.py theme={null}
def validate_output(actual: Any, expected_type: str) -> bool:
    """Validate that actual output matches expected epistemic type."""
    actual_type = classify_epistemic_type(actual)
    if not EpistemicLattice.subsumes(actual_type, expected_type):
        raise ValidationError(
            f"Type mismatch: expected {expected_type}, got {actual_type}"
        )
    return True
```

<Warning>
  **ValidationError (Level 1):** Raised when output type doesn't match declaration. Can trigger automatic refinement if configured.
</Warning>

***

## Special Type Rules

### Optional Types

Use `?` suffix for optional fields:

```axon theme={null}
type Risk {
  score: RiskScore,
  mitigation: Opinion?   // May be absent
}
```

### List Types

```axon theme={null}
type ContractAnalysis {
  parties: List<Party>,
  risks: List<Risk>
}
```

### Range Types

```axon theme={null}
type RiskScore(0.0..1.0)     // Compile-time range constraint
type AgeInYears(0..150)       // Integer range
```

### Union Types (Planned)

```axon theme={null}
type Outcome = Success | Failure | Pending  // Coming in Phase 5
```

***

## Type Inference

AXON performs **limited type inference** for intermediate values:

```axon theme={null}
step Extract {
  given: doc                  // Type inferred from doc: Document
  ask: "Extract entities"
  output: EntityMap           // Explicit declaration required
}

step Assess {
  given: Extract.output       // Type inferred as EntityMap
  ask: "Assess risks"
  output: RiskAnalysis
}
```

<Info>
  **Design Choice:** Step outputs require explicit type declarations for clarity and safety. Intermediate expressions support inference.
</Info>

***

## Comparison with Other Type Systems

| Feature                 | TypeScript | Python  | Haskell | **AXON** |
| ----------------------- | ---------- | ------- | ------- | -------- |
| Structural types        | ✅          | ❌       | ❌       | ✅        |
| Epistemic types         | ❌          | ❌       | ❌       | ✅        |
| Runtime validation      | ❌          | Partial | ❌       | ✅        |
| Uncertainty propagation | ❌          | ❌       | ❌       | ✅        |
| Semantic subsumption    | ❌          | ❌       | Partial | ✅        |

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Cognitive Primitives" icon="brain" href="/axon-docs/axon-docs/concepts/cognitive-primitives">
    Learn about the 12 core primitives
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation" href="/axon-docs/axon-docs/concepts/error-handling">
    See how type errors are handled
  </Card>

  <Card title="Compilation Pipeline" icon="gears" href="/axon-docs/axon-docs/concepts/compilation-pipeline">
    Understand type checking in the compiler
  </Card>

  <Card title="Examples" icon="code" href="/axon-docs/axon-docs/examples/contract-analyzer">
    See types in real programs
  </Card>
</CardGroup>
