SWT3 AI Witness SDK v0.6.3

Developer Documentation

Prove your AI followed the rules. With tamper-proof evidence. Three lines of code. Zero data retained. 113 AI procedures across 61 namespaces. 9 languages. 36 frameworks.

$ pip install swt3-ai
$ npm install @tenova/swt3-ai
$ npm install @tenova/swt3-mcp
$ cargo add swt3-ai
$ dotnet add package swt3-ai
$ gem install swt3-ai
gradle io.tenova:swt3-ai:0.1.0

Quickstart

Wrap your AI client. Every inference is witnessed automatically. Your response is untouched.

Python
TypeScript
from swt3_ai import Witness
from openai import OpenAI

witness = Witness(
    endpoint="https://sovereign.tenova.io",
    api_key="axm_live_...",
    tenant_id="YOUR_ENCLAVE",
)
client = witness.wrap(OpenAI())

# Every inference is now witnessed. Response is untouched.
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Hello"}],
)
print(response.choices[0].message.content)

What happens per inference: Intercept > Hash prompt/response locally > Extract factors (model, latency, tokens, guardrails) > Clear raw data from wire > Anchor to SWT3 ledger in background > Return your response untouched.

CLI: Compliance Status at a Glance

After installing the SDK, run swt3 status to see your compliance posture. Like terraform plan for compliance.

# Brief summary (default)
$ swt3 status

# Full detail with per-procedure breakdown
$ swt3 status --full

# Machine-readable for CI/CD
$ swt3 status --json

# Filter by framework
$ swt3 status --framework EU-AI-ACT

Supported Providers

ProviderPythonTypeScriptDetection
OpenAIv0.6.3v0.6.3Auto (openai module)
Anthropicv0.6.3v0.6.3Auto (anthropic module)
AWS Bedrockv0.6.3v0.6.3Auto (botocore/BedrockRuntimeClient)
xAI (Grok)v0.6.3v0.6.3Via OpenAI-compatible client (api.x.ai)
LiteLLM (100+)v0.6.3N/AAuto (litellm module)
Vercel AI SDKN/Av0.6.3onFinish callback
NVIDIA Dynamov0.6.3N/A@witness_endpoint() decorator / WitnessInterceptor
MCP ServerN/Av0.6.3@tenova/swt3-mcp (33 tools, 2 resources)
Ollama / vLLMv0.6.3v0.6.3Via OpenAI-compatible client
Customv0.6.3v0.6.3@witness.inference() decorator / witness.record()

OpenAI

Python
TypeScript
client = witness.wrap(OpenAI())
response = client.chat.completions.create(model="gpt-4o", messages=[...])

Anthropic

Python
TypeScript
client = witness.wrap(Anthropic())
message = client.messages.create(model="claude-sonnet-4-20250514", max_tokens=1024, messages=[...])

AWS Bedrock

Python
TypeScript
import boto3
bedrock = boto3.client("bedrock-runtime", region_name="us-east-1")
client = witness.wrap(bedrock)

response = client.converse(
    modelId="anthropic.claude-3-5-sonnet-20241022-v2:0",
    messages=[{"role": "user", "content": [{"text": "Hello"}]}],
)

xAI (Grok)

Python
TypeScript
# Grok uses the OpenAI-compatible API
client = witness.wrap(OpenAI(
    base_url="https://api.x.ai/v1",
    api_key="xai-...",
))
response = client.chat.completions.create(model="grok-3", messages=[...])

Ollama / Local Models

Python
# Ollama exposes an OpenAI-compatible API
from openai import OpenAI

client = witness.wrap(OpenAI(base_url="http://localhost:11434/v1"))
response = client.chat.completions.create(model="llama3", messages=[...])

Clearing Levels (Amnesia Protocol)

Clearing controls what leaves your infrastructure. Your code always gets the full response. Clearing only affects the wire payload sent to the witness ledger.

LevelNameOn the WireUse Case
0AnalyticsHashes + factors + model ID + provider + guardrailsInternal dashboards
1StandardHashes + factors + model ID + providerDefault. Production SaaS
2SensitiveHashes + factors + model ID onlyHealthcare, legal, PII
3ClassifiedNumeric factors only. Model ID hashed.Defense, SCIF, air-gapped
Python
TypeScript
# Level 2: Healthcare / Legal - no provider names on wire
witness = Witness(
    endpoint="...", api_key="axm_...", tenant_id="...",
    clearing_level=2,
)

