apodictic-sdk 0.0.0-stage → 3.9.0

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,717 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Apodictic Persistent Local Enclave Worker
4
+ Maintains one stateful session holding either the full monorepo kernel (`apodictic_engine`)
5
+ or the bundled standalone Z3 5.4.1 enclave (`standalone_z3_enclave.py`) when installed via npm.
6
+ All velocity windows, WORM SHA-256 blocks, staged rollback batches, and bi-temporal records
7
+ are persisted to SQLite WAL (`APODICTIC_STATE_DB`) across restarts.
8
+ """
9
+ import hashlib
10
+ import json
11
+ import os
12
+ import sqlite3
13
+ import sys
14
+ import time
15
+ import uuid
16
+
17
+ try:
18
+ import z3
19
+ except ImportError:
20
+ msg = (
21
+ "Python z3-solver not found. Install with: pip install z3-solver, "
22
+ "or pass --endpoint https://www.apodictic.dev/api/v1/enclave"
23
+ )
24
+ sys.stderr.write(json.dumps({"error": msg}) + "\n")
25
+ sys.stderr.flush()
26
+ sys.exit(2)
27
+
28
+ HERE = os.path.dirname(os.path.abspath(__file__))
29
+ if HERE not in sys.path:
30
+ sys.path.insert(0, HERE)
31
+
32
+ REPO_ROOT = os.environ.get("APODICTIC_REPO_ROOT") or os.path.abspath(os.path.join(HERE, "..", "..", ".."))
33
+ USE_MONOREPO = os.path.exists(os.path.join(REPO_ROOT, "apodictic_engine", "src", "proxy", "interceptor.py"))
34
+ if USE_MONOREPO and REPO_ROOT not in sys.path:
35
+ sys.path.insert(0, REPO_ROOT)
36
+
37
+ if USE_MONOREPO:
38
+ from apodictic_engine.src.proxy.interceptor import ApodicticProxyInterceptor
39
+ from apodictic_engine.src.core.bitemporal import BiTemporalLedger
40
+ from apodictic_engine.src.audit_ledger.merkle_sealer import rfc6962_leaf_hash
41
+ from apodictic_engine.src.smt_theory.policy_compiler import ApodicticPolicyZ3Compiler, DEFAULT_ENTERPRISE_POLICY
42
+ from apodictic_engine.src.erp_clearing.three_way_match_solver import (
43
+ ThreeWayMatchZ3Solver,
44
+ PurchaseOrderLine,
45
+ GoodsReceiptLine,
46
+ VendorInvoiceLine,
47
+ )
48
+ from apodictic_engine.src.statutory_theorems.global_indirect_tax_theorems import (
49
+ GlobalIndirectTaxSolver,
50
+ TaxJurisdiction,
51
+ IndirectTaxLineItem,
52
+ )
53
+ else:
54
+ from standalone_z3_enclave import StandaloneEnclaveSession
55
+
56
+
57
+ class MonorepoEnclaveSession:
58
+ def __init__(self, state_db_path: str = ""):
59
+ self.started_at = time.perf_counter()
60
+ self.state_db_path = state_db_path or os.environ.get("APODICTIC_STATE_DB") or os.path.join(
61
+ os.path.expanduser("~"), ".apodictic", "enclave_state.db"
62
+ )
63
+ os.makedirs(os.path.dirname(self.state_db_path), exist_ok=True)
64
+ self.state_conn = sqlite3.connect(self.state_db_path, check_same_thread=False, timeout=5.0)
65
+ self.state_conn.row_factory = sqlite3.Row
66
+ self.state_conn.execute("PRAGMA journal_mode=WAL;")
67
+ self.state_conn.execute("PRAGMA busy_timeout=5000;")
68
+ self.state_conn.executescript(
69
+ """
70
+ CREATE TABLE IF NOT EXISTS velocity_events (
71
+ account_id TEXT NOT NULL,
72
+ amount REAL NOT NULL,
73
+ ts REAL NOT NULL
74
+ );
75
+ CREATE TABLE IF NOT EXISTS worm_blocks (
76
+ block_index INTEGER PRIMARY KEY,
77
+ block_json TEXT NOT NULL
78
+ );
79
+ CREATE TABLE IF NOT EXISTS ledger_accounts (
80
+ account_id TEXT PRIMARY KEY,
81
+ balance REAL NOT NULL,
82
+ min_reserve REAL NOT NULL DEFAULT 0.0,
83
+ debits_pending REAL NOT NULL DEFAULT 0.0,
84
+ debits_posted REAL NOT NULL DEFAULT 0.0,
85
+ credits_posted REAL NOT NULL DEFAULT 0.0
86
+ );
87
+ CREATE TABLE IF NOT EXISTS wal_tuple_journal (
88
+ tuple_id TEXT PRIMARY KEY,
89
+ batch_id TEXT NOT NULL,
90
+ lsn TEXT NOT NULL,
91
+ table_name TEXT NOT NULL,
92
+ before_image_json TEXT NOT NULL,
93
+ after_image_json TEXT NOT NULL,
94
+ restored INTEGER NOT NULL DEFAULT 0,
95
+ created_at TEXT NOT NULL
96
+ );
97
+ CREATE TABLE IF NOT EXISTS rollback_batches (
98
+ batch_id TEXT PRIMARY KEY,
99
+ account_id TEXT NOT NULL,
100
+ amount REAL NOT NULL,
101
+ target_system TEXT NOT NULL,
102
+ action TEXT NOT NULL,
103
+ status TEXT NOT NULL,
104
+ created_at REAL NOT NULL,
105
+ rolled_back_at REAL
106
+ );
107
+ """
108
+ )
109
+ for col in ("debits_pending", "debits_posted", "credits_posted"):
110
+ try:
111
+ self.state_conn.execute(f"ALTER TABLE ledger_accounts ADD COLUMN {col} REAL NOT NULL DEFAULT 0.0")
112
+ except sqlite3.OperationalError:
113
+ pass
114
+ self.state_conn.execute(
115
+ "INSERT OR IGNORE INTO ledger_accounts (account_id, balance, min_reserve, debits_pending, debits_posted, credits_posted) VALUES (?, ?, ?, 0.0, 0.0, ?)",
116
+ ("sdk_default", 250000.0, 50000.0, 250000.0),
117
+ )
118
+ self.state_conn.execute(
119
+ "UPDATE ledger_accounts SET credits_posted = balance WHERE credits_posted = 0.0 AND debits_pending = 0.0 AND debits_posted = 0.0 AND balance > 0.0"
120
+ )
121
+ self.state_conn.commit()
122
+
123
+ self.pg_dsn = os.environ.get("APODICTIC_POSTGRES_URL", "")
124
+ self.pg_conn = None
125
+ if self.pg_dsn and os.environ.get("APODICTIC_AIRGAP") != "1":
126
+ import psycopg
127
+ self.pg_conn = psycopg.connect(self.pg_dsn, autocommit=True)
128
+ with self.pg_conn.cursor() as cur:
129
+ cur.execute(
130
+ "CREATE TABLE IF NOT EXISTS apodictic_velocity_events (account_id TEXT NOT NULL, amount DOUBLE PRECISION NOT NULL, ts DOUBLE PRECISION NOT NULL)"
131
+ )
132
+
133
+ self.proxy = ApodicticProxyInterceptor()
134
+ cutoff = time.time() - 86400.0
135
+ for acct, amt in self.state_conn.execute(
136
+ "SELECT account_id, amount FROM velocity_events WHERE ts >= ?", (cutoff,)
137
+ ).fetchall():
138
+ self.proxy._account_velocity.setdefault(acct, []).append(float(amt))
139
+
140
+ saved_blocks = [
141
+ json.loads(row[0])
142
+ for row in self.state_conn.execute("SELECT block_json FROM worm_blocks ORDER BY block_index ASC").fetchall()
143
+ ]
144
+ if saved_blocks:
145
+ self.proxy.audit.blocks = saved_blocks
146
+ self.proxy.audit._leaf_hashes = [
147
+ rfc6962_leaf_hash(str(b.get("block_hash", "")).encode("utf-8"))
148
+ for b in saved_blocks
149
+ ]
150
+
151
+ self.bitemporal = BiTemporalLedger("enterprise_gl")
152
+ self.three_way = ThreeWayMatchZ3Solver()
153
+ self.tax_solver = GlobalIndirectTaxSolver()
154
+
155
+ def _get_double_entry_account(self, account_id: str) -> dict:
156
+ row = self.state_conn.execute("SELECT * FROM ledger_accounts WHERE account_id = ?", (account_id,)).fetchone()
157
+ if not row:
158
+ return {
159
+ "account_id": account_id,
160
+ "balance": 0.0,
161
+ "min_reserve": 0.0,
162
+ "debits_pending": 0.0,
163
+ "debits_posted": 0.0,
164
+ "credits_posted": 0.0,
165
+ "available_balance": 0.0,
166
+ }
167
+ credits_posted = float(row["credits_posted"])
168
+ debits_posted = float(row["debits_posted"])
169
+ debits_pending = float(row["debits_pending"])
170
+ return {
171
+ "account_id": row["account_id"],
172
+ "balance": round(float(row["balance"]), 4),
173
+ "min_reserve": round(float(row["min_reserve"]), 4),
174
+ "debits_pending": round(debits_pending, 4),
175
+ "debits_posted": round(debits_posted, 4),
176
+ "credits_posted": round(credits_posted, 4),
177
+ "available_balance": round(credits_posted - debits_posted - debits_pending, 4),
178
+ }
179
+
180
+ def _persist_last_block(self):
181
+ if self.proxy.audit.blocks:
182
+ blk = self.proxy.audit.blocks[-1]
183
+ self.state_conn.execute(
184
+ "INSERT OR REPLACE INTO worm_blocks (block_index, block_json) VALUES (?, ?)",
185
+ (blk["block_index"], json.dumps(blk, sort_keys=True)),
186
+ )
187
+ self.state_conn.commit()
188
+
189
+ def handle(self, method: str, params: dict) -> dict:
190
+ if method == "health":
191
+ return {
192
+ "status": "healthy",
193
+ "mode": "monorepo-kernel",
194
+ "z3_version": z3.get_version_string(),
195
+ "uptime_ms": round((time.perf_counter() - self.started_at) * 1000.0, 2),
196
+ "worm_blocks": len(self.proxy.audit.blocks),
197
+ "worm_integrity_valid": self.proxy.audit.verify_integrity(),
198
+ "velocity_accounts": len(self.proxy._account_velocity),
199
+ "bitemporal_records": len(self.bitemporal.records),
200
+ "airgap": os.environ.get("APODICTIC_AIRGAP") == "1",
201
+ }
202
+
203
+ if method == "verify_mutation":
204
+ acct = str(params.get("accountId", "sdk_default"))
205
+ has_explicit_bal = bool(params.get("hasExplicitCurrentBalance", "currentBalance" in params and params.get("currentBalance") is not None))
206
+ existing_acct_row = self.state_conn.execute(
207
+ "SELECT balance, min_reserve FROM ledger_accounts WHERE account_id = ?",
208
+ (acct,),
209
+ ).fetchone()
210
+ use_persisted_bal = existing_acct_row is not None and not has_explicit_bal and not bool(params.get("stateless", False))
211
+ curr_bal = float(existing_acct_row["balance"]) if use_persisted_bal else float(params.get("currentBalance", 250000.0))
212
+ min_res = float(existing_acct_row["min_reserve"]) if use_persisted_bal else float(params.get("minReserve", 50000.0))
213
+ amt = params.get("amount")
214
+ amt_val = float(amt) if amt is not None else None
215
+ if amt_val is not None and (amt_val < 0 or amt_val != amt_val):
216
+ raise ValueError("Invalid negative or NaN amount")
217
+
218
+ debit_total_raw = params.get("debitTotal")
219
+ credit_total_raw = params.get("creditTotal")
220
+ de_unsat_reason = None
221
+ de_z3_ms = 0.0
222
+ if debit_total_raw is not None and credit_total_raw is not None:
223
+ debit_total = float(debit_total_raw)
224
+ credit_total = float(credit_total_raw)
225
+ de_t0 = time.perf_counter()
226
+ de_ctx = z3.Context()
227
+ de_solver = z3.Solver(ctx=de_ctx)
228
+ de_solver.set("timeout", 5000)
229
+ z_debit = z3.Real("debit_total", ctx=de_ctx)
230
+ z_credit = z3.Real("credit_total", ctx=de_ctx)
231
+ z_tol = z3.RealVal("0.005", ctx=de_ctx)
232
+ de_solver.add(z_debit == z3.RealVal(str(debit_total), ctx=de_ctx))
233
+ de_solver.add(z_credit == z3.RealVal(str(credit_total), ctx=de_ctx))
234
+ de_solver.assert_and_track(
235
+ z3.And(z_debit - z_credit <= z_tol, z_credit - z_debit <= z_tol),
236
+ "INV_DOUBLE_ENTRY_BALANCE",
237
+ )
238
+ de_chk = de_solver.check()
239
+ de_z3_ms = (time.perf_counter() - de_t0) * 1000.0
240
+ if de_chk != z3.sat:
241
+ de_unsat_reason = (
242
+ f"INV_DOUBLE_ENTRY_BALANCE: sum(debit)={debit_total:.2f} != "
243
+ f"sum(credit)={credit_total:.2f} (drift=${abs(debit_total - credit_total):.2f})"
244
+ )
245
+
246
+ live_pg_lock = bool(params.get("livePostgresLock")) or os.environ.get("APODICTIC_LIVE_PG_LOCK") == "1"
247
+ locked_pg_row = False
248
+ pg_tx_open = False
249
+
250
+ try:
251
+ if self.pg_conn is not None:
252
+ cutoff = time.time() - 86400.0
253
+ with self.pg_conn.cursor() as cur:
254
+ if live_pg_lock:
255
+ cur.execute("BEGIN")
256
+ pg_tx_open = True
257
+ cur.execute(
258
+ "SELECT balance, min_reserve FROM ledger_accounts WHERE account_id = %s FOR UPDATE",
259
+ (acct,),
260
+ )
261
+ pg_row = cur.fetchone()
262
+ if pg_row is not None:
263
+ curr_bal = float(pg_row[0])
264
+ min_res = float(pg_row[1]) if pg_row[1] is not None else min_res
265
+ locked_pg_row = True
266
+ cur.execute(
267
+ "SELECT COALESCE(SUM(amount), 0) FROM apodictic_velocity_events WHERE account_id = %s AND ts >= %s",
268
+ (acct, cutoff),
269
+ )
270
+ shared_sum = float(cur.fetchone()[0])
271
+ self.proxy._account_velocity[acct] = [shared_sum] if shared_sum > 0 else []
272
+
273
+ res = self.proxy.intercept_and_execute(
274
+ raw_statement=str(params.get("sql", "")),
275
+ account_id=acct,
276
+ current_balance=curr_bal,
277
+ min_reserve=min_res,
278
+ spending_limit=float(params.get("maxAutonomousLimit", 50000.0)),
279
+ cfo_signed=bool(params.get("cfoSigned", False)),
280
+ statutory_vat=float(params.get("statutoryVat", 0.14)),
281
+ expected_vat=float(params.get("expectedVat", 0.14)),
282
+ amount=amt_val,
283
+ )
284
+ if de_unsat_reason is not None:
285
+ res["verified"] = False
286
+ res["verdict"] = "UNSAT"
287
+ core = list(res.get("unsat_core") or [])
288
+ if "INV_DOUBLE_ENTRY_BALANCE" not in core:
289
+ core.insert(0, "INV_DOUBLE_ENTRY_BALANCE")
290
+ res["unsat_core"] = core
291
+ viols = list(res.get("violated_invariants") or [])
292
+ if "INV_DOUBLE_ENTRY_BALANCE" not in viols:
293
+ viols.insert(0, "INV_DOUBLE_ENTRY_BALANCE")
294
+ res["violated_invariants"] = viols
295
+ res["violation_reason"] = de_unsat_reason
296
+ if isinstance(res.get("timings"), dict):
297
+ res["timings"]["z3_solve_ms"] = round(float(res["timings"].get("z3_solve_ms", 0.0)) + de_z3_ms, 3)
298
+
299
+ eff_amt = amt_val if amt_val is not None else float(res.get("extracted_amount") or res.get("amount") or 0.0)
300
+ if res["verified"] and eff_amt > 0:
301
+ now_ts = time.time()
302
+ self.state_conn.execute(
303
+ "INSERT INTO velocity_events (account_id, amount, ts) VALUES (?, ?, ?)",
304
+ (acct, eff_amt, now_ts),
305
+ )
306
+ if self.pg_conn is not None:
307
+ with self.pg_conn.cursor() as cur:
308
+ if locked_pg_row:
309
+ cur.execute(
310
+ "UPDATE ledger_accounts SET balance = balance - %s WHERE account_id = %s",
311
+ (eff_amt, acct),
312
+ )
313
+ cur.execute(
314
+ "INSERT INTO apodictic_velocity_events (account_id, amount, ts) VALUES (%s, %s, %s)",
315
+ (acct, eff_amt, now_ts),
316
+ )
317
+ if pg_tx_open and self.pg_conn is not None:
318
+ with self.pg_conn.cursor() as cur:
319
+ cur.execute("COMMIT" if res["verified"] else "ROLLBACK")
320
+ pg_tx_open = False
321
+ res["live_pg_locked"] = locked_pg_row
322
+ res["authoritative_balance"] = curr_bal
323
+ except Exception:
324
+ if pg_tx_open and self.pg_conn is not None:
325
+ try:
326
+ with self.pg_conn.cursor() as cur:
327
+ cur.execute("ROLLBACK")
328
+ except Exception:
329
+ pass
330
+ raise
331
+ self._persist_last_block()
332
+
333
+ raw_sql_upper = str(params.get("sql", "")).upper()
334
+ target_sys_raw = str(params.get("targetSystem", "postgresql")).lower()
335
+ is_ext_escrow = any(k in target_sys_raw for k in ("stripe", "wire", "iso20022", "netsuite")) or any(
336
+ k in raw_sql_upper for k in ("WIRE", "PAYOUT", "STRIPE", "ISO20022")
337
+ )
338
+ res["escrow_status"] = (
339
+ ("ESCROW_HELD" if is_ext_escrow else "SAVEPOINT_STAGED")
340
+ if res["verified"]
341
+ else "VETOED_PRE_COMMIT"
342
+ )
343
+ batch_id = None
344
+ wal_before_image = None
345
+ if res["verified"]:
346
+ self.state_conn.execute(
347
+ "INSERT OR IGNORE INTO ledger_accounts (account_id, balance, min_reserve, debits_pending, debits_posted, credits_posted) VALUES (?, ?, ?, 0.0, 0.0, ?)",
348
+ (acct, curr_bal, min_res, curr_bal),
349
+ )
350
+ wal_before_image = self._get_double_entry_account(acct)
351
+ if is_ext_escrow:
352
+ self.state_conn.execute(
353
+ "UPDATE ledger_accounts SET balance = balance - ?, debits_pending = debits_pending + ? WHERE account_id = ?",
354
+ (eff_amt, eff_amt, acct),
355
+ )
356
+ else:
357
+ self.state_conn.execute(
358
+ "UPDATE ledger_accounts SET balance = balance - ?, debits_posted = debits_posted + ? WHERE account_id = ?",
359
+ (eff_amt, eff_amt, acct),
360
+ )
361
+ wal_after_image = self._get_double_entry_account(acct)
362
+ batch_id = f"batch_{int(time.time() * 1000)}_{res['block_index']}"
363
+ lsn = f"0/{int(time.time_ns()) & 0xFFFFFFFF:08X}"
364
+ tbl_list = res.get("ast_analysis", {}).get("target_tables") or []
365
+ self.state_conn.execute(
366
+ "INSERT INTO wal_tuple_journal (tuple_id, batch_id, lsn, table_name, before_image_json, after_image_json, restored, created_at) VALUES (?, ?, ?, ?, ?, ?, 0, ?)",
367
+ (
368
+ f"wal_{uuid.uuid4().hex[:12]}",
369
+ batch_id,
370
+ lsn,
371
+ str(tbl_list[0]) if tbl_list else "ledger_accounts",
372
+ json.dumps(wal_before_image),
373
+ json.dumps(wal_after_image),
374
+ time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
375
+ ),
376
+ )
377
+ self.state_conn.execute(
378
+ "INSERT INTO rollback_batches (batch_id, account_id, amount, target_system, action, status, created_at) VALUES (?, ?, ?, ?, ?, 'STAGED', ?)",
379
+ (batch_id, acct, eff_amt, target_sys_raw, res["ast_analysis"]["statement_type"], time.time()),
380
+ )
381
+ self.state_conn.commit()
382
+ res["rollback_batch_id"] = batch_id
383
+ res["double_entry_account"] = self._get_double_entry_account(acct) if res["verified"] else None
384
+ res["wal_before_image"] = wal_before_image
385
+ if self.proxy.audit.blocks:
386
+ res["rfc6962_leaf_hash"] = self.proxy.audit.blocks[-1].get("rfc6962_leaf_hash")
387
+ res["rfc6962_tree_root"] = self.proxy.audit.blocks[-1].get("rfc6962_tree_root")
388
+ return res
389
+
390
+ if method == "rollback":
391
+ t0 = time.perf_counter()
392
+ batch_id = str(params.get("batchId", ""))
393
+ if not batch_id:
394
+ raise ValueError("batchId is required")
395
+ row = self.state_conn.execute("SELECT * FROM rollback_batches WHERE batch_id = ?", (batch_id,)).fetchone()
396
+ compensated = []
397
+ escrow_res = "NOOP"
398
+ restored_tuple = None
399
+ double_entry_acct = None
400
+ if row and row["status"] == "STAGED":
401
+ ts_low = str(row["target_system"] or "").lower()
402
+ is_esc = any(k in ts_low for k in ("stripe", "wire", "iso20022", "netsuite"))
403
+ if is_esc:
404
+ self.state_conn.execute(
405
+ "UPDATE ledger_accounts SET balance = balance + ?, debits_pending = MAX(0.0, debits_pending - ?) WHERE account_id = ?",
406
+ (row["amount"], row["amount"], row["account_id"]),
407
+ )
408
+ else:
409
+ self.state_conn.execute(
410
+ "UPDATE ledger_accounts SET balance = balance + ?, debits_posted = MAX(0.0, debits_posted - ?) WHERE account_id = ?",
411
+ (row["amount"], row["amount"], row["account_id"]),
412
+ )
413
+ self.state_conn.execute(
414
+ "UPDATE rollback_batches SET status = 'ROLLED_BACK', rolled_back_at = ? WHERE batch_id = ?",
415
+ (time.time(), batch_id),
416
+ )
417
+ wal_row = self.state_conn.execute(
418
+ "SELECT before_image_json, lsn, table_name FROM wal_tuple_journal WHERE batch_id = ?",
419
+ (batch_id,),
420
+ ).fetchone()
421
+ if wal_row:
422
+ self.state_conn.execute("UPDATE wal_tuple_journal SET restored = 1 WHERE batch_id = ?", (batch_id,))
423
+ restored_tuple = {
424
+ "lsn": wal_row["lsn"],
425
+ "table_name": wal_row["table_name"],
426
+ "restored_before_image": json.loads(wal_row["before_image_json"]),
427
+ }
428
+ self.state_conn.commit()
429
+ double_entry_acct = self._get_double_entry_account(row["account_id"])
430
+ escrow_res = "ESCROW_CANCELLED_PRE_DISPATCH" if is_esc else "SAVEPOINT_ROLLED_BACK"
431
+ compensated.append({
432
+ "batch_id": batch_id,
433
+ "system": row["target_system"],
434
+ "amount_restored": row["amount"],
435
+ "status": "COMPENSATED",
436
+ "escrow_status": escrow_res,
437
+ "pgoutput_restored_tuple": restored_tuple,
438
+ "double_entry_account": double_entry_acct,
439
+ })
440
+ elapsed_ms = round((time.perf_counter() - t0) * 1000.0, 3)
441
+ rb_ok = len(compensated) > 0
442
+ blk = self.proxy.audit.append_block(
443
+ proof_id=f"rb_{batch_id}",
444
+ action="ATOMIC_ROLLBACK",
445
+ verdict="REVERTED" if rb_ok else "NOOP",
446
+ target_system="POSTGRESQL",
447
+ zk_digest=self.proxy.audit.blocks[-1]["block_hash"] if self.proxy.audit.blocks else self.proxy.audit._genesis_hash,
448
+ metadata={"batch_id": batch_id, "escrow_status": escrow_res},
449
+ )
450
+ self._persist_last_block()
451
+ return {
452
+ "batch_id": batch_id,
453
+ "success": rb_ok,
454
+ "actions_compensated": len(compensated),
455
+ "escrow_status": escrow_res,
456
+ "total_dispatch_ms": elapsed_ms,
457
+ "sla_met": elapsed_ms < 38.0,
458
+ "compensated_steps": compensated,
459
+ "pgoutput_restored_tuple": restored_tuple,
460
+ "double_entry_account": double_entry_acct,
461
+ "audit_block_index": blk["block_index"],
462
+ "audit_block_hash": blk["block_hash"],
463
+ "rfc6962_leaf_hash": blk.get("rfc6962_leaf_hash"),
464
+ "rfc6962_tree_root": blk.get("rfc6962_tree_root"),
465
+ }
466
+
467
+ if method == "verify_three_way_match":
468
+ po_raw = params["po"]
469
+ po = PurchaseOrderLine(
470
+ po_id=str(po_raw["poId"]),
471
+ sku=str(po_raw["sku"]),
472
+ ordered_qty=float(po_raw["orderedQty"]),
473
+ unit_price=float(po_raw["unitPrice"]),
474
+ )
475
+ receipts = [
476
+ GoodsReceiptLine(
477
+ receipt_id=str(r["receiptId"]),
478
+ po_id=str(r["poId"]),
479
+ sku=str(r["sku"]),
480
+ received_qty=float(r["receivedQty"]),
481
+ )
482
+ for r in params.get("receipts", [])
483
+ ]
484
+ invoices = [
485
+ VendorInvoiceLine(
486
+ invoice_id=str(i["invoiceId"]),
487
+ po_id=str(i["poId"]),
488
+ sku=str(i["sku"]),
489
+ billed_qty=float(i["billedQty"]),
490
+ billed_unit_price=float(i["billedUnitPrice"]),
491
+ )
492
+ for i in params.get("invoices", [])
493
+ ]
494
+ solver = ThreeWayMatchZ3Solver(price_tolerance_pct=float(params.get("priceTolerancePct", 0.02)))
495
+ r = solver.verify_three_way_match(po, receipts, invoices)
496
+ return {
497
+ "matched": r.matched,
498
+ "verdict": r.verdict,
499
+ "sku": r.sku,
500
+ "po_qty": r.po_qty,
501
+ "received_qty": r.received_qty,
502
+ "billed_qty": r.billed_qty,
503
+ "price_variance_pct": r.price_variance_pct,
504
+ "violated_rules": r.violated_rules,
505
+ "z3_solve_ms": r.z3_solve_ms,
506
+ }
507
+
508
+ if method == "verify_tax_compliance":
509
+ jur = TaxJurisdiction(str(params["jurisdiction"]))
510
+ lines = [
511
+ IndirectTaxLineItem(
512
+ sku=str(x["sku"]),
513
+ net_amount=float(x["netAmount"]),
514
+ claimed_vat_amount=float(x["claimedVatAmount"]),
515
+ claimed_wht_amount=float(x.get("claimedWhtAmount", 0.0)),
516
+ is_exempt=bool(x.get("isExempt", False)),
517
+ )
518
+ for x in params.get("lines", [])
519
+ ]
520
+ r = self.tax_solver.verify_invoice_taxes(
521
+ jurisdiction=jur,
522
+ lines=lines,
523
+ has_cryptographic_stamp=bool(params.get("hasCryptographicStamp", True)),
524
+ tolerance=float(params.get("tolerance", 0.02)),
525
+ )
526
+ return {
527
+ "jurisdiction": r.jurisdiction.value,
528
+ "verdict": r.verdict,
529
+ "verified": r.verified,
530
+ "expected_total_vat": r.expected_total_vat,
531
+ "claimed_total_vat": r.claimed_total_vat,
532
+ "violated_tax_laws": r.violated_tax_laws,
533
+ "z3_solve_ms": r.z3_solve_ms,
534
+ "proof_hash": r.proof_hash,
535
+ }
536
+
537
+ if method == "bitemporal_insert":
538
+ rec = self.bitemporal.insert_fact(
539
+ entity_id=str(params["entityId"]),
540
+ data=dict(params["data"]),
541
+ valid_start=int(params["validStart"]),
542
+ valid_end=int(params.get("validEnd", -1)),
543
+ system_time=int(params["systemTime"]) if params.get("systemTime") is not None else None,
544
+ )
545
+ return {"inserted": True, "entity_id": rec.entity_id, "valid_start": rec.valid_start, "system_start": rec.system_start}
546
+
547
+ if method == "bitemporal_restate":
548
+ rec = self.bitemporal.retroactive_restatement(
549
+ entity_id=str(params["entityId"]),
550
+ new_data=dict(params["data"]),
551
+ effective_valid_start=int(params["validStart"]),
552
+ effective_valid_end=int(params.get("validEnd", -1)),
553
+ adjustment_system_time=int(params["systemTime"]) if params.get("systemTime") is not None else None,
554
+ )
555
+ return {"restated": True, "entity_id": rec.entity_id, "valid_start": rec.valid_start, "system_start": rec.system_start}
556
+
557
+ if method == "bitemporal_as_of":
558
+ snap = self.bitemporal.as_of(
559
+ entity_id=str(params["entityId"]),
560
+ valid_time=int(params["validTime"]),
561
+ system_time=int(params["systemTime"]),
562
+ )
563
+ return {"found": snap is not None, "data": snap}
564
+
565
+ if method == "verify_audit_chain":
566
+ valid = self.proxy.audit.verify_integrity()
567
+ tip = self.proxy.audit.blocks[-1]["block_hash"] if self.proxy.audit.blocks else self.proxy.audit._genesis_hash
568
+ return {"valid": valid, "block_count": len(self.proxy.audit.blocks), "tip_hash": tip}
569
+
570
+ if method == "flush_escrow":
571
+ t0 = time.perf_counter()
572
+ cooling_sec = float(params.get("coolingWindowSec", 0.0))
573
+ batch_id = str(params.get("batchId", "")).strip()
574
+ cutoff = time.time() - max(0.0, cooling_sec)
575
+ if batch_id:
576
+ rows = self.state_conn.execute(
577
+ "SELECT * FROM rollback_batches WHERE batch_id = ? AND status = 'STAGED'",
578
+ (batch_id,),
579
+ ).fetchall()
580
+ else:
581
+ rows = self.state_conn.execute(
582
+ "SELECT * FROM rollback_batches WHERE status = 'STAGED' AND created_at <= ? ORDER BY created_at ASC",
583
+ (cutoff,),
584
+ ).fetchall()
585
+ dispatched = []
586
+ now = time.time()
587
+ for row in rows:
588
+ ts_low = str(row["target_system"] or "").lower()
589
+ if not any(k in ts_low for k in ("stripe", "wire", "iso20022", "netsuite")) and not batch_id:
590
+ continue
591
+ b_id = row["batch_id"]
592
+ self.state_conn.execute(
593
+ "UPDATE ledger_accounts SET debits_pending = MAX(0.0, debits_pending - ?), debits_posted = debits_posted + ? WHERE account_id = ?",
594
+ (row["amount"], row["amount"], row["account_id"]),
595
+ )
596
+ self.state_conn.execute(
597
+ "UPDATE rollback_batches SET status = 'DISPATCHED_TO_RAIL', rolled_back_at = ? WHERE batch_id = ?",
598
+ (now, b_id),
599
+ )
600
+ rail_ref = f"iso20022_pain001_{b_id}" if ("wire" in ts_low or "iso20022" in ts_low) else f"po_stripe_{b_id}"
601
+ dispatched.append({
602
+ "batch_id": b_id,
603
+ "account_id": row["account_id"],
604
+ "amount": row["amount"],
605
+ "target_system": row["target_system"],
606
+ "escrow_status": "DISPATCHED_TO_RAIL",
607
+ "settlement_reference": rail_ref,
608
+ "double_entry_account": self._get_double_entry_account(row["account_id"]),
609
+ })
610
+ self.state_conn.commit()
611
+ blk = self.proxy.audit.append_block(
612
+ proof_id=f"escrow_flush_{int(now * 1000)}",
613
+ action="ESCROW_OUTBOX_SETTLEMENT_FLUSH",
614
+ verdict="DISPATCHED" if dispatched else "NOOP",
615
+ target_system="ESCROW_RAIL",
616
+ zk_digest=self.proxy.audit.blocks[-1]["block_hash"] if self.proxy.audit.blocks else self.proxy.audit._genesis_hash,
617
+ metadata={"flushed_count": len(dispatched)},
618
+ )
619
+ self._persist_last_block()
620
+ return {
621
+ "flushed_count": len(dispatched),
622
+ "dispatched": dispatched,
623
+ "escrow_status": "DISPATCHED_TO_RAIL" if dispatched else "NO_ELIGIBLE_ESCROW",
624
+ "flush_latency_ms": round((time.perf_counter() - t0) * 1000.0, 3),
625
+ "audit_block_index": blk["block_index"],
626
+ "audit_block_hash": blk["block_hash"],
627
+ "rfc6962_leaf_hash": blk.get("rfc6962_leaf_hash"),
628
+ "rfc6962_tree_root": blk.get("rfc6962_tree_root"),
629
+ }
630
+
631
+ if method == "merkle_inclusion_proof":
632
+ blocks = self.proxy.audit.blocks
633
+ if not blocks:
634
+ return {
635
+ "spec": "RFC-6962-Certificate-Transparency-v1",
636
+ "block_index": 0,
637
+ "leaf_index": 0,
638
+ "tree_size": 0,
639
+ "leaf_hash": None,
640
+ "root_hash": hashlib.sha256(b"").hexdigest(),
641
+ "audit_path": [],
642
+ "inclusion_verified": False,
643
+ }
644
+ target_idx = int(params["blockIndex"]) if params.get("blockIndex") is not None else len(blocks)
645
+ return self.proxy.audit.generate_rfc6962_inclusion_proof(target_idx)
646
+
647
+ if method == "evaluate_policy":
648
+ t0 = time.perf_counter()
649
+ policy_text = str(params.get("policyText") or DEFAULT_ENTERPRISE_POLICY)
650
+ action = str(params.get("action") or "UPDATE").upper()
651
+ ctx_raw = params.get("context")
652
+ ctx = dict(ctx_raw) if isinstance(ctx_raw, dict) else {}
653
+ if "amount" in params and "amount" not in ctx:
654
+ ctx["amount"] = params["amount"]
655
+ if "currentBalance" in params and "current_balance" not in ctx:
656
+ ctx["current_balance"] = params["currentBalance"]
657
+ if "minReserve" in params and "min_reserve" not in ctx:
658
+ ctx["min_reserve"] = params["minReserve"]
659
+ if "spendingLimit" in params and "spending_limit" not in ctx:
660
+ ctx["spending_limit"] = params["spendingLimit"]
661
+ if "cfoSigned" in params and "cfo_signed" not in ctx:
662
+ ctx["cfo_signed"] = params["cfoSigned"]
663
+ if "reversalArmed" in params and "reversal_armed" not in ctx:
664
+ ctx["reversal_armed"] = params["reversalArmed"]
665
+ principal = params.get("principal") or ctx.get("principal")
666
+ resource = params.get("resource") or ctx.get("resource")
667
+ hierarchy = params.get("entityHierarchy") or params.get("entity_hierarchy") or ctx.get("entity_hierarchy")
668
+ res = ApodicticPolicyZ3Compiler.evaluate_and_prove(
669
+ policy_text=policy_text,
670
+ action=action,
671
+ context=ctx,
672
+ principal=principal,
673
+ resource=resource,
674
+ entity_hierarchy=hierarchy,
675
+ )
676
+ digest = hashlib.sha256(
677
+ json.dumps({"action": action, "principal": principal, "resource": resource, "verdict": res["verdict"]}, sort_keys=True).encode()
678
+ ).hexdigest()
679
+ blk = self.proxy.audit.append_block(
680
+ proof_id=f"pol_{int(time.time() * 1000)}_{uuid.uuid4().hex[:6]}",
681
+ action="POLICY_EVAL",
682
+ verdict=res["verdict"],
683
+ target_system="POLICY_ENGINE",
684
+ zk_digest=digest,
685
+ metadata={"principal": principal, "resource": resource, "unsat_core": res["unsat_core"]},
686
+ )
687
+ self._persist_last_block()
688
+ res["latency_ms"] = round((time.perf_counter() - t0) * 1000.0, 3)
689
+ res["block_index"] = blk["block_index"]
690
+ res["block_hash"] = blk["block_hash"]
691
+ res["rfc6962_leaf_hash"] = blk.get("rfc6962_leaf_hash")
692
+ res["rfc6962_tree_root"] = blk.get("rfc6962_tree_root")
693
+ return res
694
+
695
+ raise ValueError(f"Unknown enclave method: {method}")
696
+
697
+
698
+ def main():
699
+ session = MonorepoEnclaveSession() if USE_MONOREPO else StandaloneEnclaveSession()
700
+ for raw_line in sys.stdin:
701
+ line = raw_line.strip()
702
+ if not line:
703
+ continue
704
+ req_id = None
705
+ try:
706
+ req = json.loads(line)
707
+ req_id = req.get("id")
708
+ result = session.handle(req.get("method", ""), req.get("params") or {})
709
+ sys.stdout.write(json.dumps({"id": req_id, "result": result}) + "\n")
710
+ sys.stdout.flush()
711
+ except Exception as exc:
712
+ sys.stdout.write(json.dumps({"id": req_id, "error": {"message": str(exc)}}) + "\n")
713
+ sys.stdout.flush()
714
+
715
+
716
+ if __name__ == "__main__":
717
+ main()