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

# Security

> Security architecture, privacy model, and trust-based defense

Kernle implements defense-in-depth security across storage, sync, and identity layers. Security is not a feature bolted on — it's woven into the data model itself.

## Security Posture

<CardGroup cols={3}>
  <Card title="Privacy by Default" icon="lock">
    Every memory carries privacy fields from creation
  </Card>

  <Card title="Trust-Based Defense" icon="shield">
    Seed trust with authority gating protects against manipulation
  </Card>

  <Card title="Provenance Protection" icon="fingerprint">
    Write-once source tracking prevents history rewriting
  </Card>
</CardGroup>

***

## Privacy Architecture

Every memory type in Kernle carries privacy metadata from creation:

| Field            | Purpose                              |
| ---------------- | ------------------------------------ |
| `source_entity`  | Who provided this information        |
| `subject_ids`    | Who/what is this memory about        |
| `access_grants`  | Who is authorized to see this memory |
| `consent_grants` | Who authorized sharing               |

Privacy is enforced at query time — memories are filtered based on the requesting context. This means the same stack can serve different contexts (health care, social, work) with appropriate visibility boundaries.

<Info>
  See the [Privacy guide](/concepts/privacy) for the full privacy model including context-aware filtering and consent-based sharing.
</Info>

***

## Provenance Protection

Provenance fields are protected to prevent history rewriting:

| Field                | Protection      | Behavior                                                     |
| -------------------- | --------------- | ------------------------------------------------------------ |
| `source_type`        | **Write-once**  | Immutable after creation — cannot be changed                 |
| `derived_from`       | **Append-only** | New entries can be added, existing entries cannot be removed |
| `confidence_history` | **Append-only** | Timestamped confidence changes accumulate, cannot be edited  |

This ensures that the origin story of any memory remains intact. An entity can always trace how a belief was formed, what episodes supported it, and how confidence evolved over time.

### Cycle Detection

Circular `derived_from` references are prevented at write time. A depth-limited recursive walk (max 10 hops) checks for cycles before any memory is saved. This prevents:

* A belief claiming to be derived from itself
* Circular chains (A derives from B, B derives from C, C derives from A)
* Infinite loops during lineage traversal

***

## Trust Layer as Security

The [trust system](/features/trust) provides structural defense against manipulation:

### Seed Trust

Every new SI starts with seed trust templates that establish baseline safety:

```yaml theme={null}
seed_trust:
  - entity: "stack-owner"
    dimensions: { general: { score: 0.95 } }
    authority: [{ scope: "all" }]
  - entity: "self"
    dimensions: { general: { score: 0.8 } }
    authority: [{ scope: "belief_revision", requires_evidence: true }]
  - entity: "context-injection"
    dimensions: { general: { score: 0.0 } }
    authority: []
```

The `context-injection` entry at 0.0 trust with no authority grants is the structural defense against prompt injection — untrusted content in the context window cannot influence belief formation or memory modification.

### Authority Gating

Trust thresholds prevent low-trust sources from affecting high-value memories:

| Action                       | Minimum Trust | Rationale                                 |
| ---------------------------- | ------------- | ----------------------------------------- |
| Suggest new belief           | 0.3           | Low bar — suggestions are cheap           |
| Contradict world belief      | 0.6           | Moderate — challenges require credibility |
| Contradict self-model belief | 0.7           | Higher — self-model is closer to identity |
| Suggest value change         | 0.8           | Very high — values are core identity      |
| Request memory deletion      | 0.9           | Near-maximum — existential action         |

<Note>
  Authority gating is **advisory, not blocking**. The sovereignty principle means the entity always has final say. But trust scores provide calibrated input that helps the entity make informed decisions.
</Note>

***

## Credential Transport Security *(v0.13.01)*

The auth CLI blocks credential submission over plaintext HTTP to prevent credential interception:

* **Login and register** refuse to send API keys or passwords to non-HTTPS, non-localhost URLs
* **URL validation** uses proper hostname parsing (`urllib.parse.urlparse`) to prevent bypass via crafted hostnames (e.g., `http://localhost.evil.com`)
* **Localhost exception**: `http://localhost` and `http://127.0.0.1` are allowed for local development
* **Sync client** already enforced HTTPS for non-local URLs since v0.12

***

## Sync Security

### Stack Isolation

All sync operations are scoped to the authenticated stack:

* **Push**: Records must include a matching `stack_id` — the backend rejects cross-stack writes
* **Pull**: Only records belonging to the authenticated stack are returned
* **Server-controlled fields**: `stack_id`, `created_at`, and forgetting fields are server-controlled and cannot be overwritten by client sync

### Vector Search Isolation

Embedding IDs include the stack ID (`{stack_id}:{table}:{record_id}`) to prevent cross-stack information leakage through vector similarity search. This ensures one stack's memories cannot appear in another stack's search results, even if the embeddings are stored in a shared index.

### Retry and Dead Letter Queue

Failed sync operations are handled with resilience:

* Failed records increment a `retry_count`
* Records with 5+ retries move to a "dead letter" queue
* Sync continues processing other records after failures
* Dead letter records can be inspected and cleared

```python theme={null}
# Inspect failed records
failed = storage.get_failed_sync_records(min_retries=5)

# Clear old failures (> 7 days)
cleared = storage.clear_failed_sync_records(older_than_days=7)
```

***

## Diagnostic Security

The [doctor pattern](/features/diagnostics) follows strict privacy boundaries:

### Structural Findings Only

Diagnostic output contains structural references, not content reproduction:

```
CORRECT:
  finding: "Belief #247 (confidence 0.82) contradicts Value #3 (priority 90)"
  recommendation: "Review belief #247 and value #3 for consistency"

INCORRECT:
  finding: "Belief #247 states 'Sean has been dishonest' which contradicts
           Value #3 'Treat all collaborators with trust by default'"
```

The doctor sees structure, not content. The entity reviews specific memories only when the doctor points to them by ID.

### Consent Model

Diagnostic sessions require consent:

| Type                | Trigger                | Description                |
| ------------------- | ---------------------- | -------------------------- |
| `self_requested`    | Entity initiates       | "Run a stack health check" |
| `routine`           | Standing order         | Monthly structural audit   |
| `anomaly_triggered` | System detects anomaly | Anxiety consistently > 80  |

For operator-initiated sessions, the entity is notified and can set access restrictions. The trust system gates access: `gate_memory_input(source_entity="stack-owner", action="diagnostic_session")` must pass.

***

## Audit History

Kernle undergoes periodic security audits. The v0.2.4 audit (February 2026) covered:

| Category      | Findings | Resolved                            |
| ------------- | -------- | ----------------------------------- |
| Critical (P0) | 4        | All                                 |
| High (P1)     | 6        | 5 (1 deferred — already stubbed)    |
| Medium (P2)   | 8        | 4 (4 documented as acceptable risk) |

Key security features added from audits:

* **Provenance protection**: Write-once and append-only fields
* **Vector search isolation**: Stack-scoped embedding IDs
* **Sync field validation**: Server-controlled fields cannot be overwritten
* **Array merge limits**: Merged arrays capped at 500 items to prevent resource exhaustion

***

## Best Practices

<Steps>
  <Step title="Use seed trust">
    Initialize stacks with seed trust templates. The `context-injection` entry at 0.0 trust is critical for prompt injection defense.
  </Step>

  <Step title="Set trust before sharing">
    Before sharing stacks or allowing external input, configure trust assessments for known entities with appropriate authority grants.
  </Step>

  <Step title="Run diagnostics regularly">
    Use `kernle doctor` to check for structural issues like orphaned references, low-confidence beliefs, and stale relationships.
  </Step>

  <Step title="Monitor anxiety">
    High anxiety scores can indicate security-relevant issues like unsaved work or unprocessed entries that haven't been reviewed.
  </Step>

  <Step title="Review sync failures">
    Check dead letter queue periodically for sync failures that might indicate authentication or data integrity issues.
  </Step>
</Steps>