At Level 1+, raw prompts and responses never leave your infrastructure. Only SHA-256 hashes and numeric factors travel on the wire. This satisfies both GDPR Article 17 (right to erasure) and EU AI Act Article 12 (record-keeping) simultaneously.

Configuration Reference

ParameterDefaultDescription
endpointrequiredWitness endpoint URL
api_key / apiKeyrequiredAPI key (axm_* prefix)
tenant_id / tenantIdrequiredYour enclave identifier
clearing_level / clearingLevel1Clearing level (0-3)
buffer_size / bufferSize10Flush after N anchors
flush_interval / flushInterval5.0Flush after N seconds
timeout10.0HTTP timeout for flush
max_retries / maxRetries3Retry count before dead-letter
latency_threshold_ms30000AI-INF.2 latency threshold (ms)
guardrails_required0AI-GRD.1 required guardrail count
guardrail_names[]Names of active guardrails
factor_handoff / factorHandoffNoneHandoff method: "file" (webhook, vault, KMS planned)
factor_handoff_path / factorHandoffPathNoneDirectory for handoff files (required when handoff="file")
agent_id / agentIdNoneCryptographic agent identity (AI-ID.1)
signing_key / signingKeyNoneHMAC-SHA256 key for payload non-repudiation
strictFalseGatekeeper mode: block inference on witness failure
jurisdictionNoneISO 3166-1 jurisdiction code (CJT field, survives all clearing)
legal_basis / legalBasisNoneGDPR legal basis (CJT field, survives all clearing)
purpose_class / purposeClassNoneProcessing purpose classification (CJT field)
authorization_id / authorizationIdNonePre-inference authorization gate reference
on_flush / onFlushNoneCallback invoked after each successful flush

Witnessed Procedures

Each inference produces anchors for these procedures. Full factor definitions are in the UCT Registry.

Inference & Model

ProcedureDomainWhat It ProvesEU AI Act
AI-INF.1InferencePrompt and response were captured (provenance)Art.12(1)
AI-INF.2InferenceLatency within threshold (detects model swaps)Art.12(2)
AI-INF.3InferenceInference volume tracking (rate governance)Art.12(2)
AI-MDL.1ModelDeployed model matches approved identityArt.9(4)(a)
AI-MDL.2ModelModel version identifier recordedArt.12(2)(b)
AI-MDL.5ModelWeight file integrity (SHA-256 hash)Art.15(3)
AI-MDL.6ModelAdapter stack attestation (LoRA, QLoRA)Art.12(2)
AI-MDL.7ModelQuantization parameters witnessedArt.12(2)

Guardrails & Security

ProcedureDomainWhat It ProvesEU AI Act
AI-GRD.1GuardrailRequired safety filters were activeArt.9(2)(a)
AI-GRD.2SafetyNo refusal or content filter triggeredArt.15(3)
AI-GRD.3GatekeeperPre-inference policy gate enforcedArt.9(4)
AI-SEC.1SecurityAdversarial threat detection witnessedArt.15(4)
AI-SEC.2ValidationInput validated and sanitized before inferenceArt.15(3)

Agent & Access

ProcedureDomainWhat It ProvesEU AI Act
AI-TOOL.1Tool CallAgent tool/function call witnessed with outcomeArt.12(1)
AI-ID.1IdentityAgent cryptographic identity assertedArt.12(1)
AI-ACC.1AccessAgent resource access witnessed with scopeArt.9(4)(c)
AI-REV.1RevocationPreviously-issued anchor revoked with reasonArt.14(4)(d)
AI-DEL.1DelegationPermission delegation tree with scope bindingArt.9(4)
AI-COST.1CostResource consumption witnessed (tokens, cost)Art.53

Governance & Lifecycle

ProcedureDomainWhat It ProvesFramework
AI-EMRG.1EmergencyEmergency override lifecycle with authorizationArt.14(4)
AI-DRIFT.2DriftConsequence-mapped drift thresholdsMANAGE 4.2
AI-ASSESS.1AssessmentChampion-challenger model assessmentMAP 2.3
AI-GOV.1GovernanceAI governance framework attestationGOVERN 1.1
AI-RISK.1RiskRisk register with sources and residual riskMAP 2.1
AI-IMPACT.1ImpactSocietal impact assessmentMAP 5.2
AI-IR.1IncidentAI-specific incident responseMANAGE 3.1
AI-LOG.1LoggingImmutable audit log attestationArt.12(1)

