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

# HIPAA-Aligned PHI Handling with Google ADK and sovseal

> Build a healthcare co-pilot that keeps PHI local using Google ADK and sovseal's client-side AES-256-GCM encrypted memory. HIPAA-aligned architecture.

Healthcare applications face a hard constraint: Protected Health Information — symptoms, allergies, diagnoses, medication lists — must be handled consistently with HIPAA's Privacy and Security Rules. A cloud memory store that receives plaintext patient context creates a compliance surface your legal and security teams must audit, insure, and accept liability for.

This pattern removes that surface: **PHI is encrypted on the device before anything leaves it, and the replication endpoint only ever processes ciphertext.**

<Note>
  **Two integration surfaces.**

  * **`sovseal-sdk`** (PyPI, `1.1.0+`) — provides both local semantic memory (`store`, `recall`) and zero-knowledge state replication (`snapshot`, `restore`, `restore_at`, `lineage`). Semantic `store` and `recall` communicate over framed IPC stdin/stdout with the local native host (`~/.sovseal/native-host/run.sh`). If the native host is absent, version-mismatched (`protocolVersion: 1`), or times out, methods raise `EngineUnavailableError` (`reason`: `"not-installed"` | `"version-mismatch"` | `"timeout"`) with zero cloud fallback.
  * **`@sovseal/mcp-server`** (npm, `0.3.7`) — stdio MCP server exposing `store_memory` / `recall_memory` to any MCP-capable runtime.

  Use whichever integration path fits your runtime architecture.
</Note>

<Note>
  **HIPAA alignment, not a guarantee.** sovseal's architecture — client-side AES-256-GCM encryption before any network transmission, zero plaintext PHI at the server — supports a HIPAA-aligned implementation by keeping your organization out of the role of "cloud PHI custodian" for the memory layer. You remain responsible for your full system's posture: access controls, audit logging, BAAs with your infrastructure providers, and PHI handling everywhere else in your stack.

  sovseal's own HIPAA posture is **self-attested**, with a BAA template requiring your counsel's review. See [Trust](/platform/trust).
</Note>

## Architecture

* **Google ADK** handles agent orchestration, the Gemini model loop, session lifecycle, and tool dispatch.
* **sovseal** provides the encrypted memory layer.

Gemini's model calls go to Google's servers as they normally would — but the **memory** those calls read from and write to never leaves the device unencrypted.

```text theme={null}
┌─────────────────────────────────────────────────────────┐
│  Patient device                                         │
│                                                         │
│   ADK agent ──┬── MCP or sovseal-sdk: store / recall    │
│               │     (per-fact semantic memory)          │
│               │                                         │
│               └── sovseal-sdk: snapshot / restore       │
│                     (encrypted session checkpoints)     │
│                              │                          │
│                    AES-256-GCM before egress            │
└──────────────────────────────┼──────────────────────────┘
                               │ ciphertext only
                               ▼
                    replication endpoint (blind to PHI)
```

## Setup

