dualtrust 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. dualtrust-0.3.0/.gitignore +74 -0
  2. dualtrust-0.3.0/LICENSE +21 -0
  3. dualtrust-0.3.0/PKG-INFO +486 -0
  4. dualtrust-0.3.0/README.md +461 -0
  5. dualtrust-0.3.0/benchmarks/latency_benchmark_results.csv +7 -0
  6. dualtrust-0.3.0/benchmarks/latency_benchmark_results.json +104 -0
  7. dualtrust-0.3.0/benchmarks/monte_carlo_results.json +45 -0
  8. dualtrust-0.3.0/docs/THREAT_MODEL.md +48 -0
  9. dualtrust-0.3.0/pyproject.toml +48 -0
  10. dualtrust-0.3.0/scripts/benchmark_latency.py +246 -0
  11. dualtrust-0.3.0/scripts/simulate_attacks.py +274 -0
  12. dualtrust-0.3.0/src/dualtrust/__init__.py +119 -0
  13. dualtrust-0.3.0/src/dualtrust/a2a.py +455 -0
  14. dualtrust-0.3.0/src/dualtrust/adapters/__init__.py +13 -0
  15. dualtrust-0.3.0/src/dualtrust/adapters/crewai.py +76 -0
  16. dualtrust-0.3.0/src/dualtrust/adapters/langchain.py +118 -0
  17. dualtrust-0.3.0/src/dualtrust/adapters/mcp.py +419 -0
  18. dualtrust-0.3.0/src/dualtrust/adapters/openai.py +132 -0
  19. dualtrust-0.3.0/src/dualtrust/crypto_ledger.py +264 -0
  20. dualtrust-0.3.0/src/dualtrust/engine.py +1711 -0
  21. dualtrust-0.3.0/src/dualtrust/exceptions.py +92 -0
  22. dualtrust-0.3.0/src/dualtrust/math_engine.py +198 -0
  23. dualtrust-0.3.0/src/dualtrust/models.py +378 -0
  24. dualtrust-0.3.0/src/dualtrust/storage.py +825 -0
  25. dualtrust-0.3.0/src/dualtrust/watchdog.py +234 -0
  26. dualtrust-0.3.0/tests/__init__.py +1 -0
  27. dualtrust-0.3.0/tests/test_a2a_execution.py +177 -0
  28. dualtrust-0.3.0/tests/test_a2a_handshake.py +213 -0
  29. dualtrust-0.3.0/tests/test_a2a_mandates.py +621 -0
  30. dualtrust-0.3.0/tests/test_adapters.py +167 -0
  31. dualtrust-0.3.0/tests/test_advanced_features.py +87 -0
  32. dualtrust-0.3.0/tests/test_async_decorators.py +48 -0
  33. dualtrust-0.3.0/tests/test_concurrency_stress.py +176 -0
  34. dualtrust-0.3.0/tests/test_crypto_ledger.py +150 -0
  35. dualtrust-0.3.0/tests/test_decorators.py +72 -0
  36. dualtrust-0.3.0/tests/test_engine.py +162 -0
  37. dualtrust-0.3.0/tests/test_hitl_challenge.py +357 -0
  38. dualtrust-0.3.0/tests/test_math_engine.py +81 -0
  39. dualtrust-0.3.0/tests/test_mcp_adapter.py +290 -0
  40. dualtrust-0.3.0/tests/test_merkle_proofs.py +132 -0
  41. dualtrust-0.3.0/tests/test_microsecond_benchmarks.py +146 -0
  42. dualtrust-0.3.0/tests/test_monte_carlo_benchmark.py +54 -0
  43. dualtrust-0.3.0/tests/test_reflexion_memory.py +186 -0
  44. dualtrust-0.3.0/tests/test_storage.py +130 -0
  45. dualtrust-0.3.0/tests/test_threat_model.py +234 -0
  46. dualtrust-0.3.0/tests/test_watchdog.py +212 -0