Data & Fairness

ProcedureDomainWhat It ProvesFramework
AI-DATA.1DataTraining data provenanceArt.10(2)
AI-FAIR.1FairnessBias detection metricsArt.10(2)(f)
AI-EXPL.1ExplainExplainability report producedArt.13
AI-HITL.1HITLHuman override capability verifiedArt.14(1)
AI-RAG.1RAGContext retrieval provenanceArt.12(1)
AI-RAG.2RAGContext relevance scoringArt.12(1)

113 AI procedures across 61 namespaces and 36 regulatory frameworks. View full catalog.

Agent Witnessing

For AI agents that use tools, access resources, or operate in multi-agent chains. Every agent action produces a cryptographic anchor.

Agent Identity & Signing (AI-ID.1)

Bind a cryptographic identity to every anchor. Combined with a signing key, this provides non-repudiation: proof that a specific agent produced a specific output.

Python
TypeScript
witness = Witness(
    endpoint="...", api_key="axm_...", tenant_id="...",
    agent_id="compliance-agent-v3",
    signing_key="hmac-secret-key-here",  # HMAC-SHA256
)

Tool Witnessing (AI-TOOL.1)

Witness every tool or function call your agent makes. Captures tool name, arguments hash, and outcome.

Python
TypeScript
# Wrap a tool function
@witness.wrap_tool(name="search_database")
def search_db(query: str) -> list:
    return db.search(query)

# Every call to search_db() now produces an AI-TOOL.1 anchor
results = search_db("compliance violations Q1")

Access Control Witnessing (AI-ACC.1)

Witness resource access with scope. Proves what your agent accessed and with what permissions.

Python
TypeScript
# Wrap a resource accessor
@witness.wrap_access(resource="patient_records", scope="read")
def get_patient(patient_id: str) -> dict:
    return ehr.get(patient_id)

# AI-ACC.1 anchor: resource=patient_records, scope=read, outcome=success

Anchor Revocation (AI-REV.1)

Revoke a previously-issued anchor. The revocation itself is witnessed, creating an immutable record of the recall.

Python
TypeScript
# Revoke an anchor by fingerprint
witness.revoke(
    fingerprint="a1b2c3d4e5f6",
    reason="model_recall",  # 7 reason codes
)

# Reason codes: unspecified, model_recall, policy_violation,
# data_contamination, consent_withdrawal, regulatory_order, error_correction

CJT Fields (EU AI Act Compliance)

Jurisdiction, legal basis, and purpose classification fields survive all clearing levels. Required for EU AI Act Art. 12 record-keeping and GDPR lawful basis documentation.

Python
TypeScript
witness = Witness(
    endpoint="...", api_key="axm_...", tenant_id="...",
    jurisdiction="DE",            # ISO 3166-1
    legal_basis="GDPR-6-1-f",     # Legitimate interest
    purpose_class="fraud_detection",
    authorization_id="AUTH-2026-0042",  # Pre-inference gate
)

Gatekeeper Mode

Block inference if the witness endpoint is unreachable. For regulated environments where unwitnessed inferences are not acceptable.

witness = Witness(
    endpoint="...", api_key="axm_...", tenant_id="...",
    strict=True,  # Raises GatekeeperError if endpoint unreachable
)

# Default (strict=False): inference proceeds, witness retries in background
# Gatekeeper (strict=True): inference blocked until witness confirms

Multi-Agent Chains

Link anchors across agents in a workflow using cycle_id. Each agent in the chain references the same cycle, creating a traceable execution graph.

witness_a = Witness(endpoint="...", agent_id="planner", signing_key="...")
witness_b = Witness(endpoint="...", agent_id="executor", signing_key="...")

# Both agents share the same cycle_id
cycle = "cycle-2026-04-26-001"
client_a = witness_a.wrap(OpenAI(), cycle_id=cycle)
client_b = witness_b.wrap(OpenAI(), cycle_id=cycle)

# Anchors from both agents are linked in the ledger

Governance (v0.6.x)

Production AI systems delegate permissions, burn tokens across providers, and run on heterogeneous infrastructure. These features make governance evidence part of the witness record.

Delegation Trees (AI-DEL.1)

Witness hierarchical permission delegation with scope binding, depth tracking, and cascade revocation intent. When Agent A delegates to Agent B and B sub-delegates to Agent C, auditors need to see the full tree.

