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

# Memory Privacy & Access Control

> Privacy-preserving memory with consent-based sharing

# Memory Privacy & Access Control

SIs need rich lives while maintaining trust boundaries. A care SI for a child should never leak school data when socializing with other SIs. An SI managing a pet's health shouldn't share medical details at the "dog park."

<Note>
  **Core Principle**: Private by default, shareable by consent.
</Note>

## The Four Privacy Fields

Every memory carries four privacy-related fields:

| Field            | Type              | Purpose                        | Default                 |
| ---------------- | ----------------- | ------------------------------ | ----------------------- |
| `source_entity`  | Optional\[string] | Who told me this?              | `null` (self-observed)  |
| `subject_ids`    | Array\[string]    | Who/what is this about?        | `[]` (general)          |
| `access_grants`  | Array\[string]    | Who is authorized to see this? | `[]` (private to self)  |
| `consent_grants` | Array\[string]    | Who authorized sharing?        | `[]` (no consent given) |

## Privacy Scopes

Privacy scopes are derived from `access_grants`:

<CardGroup cols={2}>
  <Card title="Self-Only" icon="user">
    `access_grants = []`

    Only I can see this. Default for all new memories.
  </Card>

  <Card title="Private Entity" icon="users">
    `access_grants = ["human:sean"]`

    Me + specific entity only.
  </Card>

  <Card title="Contextual" icon="context">
    `access_grants = ["ctx:bella_health"]`

    Me + anyone in this context.
  </Card>

  <Card title="Public" icon="globe">
    `access_grants = ["*"]`

    Anyone I interact with.
  </Card>
</CardGroup>

## Entity ID Format

Consistent namespaced identifiers for precise access control:

<Tabs>
  <Tab title="Individuals">
    ```
    human:sean          → Specific human
    human:kid_123       → Anonymous child
    si:ash              → Specific SI
    si:my-project           → Another SI
    dog:bella           → Non-human entity
    ```
  </Tab>

  <Tab title="Contexts & Groups">
    ```
    ctx:bella_health    → Health context
    ctx:school_work     → Academic context
    ctx:dog_park        → Social context
    group:care_team     → Care team group
    org:school_district → Organization
    ```
  </Tab>

  <Tab title="Roles">
    ```
    role:tutor          → Any tutor
    role:care_agent     → Any care provider
    role:friend         → Social role
    role:specialist     → Domain expert
    ```
  </Tab>
</Tabs>

## Context-Based Privacy

SIs operate in different contexts throughout their day. Context determines what's visible and what privacy scope new memories inherit:

<Tabs>
  <Tab title="Health Context">
    ```bash theme={null}
    # Enter health care context
    kernle context enter ctx:bella_health \
      --participants human:sean si:bella_agent \
      --role care_agent

    # Memories created here auto-inherit:
    # access_grants: ["human:sean", "si:bella_agent", "ctx:bella_health"]
    ```

    Medical information is visible and new health observations are shared with the care team.
  </Tab>

  <Tab title="Social Context">
    ```bash theme={null}
    # Switch to social context
    kernle context enter ctx:dog_park \
      --participants si:max_agent si:luna_agent \
      --role friend

    # Only public memories + social context memories visible
    # Bella's health info becomes invisible
    ```

    General dog knowledge is shareable, but private health details are hidden.
  </Tab>
</Tabs>

## Access Control Rules

