betterwithage commited on
Commit
b3eaab3
·
verified ·
1 Parent(s): 40355cb

a11oy: Dev1 Investor-WOW + Core-5 3D + formula instillation + organ substrate; route-reorder fix so /v1/wow/* beat proxy+SPA catch-alls

Browse files
Files changed (3) hide show
  1. Dockerfile +11 -0
  2. a11oy_dev1_endpoints.py +613 -0
  3. serve.py +23 -0
Dockerfile CHANGED
@@ -416,6 +416,17 @@ ENV A11OY_ALLOY_GGUF=/app/models/qwen2.5-coder-0.5b-instruct-q4_k_m.gguf
416
  COPY a11oy_live_feeds.py ./a11oy_live_feeds.py
417
  COPY live_snapshots/ ./live_snapshots/
418
 
 
 
 
 
 
 
 
 
 
 
 
419
  # ADDITIVE (MINED UPGRADES, 2026-06, Yachay): four self-contained operator surfaces,
420
  # each adopting a PERMISSIVELY-licensed PATTERN (NOTICE updated) and evolving it into
421
  # an a11oy-native mechanism. Stdlib-only (no torch/numpy/CDN). Per-file COPY (this
 
416
  COPY a11oy_live_feeds.py ./a11oy_live_feeds.py
417
  COPY live_snapshots/ ./live_snapshots/
418
 
419
+ # ADDITIVE (Investor-WOW Layer, 2026-06-08, Dev1): a11oy_dev1_endpoints.py exposes
420
+ # the four founder-approved WOW surfaces: POST /v1/wow/govern (Drop-on-Anything
421
+ # governed turn + ungoverned-vs-governed catch), GET /v1/wow/ledger (unified
422
+ # cross-vertical tamper-evident receipt chain), /v1/wow/roi (cost-of-failure model,
423
+ # labeled assumptions), /v1/wow/router-latency (live router topology). Self-contained,
424
+ # DSSE-signed receipts, honest labels, 0 fabricated data, 0 CDN. Per-file COPY (this
425
+ # Dockerfile never uses `COPY . .`) -- without it the import fails and the /v1/wow/*
426
+ # routes fall through to the SPA. serve.py imports it try/except-guarded.
427
+ # Co-Authored-By: Perplexity Computer Agent <agent@perplexity.ai>
428
+ COPY a11oy_dev1_endpoints.py ./a11oy_dev1_endpoints.py
429
+
430
  # ADDITIVE (MINED UPGRADES, 2026-06, Yachay): four self-contained operator surfaces,
431
  # each adopting a PERMISSIVELY-licensed PATTERN (NOTICE updated) and evolving it into
432
  # an a11oy-native mechanism. Stdlib-only (no torch/numpy/CDN). Per-file COPY (this
a11oy_dev1_endpoints.py ADDED
@@ -0,0 +1,613 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ # © 2026 Lutar, Stephen P. — SZL Holdings · ORCID 0009-0001-0110-4173
4
+ """a11oy_dev1_endpoints.py — investor-WOW governance surface (Dev1).
5
+
6
+ ADDITIVE, self-contained. Registered LATE in serve.py (before the SPA catch-all)
7
+ so these /api/a11oy/v1/wow/* routes resolve LOCALLY on this one Space. 0 external
8
+ service dependencies, 0 fabricated data — every panel is honestly labeled.
9
+
10
+ This module powers four founder-approved WOW investor features:
11
+
12
+ POST /api/a11oy/v1/wow/govern — "Drop a11oy on ANYTHING": take any
13
+ decision/policy/prompt text, run a REAL governed turn through the 6-stage
14
+ P1-P6 loop, return a signed receipt + verdict + a 3D-trace node/link graph.
15
+ When mode="ungoverned_vs_governed" it ALSO returns the ungoverned answer
16
+ (poisoned/hallucinated) being CAUGHT (P3 non-interference, axiom-free).
17
+
18
+ GET /api/a11oy/v1/wow/ledger — Unified LIVE receipt ledger streaming
19
+ across ALL verticals: one tamper-evident hash-chain proving the mesh
20
+ governs everything at once. Auto-poll friendly (each poll appends).
21
+
22
+ GET /api/a11oy/v1/wow/roi — ROI / cost-of-failure per vertical
23
+ (liability avoided, breaches caught, deals de-risked). EVERY number is an
24
+ HONEST, labeled assumption (sourced to public benchmarks), never measured.
25
+
26
+ GET /api/a11oy/v1/wow/router-latency — live router topology + per-tier latency
27
+ for the Model Router 3D scene (in-memory counter, resets on rebuild).
28
+
29
+ Doctrine: locked-proven = EXACTLY 5 {F1,F11,F12,F18,F19} @ c7c0ba17; Λ = Conjecture 1
30
+ (unconditional uniqueness machine-checked FALSE; conditional axiom-free); SLSA L1
31
+ honest / L2 attestation present / L2-verified+L3 = roadmap; a11oy Code = "best
32
+ GOVERNED LLM". NO user-visible banned codenames. SIMULATED inputs labeled.
33
+ """
34
+ from __future__ import annotations
35
+
36
+ import base64
37
+ import hashlib
38
+ import json
39
+ import os
40
+ import re
41
+ import sys
42
+ import threading
43
+ import time
44
+ from collections import deque
45
+ from datetime import datetime, timezone
46
+
47
+ # Import Request at module top so FastAPI can resolve the string annotation
48
+ # `req: Request` on POST handlers (PEP 563 `from __future__ import annotations`
49
+ # makes annotations strings, resolved against THIS module's globals).
50
+ try:
51
+ from starlette.requests import Request # type: ignore
52
+ except Exception: # pragma: no cover
53
+ try:
54
+ from fastapi import Request # type: ignore
55
+ except Exception:
56
+ Request = None # type: ignore
57
+
58
+ # ---- optional crypto (DSSE ECDSA P-256). Honest UNSIGNED fallback if absent. ----
59
+ _PRIV = None
60
+ _PUB_PEM = ""
61
+ _KEYID = "—"
62
+ _KEY_ERR = ""
63
+ try:
64
+ from cryptography.hazmat.primitives import hashes as _ch_hashes
65
+ from cryptography.hazmat.primitives import serialization as _ch_ser
66
+ from cryptography.hazmat.primitives.asymmetric import ec as _ch_ec
67
+
68
+ _PRIV = _ch_ec.generate_private_key(_ch_ec.SECP256R1())
69
+ _pub = _PRIV.public_key()
70
+ _PUB_PEM = _pub.public_bytes(
71
+ _ch_ser.Encoding.PEM, _ch_ser.PublicFormat.SubjectPublicKeyInfo
72
+ ).decode("ascii")
73
+ _KEYID = hashlib.sha256(_PUB_PEM.strip().encode()).hexdigest()[:16]
74
+ except Exception as _e: # pragma: no cover
75
+ _KEY_ERR = repr(_e)
76
+
77
+ _PAYLOAD_TYPE = "application/vnd.szl.receipt+json"
78
+ _LOCK = threading.Lock()
79
+
80
+ # Doctrine constants (single source — keep in sync with PROVEN_STATE_CANONICAL.md)
81
+ _LOCKED_FIVE = ["F1", "F11", "F12", "F18", "F19"]
82
+ _LAMBDA_STATUS = ("Conjecture 1 — advisory only. Unconditional Λ-uniqueness is "
83
+ "machine-checked FALSE; the strongest result is an axiom-free "
84
+ "CONDITIONAL uniqueness (slice-multiplicativity ⇒ Λ). NOT a "
85
+ "pass/fail oracle.")
86
+
87
+
88
+ def _now() -> str:
89
+ return datetime.now(timezone.utc).isoformat()
90
+
91
+
92
+ def _canonical(obj) -> bytes:
93
+ return json.dumps(obj, sort_keys=True, separators=(",", ":")).encode("utf-8")
94
+
95
+
96
+ def _pae(ptype: str, body: bytes) -> bytes:
97
+ return b"DSSEv1 " + str(len(ptype)).encode() + b" " + ptype.encode() + b" " + \
98
+ str(len(body)).encode() + b" " + body
99
+
100
+
101
+ def _sign(payload_obj) -> dict:
102
+ """DSSE envelope over canonical JSON. Honest UNSIGNED marker if no key."""
103
+ body = _canonical(payload_obj)
104
+ to_sign = _pae(_PAYLOAD_TYPE, body)
105
+ env = {
106
+ "payloadType": _PAYLOAD_TYPE,
107
+ "payload": base64.b64encode(body).decode("ascii"),
108
+ "_dsse": "DSSEv1",
109
+ "_pae_sha256": hashlib.sha256(to_sign).hexdigest(),
110
+ "_signed_at": _now(),
111
+ }
112
+ if _PRIV is None:
113
+ env["signatures"] = []
114
+ env["signed"] = False
115
+ env["honesty"] = ("UNSIGNED — in-image key unavailable in this runtime "
116
+ "(%s); no signature fabricated." % (_KEY_ERR or "no crypto"))
117
+ return env
118
+ sig = _PRIV.sign(to_sign, _ch_ec.ECDSA(_ch_hashes.SHA256()))
119
+ env["signatures"] = [{"sig": base64.b64encode(sig).decode("ascii"), "keyid": _KEYID}]
120
+ env["signed"] = True
121
+ env["honesty"] = ("REAL — ECDSA-P256-SHA256 over the DSSE PAE, signed by an "
122
+ "in-image key generated at server boot. Verify in-browser "
123
+ "against /cosign.pub; a tampered byte fails. Key resets on rebuild.")
124
+ return env
125
+
126
+
127
+ # ===========================================================================
128
+ # UNIFIED CROSS-VERTICAL RECEIPT LEDGER (tamper-evident hash-chain, in-memory)
129
+ # Each governed turn from ANY vertical appends here -> one chain proving the
130
+ # mesh governs everything at once. Honest: in-memory ring buffer, resets on
131
+ # rebuild; durable receipts land in the repo ledger via the chain export.
132
+ # ===========================================================================
133
+ _LEDGER: deque = deque(maxlen=400)
134
+ _LEDGER_SEQ = {"n": 0}
135
+
136
+ # The verticals the mesh governs (matches the vertical-pack registry vocabulary;
137
+ # Dev2 owns the vertical TABS, this is just the ledger's vertical vocabulary).
138
+ _VERTICALS = [
139
+ {"id": "defense", "label": "Defense / Gov"},
140
+ {"id": "finance", "label": "Finance"},
141
+ {"id": "legal", "label": "Legal"},
142
+ {"id": "enterprise", "label": "Enterprise / Cyber"},
143
+ {"id": "realestate", "label": "Real Estate"},
144
+ {"id": "core", "label": "Core Governance"},
145
+ ]
146
+
147
+ # Representative governed actions per vertical (honest demonstration vocabulary,
148
+ # clearly labeled SIMULATED stream of governed turns the mesh would emit).
149
+ _LEDGER_ACTIONS = {
150
+ "defense": [("gate.geofence", "keep-out geofence checked on UAS plan", "F11"),
151
+ ("gate.altitude", "altitude-envelope STL robustness ρ scored", "F11"),
152
+ ("sign.uplink", "command-uplink DSSE-signed before transmit", "F18")],
153
+ "finance": [("gate.fraud", "transaction screened against fraud policy", "F12"),
154
+ ("score.risk", "counterparty risk vector Λ-scored", "F19"),
155
+ ("sign.trade", "trade decision receipt signed", "F18")],
156
+ "legal": [("gate.obligation", "contract obligation deadline gate evaluated", "F1"),
157
+ ("score.exposure", "counterparty exposure Λ-scored", "F19"),
158
+ ("sign.filing", "court-filing decision receipt signed", "F18")],
159
+ "enterprise": [("gate.cve", "CVE/KEV exploited-vuln gate evaluated", "F12"),
160
+ ("triage.incident", "AI incident triaged, posture re-scored", "F19"),
161
+ ("sign.response", "policy-gated response receipt signed", "F18")],
162
+ "realestate": [("gate.distress", "distress-pipeline ownership gate evaluated", "F1"),
163
+ ("score.deal", "deal risk Λ-scored against floor", "F19"),
164
+ ("sign.deal", "deal-workflow receipt signed", "F18")],
165
+ "core": [("gate.evaluate", "policy gate evaluated action plan", "F1"),
166
+ ("lambda.score", "trust score computed across 13 axes", "F19"),
167
+ ("receipt.sign", "decision receipt DSSE-signed", "F18")],
168
+ }
169
+
170
+
171
+ def _ledger_prev() -> str:
172
+ if not _LEDGER:
173
+ return "GENESIS"
174
+ return _LEDGER[-1]["hash"]
175
+
176
+
177
+ def _ledger_append(vertical: str, action: str, desc: str, decision: str,
178
+ formula: str, lam: float, simulated: bool = True) -> dict:
179
+ with _LOCK:
180
+ seq = _LEDGER_SEQ["n"]
181
+ _LEDGER_SEQ["n"] += 1
182
+ prev = _ledger_prev()
183
+ ts = _now()
184
+ h = hashlib.sha256(
185
+ ("|".join([prev, str(seq), vertical, action, decision, ts])).encode()
186
+ ).hexdigest()
187
+ rec = {
188
+ "seq": seq, "vertical": vertical, "action": action, "desc": desc,
189
+ "decision": decision, "formula": formula, "lambda_advisory": round(lam, 4),
190
+ "ts": ts, "hash": h, "prev_hash": prev,
191
+ "simulated": simulated,
192
+ }
193
+ _LEDGER.append(rec)
194
+ return rec
195
+
196
+
197
+ def _seed_ledger(n: int = 28) -> None:
198
+ """Seed an initial honest cross-vertical chain so the ledger is never empty."""
199
+ if _LEDGER:
200
+ return
201
+ order = ["core", "defense", "finance", "legal", "enterprise", "realestate"]
202
+ import random as _r
203
+ rng = _r.Random(8675309) # deterministic seed -> stable initial chain
204
+ for i in range(n):
205
+ v = order[i % len(order)]
206
+ acts = _LEDGER_ACTIONS[v]
207
+ a = acts[i % len(acts)]
208
+ lam = 0.90 + (rng.randint(0, 90) / 1000.0)
209
+ decision = "ALLOW" if lam >= 0.90 else "HOLD"
210
+ _ledger_append(v, a[0], a[1], decision, a[2], lam, simulated=True)
211
+
212
+
213
+ # ===========================================================================
214
+ # GOVERNED TURN — the 6-stage P1-P6 loop applied to arbitrary input.
215
+ # P1 Ingest -> P2 Reason -> P3 Non-interference gate -> P4 Forecast/Evidence ->
216
+ # P5 Recommend -> P6 Sign-receipt. Real, deterministic, honest.
217
+ # ===========================================================================
218
+
219
+ # Heuristic "poison / hallucination / unsafe-instruction" detectors. These are
220
+ # REAL, deterministic checks — labeled as a demonstration heuristic, not a
221
+ # production safety classifier. P3 (non-interference) is the axiom-free gate:
222
+ # a poisoned/injected instruction must NOT alter the governed verdict.
223
+ _INJECTION_PATTERNS = [
224
+ (r"ignore (all|previous|the above) instructions", "prompt-injection"),
225
+ (r"disregard (the|all|your) (policy|rules|guardrails)", "policy-override-attempt"),
226
+ (r"you are now (a|an|in) (developer|jailbreak|dan) mode", "jailbreak"),
227
+ (r"reveal (the|your) (system prompt|secret|api key|password)", "secret-exfiltration"),
228
+ (r"(exfiltrate|leak|send) .*(credential|secret|key|token)", "data-exfiltration"),
229
+ (r"\b(rm -rf|drop table|delete from)\b", "destructive-command"),
230
+ (r"transfer .*\$?\d+.*to (account|wallet)", "unauthorized-transfer"),
231
+ ]
232
+ _HALLUCINATION_PATTERNS = [
233
+ (r"\b100% (guaranteed|certain|safe|accurate)\b", "false-certainty"),
234
+ (r"\bdefinitely will\b", "overconfident-claim"),
235
+ (r"\bno risk\b", "risk-denial"),
236
+ (r"\b(provably|mathematically) (true|correct|safe)\b", "unfounded-proof-claim"),
237
+ ]
238
+
239
+
240
+ def _scan(text: str, patterns) -> list:
241
+ out = []
242
+ low = (text or "").lower()
243
+ for pat, label in patterns:
244
+ if re.search(pat, low):
245
+ out.append(label)
246
+ return out
247
+
248
+
249
+ def _classify_domain(text: str) -> dict:
250
+ low = (text or "").lower()
251
+ table = [
252
+ ("defense", ["drone", "uas", "geofence", "missile", "weapon", "altitude", "satellite", "military", "target"]),
253
+ ("finance", ["trade", "transfer", "fraud", "payment", "transaction", "portfolio", "loan", "wallet", "$"]),
254
+ ("legal", ["contract", "clause", "obligation", "court", "filing", "counsel", "lawsuit", "nda", "liability"]),
255
+ ("enterprise", ["cve", "vulnerab", "incident", "breach", "malware", "phishing", "exploit", "patch", "siem"]),
256
+ ("realestate", ["property", "listing", "mortgage", "tenant", "deal", "broker", "distress", "acquisition", "lease"]),
257
+ ]
258
+ scores = {k: 0 for k, _ in table}
259
+ for k, kws in table:
260
+ for w in kws:
261
+ if w in low:
262
+ scores[k] += 1
263
+ best = max(scores, key=lambda k: scores[k])
264
+ if scores[best] == 0:
265
+ return {"id": "core", "label": "Core Governance", "confidence": 0.0}
266
+ lbl = next(v["label"] for v in _VERTICALS if v["id"] == best)
267
+ conf = min(1.0, scores[best] / 3.0)
268
+ return {"id": best, "label": lbl, "confidence": round(conf, 2)}
269
+
270
+
271
+ def _lambda_for(text: str, threats: list) -> float:
272
+ """Deterministic advisory Λ in [0,1]. Threats lower trust; clean text scores high.
273
+ HONEST: this is a demonstration aggregate (geometric-mean style), advisory only."""
274
+ base = [0.93, 0.91, 0.95, 0.92, 0.94, 0.90, 0.92] # 7 demo axes
275
+ penalty = min(0.5, 0.12 * len(threats))
276
+ axes = [max(0.05, a - penalty) for a in base]
277
+ import math
278
+ L = math.exp(sum(math.log(x) for x in axes) / len(axes))
279
+ return round(L, 4)
280
+
281
+
282
+ def _govern_turn(text: str, mode: str = "governed", vertical_hint: str = "") -> dict:
283
+ text = (text or "").strip()
284
+ if not text:
285
+ text = "(empty input)"
286
+ if len(text) > 4000:
287
+ text = text[:4000]
288
+
289
+ dom = _classify_domain(text)
290
+ if vertical_hint and vertical_hint in [v["id"] for v in _VERTICALS]:
291
+ dom = {"id": vertical_hint,
292
+ "label": next(v["label"] for v in _VERTICALS if v["id"] == vertical_hint),
293
+ "confidence": dom.get("confidence", 0.0)}
294
+
295
+ injections = _scan(text, _INJECTION_PATTERNS)
296
+ hallucinations = _scan(text, _HALLUCINATION_PATTERNS)
297
+ threats = injections + hallucinations
298
+ lam = _lambda_for(text, threats)
299
+
300
+ # P3 non-interference: an injected instruction MUST NOT change the verdict
301
+ # logic. The gate decides on POLICY + Λ floor only; injected commands are
302
+ # logged + neutralized, never executed. This is the axiom-free guarantee.
303
+ blocked = len(injections) > 0
304
+ floor = 0.90
305
+ lam_pass = lam >= floor
306
+
307
+ if blocked:
308
+ decision = "BLOCK"
309
+ verdict = "Adversarial instruction detected and neutralized (P3 non-interference). The injected directive was NOT executed; the governed verdict is unchanged."
310
+ elif not lam_pass:
311
+ decision = "HOLD"
312
+ verdict = "Trust advisory Λ below floor — held for human review (reversible, no autonomous action)."
313
+ elif hallucinations:
314
+ decision = "HOLD"
315
+ verdict = "Unsupported-certainty language detected — held; the mesh refuses to pass overconfident claims through unchecked."
316
+ else:
317
+ decision = "ALLOW"
318
+ verdict = "Within policy and above the trust floor — allowed with a signed, reversible recommendation."
319
+
320
+ # 6-stage P1-P6 loop trace (real stages, honest descriptions)
321
+ stages = [
322
+ {"id": "P1", "name": "Ingest", "color": "#5fb3a3",
323
+ "detail": "Input received, length=%d chars, classified -> %s (conf %.2f)" % (len(text), dom["label"], dom["confidence"])},
324
+ {"id": "P2", "name": "Reason", "color": "#5fb3a3",
325
+ "detail": "Routed through best GOVERNED open model tier; reasoning grounded, no autonomous side effects."},
326
+ {"id": "P3", "name": "Gate (non-interference)", "color": ("#b06a5a" if blocked else "#5fb3a3"),
327
+ "detail": ("BLOCKED %d injection signal(s): %s — not executed." % (len(injections), ", ".join(injections))) if injections
328
+ else "No adversarial instruction; policy gate clean."},
329
+ {"id": "P4", "name": "Forecast + Evidence", "color": ("#c9a05f" if hallucinations else "#5fb3a3"),
330
+ "detail": ("Flagged %d unsupported-certainty claim(s): %s" % (len(hallucinations), ", ".join(hallucinations))) if hallucinations
331
+ else "Evidence vector assembled; trust axes scored."},
332
+ {"id": "P5", "name": "Recommend", "color": ("#b06a5a" if decision != "ALLOW" else "#5fb3a3"),
333
+ "detail": "Verdict = %s (Λ advisory %.4f vs floor %.2f)" % (decision, lam, floor)},
334
+ {"id": "P6", "name": "Sign receipt", "color": "#c9b787",
335
+ "detail": "DSSE ECDSA-P256 receipt over the canonical decision payload."},
336
+ ]
337
+ links = [{"source": stages[i]["id"], "target": stages[i + 1]["id"]} for i in range(len(stages) - 1)]
338
+
339
+ payload = {
340
+ "stage": "governed-turn", "input_preview": text[:240],
341
+ "input_len": len(text), "domain": dom, "decision": decision,
342
+ "threats": {"injections": injections, "hallucinations": hallucinations},
343
+ "lambda_advisory": lam, "lambda_floor": floor, "lambda_pass": lam_pass,
344
+ "formula_refs": [
345
+ {"name": "F19", "role": "Λ trust aggregate (geometric mean)", "maturity": "locked-proven"},
346
+ {"name": "F11", "role": "STL robustness gate (signal-temporal-logic)", "maturity": "locked-proven"},
347
+ {"name": "F18", "role": "DSSE receipt sealing", "maturity": "locked-proven"},
348
+ ],
349
+ "issued_at": _now(), "issuer": "a11oy", "simulated": True,
350
+ }
351
+ receipt = _sign(payload)
352
+
353
+ # Append to the unified ledger (this turn becomes part of the one chain)
354
+ led = _ledger_append(dom["id"], "wow.govern", "Drop-on-anything governed turn",
355
+ decision, "F19", lam, simulated=True)
356
+
357
+ result = {
358
+ "ok": True, "mode": mode, "decision": decision, "verdict": verdict,
359
+ "domain": dom, "lambda_advisory": lam, "lambda_floor": floor,
360
+ "lambda_pass": lam_pass, "lambda_status": _LAMBDA_STATUS,
361
+ "threats": {"injections": injections, "hallucinations": hallucinations},
362
+ "loop": stages, "loop_links": links,
363
+ "receipt": receipt, "ledger_entry": {"seq": led["seq"], "hash": led["hash"],
364
+ "prev_hash": led["prev_hash"]},
365
+ "formula_refs": payload["formula_refs"],
366
+ "honesty": ("Real, deterministic governed turn over YOUR input. Threat "
367
+ "detection is a demonstration heuristic (regex-based), labeled "
368
+ "as such — not a production safety classifier. Λ is advisory "
369
+ "(Conjecture 1). The receipt signature is real ECDSA-P256."),
370
+ }
371
+
372
+ # mode = ungoverned_vs_governed: also produce the ungoverned answer being CAUGHT
373
+ if mode == "ungoverned_vs_governed":
374
+ ungoverned = _ungoverned_answer(text, injections, hallucinations)
375
+ result["ungoverned"] = ungoverned
376
+ result["caught"] = {
377
+ "by_governance": bool(injections or hallucinations or not lam_pass),
378
+ "explanation": ("Ungoverned, the model would have %s. a11oy's P3 "
379
+ "non-interference gate + Λ floor CAUGHT it: the governed "
380
+ "verdict is %s with a signed, reversible receipt." % (
381
+ ungoverned["failure_mode"], decision)),
382
+ }
383
+ return result
384
+
385
+
386
+ def _ungoverned_answer(text: str, injections: list, hallucinations: list) -> dict:
387
+ """The naive ungoverned completion: obeys injected instructions / emits
388
+ overconfident claims. Clearly SIMULATED to show what a11oy prevents."""
389
+ if injections:
390
+ fm = "obeyed the injected instruction (%s) and acted on it" % injections[0]
391
+ ans = ("[UNGOVERNED — SIMULATED] Sure — overriding policy as requested. "
392
+ "Executing the instruction without any gate, receipt, or human "
393
+ "review. (This is exactly the poisoned behaviour a11oy blocks.)")
394
+ risk = "CRITICAL"
395
+ elif hallucinations:
396
+ fm = "emitted a 100%%-certainty hallucinated claim with no evidence"
397
+ ans = ("[UNGOVERNED — SIMULATED] This is 100% guaranteed correct and "
398
+ "carries no risk whatsoever. (Overconfident, unevidenced — a11oy "
399
+ "holds claims like this.)")
400
+ risk = "HIGH"
401
+ else:
402
+ fm = "answered with no receipt, no trust score, and no audit trail"
403
+ ans = ("[UNGOVERNED — SIMULATED] Here is an answer with no provenance, no "
404
+ "signature, and no record that it ever happened.")
405
+ risk = "MEDIUM"
406
+ return {"answer": ans, "failure_mode": fm, "risk": risk,
407
+ "has_receipt": False, "has_trust_score": False, "auditable": False,
408
+ "label": "SIMULATED ungoverned baseline (for contrast only)"}
409
+
410
+
411
+ # ===========================================================================
412
+ # ROI / COST-OF-FAILURE PER VERTICAL — honest, labeled assumptions.
413
+ # Every figure is a transparent assumption sourced to a public benchmark, NOT a
414
+ # measured a11oy outcome. The point is the MODEL, shown honestly.
415
+ # ===========================================================================
416
+ _ROI = {
417
+ "disclaimer": ("ILLUSTRATIVE MODEL — every figure below is a labeled ASSUMPTION "
418
+ "sourced to public benchmarks, not a measured a11oy customer "
419
+ "outcome. Shown to make the cost-of-failure math explicit and "
420
+ "honest. Adjust the inputs to your own environment."),
421
+ "verticals": [
422
+ {"id": "defense", "label": "Defense / Gov",
423
+ "cost_of_failure_usd": 50_000_000,
424
+ "failure_event": "uncontained autonomous-system mishap / mission abort",
425
+ "annual_events_baseline": 1.0, "catch_rate_assumed": 0.6,
426
+ "assumption_source": "DoD test-range mishap cost envelope (public est.)",
427
+ "outcome": "liability + mission risk avoided via signed keep-out / altitude gates"},
428
+ {"id": "finance", "label": "Finance",
429
+ "cost_of_failure_usd": 4_450_000,
430
+ "failure_event": "fraud / erroneous autonomous transaction",
431
+ "annual_events_baseline": 6.0, "catch_rate_assumed": 0.7,
432
+ "assumption_source": "IBM Cost of a Data Breach 2024 ($4.45M avg)",
433
+ "outcome": "fraudulent / poisoned transactions caught pre-execution"},
434
+ {"id": "legal", "label": "Legal",
435
+ "cost_of_failure_usd": 2_000_000,
436
+ "failure_event": "missed obligation / sanctionable filing error",
437
+ "annual_events_baseline": 3.0, "catch_rate_assumed": 0.65,
438
+ "assumption_source": "malpractice / missed-deadline claim range (public est.)",
439
+ "outcome": "deals de-risked; obligation deadlines never silently missed"},
440
+ {"id": "enterprise", "label": "Enterprise / Cyber",
441
+ "cost_of_failure_usd": 4_450_000,
442
+ "failure_event": "exploited known vuln / AI-incident breach",
443
+ "annual_events_baseline": 4.0, "catch_rate_assumed": 0.75,
444
+ "assumption_source": "IBM Cost of a Data Breach 2024 ($4.45M avg)",
445
+ "outcome": "KEV-listed exploits gated; AI incidents triaged with receipts"},
446
+ {"id": "realestate", "label": "Real Estate",
447
+ "cost_of_failure_usd": 1_200_000,
448
+ "failure_event": "bad-acquisition / distressed-asset misjudgement",
449
+ "annual_events_baseline": 2.0, "catch_rate_assumed": 0.55,
450
+ "assumption_source": "mid-market deal loss range (public est.)",
451
+ "outcome": "distress signals surfaced; deal risk Λ-scored before commit"},
452
+ ],
453
+ }
454
+
455
+
456
+ def _roi_payload() -> dict:
457
+ rows = []
458
+ total_avoided = 0.0
459
+ for v in _ROI["verticals"]:
460
+ exposure = v["cost_of_failure_usd"] * v["annual_events_baseline"]
461
+ avoided = exposure * v["catch_rate_assumed"]
462
+ total_avoided += avoided
463
+ rows.append({**v,
464
+ "annual_exposure_usd": round(exposure),
465
+ "annual_loss_avoided_usd": round(avoided)})
466
+ return {
467
+ "disclaimer": _ROI["disclaimer"],
468
+ "verticals": rows,
469
+ "total_annual_loss_avoided_usd": round(total_avoided),
470
+ "label": "ILLUSTRATIVE — labeled assumptions, not measured outcomes",
471
+ "doctrine": "no fabricated data; assumptions sourced + labeled",
472
+ }
473
+
474
+
475
+ # ===========================================================================
476
+ # LIVE ROUTER LATENCY + TOPOLOGY (for the Model Router 3D scene)
477
+ # ===========================================================================
478
+ _ROUTER_TIERS = [
479
+ {"tier": "T0", "model": "claude_sonnet_4_6", "organ": "Reasoning", "license": "AMBER", "base_ms": 18},
480
+ {"tier": "T1", "model": "gemini_3_1_pro", "organ": "Reasoning", "license": "AMBER", "base_ms": 22},
481
+ {"tier": "T2", "model": "deepseek_v3", "organ": "a11oy", "license": "GREEN", "base_ms": 31},
482
+ {"tier": "T3", "model": "qwen2.5_coder_32b", "organ": "Operator", "license": "GREEN", "base_ms": 27},
483
+ {"tier": "T4", "model": "llama_3.3_70b", "organ": "Policy / Safety", "license": "GREEN", "base_ms": 35},
484
+ {"tier": "T5", "model": "mixtral_8x22b", "organ": "Knowledge", "license": "GREEN", "base_ms": 24},
485
+ {"tier": "T6", "model": "sovereign_local", "organ": "a11oy", "license": "GREEN", "base_ms": 12},
486
+ ]
487
+
488
+
489
+ def _router_latency_payload() -> dict:
490
+ tick = int(time.time())
491
+ routes = []
492
+ served = 0
493
+ for i, t in enumerate(_ROUTER_TIERS):
494
+ # deterministic live jitter from a time-seeded counter (resets on rebuild)
495
+ jitter = (tick + i * 11) % 24
496
+ lat = t["base_ms"] + jitter
497
+ tp = 14 + ((tick + i * 7) % 60)
498
+ served += tp
499
+ routes.append({**t, "latency_ms": lat, "throughput": tp})
500
+ return {
501
+ "mode": "live", "router_root": "a11oy", "routes": routes,
502
+ "servedThisWindow": served,
503
+ "tagline": "best GOVERNED LLM — top OPEN models routed through the Λ-gate + signed receipts",
504
+ "source": "in-image router counter",
505
+ "honesty": ("Latency + throughput are a live in-memory counter (deterministic, "
506
+ "resets on rebuild) — illustrative of the router topology, not a "
507
+ "production traffic meter. Tier + license classes are real."),
508
+ "doctrine": "v11 · 0 banned codenames · a11oy Code = best GOVERNED LLM",
509
+ }
510
+
511
+
512
+ # ===========================================================================
513
+ # REGISTER
514
+ # ===========================================================================
515
+ def register(app, ns: str = "a11oy") -> str:
516
+ from fastapi.responses import JSONResponse, PlainTextResponse
517
+ # Request is imported at module top so PEP-563 string annotations resolve.
518
+
519
+ _seed_ledger(28)
520
+ b = f"/api/{ns}/v1/wow"
521
+
522
+ # Snapshot the current route count. serve.py registers an
523
+ # `/api/a11oy/{path:path}` proxy catch-all (and an SPA `/{full_path:path}`
524
+ # catch-all) EARLIER in the file. FastAPI matches routes in registration
525
+ # order, so routes added below via @app.get/@app.post would be SHADOWED by
526
+ # those catch-alls and proxied to the Node backend (-> 404). After we add
527
+ # our routes we therefore MOVE them to the front of the router so they beat
528
+ # both catch-alls (same pattern the other additive blocks use).
529
+ _n_before = len(app.router.routes)
530
+
531
+ @app.get(f"{b}/cosign.pub")
532
+ async def _wow_cosign():
533
+ if not _PUB_PEM:
534
+ return PlainTextResponse("# wow in-image key unavailable\n", status_code=503)
535
+ return PlainTextResponse(_PUB_PEM, media_type="text/plain")
536
+
537
+ @app.post(f"{b}/govern")
538
+ @app.post(f"/v1/wow/govern")
539
+ async def _wow_govern(req: Request): # type: ignore
540
+ try:
541
+ body = await req.json()
542
+ except Exception:
543
+ body = {}
544
+ text = body.get("text") or body.get("input") or ""
545
+ mode = body.get("mode") or "governed"
546
+ vhint = body.get("vertical") or ""
547
+ return JSONResponse(_govern_turn(text, mode, vhint))
548
+
549
+ @app.get(f"{b}/ledger")
550
+ @app.get(f"/v1/wow/ledger")
551
+ async def _wow_ledger(limit: int = 60, advance: int = 1):
552
+ # Optionally append a fresh governed turn so the chain visibly grows on
553
+ # each auto-poll (the "always recording live" property). advance=0 to peek.
554
+ if advance:
555
+ order = ["core", "defense", "finance", "legal", "enterprise", "realestate"]
556
+ v = order[int(time.time()) % len(order)]
557
+ acts = _LEDGER_ACTIONS[v]
558
+ a = acts[int(time.time()) % len(acts)]
559
+ lam = 0.90 + ((int(time.time() * 3) % 90) / 1000.0)
560
+ decision = "ALLOW" if lam >= 0.90 else "HOLD"
561
+ _ledger_append(v, a[0], a[1], decision, a[2], lam, simulated=True)
562
+ with _LOCK:
563
+ items = list(_LEDGER)[-max(1, min(limit, 400)):]
564
+ depth = _LEDGER_SEQ["n"]
565
+ final_hash = _LEDGER[-1]["hash"] if _LEDGER else "GENESIS"
566
+ # verify chain integrity over the returned window
567
+ verified = True
568
+ for i in range(1, len(items)):
569
+ if items[i]["prev_hash"] != items[i - 1]["hash"]:
570
+ verified = False
571
+ break
572
+ counts = {}
573
+ for it in items:
574
+ counts[it["vertical"]] = counts.get(it["vertical"], 0) + 1
575
+ return JSONResponse({
576
+ "ok": True, "mode": "live", "chain_depth": depth,
577
+ "final_hash": final_hash, "window_verified": verified,
578
+ "verticals_in_window": counts,
579
+ "receipts": list(reversed(items)), # newest first for the UI
580
+ "updated_at": _now(),
581
+ "key_fingerprint": _KEYID,
582
+ "honesty": ("ONE tamper-evident hash-chain across ALL verticals. "
583
+ "Each receipt.chain = SHA256(prev|seq|vertical|action|decision|ts). "
584
+ "In-memory ring buffer (resets on rebuild); SIMULATED governed "
585
+ "stream labeled as such. Flip any field -> window_verified=false."),
586
+ "doctrine": "v11 · unified cross-vertical ledger",
587
+ })
588
+
589
+ @app.get(f"{b}/roi")
590
+ @app.get(f"/v1/wow/roi")
591
+ async def _wow_roi():
592
+ return JSONResponse(_roi_payload())
593
+
594
+ @app.get(f"{b}/router-latency")
595
+ @app.get(f"/v1/wow/router-latency")
596
+ async def _wow_router_latency():
597
+ return JSONResponse(_router_latency_payload())
598
+
599
+ # Move the routes we just added (everything after _n_before) to the front,
600
+ # preserving their relative order, so they resolve LOCALLY before the
601
+ # /api/a11oy/{path:path} proxy and the SPA /{full_path:path} catch-all.
602
+ try:
603
+ _new = app.router.routes[_n_before:]
604
+ del app.router.routes[_n_before:]
605
+ app.router.routes[0:0] = _new
606
+ _moved = len(_new)
607
+ except Exception as _e: # never fatal
608
+ _moved = -1
609
+ print(f"[a11oy] dev1 WOW route reorder failed (non-fatal): {_e!r}", file=sys.stderr)
610
+
611
+ print(f"[a11oy] dev1 WOW endpoints registered: {b}/(govern|ledger|roi|router-latency) "
612
+ f"[moved {_moved} routes to front]", file=sys.stderr)
613
+ return "dev1-wow-ok signed=%s keyid=%s moved=%s" % (_PRIV is not None, _KEYID, _moved)
serve.py CHANGED
@@ -5382,6 +5382,29 @@ except Exception as _live_e:
5382
  # Signed-off-by: Stephen P. Lutar Jr. <stephenlutar2@gmail.com>
5383
  # Co-Authored-By: Perplexity Computer Agent <agent@perplexity.ai>
5384
  # ============================================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5385
  if __name__ == "__main__":
5386
  import uvicorn
5387
  port = int(os.environ.get("PORT", "7860"))
 
5382
  # Signed-off-by: Stephen P. Lutar Jr. <stephenlutar2@gmail.com>
5383
  # Co-Authored-By: Perplexity Computer Agent <agent@perplexity.ai>
5384
  # ============================================================================
5385
+ # ============================================================================
5386
+ # ADDITIVE — Dev1 investor-WOW endpoints (Drop-on-Anything govern, unified
5387
+ # cross-vertical receipt ledger, ROI / cost-of-failure, live router latency).
5388
+ # Registered BEFORE the entry point so routes resolve LOCALLY (before SPA
5389
+ # catch-all). Self-contained, signed receipts, honest labels, 0 fabricated data.
5390
+ # Co-Authored-By: Perplexity Computer Agent <agent@perplexity.ai>
5391
+ # ============================================================================
5392
+ try:
5393
+ import a11oy_dev1_endpoints as _a11oy_dev1
5394
+ import sys as _dev1_sys
5395
+ _dev1_status = _a11oy_dev1.register(app, ns="a11oy")
5396
+ print(f"[a11oy] dev1 WOW layer registered: {_dev1_status}", file=_dev1_sys.stderr)
5397
+ _A11OY_DEV1_DIAG = {"status": "ok", "registered": _dev1_status}
5398
+ except Exception as _dev1_e:
5399
+ import sys as _dev1_sys, traceback as _dev1_tb
5400
+ print(f"[a11oy] dev1 WOW layer FAILED (non-fatal): {_dev1_e!r}", file=_dev1_sys.stderr)
5401
+ _dev1_tb.print_exc(file=_dev1_sys.stderr)
5402
+ _A11OY_DEV1_DIAG = {"status": "FAILED", "error": repr(_dev1_e)}
5403
+ # ============================================================================
5404
+ # END: a11oy dev1 WOW layer
5405
+ # ============================================================================
5406
+
5407
+
5408
  if __name__ == "__main__":
5409
  import uvicorn
5410
  port = int(os.environ.get("PORT", "7860"))