Python
TypeScript
# Witness a delegation grant scoped to specific tools
witness.witness_delegation_tree(
    delegator_id="orchestrator-main",
    scope="read_file,write_file,execute_query",
    delegation_depth=2,
    delegates=["worker-alpha", "worker-beta"],
    cascade_revocation=True,
    time_bound_minutes=120,
)

# Convenience: scope from a tool list (sorted, joined automatically)
Witness.delegation_tree_from_tools(
    witness, "orchestrator", ["execute_query", "read_file", "write_file"],
    delegates=["worker-1"],
)

Factor semantics: fa = SHA256(delegator_id)[:8] as uint32, fb = SHA256(scope)[:8] as uint32, fc = delegation depth. Delegate identities are SHA-256 hashed in context. All factors survive every clearing level.

Resource Consumption Witnessing (AI-COST.1)

Witness cumulative resource consumption -- tokens, API calls, estimated cost -- as cryptographic evidence. Verdict is always PASS. This is a notary, not a budget enforcer.

Python
TypeScript
witness.witness_resource_consumption(
    tokens_in=1500,
    tokens_out=800,
    api_calls=3,
    cost_cents=12,
    provider="openai",
    model_id="gpt-4o",
    compute_seconds=2.4,
)

Factor semantics: fa = total tokens (in + out), fb = API call count, fc = cost in cents (-1 if unknown). Supports optional deployment context for infrastructure attribution.

Deployment Context Detection

Auto-detects cloud provider, region, runtime environment, and accelerator hardware from environment variables. Results are embedded in witness payloads. Container IDs and hostnames are SHA-256 hashed before inclusion.

Python
TypeScript
from swt3_ai.deployment import detect_deployment_context

ctx = detect_deployment_context()
# DeploymentContext(cloud_provider='aws', region='us-east-1',
#   runtime='kubernetes', accelerator_type='nvidia-gpu', ...)

# Pass to resource consumption witnessing
witness.witness_resource_consumption(
    tokens_in=1500, tokens_out=800, api_calls=3,
    deployment_context=ctx.to_dict(),
)

Detected providers: AWS, GCP, Azure, Vultr. Runtimes: Kubernetes, Lambda, ECS, Cloud Run, Azure Functions, container, bare-metal. Accelerators: NVIDIA GPU, TPU, AWS Neuron. Cached for 5 minutes.

Lifecycle Chains (v0.6.0)

Multi-anchor governance sequences linked by shared cycle IDs. Three lifecycle procedures for operational governance:

Python
TypeScript
# Emergency Override (AI-EMRG.1)
witness.witness_emergency_override(
    override_trigger="safety_incident",
    authorization_level="ciso",
    fallback_state="model_disabled",
    model_id="gpt-4o",
)

# Consequence-Mapped Drift (AI-DRIFT.2)
witness.witness_drift_consequence(
    drift_metric="psi",
    drift_value=0.23,
    threshold=0.15,
    consequence_category="financial_loss",
    response_action="retrain",
    model_id="fraud-model-v3",
)

# Champion-Challenger Assessment (AI-ASSESS.1)
witness.witness_assessment(
    champion_id="model-v2",
    challenger_id="model-v3",
    metric_name="auc_roc",
    champion_score=0.92,
    challenger_score=0.95,
    decision="promote_challenger",
)

Auto-Chaining Context Manager (v0.6.2)

Scope multiple witness calls into a single auditable cycle. All anchors within a chain block share a cycle_id for forensic reconstruction.

Python
TypeScript
# All anchors within this block share a cycle_id
with witness.chain("loan-review-workflow") as ctx:
    result = client.chat.completions.create(model="gpt-4o", messages=[...])
    witness.witness(procedure="AI-FAIR.1", factor_a="bias-check", ...)
    witness.wrap_tool(tool_name="credit_lookup", ...)
    # 3 anchors, 1 cycle_id, complete audit trail

Chains support nesting. If an exception occurs, the chain is marked incomplete (flagged during forensic reconstruction). Use swt3 reconstruct --cycle CYCLE_ID to view the full chain.

Gate Configuration (v0.6.2)

Define compliance policy as code in a .swt3-gate.yml file. Generate, validate, and evaluate against your live ledger.

CLI
# Generate a gate config from a framework crosswalk
swt3 gate --init --framework EU-AI-ACT

# Validate offline (no API key needed)
swt3 gate --validate

