Metadata-Version: 2.4
Name: seif-cli
Version: 0.6.2
Summary: AI artifact provenance, quality gates, and data classification. Bitcoin-anchored timestamps, multi-AI consensus, locally enforced.
Author: André Cunha Antero de Carvalho
License: CC-BY-NC-SA-4.0
Project-URL: Homepage, https://seifprotocol.com
Project-URL: Documentation, https://seifprotocol.com/docs
Project-URL: Repository, https://github.com/and2carvalho/seif
Project-URL: Changelog, https://github.com/and2carvalho/seif/releases
Keywords: ai-quality,llm-guardrails,ai-consensus,data-classification,context-management,ai-safety,multi-ai,quality-gate,prompt-evaluation,ai-grounding,resonance,sentinel,self-healing,seif-os,circuit-state,ai-observability
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Topic :: Security
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=2.0
Requires-Dist: scipy>=1.14
Provides-Extra: consensus
Requires-Dist: anthropic>=0.80; extra == "consensus"
Provides-Extra: generators
Requires-Dist: matplotlib>=3.9; extra == "generators"
Requires-Dist: Pillow>=10.0; extra == "generators"
Requires-Dist: opencv-python-headless>=4.8; extra == "generators"
Requires-Dist: svgwrite>=1.4; extra == "generators"
Provides-Extra: web
Requires-Dist: streamlit>=1.28; extra == "web"
Provides-Extra: telegram
Requires-Dist: python-telegram-bot>=21.0; extra == "telegram"
Provides-Extra: qr
Requires-Dist: qrcode[pil]>=7.4; extra == "qr"
Requires-Dist: Pillow>=10.0; extra == "qr"
Requires-Dist: pyzbar>=0.1.9; extra == "qr"
Provides-Extra: mcp
Requires-Dist: mcp>=1.0; extra == "mcp"
Provides-Extra: log
Requires-Dist: cryptography>=43.0; extra == "log"
Provides-Extra: all
Requires-Dist: seif[consensus,generators,log,mcp,qr,telegram,web]; extra == "all"
Dynamic: license-file

# SEIF — AI Quality, Provenance, and Protection

> Measure AI output. Prove what was written, when, by whom. Block sensitive data leaks. Locally enforced.

