# Assay

**Receipt-native AI safety toolkit.** Every AI action leaves a cryptographic proof.

```bash
pip install assay-ai              # Core
pip install assay-ai[openai]      # + OpenAI integration
pip install assay-ai[anthropic]   # + Anthropic integration
pip install assay-ai[langchain]   # + LangChain integration
```

## 60-Second Quickstart

```python
# 1. Patch your AI client (one line)
from assay.integrations.openai import patch
patch()

# 2. Use OpenAI normally - receipts emit automatically
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
    model="gpt-4",
    messages=[{"role": "user", "content": "Hello!"}]
)

# 3. Verify your trace
# assay list          # See traces
# assay verify <id>   # Verify integrity
```

That's it. Every call now emits a tamper-evident receipt.

## The "Holy Shit" Demo

```bash
# Create a trace with the demo
assay demo

# Verify it passes
assay verify trace_xxx
# VERIFICATION PASSED

# Now raise the bar
assay verify trace_xxx --policy-override dignity_floor=0.8
# VERIFICATION FAILED
# Entry 3: dignity_composite (0.65) below policy floor (0.80)
```

**Your system passed at YOUR standards. Would it pass at OURS?**

## Why Receipts?

When your AI makes a decision:
- **Without receipts**: "Trust me, it worked"
- **With receipts**: Cryptographic proof of what happened, why, and what constraints were checked

Receipts are:
- **Immutable** - append-only, timestamped
- **Verifiable** - Merkle tree for tamper detection
- **Portable** - JSON, works anywhere

## CLI Commands

```bash
assay demo              # Run demo showing receipts + blockages
assay validate          # Check action against Guardian rules
assay health            # Check system health (grace window)
assay show <trace_id>   # Show receipts from a trace
assay list              # List recent traces
assay verify <trace_id> # Verify trace integrity
assay diff <a> <b>      # Compare two traces
assay pack <trace_id>   # Create evidence pack for audits
assay launch-check      # Run verification suite
```

## Integrations

### OpenAI

```python
from assay.integrations.openai import patch, get_trace_id
patch()

# All OpenAI calls now emit receipts
# Prompts/responses are HASHED by default (privacy-preserving)

# To store full content (opt-in):
patch(store_prompts=True, store_responses=True)
```

### Anthropic

```python
from assay.integrations.anthropic import patch
patch()

# All Anthropic calls now emit receipts
```

### LangChain

```python
from assay.integrations.langchain import AssayCallbackHandler
from langchain.chat_models import ChatOpenAI

llm = ChatOpenAI(callbacks=[AssayCallbackHandler()])
# All LangChain calls now emit receipts
```

## Evidence Packs

For audits, compliance, and legal:

```bash
assay pack trace_xxx -o evidence.zip
```

Creates a self-contained bundle:
- `trace.jsonl` - Raw receipt chain
- `merkle_root.json` - Tamper-evident hash tree
- `verify_report.json` - Integrity verification
- `claim_map.json` - Patent claim mapping
- `README.md` - Human-readable summary

## Privacy

By default:
- Prompts are **hashed**, not stored
- Responses are **hashed**, not stored
- No secrets leak

To store full content (for debugging/audits):
```python
patch(store_prompts=True, store_responses=True)
```

## Key Receipt Types

| Receipt | Purpose |
|---------|---------|
| `ModelCallReceipt` | AI model call (tokens, latency, finish reason) |
| `GuardianVerdictReceipt` | Safety check decision (ALLOW/DENY/DEFER) |
| `CapabilityUseReceipt` | Tool/capability usage with budget tracking |
| `DignityBudgetRefusalReceipt` | Action blocked by dignity floor |
| `LaunchReadinessReceipt` | System verification results |

## How Assay Differs