# Evaluate against live ledger (CI/CD gate)
swt3 gate --framework eu-ai-act
# Exit code 0 = PASS, 1 = FAIL/WARN

36 frameworks supported. The gate config is the shared artifact between developer and assessor. Full specification: Gate Config Guide

Crosswalk Resolve (v0.5.9)

Map any procedure to every regulatory framework it satisfies. Offline, no network call.

Python
TypeScript
from swt3_ai import Witness

# Which frameworks does AI-INF.1 satisfy?
mappings = Witness.resolve("AI-INF.1")
# [{"framework": "EU-AI-ACT", "article": "Art.12(1)"}, ...]

# Coverage report for a framework
report = Witness.coverage("EU-AI-ACT")
# {"framework": "EU-AI-ACT", "total": 50, "covered": 42, "score": 0.84, ...}

Factor Handoff (Clearing Level 2+)

At Clearing Level 2+, factors are purged from the wire. Factor Handoff writes uncleared factor data to a local file before clearing proceeds. The handoff writes BEFORE clearing. If the write fails, the payload is NOT transmitted.

Python
TypeScript
witness = Witness(
    endpoint="...",
    api_key="axm_...",
    tenant_id="...",
    clearing_level=2,
    factor_handoff="file",
    factor_handoff_path="/secure/handoff/",
)

Full protocol spec: Factor Handoff Protocol

Advanced

Custom Pipelines

Python
TypeScript
# Decorator for custom inference functions
@witness.inference()
def my_pipeline(prompt: str) -> str:
    # Your custom logic
    return result

# Or manual recording
from swt3_ai.types import InferenceRecord
from swt3_ai.fingerprint import sha256_truncated

record = InferenceRecord(
    model_id="my-model-v2",
    model_hash=sha256_truncated("my-model-v2"),
    prompt_hash=sha256_truncated(prompt),
    response_hash=sha256_truncated(response),
    latency_ms=elapsed_ms,
    provider="custom",
)
witness.record(record)

NVIDIA Dynamo Integration

Two-layer architecture for infrastructure-level witnessing on NVIDIA Dynamo inference servers.

# Layer 1: Decorator (zero Dynamo dependencies)
from swt3_ai.adapters.dynamo import witness_endpoint

@witness_endpoint()
async def generate(request):
    async for chunk in model.generate(request.prompt):
        yield chunk

# Configure via SWT3_DSN (single env var)
# SWT3_DSN=https://axm_live_xxx@sovereign.tenova.io/YOUR_TENANT_ID
# Replace YOUR_TENANT_ID with the tenant ID from your dashboard Settings page

# Layer 2: Service-graph (Dynamo-native, pip install swt3-ai[dynamo])
from swt3_ai.adapters.dynamo_infra import WitnessInterceptor
# Injects as @service into Dynamo's depends() graph
# Adds swt3_witness_total, swt3_clearing_level metrics

OTel Export

Export witness telemetry to any OpenTelemetry-compatible backend (Jaeger, Grafana, Datadog).

Python
TypeScript
from swt3_ai.exporters.otel import OTelExporter

witness = Witness(
    endpoint="...", api_key="axm_...", tenant_id="...",
    on_flush=OTelExporter(
        endpoint="http://localhost:4318/v1/traces"
    ),
)

Flight Recorder (Resilience)

The SDK never blocks your inference. Witnessing happens in a background thread/microtask. If the endpoint is unreachable, payloads move to a dead-letter queue and drain automatically when connectivity is restored.

# Python: Check dead-letter status
print(f"Pending: {witness.pending}")

# Graceful shutdown (also happens at exit)
receipts = witness.flush()

Platform Security

Axiom container images are scanned daily for vulnerabilities. Zero-critical-CVE policy enforced. All findings are automatically documented as POA&M entries with severity-based remediation timelines (CRITICAL: 7d, HIGH: 30d, MEDIUM: 90d). Scan results are self-anchored in the witness ledger (RA-5/SI-2).

Verification

Every anchor can be independently verified without an Axiom account.

# CLI
$ axiom verify SWT3-E-CLOUD-AI-AI-INF.2-PASS-1774995559-a1b2c3d4e5f6

# Browser (zero server calls)
sovereign.tenova.io/verify

# Formula
SHA256("WITNESS:{tenant}:{procedure}:{fa}:{fb}:{fc}:{ts_ms}")[0:12]