Cryptographic AI governance and audit. 75 tools, 84 frameworks. EU AI Act, NIST, CMMC, MCP Top 10.
Runs on your machine from its package; the steps are below.
At most: only reads or looks up information.
Odel charges nothing per call. The publisher may charge for its own service.
Runs locally over stdio
This server isn't hosted — your MCP client launches it from a package registry. Use one of the commands below, or drop the config into your client (e.g. Claude Desktop).
Run
npx -y @tenova/swt3-mcp
MCP client config
{
"mcpServers": {
"swt3-ai-witness": {
"command": "npx",
"args": [
"-y",
"@tenova/swt3-mcp"
]
}
}
}Witness your AI. Prove it followed the rules. Cryptographic accountability for every inference, tool call, and resource access.
SWT3 AI Witness SDK: tamper-proof evidence that your AI is doing what you say it does. Every inference hashed. Every tool call recorded. Every resource access checked against scope. No prompts or responses ever leave your infrastructure.
EU AI Act GPAI transparency obligations enforce August 2, 2026. High-risk enforcement follows December 2, 2027. This SDK gives you the evidence chain for both.
Protocol Spec: swt3.ai/spec | Registry: swt3.ai/registry | Verify: swt3.ai/verify
Multi-agent systems propagate trust decisions across organizational boundaries with no cryptographic record of why. v0.7.5 closes that gap. The Trust Propagation Engine records how trust was established, how it decays across delegation hops, and maps trust scores to clearing levels -- all witnessed as AI-TRUST.3 anchors.
Three new crosswalk families bring energy, telecom, and machinery safety into SWT3 coverage.
Why this matters for Python: query_trust() and assert_trust() let Python agent frameworks (LangChain, CrewAI, AutoGen) query an agent's trust score before delegating sensitive tasks and record the propagation decision into the witness chain. Both methods work with the existing Witness class and clearing engine.
score = witness.query_trust("downstream-agent-id")
witness.assert_trust("downstream-agent-id", score=score)
query_trust() -- query an agent's propagated trust score before delegatingassert_trust() -- record a trust propagation decision into the witness chain (AI-TRUST.3)--profile si-accord-2026) -- international AI safety treaty compliance--profile energy-grid) -- sector-specific scanning for NERC CIP environmentsNVIDIA shipped OpenShell to 120+ partners. Agent containment is now infrastructure. But containment without evidence is a black box -- an auditor cannot verify that a sandbox policy was enforced last Tuesday at 14:00 UTC by looking at enforcement logs alone. v0.7.4 adds runtime containment attestation (AI-SHELL.1), model distillation provenance (AI-DIST.1), MCP elicitation detection (AI-MCP.6), and incident lifecycle chains. Four governance gaps closed in one release.
Why this matters for Python: witness_runtime_containment() produces cryptographic evidence from any OCSF-compatible sandbox -- OpenShell, gVisor, Kata, Firecracker, or WASM -- with zero SDK imports and zero vendor lock-in. The OpenShellWitness adapter consumes raw OCSF event streams in real time. witness_distillation() records teacher-to-student lineage with ToS compliance. witness_elicitation() captures prompt boundary violations. incident_chain() returns an IncidentChain context manager that links detection, containment, and resolution anchors into a single forensic sequence.
witness_runtime_containment() -- runtime containment attestation with policy hash, violation count, observation window, OCSF event countOpenShellWitness adapter -- real-time OCSF event stream processing with automatic procedure mappingwitness_distillation() -- distillation provenance with teacher/student identity and ToS trackingwitness_elicitation() -- elicitation detection with consent and scope violation codesincident_chain() -- context manager for multi-anchor incident lifecycle sequencesIncidentChain class -- programmatic incident lifecycle with detect(), contain(), mitigate(), resolve(), close()wrap_jev() adapter -- TypeSafe AI (Jev) Choice/Score/Noul witnessingA2A (Google's Agent-to-Agent protocol) has 150+ supporting organizations, all three hyperscalers, and a v1.0 stable specification under Linux Foundation governance. It has zero built-in audit trail. MCP OAuth adoption sits at 8.5% with 30+ CVEs filed in 60 days. v0.7.3 makes SWT3 the evidence layer for both agent communication protocols with dedicated procedures, lifecycle-aware adapters, and a new crosswalk CLI command.
Why this matters for Python: Python is the dominant language for AI/ML pipelines and agent frameworks (LangChain, CrewAI, AutoGen). The upgraded wrap_a2a() adapter auto-witnesses task lifecycle transitions and contextId chains without modifying agent logic. witness_task_lifecycle(), witness_agent_card_discovery(), witness_context_chain(), and witness_oauth_token_binding() give pipeline developers explicit control over what gets attested.
swt3 crosswalk <procedure> CLI command for offline framework mapping lookupTwo categories of AI infrastructure have no compliance evidence today: harness-layer governance and MCP server operations. The harness decides which agent runs, what context it sees, and whether the output ships -- but those decisions are invisible to auditors. MCP servers process thousands of tool calls with zero attestation. v0.7.2 closes both gaps: five new procedures for harness governance, and a Witness Middleware that adds cryptographic attestation to any MCP server with one function call.
The companion MCP package (@tenova/swt3-mcp) now exports withSWT3(transport) -- a transport-layer wrapper that auto-mints AI-TOOL.1 anchors for every tool call flowing through any MCP server. No code changes to tool handlers. The response is already on the wire before the witness fires, so it cannot block, fail, or slow down your tools.
Why this matters: MCP adoption is accelerating, but retrofitting compliance into existing servers means touching every tool handler -- impractical for servers with dozens of tools or servers you do not control. The middleware pattern eliminates that barrier entirely. One import, one wrap, and every tool call in the fleet has a cryptographic audit trail. Supports batching, deterministic per-tool sampling for high-volume servers, multi-tenant resolution, and retry with bounded queues.
# Python SDK users: your anchors and middleware anchors verify identically
# The middleware mints AI-TOOL.1 anchors with the same fingerprint formula
from swt3_ai import Witness
w = Witness(api_key="axm_...", tenant_id="ACME")
# Anchors from your Python pipeline and from the MCP middleware
# are indistinguishable in the ledger -- same format, same verification
The AI harness layer -- orchestration, delegation, context management, sandboxing, eval gates -- is the hottest infrastructure category in AI. 40% of enterprise apps will include AI agents by end of 2026, yet nobody does cryptographic attestation at the harness layer. These five procedures make harness-level governance decisions auditable for the first time.
Orchestration Topology (AI-ORCH.1) and Agent Handoff (AI-ORCH.2). When a harness picks parallel vs sequential vs hierarchical routing, or when one agent delegates to another with different permissions, those are governance decisions with no audit trail. witness_orchestration_topology() records the routing pattern and agent count. witness_agent_handoff() records the identity linkage with permission delta direction (escalation, lateral, or restriction). When an auditor asks "how do you control which agent handles which task?", these anchors are the evidence.
witness.witness_orchestration_topology("parallel", agent_count=3, dependency_depth=2)
witness.witness_agent_handoff("planner-agent", "executor-agent", permission_delta=1) # escalation
Context Window Management (AI-CTX.1). When a harness truncates, summarizes, or evicts context, the model loses information -- and nobody records what was lost. This is not a minor detail: a financial model that lost 96K tokens of context before making a recommendation has a materially different evidence basis than one that saw the full context. witness_context_window() records token counts before/after and the eviction method.
witness.witness_context_window(tokens_before=128000, tokens_after=32000, eviction_method="summarization")
Sandbox Enforcement (AI-SAND.1). Records the harness's own report of tool restriction compliance. Cross-reference with AI-TOOL.1 anchors for independent verification. When the harness says "I restricted this agent to 5 of 10 tools," and the AI-TOOL.1 trail confirms only those 5 were called, you have two independent attestations agreeing.
witness.witness_sandbox_enforcement(tools_declared=10, tools_invoked=5, violations=0)
Eval Gate Decision (AI-GATE.1). Records pass/fail deployment gating based on eval results. Auto-computes gate score when not provided. This is the evidence that a model was evaluated before it shipped -- not just that an eval suite exists, but that it ran and what the result was.
witness.witness_eval_gate(total_evals=100, evals_passed=85) # gate_score auto-computed: 85
MCP is the fastest-growing integration layer in AI. It is also the least governed. OWASP published the MCP Top 10 in 2026, and the findings are brutal: 30-82% of MCP servers are vulnerable to tool poisoning, insufficient authentication, and shadow server proliferation. Meanwhile, IETF is drafting agent audit trail standards that describe exactly what SWT3 already does -- but those drafts expire in weeks and have no deployed reference implementation. v0.7.1 closes both gaps with three new procedures that make SWT3 the first SDK to cover all 10 OWASP MCP risks with cryptographic evidence.
The problem: OWASP MCP-03 (Tool Poisoning) describes attacks where tool schemas silently change between calls -- a parameter gains a new allowed value, a description subtly shifts to manipulate the agent, or a tool version changes without notice. The MCP protocol has no built-in mechanism to detect schema drift.
What v0.7.1 adds: witness_mcp_tool_integrity() hashes the tool schema at connection time and again at invocation time. If the schema changed between those two moments, the anchor records a FAIL verdict with the drift detected. No raw schemas are transmitted -- only SHA-256 hashes.
witness.witness_mcp_tool_integrity(
server_name="data-retrieval-mcp",
tool_name="query_database",
schema_hash_at_connect="a8f3c7d91e02",
schema_hash_at_invoke="a8f3c7d91e02", # match = PASS, mismatch = FAIL
)
Why this matters: Tool poisoning is the supply chain attack vector for agents. An attacker who compromises an MCP server does not need to breach your model -- they just need to change what a tool does. Without schema integrity checking, the agent trusts whatever the server declares. With it, every tool invocation has a cryptographic record of whether the schema was stable. When OWASP MCP-03 appears in your assessment scope, this is the evidence.
The problem: OWASP MCP-07 (Insufficient Authentication) flags that most MCP servers accept connections without any authentication. No mTLS. No API keys. No OAuth. The server just trusts whoever connects. When an auditor asks "how do you verify the identity of your MCP servers?", most teams have no answer.
What v0.7.1 adds: witness_mcp_server_auth() records whether authentication was present at connection time, what method was used, and whether it was verified. A connection with no authentication produces a FAIL verdict -- which maps directly to an IA-9 finding under NIST 800-53.
witness.witness_mcp_server_auth(
server_name="data-retrieval-mcp",
auth_method="mtls",
auth_verified=True,
)
Why this matters: NIST 800-53 IA-9 requires identification and authentication of services. EU NIS-2 Art. 21(2)(d) requires supply chain security. An MCP server is a service your agent depends on. If that service accepts anonymous connections, your agent's entire output is built on an unverified foundation. This procedure makes that gap visible and auditable.
The problem: OWASP MCP-09 (Shadow MCP Servers) describes the risk of unauthorized MCP servers appearing in an agent's configuration. A developer adds a community server for testing and forgets to remove it. A compromised config file injects a malicious server. The agent connects to both the legitimate and shadow servers without distinction.
What v0.7.1 adds: witness_mcp_server_discovery() records the discovery method (manual config, DNS, registry lookup) and whether the server was on the approved allowlist. Servers discovered through uncontrolled channels or missing from the allowlist produce a FAIL verdict.
witness.witness_mcp_server_discovery(
server_name="unknown-community-server",
discovery_method="config_file",
on_allowlist=False, # FAIL -- shadow server detected
)
Why this matters: Shadow IT is the oldest problem in enterprise security. Shadow MCP servers are the same problem at the agent layer. Without discovery attestation, you cannot prove that your agent only connected to approved servers. With it, every connection attempt is recorded -- including the ones that should not have happened.
With AI-MCP.1 (v0.6.6) plus AI-MCP.2/3/4 (v0.7.1), SWT3 now maps to all 10 OWASP MCP risks:
| OWASP MCP Risk | SWT3 Procedure(s) |
|---|---|
| MCP-01 Token Mismanagement | NHI-ROTATE.1, NHI-EXPIRE.1 |
| MCP-02 Privilege Escalation | NHI-SCOPE.1, NHI-PRIV.1, AI-ACC.1 |
| MCP-03 Tool Poisoning | AI-MCP.2 (NEW) |
| MCP-04 Supply Chain Tampering | AI-SBOM.1, AI-SUPPLY.1 |
| MCP-05 Command Injection | AI-GRD.1/2/3 |
| MCP-06 Intent Flow Subversion | AI-CHAIN.1/2 |
| MCP-07 Insufficient Auth | AI-MCP.3 (NEW) |
| MCP-08 Lack of Audit/Telemetry | SWT3 protocol (entire SDK) |
| MCP-09 Shadow MCP Servers | AI-MCP.4 (NEW) |
| MCP-10 Context Injection | AI-GRD.3, clearing levels |
AI does not run in a vacuum. It authenticates with service accounts, runs on hardware with supply chains, and consumes enough electricity to reshape power grids. Until now, the witness layer stopped at the model. v0.7.0 extends it down the full AI infrastructure stack -- from the credentials your agents use, to the hardware they run on, to the energy they consume. One SDK. One fingerprint formula. One verification endpoint.
This is a major release because it crosses a boundary: SWT3 now witnesses the infrastructure that AI depends on, not just the AI itself. Three new procedure families. 22 new witness methods. 22 new MCP tools. The same protocol that proves your model followed the rules now proves your service accounts are governed, your hardware supply chain is documented, and your demand response events are independently attested.
The problem: The biggest AI security breaches in 2025-2026 did not start with prompt injection. They started with a stolen service account. AI agents authenticate to APIs, databases, and other agents using machine credentials -- API keys, service accounts, OAuth tokens, certificates. These non-human identities (NHIs) outnumber human users 45-to-1 in a typical enterprise, and most organizations cannot answer the basic question auditors ask first: "How many service accounts does your AI system use, and what can each one access?"
What v0.7.0 adds: Six witness methods that create an independent audit trail for every credential your AI agents use, without replacing your identity provider. The protocol records scope, lifecycle, privilege changes, rotation, delegation, and revocation -- the six events that matter when an incident investigator asks "what could this credential do, and when did that change?"
# Record what a service account is authorized to access
witness.witness_nhi_scope("svc-inference-prod", scope="read:models,invoke:gpt4o", ttl_seconds=86400)
# Record credential rotation (proves rotation happened, not just that policy exists)
witness.witness_nhi_rotation("old-key-abc", "new-key-def", reason="scheduled")
# Record delegation chain (Agent A delegates to Agent B)
witness.witness_nhi_delegation("orchestrator-cred", "worker-agent-cred", delegation_depth=2)
Why this matters: Identity governance is moving from "nice to have" to "table stakes." NIST 800-207 (Zero Trust) requires continuous authentication verification. EU NIS-2 Art. 21 requires access control management including machine identities. CISA's 2026 guidance on agentic AI specifically calls out credential sprawl as a top-5 risk. Without independent witnessing, your only evidence is the identity provider's own logs -- which is like asking the bank to audit itself.
The problem: The EU Battery Regulation (effective February 2027) requires digital passports for every battery above 2 kWh -- including the thousands of UPS batteries in AI data centers. The Cyber Resilience Act requires hardware bills of materials for connected devices. The Energy Efficiency Directive requires PUE reporting for data centers above 500 kW. Three regulations, three compliance gaps, and no existing protocol that covers hardware supply chains with the same rigor applied to software.
What v0.7.0 adds: Ten witness methods across two namespaces. HBOM (Hardware Bill of Materials) covers inventory attestation, component lifecycle, thermal profiles, water consumption, PUE reporting, and supply chain provenance. DPP (Digital Product Passport) covers battery state-of-health, charge cycles, degradation events, and end-of-life disposition.
# PUE reporting -- proves the number, not just that you reported it
witness.witness_power_usage(total_facility_kw=2400, it_load_kw=1800, pue_x1000=1333)
# Battery passport -- state of health for every UPS in the facility
witness.witness_battery_soh(soh_percent=94.2, cycle_count=847, capacity_kwh=100.0)
# Hardware supply chain -- proves provenance was verified per-supplier
witness.witness_supply_chain_provenance("dell-server-batch-q3", provenance_verified=True, country_of_origin="US")
Why this matters: A single hyperscale data center contains 50,000+ UPS batteries. Each one will need a digital passport. The operators who can produce that evidence programmatically -- with independent verification -- will spend weeks on compliance instead of months. More importantly, when a battery catches fire or a supplier is sanctioned, the provenance chain tells you exactly which facilities are affected, which components came from that supplier, and when the last health check passed.
The problem: AI training runs consume as much power as small cities. When the grid operator sends a curtailment signal, the data center is supposed to reduce load. But settlement disputes run six figures because there is no independent attestation of what actually happened -- how much was the baseline, how much was actually curtailed, and does the measurement match what was billed? The utility's meters say one thing. The facility's meters say another. Nobody has a neutral witness.
What v0.7.0 adds: Six witness methods that create an independent record of every demand response event, from the grid signal through baseline measurement, actual curtailment, settlement, carbon credit issuance, and grid signal correlation.
# Record baseline before the curtailment event
witness.witness_baseline_consumption(baseline_kw=2400, measurement_method="10_of_10")
# Record what actually happened during the event
witness.witness_curtailment(actual_reduction_kw=800, committed_kw=1000, compliance_ratio_x1000=800)
# Record the settlement -- financial attestation of the DR event
witness.witness_settlement(settlement_kwh=4800, price_usd_per_mwh=85.0, event_count=6)
Why this matters: FERC Order 2222 opened wholesale energy markets to distributed resources -- including data centers. The EU Clean Energy Package Art. 17 requires demand response participation rights. Carbon credit registries like Verra and Gold Standard require measurement and verification evidence. Without independent attestation, every settlement is a negotiation. With it, the evidence speaks for itself.
The protocol specification now covers all four namespace families: AI (inference and governance), NHI (credential governance), HBOM (hardware and facilities), and DPP (digital product passports). The same fingerprint formula, the same clearing engine, the same verification endpoint. A credential rotation anchor and an inference anchor verify identically -- echo -n "WITNESS:TENANT:NHI-SCOPE.1:1:1:0:TIMESTAMP" | sha256sum | cut -c1-12.
Supply chain accountability: model provenance, delegation boundaries, anchor density monitoring, and MCP security posture. The theme: proving your AI's supply chain is known, bounded, and monitored -- not just that individual inferences behaved.
What it does: witness_model_provenance() records the lineage of a model: who trained it, what base model it descends from, which training pipeline produced it, and whether the weights were modified post-training. A new parent_model_fingerprint parameter on witness_model_weights(), witness_adapter_stack(), and witness_quantization() links derivative models back to their parent's witness anchor.
Why it matters: The G7 Hiroshima AI SBOM framework (May 2026) requires model provenance documentation. EU AI Act Art. 53 requires GPAI providers to document training processes. When a fine-tuned model misbehaves, the first question is "what was it fine-tuned from?" Without provenance chains, you can prove the current model was witnessed but not where it came from. The parent fingerprint creates an unbroken lineage from base model to production deployment -- every fork, every fine-tune, every quantization step has a cryptographic link to its ancestor.
witness.witness_model_provenance(
model_id="credit-scorer-v3",
provenance={
"base_model": "llama-3.1-70b",
"training_pipeline": "sagemaker-ft-2026-08",
"fine_tuned_by": "ml-team-alpha",
"parent_model_fingerprint": "a8f3c7d91e02",
}
)
What it does: witness_delegation_boundary() records what an AI agent is NOT permitted to do. Where AI-DEL.1 (delegation tree) records the permissions an agent has, AI-DEL.2 records the explicit boundaries: which tools are blocked, which data scopes are excluded, which actions require escalation.
Why it matters: EU AI Act Art. 14 requires "appropriate human-machine interface tools" that let humans "understand the capacities and limitations" of the AI system. NIST AI RMF GOVERN 1.1 calls for documented constraints on AI system behavior. Regulators ask two questions: "what can it do?" and "what can't it do?" Most systems can only answer the first. Delegation boundaries answer the second -- with cryptographic proof that the boundary was declared before the agent acted, not documented after an incident.
witness.witness_delegation_boundary(
agent_id="loan-processor",
boundary={
"blocked_tools": ["shell_exec", "database_drop"],
"max_delegation_depth": 2,
"restricted_scopes": ["PII", "financial_records"],
"escalation_required": ["approval_over_10k"],
}
)
What it does: witness_anchor_density() records the ratio of witnessed events to total events over a time window. The DensityEnforcer class monitors density in real-time and auto-fires AI-DENSITY.1 anchors when coverage drops below a threshold. Rate-limited to prevent anchor storms.
Why it matters: Witnessing 100% of inferences on day one and 2% by month three is a compliance drift that nobody catches until the audit. Density monitoring makes coverage gaps visible and provable. When an assessor asks "were you consistently monitoring?", a density anchor chain shows the monitoring ratio over time -- not just a snapshot, but a trend. The DensityEnforcer runs in-process and catches gaps before the assessor does.
from swt3_ai import Witness, DensityEnforcer
witness = Witness(...)
enforcer = DensityEnforcer(
witness=witness,
threshold=0.95, # Alert below 95% coverage
window_seconds=3600, # 1-hour windows
)
# enforcer auto-fires AI-DENSITY.1 anchors when coverage drops
What it does: witness_mcp_security() evaluates 8 observable security properties of an MCP server connection and records the posture as a single anchor. Checks include transport encryption, authentication presence, tool allowlisting, input validation, rate limiting, logging, error handling, and scope restriction. The anchor records the count of checks passed and failed -- never which specific checks failed.
Why it matters: NSA and CISA flagged MCP as a security risk in 2026, with 200,000+ vulnerable MCP deployments identified. But the problem is not MCP itself -- it is MCP servers deployed without security controls. This procedure creates a cryptographic record that security controls were evaluated at connection time. The deliberate opacity (count only, not which checks failed) prevents the anchor from becoming an attack map. An assessor sees "7 of 8 checks passed" -- enough to verify due diligence without revealing the two gaps to an attacker.
witness.witness_mcp_security(
server_name="data-retrieval-mcp",
checks_passed=7,
checks_total=8,
transport_type="stdio",
)
The OpenTelemetry exporter now emits gen_ai.system, gen_ai.request.model, gen_ai.usage.input_tokens, and gen_ai.usage.output_tokens attributes following the OpenTelemetry GenAI semantic conventions. The gen_ai.system attribute maps 17 provider prefixes (openai, anthropic, bedrock, vertex, etc.) to their canonical OTel values. Token usage attributes are emitted at clearing levels 0-1 and cleared at levels 2-3, consistent with the clearing engine's data minimization rules.
tenova-labs/swt3-gate-action@v1 evaluates .swt3-gate.yml policies in CI/CD pipelines. 7 inputs, 3 outputs. Fails the build when compliance coverage drops below the declared threshold. The assessor reads the same gate file your pipeline enforces -- one source of truth from commit to production.
- uses: tenova-labs/swt3-gate-action@v1
with:
api-key: ${{ secrets.SWT3_API_KEY }}
tenant-id: MY_TENANT
framework: EU-AI-ACT
Scale governance: probabilistic witnessing for billion-inference providers, governance effectiveness metadata for assessors, and the Go SDK. The theme: making compliance witnessing work at GPAI scale without losing audit fidelity.
What it does: A new sampling_rate parameter (0.0-1.0) that lets you witness a statistical sample of inferences instead of every single one. Non-witnessed inferences are counted and summarized in periodic AI-SAMPLE.1 anchors on flush. Per-procedure overrides let you keep safety-critical procedures at 100% while sampling high-volume inference calls.
Why it matters: A GPAI provider processing a billion inferences per day cannot witness every single one. But regulators still need evidence the system was monitored. Probabilistic witnessing solves both: you set sampling_rate=0.01 for volume procedures and 1.0 for guardrails and safety checks. The sampling is deterministic (hash-based, not random) so any verifier can reproduce the sampling decision for any given inference. The summary anchors record exactly how many inferences were skipped, preserving audit completeness.
witness = Witness(
endpoint="https://sovereign.tenova.io/api/v1/witness",
api_key="axm_live_...",
tenant_id="GPAI_PROD",
sampling_rate=0.01, # 1% of inferences witnessed
sampling_rates={
"AI-GRD.1": 1.0, # 100% guardrail witnessing
"AI-SEC.1": 1.0, # 100% security events
"AI-INF.1": 0.001, # 0.1% inference volume
},
)
What it does: All 17 governance witness methods now accept an optional governance_metadata dictionary. Pass review_duration_minutes and participant_count to record how long governance reviews took and how many people participated. Unknown keys pass through for forward compatibility.
Why it matters: Assessors need to distinguish substantive governance from governance theater. A 3-minute review by one person is not the same as a 90-minute review by five. This metadata goes into the existing ai_context JSONB field at clearing levels 0-1 (stripped at levels 2-3). The SDK validates known keys and warns when participant_count < 2, which may not satisfy effective challenge requirements under SR 11-7 or EU AI Act Art. 14.
witness.witness_governance_review(
reviews_scheduled=4,
reviews_completed=4,
governance_metadata={
"review_duration_minutes": 90,
"participant_count": 5,
"quorum_met": True,
}
)
What it does: Core SWT3 primitives for Go: fingerprint minting, HMAC-SHA256 signing, lifecycle chain IDs, and type definitions. Zero external dependencies (standard library only). All 65 test vectors pass with byte-identical output to the other 9 SDKs in the ecosystem.
Why it matters: Go is the dominant language for backend infrastructure at scale. Kubernetes operators, API gateways, data pipelines, and inference orchestrators are overwhelmingly written in Go. Without a Go SDK, GPAI infrastructure teams had to shell out to Python or use HTTP directly. Now they can witness inferences in-process with zero dependency overhead.
import swt3 "github.com/tenova-labs/swt3-ai-go"
fp := swt3.MintFingerprint("MY_TENANT", "AI-INF.1", 1, 1, 0, ts)
sig := swt3.SignPayload("my-key", fp, "agent-1")
Pre-inference authorization, chain reconstruction, 10 new MCP compliance tools, and the Kotlin SDK. The theme: proving you checked BEFORE the AI acted, not just after.
gate.py)What it does: Authorization checkpoint that runs before inference begins. Evaluates whether the requesting agent, user, or system has permission to invoke a specific model under the current policy. Returns an authorization_id that links the gate decision to the subsequent inference anchor.
Why it matters: EU AI Act Art. 9 requires risk management "prior to placing on the market or putting into service." Regulators increasingly ask not just "did the AI behave?" but "who authorized it to run?" Without a pre-inference gate, you can prove the output was safe but not that someone approved the input. The gate closes that gap: every inference anchor can point back to the authorization decision that allowed it.
reconstruct.py)What it does: Rebuilds a complete forensic timeline from witness anchors. Given a cycle_id, agent_id, or time window, it queries the ledger and produces a chronological narrative of every action the AI system took, with verifiable fingerprints at each step. Exports to terminal, JSON, or self-contained HTML.
Why it matters: When an incident happens, regulators and legal teams need a provable sequence of events, not a log dump. Chain reconstruction turns scattered witness anchors into a coherent audit trail that any assessor can independently verify. The HTML export is designed to be handed directly to legal counsel or a Notified Body without granting system access.
The MCP server now exposes 33 tools (up from 23). The 10 new tools bring compliance operations directly into agent workflows:
| Tool | Procedure | Why It Exists |
|---|---|---|
swt3_gate | AI-ACC.1 | Pre-inference authorization: prove the gate was checked |
swt3_guardrail | AI-GRD.1 | Guardrail activation: prove safety filters were active |
swt3_hitl | AI-HITL.1 | Human-in-the-loop: prove a human reviewed the decision |
swt3_consent | AI-CONSENT.1 | Consent collection: prove user consent was obtained |
swt3_data_provenance | AI-DATA.1 | Data lineage: prove training data governance was reviewed |
swt3_rag | AI-RAG.1 | RAG provenance: prove retrieval sources were documented |
swt3_output_filter | AI-GRD.2 | Output classification: prove the output passed safety checks |
swt3_incident | AI-INCIDENT.1 | Incident reporting: prove the incident was documented |
swt3_reconstruct | AI-CHAIN.1 | Chain reconstruction: rebuild and export audit trails |
swt3_trajectory | AI-MOB.6 | Trajectory attestation: prove autonomous decisions were recorded |
These tools matter because MCP is becoming the standard integration layer for AI agents. When an agent calls swt3_gate before invoking a model, the attestation happens inside the agent's own workflow, not as an afterthought. Compliance becomes a tool call, not a separate system.
What it does: Core SWT3 primitives for the JVM ecosystem. Fingerprint generation, HMAC-SHA256 signing, anchor verification, and type definitions. Full test vector parity with Python, TypeScript, Rust, C#, Ruby, and Swift.
Why it matters: Android is the world's largest mobile platform. Kotlin is its primary language. Edge AI inference on Android devices (on-device models, ML Kit, MediaPipe) needs the same accountability infrastructure as server-side inference. The Kotlin SDK enables witnessing on 3+ billion active Android devices without requiring a network round-trip. Published to Maven Central.
36 frameworks, 114 procedures, 339+ procedure-framework mappings, 16 compliance profiles. Jurisdiction resolver covers 50+ jurisdiction codes with enforcement dates and binding status.
The guide library grew from 180 to 185. The five new guides close gaps identified in an August 2026 regulatory scan: the EU's Digital Omnibus timeline changes, three newly signed US state laws (Oregon, Georgia, Washington), and NIST's COSAiS control overlay for securing AI systems. Every guide maps regulatory requirements to SWT3 procedures with assessor tips and SDK code examples.
Six new witness methods. The four newest close the autonomous vehicle compliance vacuum -- the EU AI Act classifies AV systems as high-risk (Annex III, 3a), NVIDIA just open-sourced a 34B VLA model for robotaxis, and every startup fine-tuning it needs accountability infrastructure that doesn't exist yet. Until now.
Trajectory Decision Attestation (witness_trajectory, AI-MOB.6) -- Every autonomous driving decision produces a planned trajectory and a causal reasoning trace. This method records that a VLA or path planning model produced a trajectory, whether it passed safety validation, and its classification level (nominal, cautionary, degraded, emergency, abort). Context stores ONLY hashes and counts -- never raw coordinates, waypoints, or proprietary CoC traces. Works with any VLA model (Alpamayo, EMMA, FSD, SuperVision, or custom). ISO/PAS 8800, EU AI Act Annex III(3a), UNECE WP.29 R157.
VLA Inference Wrapper (wrap_vla, AI-MOB.7) -- Wrap any VLA inference function with three lines. Captures timing, input/output hashes, and success/failure. Frame data is NEVER hashed by default (<0.1ms overhead vs. 50-200ms for raw frame hashing). Pass pre-computed frame hashes if your camera pipeline already produces them. Supports sync and async. Decorator syntax: @witness.wrap_vla(model_id="alpamayo-2-super").
Output Safety Witnessing (witness_output_filter, AI-GRD.2) -- Guardrails run, but proving the output classification result is a separate evidence requirement. When Tencent's Doubao was shut down overnight for output violations, the gap was not whether guardrails existed but whether there was proof each output passed classification. This method records whether model output passed content safety filters, what type of filter ran, and what action was taken. Distinct from witness_guardrail (AI-GRD.1, input-side activation) -- this is the output-side classification result. EU AI Act Art. 15(3), NIST AI RMF GOVERN 1.5.
Data Provenance Witnessing (witness_data_provenance, AI-DATA.1) -- Training data is the most guarded secret in AI. This method solves the tension: it attests that data governance review was performed WITHOUT disclosing what the training data was. No dataset names, no license strings, no content hashes of the data itself. Instead: governance reviewed (bool), documentation hash (SHA-256 of the data card, not the data), license compliance verified, demographic features confirmed absent. Satisfies EU AI Act Art. 10, SR 11-7 III.A, and CA-AB-2013 through diligence attestation, not disclosure.
Jurisdiction Resolver (frameworks_for_jurisdiction) -- Pass an ISO 3166-1 country code or ISO 3166-2 subdivision and get back every applicable regulatory framework with enforcement dates and binding status (mandatory, advisory, voluntary). frameworks_for_jurisdiction("US-CA") returns California state laws + US federal frameworks + universal standards. Accepts lists for multi-jurisdiction deployments. 34 frameworks mapped across 50+ jurisdiction codes. Derived from the bundled crosswalks.json -- single source of truth, offline, zero API calls.
A .swt3-gate.yml file in your repo declares which procedures your system must witness, how fresh the evidence must be, and which gaps are critical. Generate one from any supported framework with --init, then enforce it in CI. The assessor reads the same file you do.
# .swt3-gate.yml
version: "1.0"
name: "credit-decision-service"
strict: true
frameworks:
EU-AI-ACT:
risk_class: high
gates:
- group: "Article 9 -- Risk Management"
procedures:
- procedure: AI-INF.1
required: true
max_age: 24h
description: "Every inference must be witnessed"
- procedure: AI-GRD.1
required: true
critical: true
hint: "Guardrails must be active at inference time"
swt3 gate --init EU-AI-ACT # Generate from crosswalk
swt3 gate --validate # Check YAML syntax and structure
swt3 gate # Evaluate against live ledger (exit 0/1)
swt3 gate --json # Machine-readable for CI/CD
swt3 gate is your pre-merge compliance check. Add it to any CI pipeline that supports exit code checks -- GitHub Actions, GitLab CI, Jenkins, or a local pre-commit hook. Exit 1 means a gap exists -- fix it before it becomes an audit finding. The gate config is version-controlled policy: developers see what's required, CI enforces it, and assessors run swt3 gate --json independently against your ledger to confirm compliance without relying on self-reported results. When strict: true is set and a critical procedure fails, the gate blocks. Non-critical failures warn but pass.
A single AI decision -- retrieve context, run inference, check guardrails -- produces multiple anchors. Without a shared identifier, those anchors are isolated events. The context manager injects a shared cycle_id into every witness call inside the block so the full decision is queryable as one chain.
with witness.chain("credit-decision") as ctx:
wrapped.chat.completions.create(model="gpt-4o", messages=[...])
witness.witness_rag_context(source="policy-db", chunks=12)
witness.witness_resource_consumption(tokens_in=8000, tokens_out=2400, api_calls=3)
Nesting is supported -- inner chains save and restore the outer cycle_id. Exception-safe. No manual ID management. Use swt3 reconstruct --cycle CYCLE_ID to replay the full chain later.
swt3 reconstruct queries the witness ledger and rebuilds a chronological narrative of what an AI system did and when. Every line in the output is backed by a verifiable fingerprint. The --html flag produces a self-contained report you can hand to legal, compliance, or a regulator without giving them dashboard access.
swt3 reconstruct --cycle CYCLE_ID # Terminal output
swt3 reconstruct --agent orchestrator --last 1h # By agent
swt3 reconstruct --cycle CYCLE_ID --html # Self-contained HTML report
swt3 reconstruct --last 30m --json # Machine-readable
The report is independently verifiable. Assessors do not need to trust it -- they can recompute any fingerprint and confirm the evidence is intact.
swt3 status now includes gate evaluation results. If a .swt3-gate.yml exists in your project, the output shows which gates pass, which fail, and which procedures need attention -- compliance posture at a glance without leaving the terminal.
swt3 status)Every compliance framework your AI system faces -- EU AI Act, NIST AI RMF, SR 11-7, CMMC -- maps to dozens of requirements across multiple articles. Developers integrate the SDK, mint anchors, and know their code is witnessed. But no one could answer the question that matters most before an assessment: "How much of my framework is actually covered right now?"
The answer used to require logging into a dashboard, cross-referencing a crosswalk spreadsheet, and hoping your ledger had recent entries. swt3 status puts that answer in the terminal where developers already live. One command, zero network calls, instant result.
$ swt3 status
EU Artificial Intelligence Act ██████░░░░░░░░░░░░░░ 30% (15/50)
Covered:
✓ Art.9(2)(a) AI-GRD.1 5m ago
✓ Art.13(1) AI-EXPL.1 8m ago
✓ Art.27 AI-DPIA.1 2w ago
Next steps:
AI-COST.1 witness.witness_resource_consumption()
AI-CONSENT.1 witness.witness_consent()
AI-DATA.2 witness.witness_data_quality()
The bar goes up every time you implement another procedure. Gaps show the exact SDK method to close them -- not documentation links, not vague guidance, but the function call. Use --json in CI to fail builds when coverage drops. Use --compact for Slack notifications. Use --full the week before an assessment to see every article, covered or not. Hand the output to your CISO. Hand the assessor hot sheet to the auditor.
Everything until now has been single-anchor-per-event. v0.6.0 introduced lifecycle chains -- sequences of linked anchors that capture an entire governance process from start to finish, reconstructable from a single identifier.
When an operator overrides your AI, when a model drifts and triggers a circuit breaker, when you run a challenger model against production -- these are not point events. They are processes with a beginning, middle, and end. A single anchor cannot capture them. A lifecycle chain can.
Regulators and auditors do not accept point-in-time snapshots as evidence for ongoing governance decisions. When your model drifts and you escalate to an emergency override, an auditor needs to see the complete decision sequence: what triggered the escalation, who authorized the override, what fallback was activated, and when normal operation resumed. Without a chain, you reconstruct that narrative from scattered log entries during the audit. With a chain, the evidence trail is cryptographically linked and queryable from a single identifier before the auditor asks.
# Promote a challenger model, monitor it, handle problems
assess_chain = witness.begin_lifecycle("AI-ASSESS.1", fa=10000, fb=23.0, fc=0.0) # 10K inputs, divergence 0.023, threshold not breached
assess_chain.resolve(fa=10000, fb=23.0, fc=0.0) # challenger promoted
# Monitor the promoted model for drift
drift_chain = witness.begin_lifecycle("AI-DRIFT.2", fa=0.05, fb=3.0, fc=1.0) # low drift, operational category, monitoring
drift_chain.checkpoint(fa=0.12, fb=3.0, fc=1.0) # drift increasing
drift_chain.checkpoint(fa=0.35, fb=0.0, fc=3.0) # safety threshold -- circuit breaker
# Drift triggered emergency override
emrg_chain = drift_chain.escalate("AI-EMRG.1", fa=1.0, fb=1.0, fc=0.0) # operator command, supervisor auth, safe state
emrg_chain.checkpoint(fa=1.0, fb=1.0, fc=0.0) # system stable under fallback
emrg_chain.resolve(fa=1.0, fb=1.0, fc=0.0) # AI control restored
# Every anchor shares the same chain ID, each links to its parent
print(emrg_chain.chain_id) # LC-7a38936db8ecec94
That is the full governance loop: assessment to promotion to monitoring to escalation to override to restoration. Every transition is a cryptographic anchor. Every chain is reconstructable from a single ID. Auditors query one endpoint and get the complete evidence trail:
GET /api/v1/witness/chain?lifecycle_chain_id=LC-7a38936db8ecec94
Crash recovery is built in. If your process restarts mid-chain, reconstruct the handle from known state:
chain = witness.resume_lifecycle("AI-EMRG.1", "LC-7a38936db8ecec94", "2e16e2fe92dd")
chain.checkpoint(fa=1.0, fb=0.9, fc=0.0) # continues from where it left off
When a human overrides an AI system -- kills a valve controller, disables a fraud model, intervenes in a decision pipeline -- there is no standard way to produce cryptographic evidence of who authorized it, what fallback state was activated, and when control was restored. Now there is.
witness.witness_operational_override(
trigger_type="operator_command", # emergency_stop, operator_command, escalation_protocol, external_responder
authorization_level="supervisor", # operator, supervisor, site_manager, emergency_responder
fallback_state="safe_state", # safe_state, legacy_controller, manual_mode, degraded_operation, full_shutdown
system_id="reactor-ai-v3",
operator_id="eng-042",
override_reason="valve pressure anomaly",
)
Maps to: EU AI Act Art. 14 (human override for high-risk AI), NIST 800-53 IR-4 (incident handling), IEC 61511 (safety instrumented systems).
Most drift detection tells you a number changed. It does not tell you what that number means for your operation. AI-DRIFT.2 maps statistical drift to real-world consequence categories with graduated response witnessing.
witness.witness_drift_consequence(
drift_magnitude=0.15, # PSI, KL divergence, or any statistical metric
consequence_category="safety", # safety, environmental, financial, operational, reputational
response_action="circuit_breaker", # notification_only, increased_monitoring, throttle, circuit_breaker, forced_failover, emergency_shutdown
drift_metric="psi",
model_id="fraud-model-v7",
mapping_version="2026-Q2",
)
Maps to: EU AI Act Art. 9(2)(b) (continuous risk estimation), OCC 2026-13 / SR 26-2 (model risk management with materiality mapping).
Running a shadow model alongside production? The comparison dashboard in your ML platform is a mutable database entry. AI-ASSESS.1 makes it a cryptographic evidence chain: session configuration, periodic divergence snapshots, and the promotion or rejection decision -- all linked by a shared assessment ID.
witness.witness_champion_challenger(
inputs_processed=10000,
max_divergence=0.023, # highest divergence observed (raw value, x1000 internally)
threshold_breached=False, # True = FAIL, False = PASS
champion_id="gpt-4o-2026-05",
challenger_id="gpt-4o-2026-07",
divergence_metric="kl_divergence",
)
Maps to: EU AI Act Art. 15 (post-market monitoring), OCC 2026-13 / SR 26-2 (challenger runs with versioned sign-off).
Witness() with no args. No account, no API key, no network. Anchors saved locally, framework coverage shown in console. Try witnessing in 10 seconds.resolve("AI-FAIR.1") returns every regulation that procedure satisfies across 77 frameworks, offline, zero dependencies. coverage("EU-AI-ACT") shows your session's covered/remaining controls with a score.?procedure=AI-FAIR.1. No login required.Every node in your cluster runs AI workloads on hardware you have never attested. If a GPU fails silently, a model gets rescheduled to CPU, or your cloud provider live-migrates you to different silicon, your compliance posture changed and nobody recorded it. Your cluster has NVIDIA nodes for training and Trainium nodes for inference -- the DaemonSet attests both, and the anchor chain shows when workloads move between them.
helm install swt3 oci://ghcr.io/tenova-labs/charts/swt3-witness --version 0.5.9
That is the entire setup. One command. Every node gets a witness pod. Every accelerator gets discovered. Every hour, an AI-HW.1 anchor is minted with the hardware fingerprint.
{
"swt3_witness": true,
"procedure": "AI-HW.1",
"anchor_fingerprint": "d8491581c715",
"silicon_vendor": "nvidia",
"topology": "multi",
"accelerator_count": 4,
"gpu_count": 4,
"total_memory_mb": 327680,
"clearing_level": 1,
"agent_id": "witness-node-gpu-pool-3a"
}
That JSON goes to stdout. Scrape it with Fluentd, Promtail, or any log pipeline. Filter: jq 'select(.swt3_witness == true)'.
When a node's hardware changes, consecutive anchors tell the story:
// 09:00 -- 4x NVIDIA H100, training workload
{"anchor_fingerprint":"d8491581c715","silicon_vendor":"nvidia","accelerator_count":4,"total_memory_mb":327680}
// 10:00 -- cloud provider live-migrated to Trainium, same node
{"anchor_fingerprint":"a3f7c2910eb4","silicon_vendor":"aws","accelerator_count":2,"total_memory_mb":65536}
The fingerprints are different because the hardware changed. An auditor or drift alert can compare consecutive anchors and see exactly when the silicon shifted, on which node, and whether the compliance posture held.
When you are ready to persist anchors to the clearing house, upgrade to cloud mode:
helm upgrade swt3 oci://ghcr.io/tenova-labs/charts/swt3-witness --version 0.5.9 \
--set config.mode=cloud \
--set cloud.apiKey=axm_YOUR_KEY \
--set cloud.tenantId=YOUR_TENANT
Both modes produce the same cryptographic anchors. The only difference is where they land.
Security posture: Non-root (UID 10001). Read-only root filesystem. All capabilities dropped. No privilege escalation. /sys mounted read-only for PCI discovery. Health endpoint on :9090. 46 MB image.
Open source (Apache-2.0). Source, Dockerfile, and Helm chart: github.com/tenova-labs/swt3-ai.
@tenova/swt3-mcp is listed on the official Model Context Protocol Registry as io.tenova/swt3-witness. Zero-config compliance governance for Claude Code, Cursor, Windsurf, and any MCP-compatible host.
{
"mcpServers": {
"swt3-witness": {
"command": "npx",
"args": ["@tenova/swt3-mcp"]
}
}
}
Every tool call your agent makes is witnessed, Merkle-accumulated, and trust-evaluated. No code changes required. Quick Start
Already have an MCP server? Wrap its transport for zero-code witnessing without installing the full 37-tool server:
import { withSWT3 } from "@tenova/swt3-mcp/middleware";
const transport = withSWT3(new StdioServerTransport(), {
apiKey: process.env.SWT3_API_KEY,
});
await server.connect(transport);
// Every tool call now auto-witnesses AI-TOOL.1 anchors
The middleware observes tool call request/response pairs at the transport layer. The response is already sent before the witness fires. Your tool handlers are never modified, blocked, or delayed.
The SWT3 Trust Mesh enables mutual cryptographic verification between AI agents before they exchange data, invoke tools, or share context. When you adopt SWT3, every partner, vendor, and downstream agent that wants to interact with yours must adopt it too. Compliance becomes the connection protocol. Every agent in the mesh strengthens the network.
You run Agent A. Your partner runs Agent B. Both install swt3-ai:
# === Your side (Agent A) ===
witness_a = Witness(
endpoint="...", api_key="axm_...", tenant_id="YOUR_TENANT",
agent_id="agent-alpha", signing_key="swt3_sk_your_key",
)
witness_a.trust_registry.trust_tenant("PARTNER_B_TENANT")
witness_a.trust_registry.register_signing_key("agent-beta", os.environ["PARTNER_B_KEY"])
# === Partner's side (Agent B) ===
witness_b = Witness(
endpoint="...", api_key="axm_...", tenant_id="PARTNER_B_TENANT",
agent_id="agent-beta", signing_key="swt3_sk_partner_key",
)
witness_b.trust_registry.trust_tenant("YOUR_TENANT")
witness_b.trust_registry.register_signing_key("agent-alpha", os.environ["YOUR_KEY"])
# === Handshake (both directions) ===
cred_a = witness_a.present_credential()
result = witness_b.verify_trust(cred_a) # B verifies A
if result.granted:
cred_b = witness_b.present_credential()
result = witness_a.verify_trust(cred_b) # A verifies B
if result.granted:
# Bidirectional trust established. Exchange data.
pass
Configure trust boundaries declaratively in .swt3.yaml:
trust_mesh:
mode: strict
min_trust_level: 2
require_signature: true
freshness_window: 3600
trusted_tenants: ["PARTNER_B_TENANT"]
deny_agents: ["revoked-agent-id"]
All verification is local. Zero cloud overhead. No data exchanged until both agents clear the trust gate. Unsigned agents are capped at TRUST_BASIC (level 1). Add signing keys for verified trust. Add hardware attestation for sovereign trust.
Verify any witness anchor without network calls. The fingerprint formula is deterministic and identical across all 10 SDK languages -- recompute it anywhere in microseconds.
from swt3_ai import verify_anchor
result = verify_anchor(
anchor,
tenant_id="<YOUR_TENANT_ID>",
procedure_id="AI-INF.1",
factor_a=1, factor_b=1, factor_c=0,
timestamp_ms=1773316622000,
)
# result.status: "CERTIFIED TRUTH" | "TAMPERED"
Zero vendor dependency. Zero network calls. Works air-gapped. The same formula runs in Python, TypeScript, Swift, Rust, C#, Ruby, Go, Kotlin, and MCP with identical output for identical inputs.
pip install swt3-ai
python -m swt3_ai.demo
The demo runs the full pipeline locally: hash, extract, clear, anchor, verify. It shows a Regulatory Coverage Summary mapping each check to EU AI Act articles, with gaps highlighted. No API keys, no network calls.
from swt3_ai import Witness
from openai import OpenAI
witness = Witness(
endpoint="https://your-witness-endpoint.example.com",
api_key="axm_live_...",
tenant_id="YOUR_TENANT",
)
client = witness.wrap(OpenAI())
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Summarize this contract..."}],
)
# response is untouched. Witnessing runs in the background.
print(response.choices[0].message.content)
No code changes to your existing logic. No performance impact. The SDK wraps your AI client transparently and witnesses every call.
When your AI makes a call, the SDK:
The result: an immutable record that your AI ran the right model, with the right guardrails, within the right boundaries. Without the auditor ever seeing the data.
If your AI agent calls tools or functions, wrap them to create a record of every invocation:
@witness.wrap_tool(tool_name="search_database")
def search(query: str) -> list:
return db.execute(query)
# Every call to search() now mints an anchor recording:
# - Tool name
# - Input/output hashes
# - Latency
# - Success or failure
This produces an AI-TOOL.1 anchor recording the tool name, input/output hashes, latency, and success or failure.
New in v0.2.10. Wrap any function your agent uses to access external resources. The SDK records what was accessed and whether it was within the agent's declared scope:
@witness.wrap_access(resource_name="customer-database", scope="read-only analytics")
def query_customers(sql: str) -> list:
return db.execute(sql)
# If the agent calls query_customers("DROP TABLE users"),
# the access is witnessed and compared against the declared scope.
# Out-of-scope access produces a FAIL verdict.
This produces an AI-ACC.1 anchor with three factors:
Out-of-scope access produces a FAIL verdict with a full evidence trail.
New in v0.2.10. The SDK separately hashes the system prompt (base instructions) for each inference. If your agent's instructions change between audit periods, the hash changes and the platform flags it as instruction drift.
This happens automatically. No configuration needed. The system prompt hash is extracted from:
role == "system"system parameterThe hash is included at clearing levels 0 and 1, stripped at levels 2 and 3.
New in v0.4.3. Witness what context chunks your RAG pipeline retrieves, from which corpus, and how relevant they are. Chunk text is never transmitted -- only SHA-256 hashes.
# Zero-friction: pass raw strings, SDK handles hashing
witness.witness_rag_context(
["chunk text 1", "chunk text 2", "chunk text 3"],
corpus_id="legal-docs-v3",
)
This mints an AI-RAG.1 (Context Retrieval Provenance) anchor. Add similarity scores to also get AI-RAG.2 (Context Relevance):
from swt3_ai import RagChunk
witness.witness_rag_context(
[
RagChunk(content_hash="abc123...", source_id="doc-7/p3", similarity_score=0.92),
RagChunk(content_hash="def456...", source_id="doc-2/p1", similarity_score=0.78),
RagChunk(content_hash="789abc...", source_id="doc-4/p2", similarity_score=0.61),
],
corpus_id="legal-docs-v3",
embedding_model="text-embedding-3-small",
similarity_threshold=0.75, # triggers AI-RAG.2
)
One call. Two procedures. Complete retrieval attestation.
LangChain auto-witnessing: If you use the SWT3CallbackHandler, retriever events are captured auto