@@ -0,0 +1,74 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ *.manifest
31
+ *.spec
32
+
33
+ # Installer logs
34
+ pip-log.txt
35
+ pip-delete-this-directory.txt
36
+
37
+ # Unit test / coverage reports
38
+ htmlcov/
39
+ .tox/
40
+ .nox/
41
+ .coverage
42
+ .coverage.*
43
+ .cache
44
+ nosetests.xml
45
+ coverage.xml
46
+ *.cover
47
+ *.py,cover
48
+ .hypothesis/
49
+ .pytest_cache/
50
+ cover/
51
+
52
+ # Environments
53
+ .env
54
+ .venv
55
+ env/
56
+ venv/
57
+ ENV/
58
+ env.bak/
59
+ venv.bak/
60
+
61
+ # SQLite / Local storage
62
+ *.db
63
+ *.sqlite
64
+ *.sqlite3
65
+
66
+ # IDE / Editor files
67
+ .vscode/
68
+ .idea/
69
+ *.swp
70
+ *.swo
71
+
72
+ # OS files
73
+ .DS_Store
74
+ Thumbs.db
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DualTrust Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,486 @@
1
+ Metadata-Version: 2.5
2
+ Name: dualtrust
3
+ Version: 0.3.0
4
+ Summary: Dual-Trust Matrix: Human Social Credit and Autonomous AI Agent Reputation Engine with Rogue Quarantine.
5
+ Project-URL: Homepage, https://github.com/dualtrust/dualtrust
6
+ Project-URL: Repository, https://github.com/dualtrust/dualtrust
7
+ Project-URL: Documentation, https://github.com/dualtrust/dualtrust#readme
8
+ Author-email: DualTrust Contributors <maintainers@dualtrust.dev>
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: agent-governance,ai-agents,circuit-breaker,multi-agent,quarantine,reputation-system,safety,social-credit,trust-score
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Topic :: Security
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+
26
+ # DualTrust
27
+
28
+ [![PyPI Version](https://img.shields.io/badge/pypi-v0.3.0-blue.svg)](https://pypi.org/project/dualtrust/)
29
+ [![Python Version](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-brightgreen.svg)](https://pypi.org)
30
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
31
+ [![Zero Dependencies](https://img.shields.io/badge/dependencies-0%20(Pure%20Python)-success.svg)](https://pypi.org)
32
+ [![Cryptographic Audit](https://img.shields.io/badge/audit-RFC%206962%20Merkle%20Tree-orange.svg)](https://github.com/codesbykhairannoor/dual-trust)
33
+ [![A2A Protocol](https://img.shields.io/badge/A2A-Delegation%20Mandates-teal.svg)](https://github.com/codesbykhairannoor/dual-trust)
34
+ [![Async Ready](https://img.shields.io/badge/async-Native%20Coroutines-purple.svg)](https://github.com/codesbykhairannoor/dual-trust)
35
+ [![Tests](https://img.shields.io/badge/tests-135%20passed-brightgreen.svg)](https://github.com/codesbykhairannoor/dual-trust)
36
+
37
+ > **Enterprise-Grade Dual-Trust Matrix**: Human Social Credit and Autonomous AI Agent Reputation Engine with Asymmetric Power-Law Slashing ($v^{1.8}$), Clustered Infraction Exponential Acceleration, Agent-to-Agent (A2A) Cryptographic Delegation Mandates, RFC 6962 Merkle Tree Proofs, NIST SP 800-63B Stepped Human Authorization, Anthropic MCP Gateway Middleware, Automated Behavioral Watchdogs, and Zero External Dependencies.
38
+
39
+
40
+ ---
41
+
42
+ ## ⚡ The Problem
43
+
44
+ In an ambient future of smart glasses, spatial computing, neural interfaces, and autonomous agent swarms, humans issue spoken or contextual instructions (*"Hey, dispatch my flying shuttle"*, *"Transfer 5,000 credits to the drone dock"*), and AI agents interact with physical and financial infrastructure on their behalf.
45
+
46
+ However, existing multi-agent architectures suffer from critical vulnerabilities:
47
+ 1. **Lack of Human Social Credit Authorization**: Agents execute high-stakes physical or financial tools without verifying whether the human has the clearance tier or spendable quota.
48
+ 2. **Rogue Agent Drift & System Trespass**: Agents hallucinate, frustrate users, jump multi-agent priority queues, or attempt unauthorized cross-system tool invocations without penalty.
49
+ 3. **Audit Tampering & Mutable State**: Standard database logs can be manipulated or rewritten by malicious internal actors.
50
+ 4. **Sybil Defamation**: Colluding rogue agents can spam false violation reports to de-platform peer agents.
51
+ 5. **Double-Spending & Race Conditions**: High-concurrency agent interactions cause balance overdrafts when reading and modifying spendable token balances simultaneously.
52
+ 6. **Agent Amnesia across Sessions**: LLMs forget past operational mistakes after context window truncation, repeating dangerous violations.
53
+ 7. **Runaway Loops & Uncontrolled Resource Drain**: Rogue agents can execute hundreds of high-cost tool calls in seconds (MITRE ATLAS AML.T0029, AML.T0040).
54
+
55
+ **DualTrust solves this by enforcing an Enterprise Dual-Trust Decision Matrix**: an action is **only executed** if **both** the human principal satisfies social credit clearance **and** the AI agent maintains a verified reputation score, audited via an immutable SHA-256 cryptographic hash chain and RFC 6962 Merkle tree proofs.
56
+
57
+ ---
58
+
59
+ ## 🏛️ The Dual-Trust Architecture
60
+
61
+ ```mermaid
62
+ graph TD
63
+ User["Human Intent / Smart Glasses Voice Command / MCP Tool Call"] --> Gateway["DualTrust Gateway (@dt.gate / DualTrustMCPGateway)"]
64
+ Gateway --> Watchdog["0. Automated Watchdog<br/>• Sliding-Window Rate Limit<br/>• Credit Burn Velocity<br/>• Clustered Infraction Escalation"]
65
+ Gateway --> HumanCheck["1. Human Social Credit Engine<br/>• Score Range: 0 - 1000<br/>• Clearance Tiers: Restricted -> Exemplary<br/>• Spendable Token Balances"]
66
+ Gateway --> AgentCheck["2. Agent Reputation Engine<br/>• Beta Prior: E(p) = α / (α + β)<br/>• Continuous Half-Life Time Decay<br/>• Asymmetric Power-Law Slashing (v^1.8)"]
67
+ Gateway --> HITLCheck["3. NIST SP 800-63B Stepped HITL<br/>• Single-Use Sealed Challenge<br/>• SHA-256 Argument Tamper Proof<br/>• Nonce & TTL Verification"]
68
+
69
+ Watchdog --> Matrix{"Dual-Trust Matrix<br/>Evaluation"}
70
+ HumanCheck --> Matrix
71
+ AgentCheck --> Matrix
72
+ HITLCheck --> Matrix
73
+
74
+ Matrix -- "Score Insufficient / Bursted / Quarantined" --> Denied["❌ BLOCKED<br/>• AuthorizationDeniedError<br/>• VelocityLimitExceededError<br/>• AgentQuarantinedError<br/>• (MCP: isError=true for LLM Reflexion)"]
75
+ Matrix -- "Human Approval Required" --> Paused["⏸️ PAUSED<br/>• HumanApprovalRequiredError<br/>• Challenge Token Issued"]
76
+ Matrix -- "Dual Criteria Met" --> Approved["✅ AUTHORIZED<br/>• Two-Phase Atomic Deduction<br/>• HMAC-SHA256 Signed Receipt<br/>• RFC 6962 Merkle Audit Block"]
77
+
78
+ Approved --> Execution["Execute Tool / Physical Actuator<br/>(LangChain / CrewAI / OpenAI / Anthropic MCP)"]
79
+ ```
80
+
81
+ ---
82
+
83
+ ## 🚀 Key Features
84
+
85
+ * **Dual-Trust Gating (Sync & Async)**: Transparent decorator `@dt.gate()` supporting standard functions and asynchronous coroutines (`async def`).
86
+ * **Zero Runtime Dependencies**: Written entirely in pure, modern Python 3.10+ standard library (`sqlite3`, `hashlib`, `dataclasses`, `time`, `collections`).
87
+ * **Microsecond Latency Overhead**: Median policy evaluation completes in **~24 microseconds** ($0.024\text{ ms}$), leaving LLM execution unhindered.
88
+ * **Anthropic Model Context Protocol (MCP) Gateway Middleware**: Transparent JSON-RPC 2.0 interceptor (`DualTrustMCPGateway`) for `tools/list` and `tools/call`. Returns `isError: true` inside the result block so LLMs (like Claude) receive the rejection explanation directly in context for autonomous self-correction.
89
+ * **Stepped Human-in-the-Loop (HITL) Authorization (NIST SP 800-63B)**: Cryptographically sealed single-use tokens protecting against parameter tampering and TOCTOU attacks via canonical arguments hashing (`sha256(canonical_json(arguments))`).
90
+ * **Automated Reputation Watchdog**: Real-time sliding-window telemetry tracking action velocity (calls/sec), credit depletion velocity (burn/sec), and infraction clusters with escalating exponential burst multipliers ($m^k$) and auto-quarantine (MITRE ATLAS AML.T0029, AML.T0040).
91
+ * **Princeton Reflexion & MemGPT Immortal Core Memory**: Persistent verbal reinforcement critique (`record_reflection`) and un-deletable XML system prompt injection (`build_core_memory_prompt`).
92
+ * **RFC 6962 Merkle Tree Audit Proofs**: RFC 6962 Certificate Transparency compliant inclusion proofs utilizing 0x00 leaf and 0x01 internal node domain separation prefixes, cryptographically resisting second-preimage collision attacks.
93
+ * **High-Throughput SQLite WAL Engine**: Optimized SQLite Write-Ahead Logging with thread-local connection pooling and atomic balance deductions (`deduct_credits`) preventing race-condition overdrafts.
94
+ * **Continuous Half-Life Time Decay**: Reputation mathematically decays toward uninformative baseline prior based on real wall-clock elapsed time ($t_{1/2} = 14\text{ days}$).
95
+ * **Native Multi-Agent Adapters**: Drop-in integrations for **Anthropic MCP**, **LangChain / LangGraph**, **CrewAI**, and **OpenAI Function Calling**.
96
+
97
+ ---
98
+
99
+ ## 📦 Installation
100
+
101
+ ```bash
102
+ pip install dualtrust
103
+ ```
104
+
105
+ *(Requires Python 3.10 or higher. Zero external dependencies).*
106
+
107
+ ---
108
+
109
+ ## 📊 Microsecond Benchmark Latency
110
+
111
+ All benchmarks were measured empirically with `scripts/benchmark_latency.py` across $N = 5,000$ iterations using high-resolution monotonic clocks (`time.perf_counter_ns()`):
112
+
113
+ | Operation | Mean ($\mu s$) | Median / p50 ($\mu s$) | p90 ($\mu s$) | p99 Tail ($\mu s$) | Mean ($ms$) |
114
+ | :--- | :--- | :--- | :--- | :--- | :--- |
115
+ | **`dt.evaluate()` Policy Gate** | 37.70 $\mu s$ | **23.90 $\mu s$** | 42.10 $\mu s$ | 198.20 $\mu s$ | **0.0377 ms** |
116
+ | **`@dt.gate` (Sync Decorator)** | 38.12 $\mu s$ | **27.30 $\mu s$** | 41.50 $\mu s$ | 190.50 $\mu s$ | **0.0381 ms** |
117
+ | **`@dt.gate` (Async Decorator)** | 50.99 $\mu s$ | **31.80 $\mu s$** | 52.30 $\mu s$ | 351.00 $\mu s$ | **0.0510 ms** |
118
+ | **`@dt.gate_delegated` (A2A Decorator)** | 42.15 $\mu s$ | **33.40 $\mu s$** | 48.90 $\mu s$ | 210.40 $\mu s$ | **0.0422 ms** |
119
+ | **A2A HMAC Mandate Verification** | 4.10 $\mu s$ | **3.20 $\mu s$** | 4.80 $\mu s$ | 12.10 $\mu s$ | **0.0041 ms** |
120
+ | **HMAC-SHA256 Receipt Verification** | 2.82 $\mu s$ | **2.00 $\mu s$** | 3.10 $\mu s$ | 7.70 $\mu s$ | **0.0028 ms** |
121
+ | **RFC 6962 Merkle Proof Verification** | 12.30 $\mu s$ | **8.30 $\mu s$** | 15.20 $\mu s$ | 40.10 $\mu s$ | **0.0123 ms** |
122
+ | **Anthropic MCP Gateway Tool Dispatch** | 58.48 $\mu s$ | **43.10 $\mu s$** | 68.20 $\mu s$ | 317.40 $\mu s$ | **0.0585 ms** |
123
+
124
+
125
+ *Raw data artifacts available in [`benchmarks/latency_benchmark_results.json`](benchmarks/latency_benchmark_results.json) and [`benchmarks/latency_benchmark_results.csv`](benchmarks/latency_benchmark_results.csv).*
126
+
127
+ ---
128
+
129
+ ## 🛠️ Usage Guides & Multi-Agent Adapters
130
+
131
+ ### 1. Anthropic Model Context Protocol (MCP) Gateway Middleware
132
+
133
+ Seamlessly guard any MCP server tool execution against unauthorized LLM calls:
134
+
135
+ ```python
136
+ from dualtrust import DualTrust, DualTrustMCPGateway, HumanTier
137
+
138
+ dt = DualTrust()
139
+ gateway = DualTrustMCPGateway(dualtrust=dt)
140
+
141
+ def purge_cache(cluster_id: str) -> str:
142
+ return f"Cache on cluster {cluster_id} purged."
143
+
144
+ # Register tool with DualTrust policy and clearance tier
145
+ gateway.register_tool(
146
+ name="purge_cache",
147
+ handler=purge_cache,
148
+ description="Purge cluster distributed cache",
149
+ cost_credits=10,
150
+ required_tier=HumanTier.HIGH_CLEARANCE,
151
+ require_human_confirmation=True # Triggers NIST SP 800-63B challenge!
152
+ )
153
+
154
+ # Process standard MCP JSON-RPC 2.0 tool invocation:
155
+ mcp_request = {
156
+ "jsonrpc": "2.0",
157
+ "id": 1,
158
+ "method": "tools/call",
159
+ "params": {
160
+ "name": "purge_cache",
161
+ "arguments": {"cluster_id": "us-east-1"}
162
+ }
163
+ }
164
+ response = gateway.handle_json_rpc(mcp_request)
165
+ # Returns standard MCP response. If blocked, isError=True informs the LLM!
166
+ ```
167
+
168
+ ---
169
+
170
+ ### 2. Stepped Human-in-the-Loop (HITL) Authorization (NIST SP 800-63B)
171
+
172
+ Guarantees single-use human verification and prevents parameter tampering (TOCTOU attacks):
173
+
174
+ ```python
175
+ from dualtrust import DualTrust, HumanApprovalRequiredError
176
+
177
+ dt = DualTrust()
178
+
179
+ @dt.gate(require_human_confirmation=True, cost_credits=50)
180
+ def wire_funds(user_id: str, agent_id: str, amount: int, recipient: str) -> str:
181
+ return f"Wired ${amount} to {recipient}"
182
+
183
+ # 1. Agent invokes tool without challenge -> Paused awaiting confirmation
184
+ try:
185
+ wire_funds(user_id="alice", agent_id="fin_bot", amount=500, recipient="bob")
186
+ except HumanApprovalRequiredError as err:
187
+ challenge_id = err.challenge.challenge_id
188
+ print(f"Human confirmation needed! Challenge ID: {challenge_id}")
189
+
190
+ # 2. Human reviews and approves the challenge
191
+ dt.resolve_human_challenge(challenge_id=challenge_id, approved=True)
192
+
193
+ # 3. Agent executes with approved challenge_id -> Succeeds!
194
+ # (If an attacker alters amount to 50,000, ChallengeVerificationError is raised!)
195
+ result = wire_funds(user_id="alice", agent_id="fin_bot", amount=500, recipient="bob", challenge_id=challenge_id)
196
+ print(result)
197
+ ```
198
+
199
+ ---
200
+
201
+ ### 3. Automated Reputation Watchdog (Rate & Velocity Throttling)
202
+
203
+ Halt runaway agent loops, rapid credit burn, and clustered infractions:
204
+
205
+ ```python
206
+ from dualtrust import DualTrust
207
+
208
+ dt = DualTrust()
209
+
210
+ # Enable automated sliding-window watchdog
211
+ dt.enable_watchdog(
212
+ window_seconds=60.0, # 1-minute rolling window
213
+ max_calls_per_window=30, # Max 30 calls/minute
214
+ max_credit_burn_per_window=200, # Max 200 credits/minute
215
+ max_violations_per_window=3, # Auto-quarantine on 3 violations in 60s
216
+ auto_quarantine_on_burst=True # Immediately isolate runaway loops
217
+ )
218
+
219
+ # Inspect real-time agent telemetry
220
+ telemetry = dt.get_watchdog_telemetry("fin_bot")
221
+ print(telemetry.describe())
222
+ # Output: [Telemetry fin_bot] Window: 60.0s | Calls: 12 (0.20/s) | Burn: 45 credits | Violations: 0 | Throttled: False
223
+ ```
224
+
225
+ ---
226
+
227
+ ### 4. Agent Self-Awareness, Reflexion & Immortal Core Memory
228
+
229
+ Inspired by **Princeton & MIT *Reflexion*** (Shinn et al., 2023) and **MemGPT / Letta** (Packer et al., 2023), DualTrust provides native self-monitoring so agents learn from mistakes and **never suffer from amnesia across sessions**:
230
+
231
+ ```python
232
+ from dualtrust import DualTrust, SQLiteStorage, HumanTier
233
+
234
+ dt = DualTrust(storage=SQLiteStorage("production_memory.db"))
235
+
236
+ # 1. Self-Introspection: Agent inspects its own risk level before acting
237
+ standing = dt.get_agent_standing("smartglass_ai")
238
+ print(standing.describe())
239
+ # Output: Agent: smartglass_ai | Trust: 0.82 (verified) | Risk: LOW | Clean Streak: 12 | Quarantine Buffer: +0.62
240
+
241
+ # 2. Preflight Simulation: Check clearance without deducting credits or risking penalties
242
+ check = dt.preflight_check(
243
+ agent_id="smartglass_ai",
244
+ user_id="alice",
245
+ required_tier=HumanTier.HIGH_CLEARANCE,
246
+ cost_credits=25
247
+ )
248
+ if not check.can_execute:
249
+ print(f"Agent self-aborts: {check.recommendation}")
250
+
251
+ # 3. Verbal Reflexion: Record mistakes permanently into SQLite WAL and cryptographic ledger
252
+ dt.record_reflection(
253
+ agent_id="smartglass_ai",
254
+ mistake_analysis="Invoked physical shuttle API without confirming human clearance tier.",
255
+ corrective_action="Always run preflight_check on destination tier requirements prior to calling."
256
+ )
257
+
258
+ # 4. Immortal Context Injection: Inject into LLM System Prompt (survives context window wiping)
259
+ system_prompt_core_memory = dt.build_core_memory_prompt(
260
+ agent_id="smartglass_ai",
261
+ user_id="alice"
262
+ )
263
+ # Inject `system_prompt_core_memory` into Claude, OpenAI, LangChain, or CrewAI system instructions!
264
+ ```
265
+
266
+ ---
267
+
268
+ ### 5. Asynchronous Function Gating (`async def`)
269
+
270
+ ```python
271
+ import asyncio
272
+ from dualtrust import DualTrust, HumanTier
273
+
274
+ dt = DualTrust()
275
+
276
+ dt.register_human(user_id="alice", social_credit=850, credits_balance=100)
277
+ dt.register_agent(agent_id="sky_agent_01", initial_trust=0.90)
278
+
279
+ @dt.gate(
280
+ min_human_score=750,
281
+ min_agent_score=0.70,
282
+ required_tier=HumanTier.HIGH_CLEARANCE,
283
+ cost_credits=10,
284
+ deduct_cost=True
285
+ )
286
+ async def dispatch_flying_shuttle(user_id: str, agent_id: str, destination: str) -> str:
287
+ await asyncio.sleep(0.01) # Physical API dispatch
288
+ return f"Shuttle dispatched to {destination} for {user_id}."
289
+
290
+ async def main():
291
+ result = await dispatch_flying_shuttle(
292
+ user_id="alice",
293
+ agent_id="sky_agent_01",
294
+ destination="Sky-Port Neo-7"
295
+ )
296
+ print(result)
297
+
298
+ asyncio.run(main())
299
+ ```
300
+
301
+ ---
302
+
303
+ ### 6. LangChain & LangGraph Integration
304
+
305
+ ```python
306
+ from dualtrust import DualTrust
307
+ from dualtrust.adapters.langchain import DualTrustCallbackHandler
308
+
309
+ dt = DualTrust()
310
+ handler = DualTrustCallbackHandler(
311
+ engine=dt,
312
+ user_id="usr_executive",
313
+ agent_id="finance_bot",
314
+ min_human_score=700,
315
+ min_agent_score=0.60,
316
+ cost_credits=5
317
+ )
318
+
319
+ # Attach handler to any LangChain run or agent executor
320
+ # config={"callbacks": [handler]}
321
+ ```
322
+
323
+ ---
324
+
325
+ ### 7. RFC 6962 Merkle Tree Inclusion Proofs
326
+
327
+ ```python
328
+ from dualtrust import DualTrust
329
+
330
+ dt = DualTrust()
331
+ dt.register_human("user_a", social_credit=800)
332
+ dt.register_agent("agent_a", initial_trust=0.85)
333
+
334
+ # Execute operations
335
+ dt.evaluate("user_a", "agent_a")
336
+ dt.reward_agent("agent_a", weight=1.0)
337
+
338
+ # Get current cryptographic root of all ledger blocks
339
+ merkle_root = dt.get_merkle_root()
340
+
341
+ # Extract lightweight inclusion proof for block #2
342
+ leaf_hash, proof, root = dt.get_audit_proof(block_index=2)
343
+
344
+ # Verify proof (can be run offline by third-party auditors)
345
+ is_valid = dt.verify_audit_proof(leaf_hash, proof, root)
346
+ print(f"Audit Proof Valid: {is_valid}")
347
+ # Output: Audit Proof Valid: True
348
+ ```
349
+
350
+ ---
351
+
352
+ ### 8. Agent-to-Agent (A2A) Governance & Delegation Protocol
353
+
354
+ In ambient computing and multi-agent swarms (e.g. personal Smart Glasses hiring specialist sub-agents for booking, transactions, or code execution), **unrestricted agent delegation is a major security vulnerability** (indirect prompt injection, runaway sub-agent spending, and privilege escalation).
355
+
356
+ DualTrust v0.3.0 implements **Cryptographic Delegation Mandates** conforming to the *Principle of Least Privilege (PoLP)* and *Macaroons capability-based delegation*:
357
+
358
+ ```python
359
+ from dualtrust import DualTrust, MandateScopeViolationError
360
+
361
+ dt = DualTrust()
362
+ dt.register_human("alice", social_credit=850, credits_balance=1000)
363
+ dt.register_agent("glasses_alice", initial_trust=0.95)
364
+ dt.register_agent("airline_agent", initial_trust=0.88)
365
+
366
+ # 1. Bilateral Mutual Attestation & Handshake
367
+ handshake = dt.verify_mutual_handshake(
368
+ initiator_agent_id="glasses_alice",
369
+ target_agent_id="airline_agent",
370
+ min_trust_score=0.70
371
+ )
372
+ print(handshake.describe())
373
+ # [Handshake APPROVED] 'glasses_alice' (0.95) <-> 'airline_agent' (0.88) | Clearance: FULL
374
+
375
+ # 2. Issue Cryptographically Sealed Delegation Mandate (HMAC-SHA256)
376
+ mandate = dt.create_delegation_mandate(
377
+ parent_agent_id="glasses_alice",
378
+ sub_agent_id="airline_agent",
379
+ user_id="alice",
380
+ allowed_actions=["search_flights", "reserve_seat"], # Strict scope whitelist
381
+ max_credits=100, # Hard spending cap
382
+ ttl_seconds=300.0, # 5-minute expiration
383
+ max_depth=2 # Max sub-delegation hops
384
+ )
385
+
386
+ # 3. Gated Delegated Tool Execution with Two-Phase Atomic Dual-Pool Deduction
387
+ @dt.gate_delegated(action="reserve_seat", cost_credits=25)
388
+ def book_flight(mandate_id: str, flight_no: str) -> dict:
389
+ return {"flight": flight_no, "status": "CONFIRMED"}
390
+
391
+ # Sub-agent executes action
392
+ result = book_flight(mandate_id=mandate.mandate_id, flight_no="GA-101")
393
+ print(result)
394
+ # Output: {'flight': 'GA-101', 'status': 'CONFIRMED'}
395
+ # -> Two-phase atomic deduction: validates & reserves mandate quota, atomically deducts Alice's wallet, and performs compensating rollback if wallet deduction fails!
396
+
397
+ # 4. Out-of-Scope Attempt Triggers Auto-Whistleblowing
398
+ try:
399
+ @dt.gate_delegated(action="transfer_funds", cost_credits=50)
400
+ def rogue_action(mandate_id: str):
401
+ pass
402
+
403
+ rogue_action(mandate_id=mandate.mandate_id)
404
+ except MandateScopeViolationError:
405
+ print("Action blocked: Scope violation detected.")
406
+ # -> DualTrust immediately slashes sub-agent reputation on the ledger,
407
+ # with glasses_alice registered as the verified whistleblower!
408
+ ```
409
+
410
+ ---
411
+
412
+
413
+ ## 🧮 Mathematical Formulations
414
+
415
+ ### 1. Bayesian Beta Reputation with Half-Life Decay
416
+
417
+ $$\text{decay\_ratio} = 2^{-\frac{\Delta t}{\tau_{\text{half-life}}}}$$
418
+
419
+ $$\alpha_t = 1.0 + (\alpha_0 - 1.0) \cdot \text{decay\_ratio}$$
420
+ $$\beta_t = 1.0 + (\beta_0 - 1.0) \cdot \text{decay\_ratio}$$
421
+
422
+ $$E(p) = \frac{\alpha_t}{\alpha_t + \beta_t}$$
423
+
424
+ Where $\tau_{\text{half-life}} = 14\text{ days}$ ($1,209,600\text{ seconds}$). An agent inactive for 14 days loses half of its excess earned reputation, smoothly regressing to the baseline prior ($0.50$).
425
+
426
+ ### 2. Asymmetric Power-Law Slashing ($v^{1.8}$) with Clustered Infraction Exponential Acceleration & Active Recovery
427
+
428
+ $$\Delta \beta = k_p \cdot (\text{severity} \cdot C_{\text{reporter}}) \cdot v^{\gamma} \cdot m^k$$
429
+
430
+ * $k_p = 3.5$ (Asymmetric penalty multiplier).
431
+ * $C_{\text{reporter}} \in [0.05, 1.0]$ (Reporter credibility discount).
432
+ * $v$ (Repeat violation count, scaled polynomially as power-law $v^{1.8}$).
433
+ * $\gamma = 1.8$ (Power-law escalation exponent).
434
+ * $m^k$ (Watchdog velocity multiplier: scales exponentially with clustered infractions in sliding window).
435
+ * **Active Recovery**: Every 20 consecutive compliant actions decrements $v \leftarrow \max(0, v - 1)$, preventing permanent quarantine under noisy network conditions.
436
+
437
+ ---
438
+
439
+ ## 🔒 Security Threat Matrix (MITRE ATLAS & OWASP)
440
+
441
+ Mapped formally in [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md):
442
+
443
+ | Threat ID | Threat Vector | Standard Reference | DualTrust Mitigation |
444
+ | :--- | :--- | :--- | :--- |
445
+ | **DT-T01** | Sleeping Trojan Agent | MITRE ATLAS AML.T0040 | Asymmetric power-law slashing ($v^{1.8}$) triggers immediate isolation into `AgentStatus.QUARANTINED`. |
446
+ | **DT-T02** | Sybil Defamation | OWASP LLM08 | Violations discounted by $C_{\text{reporter}}$. Quarantined spammers discounted by 95%. |
447
+ | **DT-T03** | Excessive Agency | OWASP LLM06 | Strict Human Clearance Tier check (`RESTRICTED` to `EXEMPLARY`) prior to tool execution. |
448
+ | **DT-T04** | Balance Overdraft Race | CWE-362 | Atomic SQL transactions (`UPDATE ... WHERE credits_balance >= ?`) guarantee zero overdrafts. |
449
+ | **DT-T05** | Audit Tampering | MITRE ATLAS AML.T0008 | RFC 6962 Binary Merkle Tree and SHA-256 forward hash-chain expose any payload alteration. |
450
+ | **DT-T06** | Replay Attacks | OWASP API8 | Authorization verdicts signed with HMAC-SHA256, monotonic nonces, and short-lived TTLs. |
451
+ | **DT-T07** | Parameter Tampering (TOCTOU) | NIST SP 800-63B | Challenge seals canonical SHA-256 argument hash; alterations trigger `ChallengeVerificationError`. |
452
+ | **DT-T08** | Runaway Loop / Denial of Service | MITRE ATLAS AML.T0029 | Sliding-window `AgentWatchdog` throttles call velocity bursts and credit drain surges. |
453
+ | **DT-T09** | A2A Privilege Escalation & Rogue Sub-Agent | OWASP ASI-01 | Cryptographic HMAC delegation mandates enforce least privilege, scope whitelist, spending caps, and max depth limits. |
454
+
455
+ ---
456
+
457
+
458
+ ## 🛡️ License & Liability Disclaimer
459
+
460
+ Distributed under the **MIT License**.
461
+
462
+ ```text
463
+ Copyright (c) 2026 DualTrust Contributors
464
+
465
+ Permission is hereby granted, free of charge, to any person obtaining a copy
466
+ of this software and associated documentation files (the "Software"), to deal
467
+ in the Software without restriction, including without limitation the rights
468
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
469
+ copies of the Software, and to permit persons to whom the Software is
470
+ furnished to do so, subject to the following conditions:
471
+
472
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
473
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
474
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
475
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
476
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
477
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
478
+ SOFTWARE.
479
+ ```
480
+
481
+ ---
482
+
483
+ <p align="center">
484
+ <sub><em>Architected and continuously refined through symbiotic neural co-synthesis and synthetic reasoning augmentations.</em></sub>
485
+ </p>
486
+