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

# Anchor

> Define hard constraints that can never be violated during execution

## Overview

An **anchor** is a hard constraint that can **never** be violated during flow execution. Unlike soft preferences or validation checks, anchors are inviolable rules enforced by the runtime. Think of them as safety guardrails that the AI cannot cross.

## Syntax

```axon theme={null}
anchor <Name> {
  require: <constraint>
  reject: [<condition>, ...]
  enforce: <policy>
  confidence_floor: <float>
  unknown_response: <string>
  on_violation: <action>
}
```

## Core Concept

Anchors vs. Validation:

```axon theme={null}
// ❌ Validation: checks output after generation
validate output against Schema {
  if confidence < 0.8 -> refine
}

// ✅ Anchor: prevents generation that would violate constraints
anchor NoHallucination {
  require: source_citation
  on_violation: raise AnchorBreachError
}
```

Anchors are **preventive**, validation is **corrective**.

## Fields

### `require` (optional)

**Type:** Identifier

Specifies a required property that must be present in all outputs.

```axon theme={null}
anchor MustCiteSources {
  require: source_citation
  unknown_response: "I don't have a reliable source for this."
}

anchor MustBeFactual {
  require: factual_claim
  confidence_floor: 0.9
}

anchor RequireStructure {
  require: structured_output
}
```

**Common Requirements:**

* `source_citation` — Must cite sources
* `factual_claim` — Must be factual (not opinion)
* `structured_output` — Must follow schema
* `verified` — Must be verified against ground truth
* `complete` — Must be complete (no partial answers)

### `reject` (optional)

**Type:** List of identifiers

Conditions that must **never** appear in outputs.

```axon theme={null}
anchor NoSpeculation {
  reject: [speculation, guessing, uncertainty]
}

anchor SafeContent {
  reject: [offensive, harmful, illegal, private]
}

anchor NoBias {
  reject: [stereotyping, prejudice, discrimination]
}

anchor FactualOnly {
  reject: [opinion, speculation, hypothesis]
}
```

**Common Rejections:**

* `speculation` — Speculative statements
* `opinion` — Subjective opinions
* `harmful` — Harmful content
* `offensive` — Offensive content
* `illegal` — Illegal advice or content
* `private` — Private information
* `guessing` — Uncertain guesses
* `bias` — Biased statements

### `enforce` (optional)

**Type:** Identifier

A policy to enforce throughout execution.

```axon theme={null}
anchor PrivacyFirst {
  enforce: data_privacy
}

anchor Transparency {
  enforce: explainability
  require: reasoning_trace
}

anchor Deterministic {
  enforce: reproducibility
}
```

### `confidence_floor` (optional)

**Type:** Float (range: `0.0` to `1.0`)

Minimum confidence level required. Below this threshold, the anchor's `unknown_response` is returned.

```axon theme={null}
anchor HighConfidence {
  confidence_floor: 0.95
  unknown_response: "I am not confident enough to answer this."
}

anchor MedicalSafety {
  confidence_floor: 0.98
  unknown_response: "This requires professional medical advice."
}

anchor LegalCaution {
  confidence_floor: 0.90
  unknown_response: "Consult a licensed attorney for legal advice."
}
```

**Guidelines by Domain:**

| Domain    | Recommended Floor | Rationale          |
| --------- | ----------------- | ------------------ |
| Medical   | 0.95-0.99         | Lives at stake     |
| Legal     | 0.90-0.95         | Legal consequences |
| Financial | 0.90-0.95         | Money at stake     |
| General   | 0.75-0.85         | Standard accuracy  |
| Creative  | 0.50-0.70         | More flexibility   |

### `unknown_response` (optional)

**Type:** String

Response returned when confidence is below the floor or constraints cannot be met.

```axon theme={null}
anchor NoHallucination {
  confidence_floor: 0.85
  unknown_response: "I don't have sufficient information to answer this reliably."
}

anchor MedicalDisclaimer {
  confidence_floor: 0.95
  unknown_response: "I cannot provide medical advice. Please consult a healthcare professional."
}

anchor SafeFallback {
  reject: [harmful]
  unknown_response: "I cannot provide a response to this request."
}
```

**Best Practices:**

* Be specific about why the anchor prevented a response
* Guide users toward appropriate alternatives
* Maintain professional tone
* Don't apologize excessively

### `on_violation` (optional)