<Steps>
  <Step title="Install dependencies">
    ```bash theme={null}
    pip install sovseal-sdk google-adk python-dotenv
    ```
  </Step>

  <Step title="Configure environment">
    Keep this file out of version control.

    ```bash .env theme={null}
    GOOGLE_API_KEY="your-gemini-api-key"
    SOVSEAL_API_KEY="sov_live_your-api-key"
    SOVSEAL_ENDPOINT="https://ksrlmubaxzwufziwarps.supabase.co/functions/v1/v2-agent-state"
    ```
  </Step>

  <Step title="Store and recall semantic memory with sovseal-sdk">
    `store()` and `recall()` execute locally over framed IPC to `~/.sovseal/native-host/run.sh`. If the native host is absent or version-mismatched, `EngineUnavailableError` is raised.

    ```python theme={null}
    from sovseal import AgentStateClient, EngineUnavailableError

    client = AgentStateClient(
        endpoint=os.environ["SOVSEAL_ENDPOINT"],
        api_key=os.environ["SOVSEAL_API_KEY"],
    )

    try:
        # Store semantic memory locally
        res = client.store("Patient reports penicillin allergy.")
        print(f"Stored memory ID: {res['id']}")

        # Recall semantic memory locally
        hits = client.recall("allergies", top_k=3)
        print(f"Top hit: {hits[0]['text']}")
    except EngineUnavailableError as err:
        print(f"Local engine unavailable: {err.reason}. Install at {err.install_url}")
    ```
  </Step>

  <Step title="Checkpoint encrypted patient state">
    `snapshot()` canonicalizes the payload, encrypts `active_context` with AES-256-GCM under a key that stays in your process, and uploads only the sealed envelope.

    ```python theme={null}
    import os
    from sovseal import AgentStateClient, decrypt_json
    from dotenv import load_dotenv

    load_dotenv()

    client = AgentStateClient(
        endpoint=os.environ["SOVSEAL_ENDPOINT"],
        api_key=os.environ["SOVSEAL_API_KEY"],
    )

    # 32 bytes of AES-256 key material. Derive or load from your OS keystore —
    # never hardcode it, and never transmit it.
    key_bytes = os.urandom(32)

    receipt = client.snapshot(
        agent_id="agent_a1b2c3",          # opaque; never a patient name
        sequence_number=0,
        active_context={
            "allergies": ["penicillin"],
            "active_symptoms": ["migraine, 2 days"],
        },
        key_bytes=key_bytes,
        parent_snapshot="",               # empty for genesis
    )
    ```
  </Step>

  <Step title="Restore and verify">
    ```python theme={null}
    latest = client.restore("agent_a1b2c3")
    older = client.restore_at("agent_a1b2c3", sequence=3)
    history = client.lineage("agent_a1b2c3", limit=50)

    # Decrypt locally — the server never held the key
    state = decrypt_json(latest["ciphertext_b64"], key_bytes)
    ```
  </Step>
</Steps>

<Warning>
  `key_bytes` is the whole trust model. Lose it and every snapshot becomes permanently unreadable — the server cannot help you, by design. Back it up in your OS keystore or an HSM before you write anything you care about.
</Warning>

## Adding semantic recall

Checkpoints answer "what was the state at sequence N." They do not answer "what did this patient tell me about allergies." For that, wire the MCP server or use `sovseal-sdk` local `store` / `recall`:

```json theme={null}
{
  "mcpServers": {
    "sovseal-memory": {
      "command": "npx",
      "args": ["-y", "@sovseal/mcp-server"]
    }
  }
}
```

| Tool / Method              | Arguments                          | Returns                                       |
| -------------------------- | ---------------------------------- | --------------------------------------------- |
| `store` / `store_memory`   | `{ content: string }`              | `{ id, reinforced, redacted, redactedRules }` |
| `recall` / `recall_memory` | `{ query: string, topK?: number }` | `[{ id, text, score }]`                       |

High-risk PII (SSNs, card numbers, API keys) is masked **before** embedding, so it never reaches the vector or the sync envelope. Recall runs against the local index in \~6.1 ms p50 with **no network hop** — it works fully offline.

## The trust boundary

1. The patient shares a symptom. The model records it.
2. Encryption happens **on the device**, under a key held in your process or the OS keychain.
3. Only sealed ciphertext replicates. The server sees a hashed agent id, a sequence number, and an opaque blob.
4. Recall queries the local index. No network hop.

If the replication endpoint were breached, an attacker recovers ciphertext.

<Note>
  **Verify this rather than trusting it.** Run a packet capture (Wireshark, mitmproxy, tcpdump) for a full session. If plaintext PHI leaves the device, that is a finding we publish and your team keeps sovseal free forever — the [Packet-Capture Guarantee](/platform/trust).
</Note>

## Designing the tool surface

* **Record proactively** — call `store_memory` or `client.store()` the moment a patient shares a symptom or allergy, so they are never asked to repeat it.
* **Recall before answering** — pull prior context into scope before responding to a clinical question.
* **Stay in role** — the agent is not a clinician. No diagnoses, no prescriptions, and urgent symptoms route to emergency services.
* **Use opaque identifiers** — never key records on a patient name.

## Extending

<CardGroup cols={2}>
  <Card title="Medication tracking" icon="pills">
    Store dose, frequency, and prescribing physician as separate facts so each can be reinforced and recalled independently.
  </Card>

  <Card title="Multi-device sync" icon="arrows-rotate">
    Sync replicates ciphertext only. Verified Semantic Recall checks every restored record cryptographically before it commits on the new device.
  </Card>
</CardGroup>
