sovereign-sdk-core 1.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.
@@ -0,0 +1,480 @@
1
+ Metadata-Version: 2.4
2
+ Name: sovereign-sdk-core
3
+ Version: 1.3.0
4
+ Summary: Core schemas and protocols for Sovereign Systems
5
+ Author-email: kenwalger <kenalger@comcast.net>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/kenwalger/sovereign-sdk
8
+ Project-URL: Repository, https://github.com/kenwalger/sovereign-sdk
9
+ Project-URL: Changelog, https://github.com/kenwalger/sovereign-sdk/blob/main/CHANGELOG.md
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Topic :: Security
14
+ Classifier: Topic :: Software Development :: Libraries
15
+ Requires-Python: >=3.12
16
+ Description-Content-Type: text/markdown
17
+ Requires-Dist: cryptography>=48.0.0
18
+ Requires-Dist: pydantic>=2.7.0
19
+
20
+ # Sovereign Systems SDK
21
+
22
+ **High-Integrity Cryptographic Provenance and Inbound Protection Boundaries for Agentic Workflows.**
23
+
24
+ Sovereign Systems is a local-first AI WAF and compliance gate. It intercepts every inbound payload before it reaches a model or agentic loop, strips high-entropy boilerplate, and seals the result with an Ed25519-signed `ForensicReceipt` that gives enterprise auditors mathematical proof of un-tampered boundary transformation — all running on local silicon with no external service dependency.
25
+
26
+ Every boundary crossing produces a non-repudiable chain of custody: the receipt binds the sieved payload hash and the full transformation accounting inside a single cryptographic envelope. No post-hoc mutation of the output or its metrics can go undetected.
27
+
28
+ To learn more about the philosophy and reasoning behind this project, see [PHILOSOPHY.md](PHILOSOPHY.md).
29
+
30
+ ---
31
+
32
+ ## Why an AI WAF?
33
+
34
+ Modern agentic pipelines ingest user intent through prompt text. That text is routinely bloated with conversational filler — greetings, hedging adverbs, redundant preambles — that inflates token budgets and introduces non-deterministic reasoning noise without contributing semantic content. At the same time, enterprises operating LLM workloads need the same compliance guarantees they expect from a network WAF: proof that payloads were inspected, proof that the inspection was faithful, and an append-only audit log that is tamper-evident after the fact.
35
+
36
+ Sovereign Systems provides both:
37
+
38
+ - **Inbound boundary enforcement** — every payload is sieved before a model or tool sees it.
39
+ - **Cryptographic chain of custody** — every sieved payload is sealed with a node-local Ed25519 private key into a `ForensicReceipt` that persists forever.
40
+ - **Non-repudiation** — the receipt covers the output hash and the transformation accounting under the same signature, so neither the result nor the metrics can be altered without breaking verification.
41
+ - **Local-only execution** — no telemetry leaves the host; key material never leaves the node.
42
+
43
+ ---
44
+
45
+ ## Workspace Topography
46
+
47
+ This repository is managed as an integrated `uv` workspace separating the cryptographic data tier from the execution runtime:
48
+
49
+ ```text
50
+ .
51
+ ├── .github/
52
+ │ └── workflows/
53
+ │ ├── publish.yml # PyPI release pipeline
54
+ │ └── test.yml # CI test matrix
55
+
56
+ ├── examples/
57
+ │ └── fastapi_gateway/
58
+ │ ├── app.py # Example FastAPI server with SovereignMiddleware
59
+ │ └── client.py # Example HTTP client
60
+
61
+ ├── packages/
62
+ │ ├── sovereign-core/ # Pure data tier (zero high-compute dependencies)
63
+ │ │ ├── src/sovereign_core/
64
+ │ │ │ ├── cli.py # CLI entry points (sovereign-verify)
65
+ │ │ │ ├── crypto.py # Ed25519 key management & ForensicReceipt minting
66
+ │ │ │ ├── gateway.py # Prose Tax sieve & SovereignGateway high-level API
67
+ │ │ │ └── py.typed
68
+ │ │ └── tests/
69
+ │ │ ├── test_crypto.py
70
+ │ │ ├── test_gateway.py
71
+ │ │ └── test_verification_protocol.py
72
+ │ │
73
+ │ ├── sovereign-runtime/ # Compute/Execution tier (tool & model isolation)
74
+ │ │ └── src/sovereign_runtime/
75
+ │ │ ├── router.py # Intent-based pre-flight namespace exposure
76
+ │ │ ├── __main__.py # sovereign-node entry point
77
+ │ │ └── py.typed
78
+ │ │
79
+ │ └── sovereign-fastapi/ # FastAPI/Starlette ASGI middleware adapter
80
+ │ ├── src/sovereign_fastapi/
81
+ │ │ ├── middleware.py # SovereignMiddleware — sieve-and-sign request interceptor
82
+ │ │ └── py.typed
83
+ │ └── tests/
84
+ │ └── test_middleware.py
85
+
86
+ ├── example.env # Environment variable reference
87
+ ├── main.py # Workspace-level development entry point
88
+ ├── pyproject.toml # Monorepo configuration & workspace links
89
+ └── uv.lock # Deterministic dependency lockfile
90
+ ```
91
+
92
+ ---
93
+
94
+ ## The ForensicReceipt: Sealed Transformation Accounting
95
+
96
+ Every boundary crossing produces a `ForensicReceipt`. Understanding its structure explains exactly what an enterprise auditor can prove from the output alone.
97
+
98
+ ### What is sealed
99
+
100
+ The Ed25519 signature inside every receipt covers a single canonical manifest:
101
+
102
+ ```json
103
+ {
104
+ "metadata": { ... },
105
+ "payload_hash": "<sha256-of-sieved-content>",
106
+ "timestamp": "<utc-iso8601>"
107
+ }
108
+ ```
109
+
110
+ `payload_hash` is the SHA-256 digest of the exact sieved string delivered to the model or tool. When the Prose Tax sieve is active, `metadata` always contains a `prose_tax_summary` sub-object:
111
+
112
+ ```json
113
+ "prose_tax_summary": {
114
+ "raw_token_count": 12,
115
+ "optimized_token_count": 4,
116
+ "tokens_eliminated": 8,
117
+ "tax_savings_percentage": 66.6667,
118
+ "total_tokens_saved": 8
119
+ }
120
+ ```
121
+
122
+ Because `metadata` is bound inside the signed manifest, these token counts are just as tamper-evident as `payload_hash` itself. An auditor who holds only the node's public key can independently verify:
123
+
124
+ 1. **Output integrity** — the sieved content hasn't been altered after signing (`payload_hash`).
125
+ 2. **Transformation accounting** — the before/after token delta recorded at signing time hasn't been fabricated (`prose_tax_summary` is sealed under the same signature).
126
+ 3. **Identity provenance** — the receipt was minted by the expected node, not a rogue keypair (`public_key` key-pin assertion).
127
+
128
+ Together these three checks give mathematical proof that the boundary transformation was faithful and un-tampered — equivalent to a signed audit log with built-in integrity verification.
129
+
130
+ ### Verification workflow
131
+
132
+ ```python
133
+ import asyncio
134
+ import json
135
+ from sovereign_core.gateway import SovereignGateway
136
+ from sovereign_core.crypto import SovereignKeyManager
137
+
138
+ async def main():
139
+ gateway = SovereignGateway(signing_key=".keys/sovereign_identity.pem")
140
+ result = await gateway.sieve_and_sign("Hi! Please just help me now.")
141
+
142
+ # result.content == "help me now"
143
+ # result.receipt["metadata"]["prose_tax_summary"]["tokens_eliminated"] == 4
144
+
145
+ # Verify later — requires only the public key and the original sieved payload
146
+ is_valid = SovereignKeyManager.verify_receipt(
147
+ result.receipt,
148
+ {"content": result.content},
149
+ expected_public_key=gateway.export_public_key(),
150
+ )
151
+ assert is_valid # fails if any field was mutated after signing
152
+
153
+ asyncio.run(main())
154
+ ```
155
+
156
+ ---
157
+
158
+ ## Primary Developer Interface: `SovereignGateway`
159
+
160
+ `SovereignGateway` is the single entry point for application code. It wraps the full sieve-and-sign pipeline behind a clean four-method API.
161
+
162
+ ### One-shot macro (recommended)
163
+
164
+ `sieve_and_sign()` strips Prose Tax boilerplate, fuses the transformation telemetry into the receipt metadata, and seals everything in a single awaitable call:
165
+
166
+ ```python
167
+ import asyncio
168
+ from sovereign_core.gateway import SovereignGateway
169
+
170
+ async def main():
171
+ gateway = SovereignGateway(signing_key=".keys/sovereign_identity.pem")
172
+ result = await gateway.sieve_and_sign("Hi! Please just help me now.")
173
+
174
+ # result — SovereignBoundaryResponse (Pydantic model, fully typed)
175
+ # result.content — purified string, Prose Tax stripped ("help me now")
176
+ # result.receipt — ForensicReceipt with prose_tax_summary sealed inside
177
+
178
+ print(result.content)
179
+ print(result.receipt["payload_hash"])
180
+
181
+ asyncio.run(main())
182
+ ```
183
+
184
+ Inside a FastAPI route the gateway instance lives on the application object; the route itself is already async:
185
+
186
+ ```python
187
+ from sovereign_core.gateway import SovereignGateway
188
+
189
+ gateway = SovereignGateway(signing_key=".keys/sovereign_identity.pem")
190
+
191
+ @app.post("/api/v1/ingest")
192
+ async def handle_agent_input(raw_payload: dict):
193
+ result = await gateway.sieve_and_sign(raw_payload["text"])
194
+
195
+ await reasoning_ledger.append(
196
+ payload=result.content,
197
+ receipt=result.receipt,
198
+ )
199
+ return {
200
+ "status": "sovereign_verified",
201
+ "receipt_id": result.receipt["payload_hash"],
202
+ }
203
+ ```
204
+
205
+ ### Granular two-step workflow
206
+
207
+ When the clean context is needed before signing (e.g. for intermediate validation or logging):
208
+
209
+ ```python
210
+ import asyncio
211
+ from sovereign_core.gateway import SovereignGateway
212
+
213
+ async def main():
214
+ gateway = SovereignGateway(signing_key=".keys/sovereign_identity.pem")
215
+
216
+ # 1. Strip Prose Tax — remove boilerplate, normalize whitespace
217
+ clean_context = await gateway.sieve("Hi! Please just help me now.")
218
+
219
+ # 2. Cryptographically seal — transformation telemetry fused into metadata
220
+ receipt = gateway.sign(clean_context)
221
+
222
+ print(clean_context) # "help me now"
223
+ print(receipt["payload_hash"]) # SHA-256 of {"content": "help me now"}
224
+
225
+ asyncio.run(main())
226
+ ```
227
+
228
+ ### Independent receipt verification
229
+
230
+ Receipts produced by either workflow can be verified at any time using only the public key:
231
+
232
+ ```python
233
+ from sovereign_core.crypto import SovereignKeyManager
234
+
235
+ is_valid = SovereignKeyManager.verify_receipt(
236
+ receipt,
237
+ {"content": clean_context},
238
+ expected_public_key=gateway.export_public_key(),
239
+ )
240
+ ```
241
+
242
+ ### Public key distribution & key rotation
243
+
244
+ #### Exporting a signed public key bundle
245
+
246
+ `export_public_key_bundle()` mints a self-signed `PublicKeyBundle` that proves private-key ownership at a specific point in time. The `issued_at` timestamp is sealed inside the Ed25519 attestation signature — it cannot be back-dated after the fact.
247
+
248
+ ```python
249
+ from sovereign_core.gateway import SovereignGateway
250
+
251
+ gateway = SovereignGateway(signing_key=".keys/sovereign_identity.pem")
252
+ bundle = gateway.export_public_key_bundle(node_id="node-alpha")
253
+
254
+ # bundle.public_key — base64 Ed25519 public key
255
+ # bundle.attestation — self-signed ForensicReceipt proving key ownership
256
+ # bundle.issued_at — UTC ISO 8601 timestamp (sealed inside the signature)
257
+ # bundle.node_id — human-readable node label
258
+
259
+ gateway.save_public_key_bundle(".keys/bundle.json", node_id="node-alpha")
260
+ ```
261
+
262
+ Downstream auditors and consumers can verify the bundle's attestation receipt using only `bundle.public_key` and `SovereignKeyManager.verify_receipt()` — no private key material required.
263
+
264
+ #### Key rotation with auditable succession
265
+
266
+ `rotate_keypair()` generates a fresh Ed25519 keypair, signs a canonical rotation payload with the **outgoing** private key, and atomically promotes both the new `.pem` and `.pub` files on disk. The returned `SuccessionReceipt` provides a cryptographically auditable handoff chain.
267
+
268
+ ```python
269
+ from sovereign_core.crypto import SovereignKeyManager
270
+
271
+ manager = SovereignKeyManager(key_dir=".keys")
272
+ manager.load_or_generate_keypair()
273
+
274
+ # Capture the pre-rotation key from a trusted out-of-band source before rotating
275
+ trusted_previous_key = manager.public_key
276
+
277
+ receipt = manager.rotate_keypair()
278
+ # receipt["previous_public_key"] — base64 key active before rotation
279
+ # receipt["new_public_key"] — base64 key active after rotation
280
+ # receipt["rotation_timestamp"] — UTC ISO 8601 timestamp
281
+ # receipt["succession_signature"] — Ed25519 signature by the outgoing key
282
+ ```
283
+
284
+ Verify the succession event using the out-of-band trusted copy of the previous public key. The `trusted_previous_public_key` anchor must come from a source independent of the receipt being verified — passing a key extracted from the receipt itself would be self-referential and cryptographically meaningless:
285
+
286
+ ```python
287
+ is_valid = SovereignKeyManager.verify_succession(
288
+ receipt,
289
+ trusted_previous_public_key=trusted_previous_key,
290
+ )
291
+ assert is_valid # False if any rotation field was tampered
292
+ ```
293
+
294
+ ---
295
+
296
+ ## ASGI Middleware for FastAPI / Starlette
297
+
298
+ `SovereignMiddleware` applies the sieve-and-sign boundary to every inbound JSON request transparently, without changes to route handlers:
299
+
300
+ ```python
301
+ from fastapi import FastAPI
302
+ from sovereign_fastapi.middleware import SovereignMiddleware
303
+
304
+ app = FastAPI()
305
+ app.add_middleware(
306
+ SovereignMiddleware,
307
+ signing_key=".keys/sovereign_identity.pem",
308
+ payload_field="text", # JSON key to sieve; omit to sieve the whole body
309
+ strict_mode=False, # True → return HTTP 422 on any interception error
310
+ )
311
+ ```
312
+
313
+ The middleware:
314
+ 1. Extracts the target field from the JSON body.
315
+ 2. Calls `sieve_and_sign()` on the gateway.
316
+ 3. Overwrites `request._body` so every downstream route handler sees the sieved payload.
317
+ 4. Caches the sealed receipt at `request.state.sovereign_receipt`.
318
+ 5. Injects `X-Sovereign-Receipt-Signature` and `X-Sovereign-Tokens-Saved` on the outbound response.
319
+
320
+ ---
321
+
322
+ ## Prose Tax Optimization
323
+
324
+ > **This feature is optional.** The cryptographic boundary and ForensicReceipt are produced whether or not any text is eliminated. Prose Tax optimization runs inside the audit envelope — every token count and savings metric is sealed alongside the output hash.
325
+
326
+ The sieve removes conversational boilerplate that inflates token budgets without contributing semantic content:
327
+
328
+ | Category | Examples stripped |
329
+ |---|---|
330
+ | Greeting tokens | `hi`, `hello`, `hey`, `greetings` |
331
+ | Hedging adverbs | `just`, `simply`, `actually`, `basically`, `probably` |
332
+ | Affirmation filler | `of course`, `certainly`, `absolutely`, `sure` |
333
+ | Preamble phrases | `I hope this`, `I hope that`, `I hope you` |
334
+ | Politeness tokens | `please`, `kindly` |
335
+
336
+ All patterns carry negative lookahead guards (e.g. `(?![-\w])`) so technical compound words (`hi-fi`, `just-in-time`, `certainly-not`) pass through unmarred.
337
+
338
+ ---
339
+
340
+ ## Local Development
341
+
342
+ ### Bootstrap
343
+
344
+ ```bash
345
+ uv sync
346
+ ```
347
+
348
+ ### Run tests
349
+
350
+ ```bash
351
+ uv run pytest
352
+ ```
353
+
354
+ ### Run the sovereign-node runtime
355
+
356
+ ```bash
357
+ uv run sovereign-node
358
+ ```
359
+
360
+ ---
361
+
362
+ ## Running the Workspace Examples
363
+
364
+ ### FastAPI Gateway Example
365
+
366
+ **1. Set your node secret** (required for Ed25519 key generation):
367
+
368
+ ```bash
369
+ export SOVEREIGN_NODE_SECRET=your-local-secret # Linux / macOS
370
+ $env:SOVEREIGN_NODE_SECRET = "your-local-secret" # Windows PowerShell
371
+ ```
372
+
373
+ **2. Start the example server:**
374
+
375
+ ```bash
376
+ uv run uvicorn examples.fastapi_gateway.app:app --reload
377
+ ```
378
+
379
+ The server starts on `http://127.0.0.1:8000`. On first boot it generates an Ed25519 keypair at `.keys/example_identity.pem`.
380
+
381
+ **3. In a second terminal, run the example client:**
382
+
383
+ ```bash
384
+ uv run python examples/fastapi_gateway/client.py
385
+ ```
386
+
387
+ ### Verifying a ForensicReceipt (CLI)
388
+
389
+ Export a receipt and the gateway's public key:
390
+
391
+ ```python
392
+ import asyncio
393
+ import json
394
+ from sovereign_core.gateway import SovereignGateway
395
+
396
+ async def main():
397
+ gateway = SovereignGateway()
398
+ result = await gateway.sieve_and_sign("example payload")
399
+
400
+ with open("receipt.json", "w") as f:
401
+ json.dump(result.receipt, f, indent=2)
402
+
403
+ print(gateway.export_public_key())
404
+
405
+ asyncio.run(main())
406
+ ```
407
+
408
+ Verify the receipt:
409
+
410
+ ```bash
411
+ uv run sovereign-verify \
412
+ --receipt receipt.json \
413
+ --public-key <base64-encoded-public-key>
414
+ ```
415
+
416
+ On success:
417
+
418
+ ```
419
+ Verified ✓ payload_hash: 4fec03e7...
420
+ ```
421
+
422
+ On tampered receipt:
423
+
424
+ ```
425
+ Tampered ✗ Receipt failed cryptographic verification.
426
+ payload_hash : 4fec03e7...
427
+ timestamp : 2026-05-22T...
428
+ ```
429
+
430
+ ---
431
+
432
+ ## Verification & Deep-Dive Diagnostics
433
+
434
+ ### Local Environment Configuration
435
+
436
+ `SOVEREIGN_NODE_SECRET` can be specified in a `.env` file at the repository root. The node entrypoint loads it automatically via `python-dotenv`:
437
+
438
+ ```bash
439
+ echo 'SOVEREIGN_NODE_SECRET=your-local-secret' > .env
440
+ ```
441
+
442
+ ### Standalone Tool Analysis Mode
443
+
444
+ ```bash
445
+ uv run sovereign-node --tool analyze
446
+ ```
447
+
448
+ ### Expected Console Output
449
+
450
+ ```
451
+ ====================================================
452
+ 🟢 Sovereign Node initialization sequence successful.
453
+ ====================================================
454
+ 🔄 Dispatching single tool execution: 'analyze'...
455
+ ⚠️ Standalone mode detected: Context empty. Hydrating baseline diagnostic state...
456
+
457
+ 🔒 Authenticated Forensic Receipt Proof:
458
+ {
459
+ "timestamp": "2026-05-22T15:00:00.000000+00:00",
460
+ "payload_hash": "4fec03e7083cca73cfb1152ae1d941b5a5a581fc725a43b3ee7df1d9ce697954",
461
+ "public_key": "<base64-encoded Ed25519 public key>",
462
+ "signature": "<base64-encoded Ed25519 signature>",
463
+ "metadata": {
464
+ "runtime": "async-sovereign-node",
465
+ "py_ver": "3.12.x",
466
+ "execution_success": true
467
+ }
468
+ }
469
+ ```
470
+
471
+ **Line-by-line interpretation:**
472
+
473
+ | Output line | What it proves |
474
+ |---|---|
475
+ | `🟢 Sovereign Node initialization sequence successful.` | Ed25519 keypair loaded or generated; `SOVEREIGN_NODE_SECRET` resolved; router and session context initialised. |
476
+ | `⚠️ Standalone mode detected …` | The `analyze` tool detected no upstream context and self-hydrated a baseline telemetry stream — expected behaviour in single-tool invocations. |
477
+ | `"payload_hash": "4fec03e7…"` | SHA-256 digest of the deterministically serialised execution payload. |
478
+ | `"public_key": "<base64>"` | Base64-encoded raw Ed25519 public key; verified by `_audit_receipt` before process exit. |
479
+ | `"signature": "<base64>"` | Ed25519 signature over `{"metadata": …, "payload_hash": …, "timestamp": …}`. Any mutation of these fields after issuance causes `verify_receipt` to return `False`. |
480
+ | `"execution_success": true` | The tool completed without raising an exception; the receipt is audit-clean. |