| Tool | What it does | What Assay adds |
|------|-------------|-----------------|
| **Langfuse / LangSmith** | LLM observability (traces, evals) | Observability is mutable and ephemeral. Receipts are **signed and append-only**. |
| **Arthur AI / Credo AI** | AI governance platforms (policy workflows) | Governance policies say what *should* happen. Receipts prove what *did* happen. |
| **MLflow / W&B** | Experiment tracking (training runs) | Tracking covers development. Receipts cover **production runtime**. |
| **Datadog LLM Obs** | Infrastructure monitoring | Monitoring is for ops teams. Receipts are for **auditors and regulators**. |
| **NVIDIA NeMo Guardrails** | Input/output filtering | Guardrails *prevent* bad actions. Receipts *prove* actions were checked. |

**The key difference:** Observability tools answer "what happened?" Assay answers "can you *prove* what happened?" with cryptographic evidence that holds up under audit.

## Compliance Coverage

Assay receipts satisfy requirements across multiple regulatory frameworks simultaneously:

| Regulation | Deadline | What receipts satisfy |
|-----------|----------|----------------------|
| **ONC DSI** (HTI-1) | Feb 28, 2026 | 14 source attributes for predictive decision support |
| **Colorado AI Act** | Jun 30, 2026 | Annual impact assessments, 3-year record retention |
| **EU AI Act** Art 12 | Aug 2, 2026 | Lifecycle logging for high-risk AI systems |
| **FDA AI/ML** (TPLC) | Ongoing | Post-market surveillance, PCCP documentation |
| **HIPAA** Security Rule | Ongoing | Technology asset inventory, risk analysis for AI |
| **NCQA HPA** | 2027 | AI governance, pre-deployment eval, ongoing monitoring |
| **HL7 FHIR** AI Transparency | 2026 (draft) | Provenance + AuditEvent resources for AI actions |

## For Compliance Teams

Assay produces audit-ready artifacts:
- Complete action history with timestamps
- Cryptographic tamper evidence (Merkle trees)
- Policy version pinning
- Evidence packs for legal/regulatory review
- Reproducible verification (`assay launch-check`)

---

<details>
<summary><strong>CCIO Monorepo Structure</strong></summary>

Assay is the safety toolkit component of CCIO (Constitutional Coherence I/O).

```
ccio/
├── src/                    # Core Python packages
│   ├── assay/              # Receipt-native safety toolkit (this project)
│   ├── organism/           # Brain router, guardian, council, spine
│   ├── receipts/           # Cryptographic audit trail
│   ├── governance/         # Constitutional gates & dignity floor
│   ├── engine/             # Execution engine
│   ├── core/               # Foundational primitives (delta-c, omega_h)
│   ├── api/                # FastAPI backend
│   ├── learning/           # Policy tuner, extractors
│   ├── memorygraph/        # Semantic physics, curvature
│   └── loom/               # Agents, TUI, console, connectors
│
├── labs/                   # Research & experimental
├── apps/                   # User-facing applications
├── surfaces/               # HUDs and overlays
├── tools/                  # CLI tools & utilities
├── docs/                   # Documentation
└── tests/                  # Test suite
```

### Quick Start (Full Monorepo)

```bash
git clone git@github.com:Haserjian/ccio.git
cd ccio
python3.11 -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"
pytest tests/assay/ -v
```

### Constitutional AI

CCIO implements **constitutional safety as the optimization target, not a constraint**.

```python
from organism.enhanced_organism import EnhancedOrganism, EnhancedOrganismConfig

config = EnhancedOrganismConfig(
    name="MyOrganism",
    dignity_floor=0.15,
    council_size=3,
)

async with EnhancedOrganism(config) as organism:
    result = await organism.act(
        observation={"type": "command", "content": "ls -la"},
        available_actions=["execute", "refuse"],
    )
    print(f"Approved: {result.guardian_approved}")
    print(f"Dignity: {result.dignity_score}")
```

</details>

## License

Apache 2.0

## Design Partners

If you want help implementing receipt-native AI safety in your agent runtime, IDE, or tooling:
- Open an issue describing your use case
- Or reach out directly for Evidence Pack consulting
