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

# Cognitive Primitives

> The 12 fundamental building blocks of AXON's cognitive programming model

AXON is built on **12 cognitive primitives** — foundational constructs that represent how AI models think, reason, and process information. Unlike traditional programming languages that abstract over CPU instructions, AXON abstracts over cognitive operations.

## Overview

Each primitive maps to a specific cognitive capability or constraint that LLMs naturally possess. By making these explicit in the language, AXON enables you to compose complex AI behaviors declaratively.

<CardGroup cols={2}>
  <Card title="Identity & Context" icon="user">
    `persona`, `context`, `memory`
  </Card>

  <Card title="Reasoning & Control" icon="brain">
    `reason`, `flow`, `intent`
  </Card>

  <Card title="Constraints & Validation" icon="shield">
    `anchor`, `validate`, `refine`
  </Card>

  <Card title="Tools & Synthesis" icon="wrench">
    `tool`, `probe`, `weave`
  </Card>
</CardGroup>

***

## The 12 Primitives

### 1. Persona — Cognitive Identity

Defines the **identity** and capabilities of the AI model. A persona specifies domain expertise, tone, confidence thresholds, and behavioral constraints.

<CodeGroup>
  ```axon Example: LegalExpert theme={null}
  persona LegalExpert {
    domain: ["contract law", "IP", "corporate"]
    tone: precise
    confidence_threshold: 0.85
    cite_sources: true
  }
  ```

  ```axon Example: CreativeWriter theme={null}
  persona CreativeWriter {
    domain: ["fiction", "poetry", "narrative"]
    tone: expressive
    confidence_threshold: 0.6
    creativity: high
  }
  ```
</CodeGroup>

<Tip>
  Think of personas as **cognitive profiles** that shape how the model approaches tasks. They're not just system prompts — they're type-checked, composable identities.
</Tip>

***

### 2. Context — Working Memory

Establishes the **session configuration** and working memory parameters for execution. Controls temperature, token limits, language, and computational depth.

```axon contract_analyzer.axon theme={null}
context LegalReview {
  memory: session
  language: "en"
  depth: exhaustive
  max_tokens: 4096
  temperature: 0.3
}
```

**Key Fields:**

* `memory`: `session`, `persistent`, `ephemeral`
* `temperature`: Controls randomness (0.0 = deterministic, 1.0 = creative)
* `depth`: `shallow`, `normal`, `exhaustive`
* `max_tokens`: Output length budget

***

### 3. Intent — Atomic Semantic Instruction

Represents a **single, focused semantic operation**. Intents are the smallest unit of cognitive work — they ask the model to perform one specific task.

```axon Example: Extract entities theme={null}
intent ExtractParties {
  ask: "Identify all parties mentioned in the contract"
  input: Document
  output: EntityMap
}
```

Intents are **composable** — they can be chained within flows or invoked independently.

***

### 4. Flow — Composable Cognitive Pipeline

Orchestrates **multi-step reasoning** by composing cognitive operations into a directed acyclic graph (DAG). Each step can reference outputs from previous steps.

```axon contract_analyzer.axon theme={null}
flow AnalyzeContract(doc: Document) -> ContractAnalysis {
  step Extract {
    given: doc
    ask: "Extract all parties, obligations, dates, and penalties"
    output: EntityMap
  }
  
  step Assess {
    given: Extract.output
    ask: "Identify ambiguous or risky clauses"
    output: RiskAnalysis
  }
  
  step Synthesize {
    weave [Extract.output, Assess.output]
    format: ContractAnalysis
  }
}
```

<Info>
  **Data Dependencies:** Steps automatically form a dependency graph. `Assess` won't execute until `Extract` completes. The AXON runtime handles orchestration.
</Info>

***

### 5. Reason — Explicit Chain-of-Thought

Forces the model to **show its reasoning** before producing an answer. Enables explicit chain-of-thought or tree-of-thought reasoning.

```axon Example: Logical reasoning theme={null}
step Analyze {
  reason {
    chain_of_thought: enabled
    given: contractText
    ask: "Are there ambiguous or risky clauses?"
    depth: 3
  }
  output: RiskAnalysis
}
```

**Reasoning Modes:**

* `chain_of_thought`: Linear step-by-step reasoning
* `tree_of_thought`: Branching exploration (experimental)
* `depth`: Controls reasoning steps (1-5)

***

### 6. Anchor — Hard Constraint (Never Violable)

Defines **inviolable rules** that must never be broken. Anchors are checked at runtime, and violations raise `AnchorBreachError`.

```axon contract_analyzer.axon theme={null}
anchor NoHallucination {
  require: source_citation
  confidence_floor: 0.75
  unknown_response: "I don't have sufficient information."
  on_violation: raise AnchorBreachError
}
```

<Warning>
  Anchors are **fail-fast** by design. If an anchor is breached, execution stops immediately unless a `refine` block handles recovery.