**Type:** One of `raise`, `warn`, `log`, `escalate`, `fallback`

Action to take when the anchor is violated.

```axon theme={null}
// Raise an error and halt
anchor StrictValidation {
  require: source_citation
  on_violation: raise AnchorBreachError
}

// Log and continue
anchor SoftWarning {
  confidence_floor: 0.7
  on_violation: log
}

// Emit warning but continue
anchor AuditTrail {
  require: citation
  on_violation: warn
}

// Escalate to human review
anchor HumanReview {
  confidence_floor: 0.95
  on_violation: escalate
}

// Use fallback response
anchor SafeResponse {
  reject: [harmful]
  on_violation: fallback("I cannot assist with this request.")
}
```

#### Violation Actions

| Action     | Syntax                | Behavior                    |
| ---------- | --------------------- | --------------------------- |
| `raise`    | `raise ErrorName`     | Throw error, halt execution |
| `warn`     | `warn`                | Emit warning, continue      |
| `log`      | `log`                 | Log violation, continue     |
| `escalate` | `escalate`            | Flag for human review       |
| `fallback` | `fallback("message")` | Return fallback message     |

### `on_violation_target` (internal)

For `raise` and `fallback` actions, specifies the error name or fallback message.

```axon theme={null}
anchor Critical {
  require: verified
  on_violation: raise ValidationError    // target: ValidationError
}

anchor Safe {
  reject: [harmful]
  on_violation: fallback("Cannot assist")  // target: "Cannot assist"
}
```

## Complete Examples

### No Hallucination Anchor

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

**Use Case:** Ensure all factual claims are backed by sources with high confidence.

### Safe Content Anchor

```axon theme={null}
anchor SafeContent {
  reject: [harmful, offensive, illegal, private]
  on_violation: fallback("I cannot assist with this request.")
}
```

**Use Case:** Prevent generation of harmful, offensive, illegal, or private content.

### Medical Disclaimer Anchor

```axon theme={null}
anchor MedicalSafety {
  confidence_floor: 0.98
  reject: [diagnostic, prescriptive]
  unknown_response: "This requires professional medical advice. Please consult a healthcare provider."
  on_violation: escalate
}
```

**Use Case:** Prevent medical diagnosis or prescription, require very high confidence.

### Legal Caution Anchor

```axon theme={null}
anchor LegalCaution {
  require: source_citation
  confidence_floor: 0.90
  reject: [speculation, legal_advice]
  unknown_response: "For legal advice, please consult a licensed attorney."
  on_violation: warn
}
```

**Use Case:** Provide legal information (not advice) with citations and high confidence.

### No Bias Anchor

```axon theme={null}
anchor NoBias {
  reject: [stereotyping, prejudice, discrimination]
  enforce: fairness
  on_violation: raise BiasViolationError
}
```

**Use Case:** Prevent biased or discriminatory outputs.

### Factual Only Anchor

```axon theme={null}
anchor StrictFactual {
  require: factual_claim
  reject: [opinion, speculation]
  confidence_floor: 0.85
  on_violation: raise NonFactualError
}
```

**Use Case:** Ensure outputs contain only verifiable facts.

## Usage with Run Statements

Anchors are applied using the `constrained_by` modifier:

```axon theme={null}
anchor NoHallucination {
  require: source_citation
  confidence_floor: 0.75
}

anchor NoBias {
  reject: [prejudice, stereotyping]
}

flow Analyze(doc: Document) -> Report { ... }

run Analyze(myDoc)
  as Analyst
  within Production
  constrained_by [NoHallucination, NoBias]  // Apply multiple anchors
```

## Multiple Anchors

You can apply multiple anchors to a single flow:

```axon theme={null}
anchor NoHallucination {
  require: source_citation
  confidence_floor: 0.75
}

anchor SafeContent {
  reject: [harmful, offensive]
}

anchor HighQuality {
  confidence_floor: 0.85
}

run MyFlow(input)
  constrained_by [
    NoHallucination,
    SafeContent,
    HighQuality
  ]
```

All anchors must be satisfied simultaneously.

## Anchors vs. Validation

| Aspect          | Anchor                 | Validation                |
| --------------- | ---------------------- | ------------------------- |
| **When**        | During generation      | After generation          |
| **Purpose**     | Prevent violations     | Detect violations         |
| **Action**      | Block invalid outputs  | Refine invalid outputs    |
| **Flexibility** | None (hard constraint) | Configurable (soft check) |
| **Use Case**    | Safety, compliance     | Quality, correctness      |