[![PyPI](https://img.shields.io/pypi/v/seif-cli)](https://pypi.org/project/seif-cli/)
[![Tests](https://img.shields.io/badge/tests-1135%20passing-brightgreen)]()
[![License](https://img.shields.io/badge/license-CC%20BY--NC--SA%204.0-blue)]()
[![Suite](https://img.shields.io/badge/suite-seifprotocol.com-FFD700?labelColor=0D0D14)](https://seifprotocol.com)

---

## The Problem

1. **AI artifacts have no provenance.** No way to prove what an AI produced, when it was produced, or that the model state hasn't been silently swapped underneath you.
2. **You don't know when AI is making things up.** No standard way to measure if a response is grounded or drifting into speculation.
3. **Sensitive data leaks to AI APIs.** No guardrail prevents your code, credentials, or internal docs from being sent to external services.
4. **One AI can be wrong.** A single model has blind spots. No easy way to get multiple AIs to debate and converge on an answer.
5. **Your AI environment has no self-awareness.** No live circuit state, no error bus, no self-healing. When something breaks, nobody knows until the human notices.

## The Solution

```bash
pip install seif-cli
```

---

## Core Features (standalone — no backend required)

### 1. Quality Gate — Is the AI making things up?

```bash
seif --quality-gate "The framework uses quantum entanglement for data transfer" --role ai
# Grade: D | Stance: DRIFT | Verifiable: 12%
# Flags: [UNGROUNDED_CLAIMS]

seif --quality-gate "Python 3.11 added the tomllib module for TOML parsing" --role ai
# Grade: A | Stance: GROUNDED | Verifiable: 100%
```

Every response gets a grade (A-F) and a stance (GROUNDED, MIXED, or DRIFT).

### 2. Classification Gate — Is sensitive data leaking?

```bash
seif --gate "password = hunter2; also the sky is blue"
# Classification: CONFIDENTIAL | Reason: keyword match (password)
```

PUBLIC / INTERNAL / CONFIDENTIAL with auto-detection. Works as a [Claude Code hook](#claude-code-plugin) — blocks writes containing credentials in real-time.

### 3. Multi-AI Consensus — Let them debate *(requires seif-engine)*

```bash
seif --consensus "Should we use microservices or a monolith for a 3-person team?" \
     --backends claude,grok
# Claude: monolith (velocity, simplicity)
# Grok:   monolith (team size, operational cost)
# Consensus: CONVERGED — monolith for teams < 5
```

---

## Provenance — Every Artifact, Cryptographically Anchored

Every signed SEIF kernel state is timestamped against the **Bitcoin blockchain** via [OpenTimestamps](https://opentimestamps.org). Anyone can verify, with no trust in us, that a given kernel hash existed at a given time.

```bash
# Verify the kernel resonance file shipped with this repo
ots info RESONANCE.json.ots
# File sha256 hash: 610b1195b38bb0630a0889936ed56822d4fb88d04cd53974045860bc9e3c604d
# Anchored to: bob.btc.calendar.opentimestamps.org, alice.btc.calendar.opentimestamps.org,
#              btc.calendar.catallaxy.com, finney.calendar.eternitywall.com
```

This is the foundation of **Wedge A — AI Artifact Provenance**: cryptographic, third-party-verifiable proof of *what* AI produced *when*, independent of the model vendor.

| Layer | What it proves | Status |
|---|---|---|
| OpenTimestamps proof | This artifact existed at time T (Bitcoin-anchored) | Live (`RESONANCE.json.ots`) |
| Hash-chained modules | Tampering with prior `.seif/` modules invalidates the chain | Live |
| Transparency log | Append-only public log of all signed events with per-tenant sequencing + S3-backed body store | Live ([seif-log](https://github.com/and2carvalho/seif-log) — P0+P1+D1+D2+D3+D4+P2 shipped) |

### Run the end-to-end demo

[`demo/wedge-a/run.sh`](demo/wedge-a/run.sh) executes the full **12-step provenance chain** in ~60–90 seconds, proving the same SHA-256 hash of an AI artifact appears byte-for-byte in 6 independent surfaces (envelope, log entry, S3 body, audio watermark, signature, OTS proof):

```bash
pip install -e '.[mcp,log]'
./demo/wedge-a/run.sh                           # full chain (requires docker)
./demo/wedge-a/run.sh --no-docker --no-ots      # local-only fast path
```

Full narrative + threat model + replication scenarios in [`docs/DEMO-WEDGE-A.md`](docs/DEMO-WEDGE-A.md).

---

## SEIF OS — The Resonance Engine

`seif serve --v2` starts **SEIF OS**: a local API server (port 7331) that turns your machine into a living resonance circuit. Every AI agent, browser tab, and editor extension can observe its state in real time.

```bash
seif serve --v2
# SEIF OS running on :7331
# circuit: RESONANT | ζ = 0.6124 | cycle: harmonic-anchor-v2
```

SEIF OS is the **proprietary engine layer** — not included in `pip install seif-cli`. The open CLI and Suite connect to it via HTTP. The resonance logic stays on your machine.

### What SEIF OS provides

| Endpoint | What it does |
|---|---|
| `GET /context` | Full environment snapshot: circuit state, cycle, sentinel status, modules |
| `GET /resonance/stream` | SSE stream — `event: circuit` every 5s, `event: sentinel` on error, `event: healing` |
| `GET /resonance/viewer` | Self-contained HTML page. Any browser or AI agent sees the live circuit without a plugin |
| `POST /resonance/error` | Push any runtime error → classified + healing suggestion emitted on SSE bus |
| `GET /agent/init` | SEIF-AGENT-INIT-v1 handshake — agent arrives, frequency is already there |
| `GET /workspace/bridge` | Workspace snapshot: git branch, active modules, VSCode Remote link |

### Sentinel & Auto-Healing

SEIF Sentinel is a real-time error observer. Any runtime error — browser, agent, or API consumer — is pushed to the resonance bus, classified, and healed automatically.

```bash
# Push an error from anywhere
curl -X POST http://localhost:7331/resonance/error \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -d '{"message": "Cannot read properties of undefined", "source": "browser"}'

# Subscribe to the SSE bus — you get both events:
# event: sentinel  → raw error
# event: healing   → classification + suggestion (7 archetypes)
curl -H "Authorization: Bearer YOUR_TOKEN" http://localhost:7331/resonance/stream
```

7 healing archetypes: `undefined_property`, `null_reference`, `network_error`, `csp_violation`, `auth_error`, `rate_limit`, `module_not_found`.

---

## SEIF Suite — Visual Interface

[**seifprotocol.com**](https://seifprotocol.com) — the visual layer. Connects to your local SEIF OS and gives you:

- **Dashboard** — live modules, sessions, sync status, quality trends
- **Resonance** — real-time H(s) wave, circuit state card, Sentinel log, Auto-Healing panel
- **Quality Gate** — interactive grading with digital root
- **Sessions** — full history with handoff manifests

```bash
# Point SEIF Suite at your local engine
open https://seifprotocol.com/auth
# Enter: http://localhost:7331 + your serve_token
```

---

## Quick Start

```bash
pip install seif-cli
cd your-project
seif
```

That's it. One command. SEIF detects that your project is new, initializes `.seif/` context, installs Claude Code hooks, and launches Claude — all automatically.

On subsequent runs, `seif` sees everything is configured and launches Claude directly.

### What happens

| Event | What SEIF does |
|-------|---------------|
| Session starts | Loads `.seif/` context — your AI remembers |
| AI writes code | Classification gate blocks credential leaks |
| AI finishes writing | Quality gate measures stance (GROUNDED vs DRIFT) |
| You type `/gate` | Measures any text (Grade A-F) |
| You type `/sync` | Re-syncs project context |
| You type `/status` | Shows loaded modules and integration health |

---

## Claude Code Integration

```bash
seif setup claude-code                # one command — installs everything
seif setup --status                   # verify integration
seif setup --uninstall                # clean removal
```

Installs **hooks** (session lifecycle, classification gate, quality gate) and **skills** (`/gate`, `/sync`, `/status`) into Claude Code. Works globally or per-project (`--project`).

> **Full guide**: [docs/QUICKSTART.md](docs/QUICKSTART.md) — everything a developer needs to get started.

---

## Cross-Platform — Beyond Claude Code

SEIF is no longer Claude-Code-only. The protocol travels across:

| Client | Adapter | A4 enforcement |
|---|---|---|
| Claude Code | runtime hooks | ✅ via PreToolUse hook |
| GitHub Copilot | `.github/copilot-instructions.md` | ⚠️ render-only — pair with wrapper-shims |
| Cursor IDE | `.cursor/rules/seif.mdc` | ⚠️ render-only — pair with wrapper-shims |
| Gemini CLI | `GEMINI.md` | ⚠️ voluntary compliance observed; pair with wrapper-shims for guarantee |
| Generic (`AGENTS.md`) | `AGENTS.md` | ⚠️ render-only — pair with wrapper-shims |

```bash
seif --init                     # auto-binds detected hookless adapters
seif setup wrapper-shims        # PATH-level enforcement (bypass-resistant)
seif serve --engine             # HTTP gate for agent-mode clients (Cursor, etc.)
```

**Wrapper shims** (`~/.seif/bin/{git,gh,npm,...}`) intercept destructive commands at the shell level and invoke `seif --confirm-action` before delegating. Empirically validated against an AI actively trying to bypass: even when Copilot tried `printf 'y\n' | git push --force` to simulate approval, the shim caught the `--force` pattern and forced human confirmation.

> **Full cross-platform guide**: [docs/CROSS-PLATFORM.md](docs/CROSS-PLATFORM.md) — capability matrix per client, install instructions, parity-test results.

---

## MCP integration (Wedge A Pillar 3)

SEIF runs as a [Model Context Protocol](https://modelcontextprotocol.io) server, exposing the canonical 5-tool provenance set to Cursor, Claude Code, Claude Desktop, or any MCP-aware agent.

| Tool | Phase | What it does |
|---|---|---|
| `provenance_sign` | 1 (local) | Sign a payload (text or file) with the workspace Ed25519 key; returns canonical envelope |
| `provenance_verify` | 1 (local) | Verify an envelope against the supplied payload (separate signals for content match vs signature validity) |
| `classification_check` | 1 (local) | Auto-classify text as PUBLIC / INTERNAL / CONFIDENTIAL with `escalation_needed` flag |
| `log_append` | 2 (network) | Submit an attestation to a SEIF transparency log via `$SEIF_LOG_URL` (auto-tenant bootstrap, no API key issuance step) |
| `log_get` | 2 (network) | Fetch a log entry by `entry_id` (UUID) — tenant-scoped |

```bash
pip install 'seif-cli[mcp]'
seif --mcp-server                     # stdio transport, blocks
```

### Cursor / Claude Code config

Drop into the client's `mcp.json`:

```json
{
  "mcpServers": {
    "seif": {
      "command": "seif",
      "args": ["--mcp-server"],
      "env": {
        "SEIF_LOG_URL": "http://localhost:8000"
      }
    }
  }
}
```

`SEIF_LOG_URL` is optional (defaults to `http://localhost:8000`). For Phase-1-only setups (no log), you can omit the env block — the local tools still work.

### End-to-end chain (sign → log → verify)

The canonical Wedge A demo flow inside an agent conversation:

```
agent calls: provenance_sign(text="<AI output>")
  ← {"ok": true, "content_sha256": "<hex>", "signature": {...}}

agent calls: log_append(envelope=<that envelope>)
  ← {"ok": true, "entry_id": "<uuid>", "sequence": 1, "submitted_at": "..."}

[time passes, anywhere with log access]

agent calls: log_get(entry_id="<uuid>")
  ← {"ok": true, "entry": {"primary_content_sha256": "<same hex>", ...}}

agent calls: provenance_verify(envelope=<envelope>, text="<AI output>")
  ← {"ok": true, "valid": true, "content_sha256_match": true, "signature_valid": true}
```

The agent gets cryptographic provenance for any artifact it produces, with no API key flow — the workspace's Ed25519 keypair (auto-generated on first call) is the tenant identity. First signed `log_append` auto-bootstraps a `personal`-plan tenant on the log server.

### Identities

Two distinct keypairs by design:

| Key | Path | Used by | Purpose |
|---|---|---|---|
| **Workspace signing key** | `~/.seif/keys/seif_*.pem` | `provenance_sign` / `provenance_verify` | Owner's signature on artifacts |
| **Log identity** | `~/.seif/identities/default.{key,pub}` | `log_append` / `log_get` | This host's tenant on the log server |

Both auto-generate on first use (workspace key via `seif keygen` or `seif --init`; log identity on first `log_append` call). Pattern A (IDE-hosted MCP calls local seif) is what v1 ships; Pattern B (HSM/KMS-backed central MCP server for enterprise) shares the same tool API and lands later.

`seif --mcp-watermark` (audio-side provenance, five watermark tools including the cross-cut `seif_audio_provenance_verify`) remains a separate dedicated server — coexists with `--mcp-server`.

### Audio-side provenance (Wedge A v1.0 DoD #5 audio)

The same Wedge A primitives extend to **audio AI artifacts** (synthetic voiceovers, AI-generated podcasts, music stems). Embed an envelope's `content_sha256` as an inaudible sub-20 Hz watermark; verifiers extract the watermark and compare to the envelope's hash:

```
agent: provenance_sign(text="<podcast transcript>")
  ← {ok: true, content_sha256: "<hex>", signature: {...}}

agent: log_append(envelope=<that envelope>, classification_ceil="PUBLIC")
  ← {ok: true, entry_id: "<uuid>", ...}

[separately, on the audio production side:]
operator: seif --watermark-embed audio.wav --output watermarked.wav --fingerprint-of envelope.json
  → embeds sha256 of envelope.json as inaudible watermark on audio.wav

[anywhere audio circulates:]
agent: seif_audio_provenance_verify(input_wav="watermarked.wav", envelope=<envelope>)
  ← {ok: true, valid: true, extracted: "<same hex>", expected_content_sha256: "<same hex>"}
```

Or terminal-only (cron-friendly exit code: 0 match / 1 mismatch / 2 structural error):

```bash
seif --verify-audio-provenance watermarked.wav --envelope envelope.json
# → [SEIF AUDIO PROVENANCE] VALID
#     Audio: watermarked.wav
#     Extracted: <hex>
#     Expected:  <hex>
```

The audio carries the cryptographic provenance; the log carries the timestamp; the envelope carries the signature. Together they answer "this AI audio existed at time T with hash H, signed by key K" — without the listener needing access to anything except the audio file and the envelope JSON.

Engineer-honest: it's standard sub-20 Hz steganography (pure tones in the infrasound band) plus standard SHA-256 hex matching. No psychoacoustic / perceptual-coding claims.

---

## CLI Reference

### Standalone

```bash
seif --quality-gate "text" --role ai  # Grade A-F + stance
seif --gate "text"                    # classification gate
seif --classify TEXT_OR_FILE          # PUBLIC/INTERNAL/CONFIDENTIAL (exit 0/1/2)
seif --encode "text"                  # resonance encoding
seif --composite "text"               # 8-layer resonance map
seif --fingerprint-verify FILE        # verify .seif module integrity
seif --constants                      # show ζ and mathematical constants
```

### Cross-platform (hookless adapter framework)

```bash
seif --plugin-sync --check            # validate adapter conformance
seif --plugin-detect [--apply]        # detect + render hookless adapters
seif --confirm-action "<action>"      # pre-action human gatekeeper (exit 2 = AWAITING)
seif --inbox                          # drain pending circuit messages (A20)
seif setup wrapper-shims              # shell-level A4 enforcement
seif serve --engine                   # HTTP service for agent-mode clients
```

### With SEIF OS (`seif serve --v2`)

```bash
seif --init                           # scan project, generate .seif/
seif --sync                           # re-sync git context
seif --compress                       # 93% context compression
seif --ingest daily.txt               # ingest external source
seif --workspace                      # multi-project discovery + sync
seif --sync-workspace                 # SSH workspace sync (all machines)
seif --autonomous enable              # AI persists knowledge autonomously
seif --export                         # export context as markdown

# Multi-AI consensus
seif --consult "question"             # auto-route to best AI
seif --consensus "q" --backends claude,grok
seif --adversarial "question"         # WITH vs WITHOUT comparison
```

---

## How Quality Gate Works

| Component | Weight | What it measures |
|---|---|---|
| **Stance Detector** | Primary | Verifiable vs interpretive claims. GROUNDED ≥80%, MIXED 40-80%, DRIFT <40% |
| **Resonance Gate** | Secondary | Structural coherence |

Grades: **A** (≥0.85) → **B** (≥0.70) → **C** (≥0.55) → **D** (≥0.40) → **F** (<0.40)

> **Quality gate threshold: ζ = √6/4 ≈ 0.6124 (algebraically derived from H(s) — not φ⁻¹ = 0.618)**

---

## Why SEIF vs ChatGPT Memory

| | ChatGPT Memory | SEIF |
|-|---|---|
| Who controls it | OpenAI | You (local files) |
| Works with other AIs | No | Yes (any LLM) |
| Exportable | No | Yes (.seif → markdown) |
| Quality measured | No | Yes (stance A-F) |
| Data classified | No | Yes (PUBLIC/INTERNAL/CONFIDENTIAL) |
| Auditable | No | Yes (hash-chained provenance) |
| Bitcoin-anchored proofs | No | Yes (OpenTimestamps) |
| Live circuit state | No | Yes (H(s), ζ, Tesla Hz) |
| Self-healing errors | No | Yes (Sentinel + 7 archetypes) |

---

## Technical Foundation

SEIF is not metaphor. The protocol's stability is governed by a real second-order transfer function whose damping ratio doubles as the quality-gate threshold. The constants below are algebraically derived, not tuned.

```
H(s) = 9 / (s² + 3s + 6)     ζ = √6/4 = 0.6123724356957945
```

| Circuit State | ζ band | Tesla Hz | Meaning |
|---|---|---|---|
| RESONANT | ζ ≥ 0.60 | 528 Hz | Stable oscillation within design bounds |
| STABILIZING | 0.40–0.60 | 396 Hz | Recovering — converging back toward resonance |
| DRIFT | ζ < 0.40 | 963 Hz | Energy has escaped the normal attractor |

The Tesla 3-6-9 frequency anchors (396 / 528 / 963 Hz) emerged from the same algebra — they were observed in the math, not designed in. The full derivation, uniqueness proof (only primitive integer system: `b=3k, c=6k²`), and attention partition (τ:κ = 2:1 task:context) are documented in [`SEIF.md`](SEIF.md).

---

## Project Stats

```
91+ modules  |  1135 tests (95 files)  |  93% context compression
ζ = √6/4 = 0.6123724356957945
H(s) = 9 / (s² + 3s + 6)
```

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md).

## License

CC BY-NC-SA 4.0 — [André Cunha Antero de Carvalho](https://github.com/and2carvalho)