</Warning>

**Use cases:**

* Preventing hallucinations (`NoHallucination`)
* Enforcing logical structure (`SyllogismChecker`)
* Blocking speculation (`AgnosticFallback`)
* Requiring citations (`RequiresCitation`)

***

### 7. Validate — Semantic Validation Gate

**Type-checks** the semantic meaning of outputs, not just their structure. Ensures outputs match their declared epistemic type.

```axon Example: Validate against schema theme={null}
step Check {
  validate Assess.output against: ContractSchema
  if confidence < 0.8 -> refine(max_attempts: 2)
  output: ValidatedAnalysis
}
```

Validation failures raise `ValidationError` (Level 1) and can trigger automatic refinement.

***

### 8. Refine — Adaptive Retry with Failure Context

Enables **self-healing** by automatically retrying failed operations with injected failure context. The model learns from its mistakes.

```axon Example: Retry with backoff theme={null}
step ExtractWithRetry {
  refine {
    max_attempts: 3
    backoff: exponential
    pass_failure_context: true
    on_exhaustion: fallback("default_extract")
  }
  ask: "Extract key contract terms"
  output: Terms
}
```

<Check>
  **Self-Healing Mechanism:** When a step fails validation or breaches an anchor, `refine` re-invokes the model with the exact failure reason injected into the prompt. This creates a closed feedback loop.
</Check>

***

### 9. Memory — Persistent Semantic Storage

Provides **long-term storage** for semantic values across sessions. Unlike context (working memory), memory persists beyond execution.

```axon Example: User preferences theme={null}
memory UserPreferences {
  schema: {
    language: String,
    expertise_level: String,
    topics_of_interest: List<String>
  }
  backend: vector
  ttl: 30d
}
```

Supports multiple backends:

* `in_memory`: Fast, ephemeral
* `vector`: Semantic search (embeddings)
* `kv`: Key-value store

***

### 10. Tool — External Invocable Capability

Bridges the model to **external capabilities** like web search, code execution, file I/O, or API calls.

```axon contract_analyzer.axon theme={null}
tool WebSearch {
  provider: brave
  max_results: 5
  timeout: 10s
}
```

**Built-in Tools:**

* `WebSearch` — Internet search (Serper.dev)
* `FileReader` — Local filesystem access
* `CodeExecutor` — Run code sandboxed
* `Calculator` — Math operations
* `DateTime` — Time/date utilities

See [Tool System](/axon-docs/axon-docs/concepts/tool-system) for details.

***

### 11. Probe — Directed Information Extraction

Performs **targeted extraction** of specific information from unstructured data.

```axon Example: Extract obligations theme={null}
step ExtractObligations {
  probe doc for [parties, obligations, dates, penalties]
  output: EntityMap
}
```

Probes are **type-aware** — the runtime knows what to look for and validates the extraction.

***

### 12. Weave — Semantic Synthesis

**Combines multiple outputs** into a coherent whole. Unlike simple concatenation, weaving performs semantic integration.

```axon Example: Synthesize report theme={null}
step Report {
  weave [Extract.output, Assess.output, Check.output]
  format: StructuredReport
  include: [summary, risks, recommendations]
}
```

<Tip>
  Weaving is **context-aware** — the model understands the semantic relationships between inputs and produces a unified representation.
</Tip>

***

## Composability

Primitives are designed to **compose naturally**:

```axon Full pipeline example theme={null}
run AnalyzeContract(myDoc)
  as LegalExpert              // persona
  within LegalReview           // context
  constrained_by [NoHallucination]  // anchor
  on_failure: retry(backoff: exponential)  // refine
```

This single `run` statement combines:

* **Persona** (who)
* **Context** (how)
* **Flow** (what)
* **Anchor** (constraints)
* **Refine** (recovery)

***

## Design Philosophy

<AccordionGroup>
  <Accordion title="Declarative over Imperative">
    Primitives describe **what** you want, not **how** to do it. The AXON runtime handles orchestration.
  </Accordion>

  <Accordion title="Semantic over Syntactic">
    Primitives operate on **meaning**, not bytes. Types represent epistemic states, not memory layouts.
  </Accordion>

  <Accordion title="Composable Cognition">
    Primitives snap together like neural networks — small units compose into complex behaviors.
  </Accordion>

  <Accordion title="Failure as First-Class">
    `refine`, `validate`, and `anchor` make failure handling explicit and automatic.
  </Accordion>
</AccordionGroup>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Type System" icon="sitemap" href="/axon-docs/axon-docs/concepts/type-system">
    Learn about AXON's epistemic types
  </Card>

  <Card title="Compilation Pipeline" icon="gears" href="/axon-docs/axon-docs/concepts/compilation-pipeline">
    See how primitives compile to prompts
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation" href="/axon-docs/axon-docs/concepts/error-handling">
    Understand the 6-level error hierarchy
  </Card>

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