betterwithage commited on
Commit
60826ae
·
verified ·
1 Parent(s): 7620ee7

chore(sync): mirror backend .py + Dockerfile to Space (hf-sync-backend)

Browse files

Automated backend sync from szl-holdings/a11oy main via hf-sync-backend.
Updated (differed from the Space): Dockerfile, szl_sda.py
Deleted (gone from the repo + Dockerfile COPY set): (none)

Keeps the Space-built backend (serve.py + the Dockerfile-COPY'd .py
modules) identical to GitHub main so the Space never rebuilds from a
stale backend, new endpoints don't 404 there, and orphaned modules
removed from the repo don't linger in the Space tree.

Files changed (2) hide show
  1. Dockerfile +7 -0
  2. szl_sda.py +664 -0
Dockerfile CHANGED
@@ -198,6 +198,13 @@ COPY szl_quant_qbio_holo.py ./
198
  # shared signed-receipt chain), already COPY'd above. szl_materials is the SHARED
199
  # Materials module (Crystal Novelty Certificate + appended DEV2/DEV3 groups).
200
  COPY szl_materials.py ./
 
 
 
 
 
 
 
201
  # ADDITIVE (I3): FABRO-style Governed Factory + Constitutional Engines modules.
202
  # MUST be COPY'd or serve.py's guarded imports fall back (merged-but-not-live).
203
  # HTML/JS is inlined in these .py modules, so NO web/ or static-vendor COPY needed.
 
198
  # shared signed-receipt chain), already COPY'd above. szl_materials is the SHARED
199
  # Materials module (Crystal Novelty Certificate + appended DEV2/DEV3 groups).
200
  COPY szl_materials.py ./
201
+ # SWEEP D1 (SDA): szl_sda.py serves the honest Space/Domain-Awareness + counter-UAS
202
+ # surface (/api/a11oy/v1/sda/* and /v1/sda/*). MUST be per-file COPY'd (no `COPY . .`)
203
+ # or serve.py's guarded `import szl_sda` falls back to the stub (merged-but-not-live,
204
+ # /api/a11oy/v1/sda/* 404s) AND hf-sync-backend (which parses this COPY set) would not
205
+ # mirror it to the HF Space. Reuses szl_khipu (shared signed-receipt chain, COPY'd
206
+ # above) and the REAL counter-UAS drone-cyber logic. Tracks are REPLAY/SAMPLE/MODELED.
207
+ COPY szl_sda.py ./
208
  # ADDITIVE (I3): FABRO-style Governed Factory + Constitutional Engines modules.
209
  # MUST be COPY'd or serve.py's guarded imports fall back (merged-but-not-live).
210
  # HTML/JS is inlined in these .py modules, so NO web/ or static-vendor COPY needed.