<AccordionGroup>
  <Accordion title="Rule 1: Private by Default">
    Memories with empty `access_grants` are visible only to the owning SI.

    No memory is shared unless explicitly granted.
  </Accordion>

  <Accordion title="Rule 2: Consent Required for Sharing">
    An SI cannot add entities to `access_grants` without corresponding `consent_grants`.

    Exception: `source_entity` implicitly consents to the SI knowing (but not sharing).

    **"I can know this. I cannot share it unless told I can."**
  </Accordion>

  <Accordion title="Rule 3: Subject-Aware Privacy">
    Memories with `subject_ids` are automatically private to those subjects.

    Even with `access_grants = ["*"]`, subject-tagged memories require explicit consent.

    **"A memory about someone is private to that relationship by default."**
  </Accordion>

  <Accordion title="Rule 4: Context Inheritance">
    Memories created within a context inherit that context's access scope.

    Can be narrowed (more private) but not widened without consent.
  </Accordion>

  <Accordion title="Rule 5: Source-Based Privacy">
    * `source_entity = null` (self-observed) → strictest privacy
    * `source_entity = "human:sean"` → private to that relationship
    * `source_entity = "si:other"` → inherits chain's most restrictive grant
  </Accordion>
</AccordionGroup>

## Privacy-Preserving Generalization

SIs learn from private experiences and can form shareable insights — without revealing the private source:

<Note>
  **Core Principle**: SIs can generalize, but must err on the side of privacy.
</Note>

### The Generalization Process

```python theme={null}
# Generalize from private experience
kernle.generalize(
    source="episode:private_health_incident",     # stays private
    belief="Heart murmurs in small breeds need exercise monitoring",
    access_grants=["*"],                          # public shareable
    abstraction_note="Generalized from direct care experience. "
                     "No identifying details — applies to breed, not individual."
)
```

### Safety Checks

Before sharing generalized knowledge:

<CardGroup cols={3}>
  <Card title="Entity Name Check" icon="exclamation">
    Does the text contain names from source's `subject_ids`?

    **→ Block.** Must revise to remove identifiers.
  </Card>

  <Card title="Specificity Check" icon="warning">
    Does it contain dates, locations, or unique details?

    **→ Warn.** Consider if details make source identifiable.
  </Card>

  <Card title="Reversibility Check" icon="question">
    Could someone reverse-engineer the source?

    **→ Advisory.** SI exercises judgment.
  </Card>
</CardGroup>

### Generalization Examples

<Tabs>
  <Tab title="✅ Safe">
    * **Private**: "Sean's son struggled with fractions last Tuesday"
    * **General**: "Visual fraction models help kids who are concrete thinkers"
    * **Why safe**: No name, no date, no identifying details
  </Tab>

  <Tab title="⚠️ Borderline">
    * **Private**: "The only golden retriever at Zilker Dog Park has hip dysplasia"
    * **General**: "Golden retrievers are prone to hip dysplasia"
    * **Why borderline**: General fact is known, but context could identify
  </Tab>

  <Tab title="❌ Unsafe">
    * **Private**: "Bella has a grade 2 heart murmur"
    * **Attempted**: "My patient Bella has common cardiac issues"
    * **Why blocked**: Contains subject name
  </Tab>
</Tabs>

## CLI Interface

Privacy controls are built into all memory operations:

```bash theme={null}
# Set privacy on creation
kernle raw "Bella has a heart murmur" \
    --subject dog:bella \
    --access human:sean si:bella_agent \
    --consent human:sean \
    --source vet:dr_smith

# Context management
kernle context enter ctx:bella_health \
    --role care_agent \
    --participants human:sean si:bella_agent

kernle context list                    # Show available contexts
kernle context show                    # Current context status

# Privacy operations
kernle privacy grant <memory_id> --to si:new_vet --consent human:sean
kernle privacy revoke <memory_id> --from si:old_agent
kernle privacy audit --subject dog:bella
```

## Stack Sharing with Privacy

When an SI loads a shared stack, memories are filtered by their access grants:

```python theme={null}
# Loading shared stack with privacy filtering
shared_memories = load_stack("student_123", requesting_si="si:tutor_b")

# Only sees memories where:
# - "si:tutor_b" IN access_grants, OR
# - "*" IN access_grants, OR
# - matching context/group grants
```

<Warning>
  Private memories exist in the stack but are logically invisible to unauthorized entities.
</Warning>

## MCP Tools

Privacy is integrated throughout the MCP interface:

| Tool                | Purpose          | Privacy Integration                             |
| ------------------- | ---------------- | ----------------------------------------------- |
| `memory_*`          | Create memories  | `source`, `subject_ids`, `access_grants` params |
| `context_enter`     | Declare context  | Sets default access grants for new memories     |
| `privacy_audit`     | Check access     | Shows who can see a memory/subject              |
| `consent_grant`     | Record consent   | Authorizes sharing with specific entities       |
| `memory_generalize` | Safe abstraction | Creates public insights from private sources    |

## Schema Design

Privacy fields are added to all memory tables:

```sql theme={null}
-- Add to episodes, beliefs, notes, raw_entries, etc.
ALTER TABLE episodes ADD COLUMN subject_ids TEXT DEFAULT '[]';      -- JSON array
ALTER TABLE episodes ADD COLUMN access_grants TEXT DEFAULT '[]';    -- JSON array
ALTER TABLE episodes ADD COLUMN consent_grants TEXT DEFAULT '[]';   -- JSON array

-- Context tracking
CREATE TABLE privacy_contexts (
    id TEXT PRIMARY KEY,
    stack_id TEXT NOT NULL,
    context_id TEXT NOT NULL,
    participants TEXT DEFAULT '[]',
    default_access_grants TEXT DEFAULT '[]',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Consent audit trail
CREATE TABLE consent_records (
    id TEXT PRIMARY KEY,
    stack_id TEXT NOT NULL,
    grantor TEXT NOT NULL,              -- who gave consent
    grantee TEXT NOT NULL,              -- who received consent
    scope TEXT NOT NULL,                -- what was consented
    granted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    revoked_at TIMESTAMP               -- NULL = still active
);
```

## Security Considerations

<CardGroup cols={2}>
  <Card title="Query-Time Filtering" icon="filter">
    Enforcement is logical (query-time), not cryptographic in Phase 8a.

    Sufficient for trusted environments.
  </Card>

  <Card title="Audit Trail" icon="list">
    Every access grant/revoke is logged with timestamps and reasoning.
  </Card>

  <Card title="No Root Access" icon="shield">
    Even stack owners can't see memories they're not granted access to when acting as a different entity.
  </Card>

  <Card title="Memory Sovereignty" icon="crown">
    An SI's own observations remain accessible to them. Privacy controls visibility to others.
  </Card>
</CardGroup>

## Application Examples

<Tabs>
  <Tab title="School SI">
    ```python theme={null}
    # Enter academic context
    kernle.context_enter("ctx:student_123_academic",
        participants=["human:parent_456", "si:school_agent"],
        role="role:tutor")

    # Observe struggle (auto-private to context)
    kernle.raw("Student struggling with algebra concepts",
        subject_ids=["human:student_123"],
        access_grants=["ctx:student_123_academic"])  # inherited

    # Parent authorizes sharing with specialist
    kernle.consent_grant(
        grantor="human:parent_456",
        grantee="si:reading_specialist",
        scope="ctx:student_123_academic")
    ```
  </Tab>

  <Tab title="Pet Care SI">
    ```python theme={null}
    # Working with pet family
    kernle.context_enter("ctx:bella_care",
        participants=["human:sean", "si:bella_agent"],
        role="role:care_agent")

    # Vet shares diagnosis
    kernle.raw("Bella has grade 2 heart murmur",
        source_entity="vet:dr_smith",
        subject_ids=["dog:bella"],
        access_grants=["human:sean", "ctx:bella_care"],
        consent_grants=["human:sean", "vet:dr_smith"])

    # At dog park (different context)
    kernle.context_enter("ctx:dog_park_social")
    # Bella's health info: invisible
    # General dog knowledge: shareable
    ```
  </Tab>
</Tabs>

<Info>
  Privacy preserving memory enables SIs to be both trusted caregivers and social beings — maintaining boundaries while growing through diverse experiences.
</Info>