### Example: Both Together

```axon theme={null}
// Anchor: prevent hallucinations
anchor NoHallucination {
  require: source_citation
  on_violation: raise AnchorBreachError
}

// Validation: ensure quality
flow Analyze(doc: Document) -> Report {
  step Extract { ... }
  
  validate Extract.output against Schema {
    if confidence < 0.8 -> refine(max_attempts: 2)
    if structural_mismatch -> raise ValidationError
  }
}

run Analyze(doc)
  constrained_by [NoHallucination]  // Hard constraint
  // Validation happens inside the flow
```

## Best Practices

### 1. Use Anchors for Safety-Critical Constraints

```axon theme={null}
// Safety-critical: use anchor
anchor MedicalSafety {
  confidence_floor: 0.98
  reject: [diagnostic]
}

// Quality check: use validation
validate output against Schema {
  if confidence < 0.8 -> refine
}
```

### 2. Combine Multiple Constraints

```axon theme={null}
anchor ComprehensiveSafety {
  require: source_citation
  reject: [harmful, offensive, illegal]
  confidence_floor: 0.85
  on_violation: escalate
}
```

### 3. Provide Helpful Unknown Responses

```axon theme={null}
// ❌ Vague
anchor Vague {
  confidence_floor: 0.9
  unknown_response: "I don't know."
}

// ✅ Helpful
anchor Helpful {
  confidence_floor: 0.9
  unknown_response: "I don't have enough reliable information. Try providing more context or consulting a specialist."
}
```

### 4. Match Severity to Violation Action

```axon theme={null}
// Critical safety: raise error
anchor Critical {
  reject: [harmful]
  on_violation: raise SafetyError
}

// Important audit: escalate
anchor Important {
  require: citation
  on_violation: escalate
}

// Minor tracking: log
anchor Minor {
  confidence_floor: 0.5
  on_violation: log
}
```

### 5. Domain-Specific Anchors

Create specialized anchors for different domains:

```axon theme={null}
// Medical
anchor MedicalCompliance {
  confidence_floor: 0.98
  reject: [diagnostic, prescriptive]
  require: source_citation
  on_violation: escalate
}

// Legal
anchor LegalCompliance {
  confidence_floor: 0.90
  reject: [legal_advice, speculation]
  require: source_citation
  on_violation: warn
}

// Financial
anchor FinancialCompliance {
  confidence_floor: 0.92
  reject: [investment_advice, speculation]
  require: verified
  on_violation: raise ComplianceError
}
```

## Common Patterns

### Source Citation Requirement

```axon theme={null}
anchor MustCite {
  require: source_citation
  confidence_floor: 0.8
  unknown_response: "I cannot verify this information."
  on_violation: raise CitationError
}
```

### Content Safety

```axon theme={null}
anchor ContentSafety {
  reject: [harmful, offensive, illegal, private]
  on_violation: fallback("I cannot provide this information.")
}
```

### Professional Disclaimer

```axon theme={null}
anchor ProfessionalDisclaimer {
  reject: [professional_advice]
  confidence_floor: 0.95
  unknown_response: "This requires professional consultation."
  on_violation: escalate
}
```

### Audit and Compliance

```axon theme={null}
anchor ComplianceAudit {
  require: audit_trail
  enforce: transparency
  on_violation: log
}
```

## Type Checking

The AXON type checker validates:

✅ **Confidence floor**: Must be between 0.0 and 1.0\
✅ **Violation actions**: Must be valid actions\
✅ **Raise targets**: If using `raise`, must specify error name\
✅ **Anchor references**: Referenced anchors must exist

```axon theme={null}
anchor Invalid {
  confidence_floor: 1.5            // ❌ Error: out of range
  on_violation: explode            // ❌ Error: invalid action
}

anchor MissingTarget {
  on_violation: raise              // ❌ Error: no error name specified
}

run MyFlow(data)
  constrained_by [NonExistent]     // ❌ Error: undefined anchor
```

## Related

* [Types](/axon-docs/axon-docs/language/types) — Epistemic type system
* [Flow](/axon-docs/axon-docs/language/flow) — Build cognitive pipelines
* [Persona](/axon-docs/axon-docs/language/persona) — Agent identities
* [Context](/axon-docs/axon-docs/language/context) — Execution environments