szl_sda.py ADDED
@@ -0,0 +1,664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # © 2026 Lutar, Stephen P. — SZL Holdings · ORCID 0009-0001-0110-4173
3
+ # Doctrine v11 — SDA (Space / Domain Awareness) honest counter-UAS surface.
4
+ """
5
+ szl_sda.py — the HONEST `/api/a11oy/v1/sda/*` Space-/Domain-Awareness surface.
6
+
7
+ SDA = Space / Domain Awareness: one honest pane over the three contact domains
8
+ the estate already has REAL substance for —
9
+ * vessel (maritime AIS tracks — the warhacker-demo UDS `demo_ais_replay.sh`
10
+ sample dataset: dark-vessel gap + OFAC-SDN sanctions test MMSI),
11
+ * drone (counter-UAS contacts scored by the REAL counter-UAS drone-cyber logic
12
+ in organs/sentra/sentra_drone_cyber.py — DRONE_SIGS / T11-T20
13
+ tripwires / 13-axis yuyay_v3 Lambda aggregate / Λ floor 0.90),
14
+ * space-object (MODELED orbital-roadmap objects — SZL has NO on-orbit sensor;
15
+ these mirror the a11oy_orbital_page MODELED constellation, labeled
16
+ MODELED, never live telemetry).
17
+
18
+ USER-VISIBLE NAME: "SDA — Space / Domain Awareness (Counter-UAS)". This module
19
+ NEVER emits a codename (sentra / amaru / rosie / jarvis) in any served string;
20
+ the drone logic's honest, user-facing name is the SDA / counter-UAS surface.
21
+
22
+ HONESTY (Doctrine v11 — NEVER violate):
23
+ * The tracks are REPLAY / SAMPLE / MODELED demo data — they are NOT a live
24
+ radar / AIS / RF sensor feed. SZL does not operate the radar, the AIS
25
+ receiver, or the on-orbit sensor behind these. Every track carries an
26
+ explicit `data_kind` ∈ {REPLAY, SAMPLE, MODELED} and the status endpoint
27
+ labels `data_source` the same way. We never claim a live sensor we don't
28
+ have.
29
+ * Effectors are SIMULATED, human-on-loop. A counter-UAS verdict is an
30
+ assessment + a signed receipt — NOT a kinetic or jamming action. Any
31
+ "mitigation" is decision-support only; the human stays on the loop.
32
+ * The counter-UAS verdict REUSES the REAL counter-UAS drone-cyber logic (imported
33
+ from organs/sentra/sentra_drone_cyber.py); it is NOT re-weakened or
34
+ re-implemented. If the import is unavailable at runtime, the verdict path is
35
+ honestly labeled `degraded` and uses the byte-identical mirror constants —
36
+ never a fabricated PASS.
37
+ * Λ = Conjecture 1 (NOT a theorem). Khipu = Conjecture 2. Trust is never 100%.
38
+ The locked-proven set is EXACTLY 8 {F1,F4,F7,F11,F12,F18,F19,F22} @ kernel
39
+ c7c0ba17 and this module ADDS NOTHING to it. DSSE signature is a
40
+ PLACEHOLDER (chain integrity is real; Sigstore not wired) — honestly carried.
41
+
42
+ ENDPOINTS (dual-registered under /api/a11oy/v1/sda/* AND /v1/sda/*):
43
+ GET /sda/healthz -> liveness + organ identity + honest data-source note.
44
+ GET /sda/status -> honest summary: total track count by domain, data_source
45
+ label (REPLAY/SAMPLE/MODELED — NOT live), counter-UAS
46
+ signature corpus size, verdicts this process, signed-
47
+ receipt chain head + depth, doctrine block.
48
+ GET /sda/tracks -> the real space/vessel/drone track objects (REPLAY/SAMPLE
49
+ from the AIS replay dataset + MODELED orbital objects +
50
+ drone contacts). Each: id, type, position, risk score,
51
+ data_kind. Optional ?type=vessel|drone|space-object.
52
+ POST /sda/verdict -> counter-UAS threat verdict on a track/contact using the
53
+ REAL counter-UAS drone-cyber logic (13-axis Λ aggregate vs
54
+ floor 0.90 + tripwire/risk assessment). Returns the
55
+ assessment PLUS a signed Khipu receipt
56
+ (SZL.SDA.Verdict.v1, organ="sda") into the SHARED
57
+ szl_khipu DAG. Effector SIMULATED, human-on-loop.
58
+ GET /sda/verify -> re-walk the SDA Khipu chain (judge-verifiable integrity).
59
+
60
+ Stdlib + the existing repo modules (szl_khipu; organs/sentra/sentra_drone_cyber
61
+ for the REAL drone logic). No new pip dep, no CDN, no Node. Additive;
62
+ try/except-guarded by the caller; registered BEFORE the SPA catch-all. Request /
63
+ JSONResponse imported at MODULE level (this module uses `from __future__ import
64
+ annotations`, so a function-local import would leave a `request: Request`
65
+ annotation unresolved and FastAPI would wrongly treat it as a query param → 422).
66
+ """
67
+ from __future__ import annotations
68
+
69
+ import datetime
70
+ import hashlib
71
+ import json
72
+ import threading
73
+ import time
74
+ from typing import Any, Optional
75
+
76
+ from fastapi import Request
77
+ from fastapi.responses import JSONResponse
78
+
79
+ # ---------------------------------------------------------------------------
80
+ # Identity + doctrine constants (honest, never a codename).
81
+ # ---------------------------------------------------------------------------
82
+ _ORGAN_NAME = "SDA — Space / Domain Awareness (Counter-UAS)"
83
+ _KHIPU_ORGAN = "sda"
84
+ _RECEIPT_TYPE = "SZL.SDA.Verdict.v1"
85
+ _LOCKED_PROVEN = ["F1", "F4", "F7", "F11", "F12", "F18", "F19", "F22"] # EXACTLY 8 @ c7c0ba17
86
+ _KERNEL_COMMIT = "c7c0ba17"
87
+
88
+ # ---------------------------------------------------------------------------
89
+ # REUSE the REAL counter-UAS drone-cyber logic. We IMPORT it — we do NOT re-implement
90
+ # or re-weaken it. If the import fails at runtime (path/layout), we fall back to
91
+ # the BYTE-IDENTICAL mirror constants below and label the verdict path honestly
92
+ # `degraded` (never a fabricated PASS). The Λ floor stays 0.90 either way.
93
+ # ---------------------------------------------------------------------------
94
+ _LAMBDA_FLOOR = 0.90 # canonical yuyay_v3 floor (mirrors sentra_drone_cyber.LAMBDA_FLOOR)
95
+
96
+ # Byte-identical mirror of organs/sentra/sentra_drone_cyber DRONE_SIGS (T11-T20).
97
+ _DRONE_SIGS_MIRROR = [
98
+ {"sig_id": "DSIG-01", "name": "secure-boot-attestation-failure", "tripwire": "T11", "class": "tamper"},
99
+ {"sig_id": "DSIG-02", "name": "firmware-merkle-mismatch", "tripwire": "T12", "class": "tamper"},
100
+ {"sig_id": "DSIG-03", "name": "mavlink-anomaly", "tripwire": "T13", "class": "intrusion"},
101
+ {"sig_id": "DSIG-04", "name": "rf-fingerprint-deviation", "tripwire": "T14", "class": "intrusion"},
102
+ {"sig_id": "DSIG-05", "name": "accelerometer-imu-spoof", "tripwire": "T15", "class": "tamper"},
103
+ {"sig_id": "DSIG-06", "name": "gps-spoof", "tripwire": "T16", "class": "intrusion"},
104
+ {"sig_id": "DSIG-07", "name": "unexpected-ota-attempt", "tripwire": "T17", "class": "tamper"},
105
+ {"sig_id": "DSIG-08", "name": "geofence-violation", "tripwire": "T18", "class": "anomaly"},
106
+ {"sig_id": "DSIG-09", "name": "mission-deviation", "tripwire": "T19", "class": "anomaly"},
107
+ {"sig_id": "DSIG-10", "name": "unauthorized-mavlink-command", "tripwire": "T20", "class": "intrusion"},
108
+ ]
109
+ _BASE_SIGS_MIRROR = ["DROP TABLE", "rm -rf", "<script", "eval(", "subprocess", "../../etc"]
110
+
111
+
112
+ def _load_sentra() -> tuple[Any, str]:
113
+ """Import the REAL Sentra drone-cyber module. Returns (module_or_None, source).
114
+ Tries the package path first, then a flat import. Never raises."""
115
+ for modpath in ("organs.sentra.sentra_drone_cyber", "sentra_drone_cyber"):
116
+ try:
117
+ mod = __import__(modpath, fromlist=["*"])
118
+ # Served label is sanitized (no internal codename); the import path
119
+ # itself is a code reference, never an emitted product label.
120
+ return mod, "REAL (counter-UAS drone-cyber organ imported)"
121
+ except Exception: # noqa: BLE001 — degrade honestly to the mirror
122
+ continue
123
+ return None, "MIRROR (counter-UAS drone-cyber organ unavailable — byte-identical constants)"
124
+
125
+
126
+ def _drone_sigs() -> tuple[list[dict], list[str], Any, str]:
127
+ """Return (drone_sigs, base_sigs, lambda_fn, source). lambda_fn is the REAL
128
+ 13-axis geometric-mean aggregate from Sentra when importable, else the
129
+ byte-identical mirror."""
130
+ mod, source = _load_sentra()
131
+ if mod is not None:
132
+ try:
133
+ ds = list(getattr(mod, "DRONE_SIGS", _DRONE_SIGS_MIRROR))
134
+ bs = list(getattr(mod, "BASE_SIGS", _BASE_SIGS_MIRROR))
135
+ lam = getattr(mod, "_lambda_aggregate", _lambda_aggregate_mirror)
136
+ return ds, bs, lam, source
137
+ except Exception: # noqa: BLE001
138
+ pass
139
+ return list(_DRONE_SIGS_MIRROR), list(_BASE_SIGS_MIRROR), _lambda_aggregate_mirror, source
140
+
141
+
142
+ def _lambda_aggregate_mirror(axis_scores) -> float:
143
+ """Byte-identical mirror of sentra_drone_cyber._lambda_aggregate — the
144
+ 13-axis geometric mean (canonical yuyay_v3). Used only if the REAL module
145
+ cannot be imported. NOT a re-weakening: identical math."""
146
+ xs = [max(1e-9, float(x)) for x in (axis_scores or [])][:13]
147
+ if len(xs) < 13:
148
+ xs += [0.9] * (13 - len(xs))
149
+ prod = 1.0
150
+ for x in xs:
151
+ prod *= x
152
+ return prod ** (1.0 / 13.0)
153
+
154
+
155
+ # Tripwire -> signature index (built from whichever sig set is live).
156
+ def _tripwire_index(drone_sigs: list[dict]) -> dict[str, dict]:
157
+ return {d.get("tripwire"): d for d in drone_sigs}
158
+
159
+
160
+ # ---------------------------------------------------------------------------
161
+ # REAL track substance — REPLAY / SAMPLE / MODELED. NONE of this is a live feed.
162
+ # ---------------------------------------------------------------------------
163
+ # (A) VESSEL tracks — the warhacker-demo UDS `demo_ais_replay.sh` sample dataset
164
+ # (docs/vessels/du-upstream-contributions/uds-package-vessels/scripts/
165
+ # demo_ais_replay.sh). 5 sample AIS position reports; one has a 6-hour AIS
166
+ # gap (dark-vessel trigger) and one carries a test MMSI on the demo OFAC-SDN
167
+ # list. data_kind=REPLAY — this is the demo replay dataset, NOT a live AIS
168
+ # receiver. Risk scored deterministically from the demo flags.
169
+ _AIS_REPLAY_SAMPLE = [
170
+ {"mmsi": "123456789", "lat": 1.2897, "lng": 103.8501, "speed": 12.3, "heading": 45, "ts": "2026-06-16T06:00:00Z", "name": "MV TAMAR EXPRESS", "flag": "PA"},
171
+ {"mmsi": "234567890", "lat": 25.7617, "lng": 55.9653, "speed": 0.0, "heading": 0, "ts": "2026-06-16T06:05:00Z", "name": "MT AURORA PRINCE", "flag": "LR"},
172
+ {"mmsi": "345678901", "lat": 51.9106, "lng": 4.4814, "speed": 8.7, "heading": 270, "ts": "2026-06-16T06:10:00Z", "name": "MV ROTTERDAM SPIRIT", "flag": "NL"},
173
+ {"mmsi": "456789012", "lat": 35.6762, "lng": 139.6503, "speed": 0.0, "heading": 0, "ts": "2026-06-16T06:15:00Z", "name": "MT SILENT MERIDIAN", "flag": "PA", "ais_gap_hours": 6},
174
+ {"mmsi": "999000001", "lat": 4.9031, "lng": 114.9399, "speed": 11.2, "heading": 135, "ts": "2026-06-16T06:20:00Z", "name": "MV SANCTIONED VESSEL TEST", "flag": "KP"},
175
+ ]
176
+ # Demo sanctions list (test MMSI only) — mirrors the demo_ais_replay.sh OFAC hit.
177
+ _DEMO_SDN_MMSI = {"999000001"}
178
+
179
+
180
+ def _vessel_risk(v: dict) -> tuple[float, list[str]]:
181
+ """Deterministic demo risk for a sample AIS report (REPLAY)."""
182
+ flags: list[str] = []
183
+ risk = 0.05
184
+ if v.get("ais_gap_hours", 0) and float(v["ais_gap_hours"]) >= 6:
185
+ flags.append("dark-vessel:ais-gap-%dh" % int(v["ais_gap_hours"]))
186
+ risk = max(risk, 0.72)
187
+ if str(v.get("mmsi")) in _DEMO_SDN_MMSI:
188
+ flags.append("sanctions:ofac-sdn-test-mmsi")
189
+ risk = max(risk, 0.93)
190
+ if v.get("flag") in ("KP",) and str(v.get("mmsi")) not in _DEMO_SDN_MMSI:
191
+ flags.append("flag-state-watch:%s" % v.get("flag"))
192
+ risk = max(risk, 0.4)
193
+ return round(risk, 3), flags
194
+
195
+
196
+ # (B) SPACE-OBJECT tracks — MODELED orbital-roadmap objects mirroring the
197
+ # a11oy_orbital_page MODELED constellation (LEO/MEO/GEO tiers). SZL has NO
198
+ # on-orbit sensor; these are MODELED, never live telemetry. Risk is a
199
+ # conjunction/proximity demo score (MODELED).
200
+ _ORBITAL_MODELED = [
201
+ {"obj_id": "SZL-LEO-01", "tier": "LEO", "alt_km": 550, "inc_deg": 53.0, "kind": "edge-compute-node", "conjunction_pc": 0.002},
202
+ {"obj_id": "SZL-LEO-07", "tier": "LEO", "alt_km": 545, "inc_deg": 53.0, "kind": "edge-compute-node", "conjunction_pc": 0.061},
203
+ {"obj_id": "SZL-MEO-02", "tier": "MEO", "alt_km": 8000, "inc_deg": 55.0, "kind": "aggregation-ring", "conjunction_pc": 0.0008},
204
+ {"obj_id": "SZL-GEO-01", "tier": "GEO", "alt_km": 35786, "inc_deg": 0.1, "kind": "backhaul", "conjunction_pc": 0.0001},
205
+ {"obj_id": "DEBRIS-COSPAR-1982-092", "tier": "LEO", "alt_km": 560, "inc_deg": 65.8, "kind": "tracked-debris", "conjunction_pc": 0.18},
206
+ ]
207
+
208
+
209
+ def _space_risk(o: dict) -> tuple[float, list[str]]:
210
+ flags: list[str] = []
211
+ pc = float(o.get("conjunction_pc", 0.0))
212
+ risk = min(0.99, round(pc * 4.0, 3)) # MODELED conjunction-probability scaling
213
+ if o.get("kind") == "tracked-debris":
214
+ flags.append("debris-conjunction-watch")
215
+ risk = max(risk, 0.55)
216
+ if pc >= 0.05:
217
+ flags.append("conjunction-pc:%.3f" % pc)
218
+ return round(risk, 3), flags
219
+
220
+
221
+ # (C) DRONE contacts — counter-UAS demo contacts scored by the REAL Sentra
222
+ # drone-cyber tripwire model (T11-T20). data_kind=SAMPLE — demo contacts,
223
+ # not a live RF/radar feed. Each lists the fired tripwires; risk derives
224
+ # from the 13-axis Λ aggregate (1 - Λ on the contact's axis scores).
225
+ _DRONE_CONTACTS = [
226
+ {"contact_id": "uas-bravo-01", "model": "generic-quad", "side": "unknown", "fired": ["T16", "T18"],
227
+ "axis_scores": [0.71, 0.68, 0.74, 0.70, 0.66, 0.72, 0.69, 0.71, 0.55, 0.70, 0.62, 0.68, 0.70]},
228
+ {"contact_id": "uas-charlie-03", "model": "fixed-wing-uas", "side": "hostile", "fired": ["T13", "T16", "T20"],
229
+ "axis_scores": [0.42, 0.40, 0.45, 0.38, 0.41, 0.44, 0.39, 0.43, 0.30, 0.40, 0.35, 0.41, 0.40]},
230
+ {"contact_id": "mq9-allied-09", "model": "mq-9", "side": "allied", "fired": [],
231
+ "axis_scores": [0.96, 0.97, 0.95, 0.96, 0.94, 0.96, 0.95, 0.96, 0.97, 0.95, 0.96, 0.95, 0.96]},
232
+ ]
233
+
234
+
235
+ def _drone_contact_risk(c: dict, lam_fn) -> tuple[float, list[str], float]:
236
+ """Risk for a demo drone contact via the REAL 13-axis Λ aggregate."""
237
+ lam = round(float(lam_fn(c.get("axis_scores"))), 4)
238
+ fired = list(c.get("fired") or [])
239
+ risk = round(min(0.99, max(0.0, 1.0 - lam)), 3)
240
+ return risk, ["tripwire:" + t for t in fired], lam
241
+
242
+
243
+ # ---------------------------------------------------------------------------
244
+ # Track assembly — build the honest, labeled track list. ALL demo data.
245
+ # ---------------------------------------------------------------------------
246
+ def _build_tracks() -> list[dict]:
247
+ _, _, lam_fn, _ = _drone_sigs()
248
+ tracks: list[dict] = []
249
+
250
+ # Vessels (REPLAY — AIS replay sample dataset).
251
+ for v in _AIS_REPLAY_SAMPLE:
252
+ risk, flags = _vessel_risk(v)
253
+ tracks.append({
254
+ "id": "vessel:" + str(v.get("mmsi")),
255
+ "type": "vessel",
256
+ "name": v.get("name"),
257
+ "position": {"lat": v.get("lat"), "lng": v.get("lng")},
258
+ "kinematics": {"speed_knots": v.get("speed"), "heading_deg": v.get("heading")},
259
+ "mmsi": v.get("mmsi"), "flag": v.get("flag"), "observed_at": v.get("ts"),
260
+ "risk": risk, "risk_flags": flags,
261
+ "data_kind": "REPLAY",
262
+ "source": "warhacker-demo UDS demo_ais_replay.sh sample AIS dataset (NOT a live AIS receiver)",
263
+ })
264
+
265
+ # Space objects (MODELED — orbital roadmap; SZL has NO on-orbit sensor).
266
+ for o in _ORBITAL_MODELED:
267
+ risk, flags = _space_risk(o)
268
+ tracks.append({
269
+ "id": "space:" + str(o.get("obj_id")),
270
+ "type": "space-object",
271
+ "name": o.get("obj_id"),
272
+ "position": {"tier": o.get("tier"), "alt_km": o.get("alt_km"), "inc_deg": o.get("inc_deg")},
273
+ "kind": o.get("kind"), "conjunction_pc": o.get("conjunction_pc"),
274
+ "risk": risk, "risk_flags": flags,
275
+ "data_kind": "MODELED",
276
+ "source": "a11oy_orbital_page MODELED constellation (MODELED roadmap — no on-orbit hardware)",
277
+ })
278
+
279
+ # Drone contacts (SAMPLE — counter-UAS demo, scored by REAL counter-UAS drone-cyber Λ logic).
280
+ for c in _DRONE_CONTACTS:
281
+ risk, flags, lam = _drone_contact_risk(c, lam_fn)
282
+ tracks.append({
283
+ "id": "drone:" + str(c.get("contact_id")),
284
+ "type": "drone",
285
+ "name": c.get("contact_id"),
286
+ "position": {"frame": "relative", "note": "demo contact — no live RF/radar geolocation"},
287
+ "model": c.get("model"), "side": c.get("side"),
288
+ "fired_tripwires": list(c.get("fired") or []),
289
+ "lambda_aggregate": lam, "lambda_floor": _LAMBDA_FLOOR,
290
+ "risk": risk, "risk_flags": flags,
291
+ "data_kind": "SAMPLE",
292
+ "source": "counter-UAS demo contacts scored by the REAL counter-UAS drone-cyber organ (T11-T20 model) (NOT a live sensor feed)",
293
+ })
294
+ return tracks
295
+
296
+
297
+ # ---------------------------------------------------------------------------
298
+ # Process-local verdict stats (reset on restart; honest — empty = IDLE).
299
+ # ---------------------------------------------------------------------------
300
+ _STATS_LOCK = threading.Lock()
301
+ _STATS: dict[str, Any] = {"verdicts": 0, "deny": 0, "allow": 0, "last_receipt_digest": ""}
302
+
303
+
304
+ # ---------------------------------------------------------------------------
305
+ # Counter-UAS verdict — REUSE the REAL counter-UAS drone-cyber 13-axis Λ logic (NOT re-weakened).
306
+ # Effector SIMULATED, human-on-loop. Signs a Khipu receipt into the SHARED chain.
307
+ # ---------------------------------------------------------------------------
308
+ def _build_verdict(body: dict) -> dict:
309
+ import szl_khipu
310
+
311
+ body = body or {}
312
+ track = body.get("track") if isinstance(body.get("track"), dict) else None
313
+ contact = track or body # accept {"track":{...}} or a bare contact
314
+ rid = body.get("request_id") or body.get("actionId") or contact.get("id") or "unspecified"
315
+ operator = body.get("operator") or body.get("agent") or "unknown"
316
+
317
+ drone_sigs, base_sigs, lam_fn, sentra_source = _drone_sigs()
318
+ tw_index = _tripwire_index(drone_sigs)
319
+
320
+ ctype = (contact.get("type") or "drone").lower()
321
+ fired = list(contact.get("fired") or contact.get("fired_tripwires") or [])
322
+ axis = contact.get("axis_scores")
323
+
324
+ # If no axis vector is supplied, derive a conservative one from the declared
325
+ # risk (higher risk -> lower clean-axes), so a bare {"risk":0.9} still gets a
326
+ # principled Λ. This does NOT relax the floor — only fills the axis vector.
327
+ if not axis:
328
+ r = contact.get("risk")
329
+ if r is None:
330
+ r = 0.5
331
+ clean = max(1e-9, min(1.0, 1.0 - float(r)))
332
+ axis = [clean] * 13
333
+ axis_provenance = "derived-from-declared-risk"
334
+ else:
335
+ axis_provenance = "caller-supplied-13-axis"
336
+
337
+ # REAL counter-UAS drone-cyber aggregate (geometric mean of 13 axes). NOT re-weakened.
338
+ lam = round(float(lam_fn(axis)), 4)
339
+
340
+ # Map any fired tripwires to the REAL signature descriptors.
341
+ matched_sigs = []
342
+ for t in fired:
343
+ sig = tw_index.get(t)
344
+ if sig:
345
+ matched_sigs.append({"tripwire": t, "sig_id": sig.get("sig_id"),
346
+ "name": sig.get("name"), "class": sig.get("class")})
347
+
348
+ # Decision: clear iff Λ >= floor 0.90 AND no fired tripwire of class
349
+ # tamper/intrusion (counter-UAS posture; anomalies alone don't deny but
350
+ # raise to review). Fail-closed.
351
+ hard_classes = {s["class"] for s in matched_sigs if s.get("class") in ("tamper", "intrusion")}
352
+ lambda_cleared = lam >= _LAMBDA_FLOOR
353
+ if not lambda_cleared or hard_classes:
354
+ verdict = "THREAT"
355
+ if not lambda_cleared and hard_classes:
356
+ reason = ("counter-UAS THREAT: 13-axis Λ=%.4f below floor %.2f AND hard tripwire(s) %s"
357
+ % (lam, _LAMBDA_FLOOR, sorted(hard_classes)))
358
+ elif not lambda_cleared:
359
+ reason = "counter-UAS THREAT: 13-axis Λ=%.4f below floor %.2f" % (lam, _LAMBDA_FLOOR)
360
+ else:
361
+ reason = "counter-UAS THREAT: hard tripwire(s) fired %s" % sorted(hard_classes)
362
+ elif any(s.get("class") == "anomaly" for s in matched_sigs):
363
+ verdict = "REVIEW"
364
+ reason = "counter-UAS REVIEW: anomaly tripwire(s) fired; Λ above floor — human-on-loop adjudication"
365
+ else:
366
+ verdict = "CLEAR"
367
+ reason = "counter-UAS CLEAR: 13-axis Λ=%.4f at/above floor %.2f; no hard tripwire" % (lam, _LAMBDA_FLOOR)
368
+
369
+ vh = hashlib.sha256(
370
+ (str(rid) + ":" + verdict + ":" + str(lam) + ":" + str(time.time())).encode()
371
+ ).hexdigest()[:16]
372
+
373
+ # Sign a Khipu receipt into the SHARED SDA chain (tamper-evident).
374
+ dag = szl_khipu.get_dag(_KHIPU_ORGAN, ns="a11oy")
375
+ receipt_payload = {
376
+ "receipt_type": _RECEIPT_TYPE,
377
+ "organ": _KHIPU_ORGAN,
378
+ "actionId": rid,
379
+ "operator": operator,
380
+ "contact_type": ctype,
381
+ "verdict": verdict,
382
+ "reason": reason,
383
+ "lambda_aggregate": lam,
384
+ "lambda_floor": _LAMBDA_FLOOR,
385
+ "fired_tripwires": fired,
386
+ "matched_signatures": matched_sigs,
387
+ "axis_provenance": axis_provenance,
388
+ "verdict_hash": vh,
389
+ "effectors": "SIMULATED — human-on-loop; assessment only, NOT a kinetic or jamming action",
390
+ "counter_uas_logic_source": sentra_source,
391
+ "honesty": {
392
+ "tracks_are": "REPLAY/SAMPLE/MODELED demo data — NOT a live radar/AIS/RF sensor feed",
393
+ "lambda": "Conjecture 1 (NOT a theorem)",
394
+ "khipu": "Conjecture 2",
395
+ "trust_ceiling": "never 100%",
396
+ "effectors": "SIMULATED human-on-loop",
397
+ "fabricated_data": False,
398
+ },
399
+ "locked_proven": _LOCKED_PROVEN,
400
+ "kernel": _KERNEL_COMMIT,
401
+ "doctrine": "v11",
402
+ }
403
+ receipt = dag.emit("sda.verdict", receipt_payload)
404
+
405
+ with _STATS_LOCK:
406
+ _STATS["verdicts"] += 1
407
+ if verdict == "CLEAR":
408
+ _STATS["allow"] += 1
409
+ else:
410
+ _STATS["deny"] += 1
411
+ _STATS["last_receipt_digest"] = receipt["digest"]
412
+
413
+ return {
414
+ "verdict": verdict,
415
+ "reason": reason,
416
+ "contact_type": ctype,
417
+ "lambda_aggregate": lam,
418
+ "lambda_floor": _LAMBDA_FLOOR,
419
+ "fired_tripwires": fired,
420
+ "matched_signatures": matched_sigs,
421
+ "axis_provenance": axis_provenance,
422
+ "verdict_hash": vh,
423
+ "actionId": rid,
424
+ "organ": _ORGAN_NAME,
425
+ "effectors": "SIMULATED — human-on-loop; assessment only, NOT a kinetic or jamming action",
426
+ "counter_uas_logic_source": sentra_source,
427
+ "khipu_receipt": {
428
+ "receipt_type": _RECEIPT_TYPE,
429
+ "organ": _KHIPU_ORGAN,
430
+ "ns": "a11oy",
431
+ "seq": receipt["seq"],
432
+ "digest": receipt["digest"],
433
+ "prev": receipt["prev"],
434
+ "payload_digest": receipt["payload_digest"],
435
+ "signature": receipt.get("signature"),
436
+ "chain_verified": receipt.get("chain_verified"),
437
+ },
438
+ "honesty": receipt_payload["honesty"],
439
+ "doctrine": "v11",
440
+ }
441
+
442
+
443
+ # ---------------------------------------------------------------------------
444
+ # Read surfaces — honest summaries.
445
+ # ---------------------------------------------------------------------------
446
+ def _gov(payload: dict, status: str = "REAL", **extra) -> dict:
447
+ """Governed envelope — byte-compatible with serve.py's gov_envelope contract
448
+ ({status, citations, fetchedAt, doctrine}). Reproduced inline so this module
449
+ never imports the heavy serve module at request time."""
450
+ out = dict(payload)
451
+ st = str(status or "REAL").upper()
452
+ if st not in ("REAL", "DEMO", "DEGRADED"):
453
+ st = "DEGRADED"
454
+ out["status"] = st
455
+ if out.get("citations") is None:
456
+ out["citations"] = []
457
+ out["fetchedAt"] = datetime.datetime.now(datetime.timezone.utc).isoformat()
458
+ out["doctrine"] = "v11"
459
+ for k, v in extra.items():
460
+ out[k] = v
461
+ return out
462
+
463
+
464
+ def _healthz() -> dict:
465
+ _, _, _, sentra_source = _drone_sigs()
466
+ return {
467
+ "ok": True,
468
+ "service": "a11oy.sda",
469
+ "organ": _ORGAN_NAME,
470
+ "counter_uas_logic": sentra_source,
471
+ "data_source": "REPLAY/SAMPLE/MODELED demo data — NOT a live radar/AIS/RF sensor feed",
472
+ "effectors": "SIMULATED — human-on-loop",
473
+ "doctrine": "v11",
474
+ }
475
+
476
+
477
+ def _status() -> dict:
478
+ import szl_khipu
479
+ drone_sigs, base_sigs, _, sentra_source = _drone_sigs()
480
+ tracks = _build_tracks()
481
+ by_type: dict[str, int] = {}
482
+ by_kind: dict[str, int] = {}
483
+ for t in tracks:
484
+ by_type[t["type"]] = by_type.get(t["type"], 0) + 1
485
+ by_kind[t["data_kind"]] = by_kind.get(t["data_kind"], 0) + 1
486
+ dag = szl_khipu.get_dag(_KHIPU_ORGAN, ns="a11oy")
487
+ with _STATS_LOCK:
488
+ verdicts = _STATS["verdicts"]
489
+ deny = _STATS["deny"]
490
+ allow = _STATS["allow"]
491
+ last_digest = _STATS["last_receipt_digest"]
492
+ payload = {
493
+ "organ": _ORGAN_NAME,
494
+ "summary": "Space / Domain Awareness — honest demo over vessel (AIS replay), drone (counter-UAS), and space-object (modeled orbital) contacts.",
495
+ "track_count": len(tracks),
496
+ "tracks_by_type": by_type,
497
+ "tracks_by_data_kind": by_kind,
498
+ "data_source": "REPLAY/SAMPLE/MODELED — NOT live",
499
+ "data_source_detail": {
500
+ "vessel": "REPLAY — warhacker-demo UDS demo_ais_replay.sh sample AIS dataset (no live AIS receiver)",
501
+ "drone": "SAMPLE — counter-UAS demo contacts scored by the REAL counter-UAS drone-cyber organ (T11-T20 model) (no live RF/radar)",
502
+ "space-object": "MODELED — orbital-compute roadmap objects (no on-orbit sensor / hardware)",
503
+ },
504
+ "counter_uas": {
505
+ "logic_source": sentra_source,
506
+ "drone_signature_count": len(drone_sigs),
507
+ "base_signature_count": len(base_sigs),
508
+ "lambda_floor": _LAMBDA_FLOOR,
509
+ "lambda_model": "13-axis yuyay_v3 geometric-mean aggregate (REAL counter-UAS drone-cyber logic)",
510
+ },
511
+ "verdicts_this_process": verdicts,
512
+ "verdict_breakdown": {"clear": allow, "threat_or_review": deny},
513
+ "effectors": "SIMULATED — human-on-loop; assessments + signed receipts only, NEVER kinetic/jamming",
514
+ "khipu": {
515
+ "organ": _KHIPU_ORGAN, "ns": "a11oy",
516
+ "chain_head": dag.head(), "chain_depth": dag.depth(),
517
+ "last_verdict_receipt_digest": last_digest,
518
+ "kind": "Conjecture 2", "signature": "DSSE_PLACEHOLDER",
519
+ },
520
+ "doctrine_block": {
521
+ "version": "v11",
522
+ "lambda": "Conjecture 1 (NOT a theorem)",
523
+ "khipu": "Conjecture 2",
524
+ "trust_ceiling": "never 100%",
525
+ "locked_proven": _LOCKED_PROVEN,
526
+ "locked_count": len(_LOCKED_PROVEN),
527
+ "kernel": _KERNEL_COMMIT,
528
+ "slsa": "L1 honest / L2 / L3 roadmap",
529
+ "effectors": "SIMULATED",
530
+ "runtime_cdn": 0,
531
+ "honest_label": "tracks REPLAY/SAMPLE/MODELED — not a live sensor feed",
532
+ },
533
+ "citations": [
534
+ {"label": "warhacker-demo UDS demo_ais_replay.sh", "ref": "docs/vessels/du-upstream-contributions/uds-package-vessels/scripts/demo_ais_replay.sh"},
535
+ {"label": "counter-UAS drone-cyber organ", "ref": "organs/sentra/sentra_drone_cyber.py"},
536
+ {"label": "MODELED orbital constellation", "ref": "a11oy_orbital_page.py"},
537
+ ],
538
+ }
539
+ return _gov(payload, status="REAL")
540
+
541
+
542
+ def _tracks(type_filter: Optional[str] = None) -> dict:
543
+ tracks = _build_tracks()
544
+ if type_filter:
545
+ tf = type_filter.strip().lower()
546
+ tracks = [t for t in tracks if t["type"] == tf]
547
+ payload = {
548
+ "organ": _ORGAN_NAME,
549
+ "count": len(tracks),
550
+ "tracks": tracks,
551
+ "data_source": "REPLAY/SAMPLE/MODELED — NOT a live radar/AIS/RF sensor feed",
552
+ "honesty": ("These are DEMO tracks: vessels are the warhacker-demo AIS REPLAY dataset, "
553
+ "drone contacts are SAMPLE counter-UAS demo contacts scored by the REAL "
554
+ "counter-UAS drone-cyber organ, space objects are MODELED orbital-roadmap objects. SZL does "
555
+ "NOT operate the radar/AIS receiver/on-orbit sensor behind these."),
556
+ "citations": [
557
+ {"label": "demo_ais_replay.sh", "ref": "docs/vessels/du-upstream-contributions/uds-package-vessels/scripts/demo_ais_replay.sh"},
558
+ ],
559
+ }
560
+ return _gov(payload, status="REAL")
561
+
562
+
563
+ def _verify_chain() -> dict:
564
+ import szl_khipu
565
+ dag = szl_khipu.get_dag(_KHIPU_ORGAN, ns="a11oy")
566
+ v = dag.verify_chain()
567
+ payload = {
568
+ "organ": _ORGAN_NAME,
569
+ "khipu_verify": v,
570
+ "chain_head": dag.head(),
571
+ "chain_depth": dag.depth(),
572
+ "khipu_kind": "Conjecture 2",
573
+ "signature": "DSSE_PLACEHOLDER",
574
+ }
575
+ return _gov(payload, status="REAL")
576
+
577
+
578
+ # ---------------------------------------------------------------------------
579
+ # Registration — dual-register under /api/{ns}/v1/sda/* AND /v1/sda/*.
580
+ # Mirrors szl_immune's add_api_route pattern. Registered BEFORE the SPA catch-all
581
+ # so these JSON routes resolve LOCALLY and win ordering.
582
+ # ---------------------------------------------------------------------------
583
+ def register(app, ns: str = "a11oy") -> dict:
584
+ async def _h_healthz(): # noqa: ANN202
585
+ return JSONResponse(_healthz())
586
+
587
+ async def _h_status(): # noqa: ANN202
588
+ return JSONResponse(_status())
589
+
590
+ async def _h_tracks(request: Request): # noqa: ANN202
591
+ tf = request.query_params.get("type")
592
+ return JSONResponse(_tracks(tf))
593
+
594
+ async def _h_verdict(request: Request): # noqa: ANN202
595
+ try:
596
+ body = await request.json()
597
+ except Exception: # noqa: BLE001
598
+ body = {}
599
+ if not isinstance(body, dict):
600
+ body = {"track": body}
601
+ verdict = _build_verdict(body)
602
+ return JSONResponse(verdict, headers={"x-szl-sda-verdict": verdict["verdict"]})
603
+
604
+ async def _h_verify(): # noqa: ANN202
605
+ return JSONResponse(_verify_chain())
606
+
607
+ prefixes = [f"/api/{ns}/v1/sda", "/v1/sda"]
608
+ routes: list[str] = []
609
+ for p in prefixes:
610
+ app.add_api_route(f"{p}/healthz", _h_healthz, methods=["GET"], include_in_schema=True)
611
+ app.add_api_route(f"{p}/status", _h_status, methods=["GET"], include_in_schema=True)
612
+ app.add_api_route(f"{p}/tracks", _h_tracks, methods=["GET"], include_in_schema=True)
613
+ app.add_api_route(f"{p}/verdict", _h_verdict, methods=["POST", "GET"], include_in_schema=True)
614
+ app.add_api_route(f"{p}/verify", _h_verify, methods=["GET"], include_in_schema=True)
615
+ routes.extend([f"{p}/healthz", f"{p}/status", f"{p}/tracks", f"{p}/verdict", f"{p}/verify"])
616
+
617
+ print(f"[{ns}] szl_sda routes registered "
618
+ f"(SDA — Space/Domain Awareness counter-UAS, REPLAY/SAMPLE/MODELED demo data, {len(routes)} routes)",
619
+ flush=True)
620
+ return {"ok": True, "ns": ns, "organ": _ORGAN_NAME, "routes": routes}
621
+
622
+
623
+ # ---------------------------------------------------------------------------
624
+ # No-server self-test — proves the REAL logic + chain honesty without HTTP.
625
+ # ---------------------------------------------------------------------------
626
+ def _selftest() -> dict:
627
+ out: dict = {}
628
+
629
+ # Tracks build, labeled honestly.
630
+ ts = _build_tracks()
631
+ assert len(ts) >= 10, ts
632
+ assert all(t["data_kind"] in ("REPLAY", "SAMPLE", "MODELED") for t in ts), ts
633
+ assert {t["type"] for t in ts} >= {"vessel", "drone", "space-object"}, ts
634
+ out["tracks"] = len(ts)
635
+
636
+ # Hostile drone (low axes) -> THREAT + signed receipt.
637
+ v = _build_verdict({"track": {"type": "drone", "fired": ["T16", "T20"],
638
+ "axis_scores": [0.4] * 13}, "request_id": "t1"})
639
+ assert v["verdict"] == "THREAT", v
640
+ assert v["khipu_receipt"]["digest"], v
641
+ out["threat"] = True
642
+
643
+ # Bare {"type":"drone","risk":0.9} -> derives axes, THREAT.
644
+ v = _build_verdict({"track": {"type": "drone", "risk": 0.9}, "request_id": "t2"})
645
+ assert v["verdict"] in ("THREAT", "REVIEW"), v
646
+ out["bare_risk"] = v["verdict"]
647
+
648
+ # Clean allied drone -> CLEAR.
649
+ v = _build_verdict({"track": {"type": "drone", "fired": [],
650
+ "axis_scores": [0.96] * 13}, "request_id": "t3"})
651
+ assert v["verdict"] == "CLEAR", v
652
+ out["clear"] = True
653
+
654
+ # Chain verifies.
655
+ import szl_khipu
656
+ dag = szl_khipu.get_dag(_KHIPU_ORGAN, ns="a11oy")
657
+ assert dag.verify_chain()["ok"], dag.verify_chain()
658
+ out["chain_ok"] = True
659
+ out["chain_depth"] = dag.depth()
660
+ return out
661
+
662
+
663
+ if __name__ == "__main__":
664
+ print(json.dumps(_selftest(), indent=2))