Release v2.8.0: Authentic 2x2 homepage UI closeups and zero-synthetic-data market research & zero-PII telemetry suite (Strategies 1A/1B/2A/2B/2C/3A/3B/4B/4C/5A/5B)
This commit is contained in:
1 parent
6aeaf4bc6f
commit
50efacaba5
49 files changed
+748
-188
No files matched your search
@@ -1,3 +1,3 @@
|
||||
"""hyperstitionstud_io — Shared Common Library for the hyperstitionstud.io workspace (v2.7.0)."""
|
||||
__version__ = "2.7.0"
|
||||
"""hyperstitionstud_io — Shared Common Library for the hyperstitionstud.io workspace (v2.8.0)."""
|
||||
__version__ = "2.8.0"
|
||||
NAMESPACE_URN = "urn:io:hyperstitionstud"
|
||||
@@ -177,6 +177,8 @@ CREATE TABLE IF NOT EXISTS api_endpoint_rollups (
|
||||
method TEXT NOT NULL,
|
||||
endpoint_pattern TEXT NOT NULL,
|
||||
total_requests INTEGER NOT NULL DEFAULT 0,
|
||||
external_requests INTEGER NOT NULL DEFAULT 0,
|
||||
internal_requests INTEGER NOT NULL DEFAULT 0,
|
||||
status_2xx INTEGER NOT NULL DEFAULT 0,
|
||||
status_304 INTEGER NOT NULL DEFAULT 0,
|
||||
status_4xx INTEGER NOT NULL DEFAULT 0,
|
||||
@@ -193,7 +195,8 @@ CREATE TABLE IF NOT EXISTS api_audit_ringbuffer (
|
||||
endpoint TEXT NOT NULL,
|
||||
status_code INTEGER NOT NULL,
|
||||
latency_us INTEGER NOT NULL,
|
||||
isolation_ok INTEGER NOT NULL
|
||||
isolation_ok INTEGER NOT NULL,
|
||||
traffic_source TEXT NOT NULL DEFAULT 'internal_test'
|
||||
);
|
||||
|
||||
CREATE TRIGGER IF NOT EXISTS trg_prune_audit_ringbuffer
|
||||
@@ -202,8 +205,68 @@ BEGIN
|
||||
DELETE FROM api_audit_ringbuffer
|
||||
WHERE event_id <= (NEW.event_id - 200);
|
||||
END;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS api_parameter_rollups (
|
||||
param_category TEXT NOT NULL,
|
||||
param_value TEXT NOT NULL,
|
||||
total_requests INTEGER NOT NULL DEFAULT 0,
|
||||
external_requests INTEGER NOT NULL DEFAULT 0,
|
||||
internal_requests INTEGER NOT NULL DEFAULT 0,
|
||||
last_called_utc TEXT NOT NULL,
|
||||
PRIMARY KEY (param_category, param_value)
|
||||
) WITHOUT ROWID;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS static_route_rollups (
|
||||
route_prefix TEXT PRIMARY KEY,
|
||||
total_hits INTEGER NOT NULL DEFAULT 0,
|
||||
last_ingested_utc TEXT NOT NULL
|
||||
) WITHOUT ROWID;
|
||||
"""
|
||||
|
||||
ALLOWED_TELEMETRY_PARAM_ENUMS: dict[str, set[str]] = {
|
||||
"symbol": {
|
||||
"NVDA", "TSM", "ASML", "MSFT", "GOOGL", "META", "AMZN", "AAPL",
|
||||
"PLTR", "AMD", "ARM", "AVGO", "ORCL", "TSLA", "COIN", "MSTR",
|
||||
"IBIT", "BTC-USD", "ETH-USD", "SOL-USD", "SPY", "QQQ", "VIX", "ANTHR-PVT",
|
||||
},
|
||||
"lens": {
|
||||
"tierzoo", "pokedex_scanner", "corporate_board",
|
||||
"fund_manager", "fantasy_football", "schizoanalytic",
|
||||
},
|
||||
"lang": {"guile", "ts", "rust"},
|
||||
"unit_filter": {"E0", "E1", "E2", "E3", "E4", "E5", "M0", "M1", "M2", "M3", "M4", "M5"},
|
||||
"surface": {"home", "calc", "quant", "graph", "learn", "engineering", "math", "donate"},
|
||||
"donate_from": {"home", "calc", "quant", "graph", "learn", "engineering", "math"},
|
||||
"donate_copy": {"BTC", "XMR"},
|
||||
"export_action": {
|
||||
"learn_state_json", "quant_csv", "quant_json", "quant_tradingview", "graph_png",
|
||||
},
|
||||
}
|
||||
|
||||
CANONICAL_STATIC_ROUTE_PREFIXES: tuple[str, ...] = (
|
||||
"/zoology/proposal-fund-manager-novel-investment-discovery.pdf",
|
||||
"/zoology/proposal-corporate-board-technocapital-allocation.pdf",
|
||||
"/zoology/proposal-fantasy-football-technocapital-roster-engine.pdf",
|
||||
"/zoology/proposal-fund-manager-standard-english-aq.pdf",
|
||||
"/zoology/proposal-corporate-board-standard-english-aq.pdf",
|
||||
"/zoology/m7-emergent-subclass-bidirectional-aq-nucleation.pdf",
|
||||
"/zoology/tier-list-technocapital-assemblage-builds.pdf",
|
||||
"/zoology/tier-list-technocapital-assemblage-builds.png",
|
||||
"/zoology/technocapital-singularity-zoology-comprehensive-glossary.pdf",
|
||||
"/zoology/encyclopedia-of-technocapital-singularity-zoology-overview-and-manifest.pdf",
|
||||
"/encyclopedia/",
|
||||
"/calc/",
|
||||
"/quant/",
|
||||
"/graph/",
|
||||
"/learn/",
|
||||
"/engineering/",
|
||||
"/math/",
|
||||
"/donate/",
|
||||
"/archive/",
|
||||
"/ci/",
|
||||
"/",
|
||||
)
|
||||
|
||||
|
||||
def get_default_catalog_db_path() -> Path:
|
||||
env_p = os.environ.get("HYPERSTITION_CATALOG_DB_PATH")
|
||||
@@ -919,6 +982,8 @@ def truncate_telemetry_db_quiescent(
|
||||
try:
|
||||
conn.execute("DELETE FROM api_audit_ringbuffer;")
|
||||
conn.execute("DELETE FROM api_endpoint_rollups;")
|
||||
conn.execute("DELETE FROM api_parameter_rollups;")
|
||||
conn.execute("DELETE FROM static_route_rollups;")
|
||||
conn.execute("DELETE FROM sqlite_sequence WHERE name = 'api_audit_ringbuffer';")
|
||||
conn.execute("COMMIT;")
|
||||
except Exception:
|
||||
@@ -948,6 +1013,22 @@ def truncate_telemetry_db_quiescent(
|
||||
}
|
||||
|
||||
|
||||
def _ensure_telemetry_columns(conn: sqlite3.Connection) -> None:
|
||||
"""
|
||||
Idempotently migrate existing `api_endpoint_rollups` and `api_audit_ringbuffer` tables
|
||||
so older databases gain `external_requests`, `internal_requests`, and `traffic_source`.
|
||||
"""
|
||||
rollup_cols = {r[1] for r in conn.execute("PRAGMA table_info(api_endpoint_rollups)").fetchall()}
|
||||
if "external_requests" not in rollup_cols:
|
||||
conn.execute("ALTER TABLE api_endpoint_rollups ADD COLUMN external_requests INTEGER NOT NULL DEFAULT 0;")
|
||||
if "internal_requests" not in rollup_cols:
|
||||
conn.execute("ALTER TABLE api_endpoint_rollups ADD COLUMN internal_requests INTEGER NOT NULL DEFAULT 0;")
|
||||
conn.execute("UPDATE api_endpoint_rollups SET internal_requests = total_requests WHERE external_requests = 0 AND internal_requests = 0;")
|
||||
rb_cols = {r[1] for r in conn.execute("PRAGMA table_info(api_audit_ringbuffer)").fetchall()}
|
||||
if "traffic_source" not in rb_cols:
|
||||
conn.execute("ALTER TABLE api_audit_ringbuffer ADD COLUMN traffic_source TEXT NOT NULL DEFAULT 'internal_test';")
|
||||
|
||||
|
||||
def record_api_telemetry(
|
||||
protocol: str,
|
||||
method: str,
|
||||
@@ -957,10 +1038,14 @@ def record_api_telemetry(
|
||||
isolation_ok: bool = True,
|
||||
telemetry_db_path: Path | str | None = None,
|
||||
max_bytes: int | str | None = None,
|
||||
traffic_source: str = "internal_test",
|
||||
param_events: dict[str, str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Record a privacy-preserving REST (`/api/v1/*`) or MCP (`/mcp`) call in `api-telemetry.db`,
|
||||
and automatically perform a quiescent truncation if the database reaches `max_bytes` (default `100 MB`).
|
||||
separating `external_production` traffic from `internal_test` probes, recording allowlisted
|
||||
closed-set enum parameters in `api_parameter_rollups` (`Strategy 2B`), and automatically
|
||||
performing a quiescent truncation if the database reaches `max_bytes` (default `100 MB`).
|
||||
"""
|
||||
t_path = Path(telemetry_db_path) if telemetry_db_path is not None else get_default_telemetry_db_path()
|
||||
limit_bytes = parse_size_spec_bytes(max_bytes, default_bytes=DEFAULT_MAX_TELEMETRY_BYTES)
|
||||
@@ -969,11 +1054,32 @@ def record_api_telemetry(
|
||||
lat = max(0, int(latency_us))
|
||||
iso_int = 1 if isolation_ok else 0
|
||||
|
||||
src_norm = "external_production" if traffic_source == "external_production" else "internal_test"
|
||||
ext_inc = 1 if src_norm == "external_production" else 0
|
||||
int_inc = 1 if src_norm == "internal_test" else 0
|
||||
|
||||
s_2xx = 1 if 200 <= code < 300 else 0
|
||||
s_304 = 1 if code == 304 else 0
|
||||
s_4xx = 1 if 400 <= code < 500 else 0
|
||||
s_5xx = 1 if code >= 500 else 0
|
||||
|
||||
valid_params: list[tuple[str, str]] = []
|
||||
if param_events:
|
||||
for raw_cat, raw_val in param_events.items():
|
||||
if not raw_val:
|
||||
continue
|
||||
cat = str(raw_cat).strip()
|
||||
allowed_set = ALLOWED_TELEMETRY_PARAM_ENUMS.get(cat)
|
||||
if not allowed_set:
|
||||
continue
|
||||
val_cand = str(raw_val).strip()
|
||||
if cat in ("symbol", "unit_filter", "donate_copy"):
|
||||
val_cand = val_cand.upper()
|
||||
else:
|
||||
val_cand = val_cand.lower()
|
||||
if val_cand in allowed_set:
|
||||
valid_params.append((cat, val_cand))
|
||||
|
||||
try:
|
||||
t_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if _sqlite_total_disk_bytes(t_path) >= limit_bytes:
|
||||
@@ -983,34 +1089,53 @@ def record_api_telemetry(
|
||||
try:
|
||||
conn.execute("PRAGMA busy_timeout = 30000;")
|
||||
conn.executescript(TELEMETRY_SCHEMA_SQL)
|
||||
_ensure_telemetry_columns(conn)
|
||||
conn.execute("BEGIN IMMEDIATE;")
|
||||
try:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO api_endpoint_rollups (
|
||||
protocol, method, endpoint_pattern, total_requests,
|
||||
external_requests, internal_requests,
|
||||
status_2xx, status_304, status_4xx, status_5xx,
|
||||
total_latency_us, max_latency_us, last_called_utc
|
||||
) VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?)
|
||||
) VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(protocol, method, endpoint_pattern) DO UPDATE SET
|
||||
total_requests = total_requests + 1,
|
||||
status_2xx = status_2xx + excluded.status_2xx,
|
||||
status_304 = status_304 + excluded.status_304,
|
||||
status_4xx = status_4xx + excluded.status_4xx,
|
||||
status_5xx = status_5xx + excluded.status_5xx,
|
||||
total_latency_us = total_latency_us + excluded.total_latency_us,
|
||||
max_latency_us = MAX(max_latency_us, excluded.max_latency_us),
|
||||
last_called_utc = excluded.last_called_utc
|
||||
total_requests = total_requests + 1,
|
||||
external_requests = external_requests + excluded.external_requests,
|
||||
internal_requests = internal_requests + excluded.internal_requests,
|
||||
status_2xx = status_2xx + excluded.status_2xx,
|
||||
status_304 = status_304 + excluded.status_304,
|
||||
status_4xx = status_4xx + excluded.status_4xx,
|
||||
status_5xx = status_5xx + excluded.status_5xx,
|
||||
total_latency_us = total_latency_us + excluded.total_latency_us,
|
||||
max_latency_us = MAX(max_latency_us, excluded.max_latency_us),
|
||||
last_called_utc = excluded.last_called_utc
|
||||
""",
|
||||
(protocol, method, endpoint_pattern, s_2xx, s_304, s_4xx, s_5xx, lat, lat, now_utc),
|
||||
(protocol, method, endpoint_pattern, ext_inc, int_inc, s_2xx, s_304, s_4xx, s_5xx, lat, lat, now_utc),
|
||||
)
|
||||
for p_cat, p_val in valid_params:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO api_parameter_rollups (
|
||||
param_category, param_value, total_requests,
|
||||
external_requests, internal_requests, last_called_utc
|
||||
) VALUES (?, ?, 1, ?, ?, ?)
|
||||
ON CONFLICT(param_category, param_value) DO UPDATE SET
|
||||
total_requests = total_requests + 1,
|
||||
external_requests = external_requests + excluded.external_requests,
|
||||
internal_requests = internal_requests + excluded.internal_requests,
|
||||
last_called_utc = excluded.last_called_utc
|
||||
""",
|
||||
(p_cat, p_val, ext_inc, int_inc, now_utc),
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO api_audit_ringbuffer (
|
||||
timestamp_utc, endpoint, status_code, latency_us, isolation_ok
|
||||
) VALUES (?, ?, ?, ?, ?)
|
||||
timestamp_utc, endpoint, status_code, latency_us, isolation_ok, traffic_source
|
||||
) VALUES (?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(now_utc, f"{protocol}:{method} {endpoint_pattern}", code, lat, iso_int),
|
||||
(now_utc, f"{protocol}:{method} {endpoint_pattern}", code, lat, iso_int, src_norm),
|
||||
)
|
||||
conn.execute("COMMIT;")
|
||||
except Exception:
|
||||
@@ -1025,18 +1150,26 @@ def record_api_telemetry(
|
||||
os.chmod(cand, 0o666)
|
||||
except OSError:
|
||||
pass
|
||||
return {"ok": True, "db_path": str(t_path)}
|
||||
return {"ok": True, "db_path": str(t_path), "traffic_source": src_norm}
|
||||
except Exception as exc:
|
||||
return {"ok": False, "error": str(exc)}
|
||||
|
||||
|
||||
MIN_EXTERNAL_REQUESTS_FOR_CONFIDENCE = 500
|
||||
|
||||
|
||||
def get_api_telemetry_summary(telemetry_db_path: Path | str | None = None) -> dict[str, Any]:
|
||||
t_path = Path(telemetry_db_path) if telemetry_db_path is not None else get_default_telemetry_db_path()
|
||||
if not t_path.is_file():
|
||||
return {
|
||||
"db_path": str(t_path),
|
||||
"total_requests": 0,
|
||||
"external_production_requests": 0,
|
||||
"internal_test_requests": 0,
|
||||
"market_demand_confidence": "No data available",
|
||||
"endpoints": [],
|
||||
"parameter_rollups": [],
|
||||
"static_route_rollups": [],
|
||||
"recent_audit_events": [],
|
||||
"ringbuffer_count": 0,
|
||||
"byte_size": 0,
|
||||
@@ -1044,12 +1177,26 @@ def get_api_telemetry_summary(telemetry_db_path: Path | str | None = None) -> di
|
||||
conn = sqlite3.connect(str(t_path), timeout=30.0)
|
||||
conn.row_factory = sqlite3.Row
|
||||
try:
|
||||
conn.executescript(TELEMETRY_SCHEMA_SQL)
|
||||
_ensure_telemetry_columns(conn)
|
||||
rollups = [
|
||||
dict(r)
|
||||
for r in conn.execute(
|
||||
"SELECT * FROM api_endpoint_rollups ORDER BY total_requests DESC, endpoint_pattern ASC"
|
||||
).fetchall()
|
||||
]
|
||||
param_rollups = [
|
||||
dict(r)
|
||||
for r in conn.execute(
|
||||
"SELECT * FROM api_parameter_rollups ORDER BY total_requests DESC, param_category ASC, param_value ASC"
|
||||
).fetchall()
|
||||
]
|
||||
static_rollups = [
|
||||
dict(r)
|
||||
for r in conn.execute(
|
||||
"SELECT * FROM static_route_rollups ORDER BY total_hits DESC, route_prefix ASC"
|
||||
).fetchall()
|
||||
]
|
||||
recent = [
|
||||
dict(r)
|
||||
for r in conn.execute(
|
||||
@@ -1058,10 +1205,21 @@ def get_api_telemetry_summary(telemetry_db_path: Path | str | None = None) -> di
|
||||
]
|
||||
rb_cnt = conn.execute("SELECT COUNT(*) FROM api_audit_ringbuffer").fetchone()[0]
|
||||
tot_reqs = sum(int(r["total_requests"]) for r in rollups)
|
||||
ext_reqs = sum(int(r.get("external_requests", 0)) for r in rollups)
|
||||
int_reqs = sum(int(r.get("internal_requests", 0)) for r in rollups)
|
||||
if ext_reqs < MIN_EXTERNAL_REQUESTS_FOR_CONFIDENCE:
|
||||
confidence_status = "No data available"
|
||||
else:
|
||||
confidence_status = f"Sufficient external production sample (n={ext_reqs})"
|
||||
return {
|
||||
"db_path": str(t_path),
|
||||
"total_requests": tot_reqs,
|
||||
"external_production_requests": ext_reqs,
|
||||
"internal_test_requests": int_reqs,
|
||||
"market_demand_confidence": confidence_status,
|
||||
"endpoints": rollups,
|
||||
"parameter_rollups": param_rollups,
|
||||
"static_route_rollups": static_rollups,
|
||||
"recent_audit_events": recent,
|
||||
"ringbuffer_count": int(rb_cnt),
|
||||
"byte_size": _sqlite_total_disk_bytes(t_path),
|
||||
@@ -1070,6 +1228,179 @@ def get_api_telemetry_summary(telemetry_db_path: Path | str | None = None) -> di
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_longitudinal_telemetry_summary(
|
||||
telemetry_db_path: Path | str | None = None,
|
||||
max_generations: int = 12,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Aggregate `api_endpoint_rollups`, `api_parameter_rollups`, and `static_route_rollups` across
|
||||
both the active `api-telemetry.db` and up to `max_generations` rotated `.{1..K}.gz` snapshots
|
||||
(`Strategy 2C`: `--telemetry-history`).
|
||||
"""
|
||||
import tempfile
|
||||
|
||||
t_path = Path(telemetry_db_path) if telemetry_db_path is not None else get_default_telemetry_db_path()
|
||||
endpoint_totals: dict[tuple[str, str, str], dict[str, Any]] = {}
|
||||
param_totals: dict[tuple[str, str], dict[str, Any]] = {}
|
||||
static_totals: dict[str, dict[str, Any]] = {}
|
||||
generations_scanned: list[str] = []
|
||||
|
||||
def _merge_summary(s: dict[str, Any], label: str) -> None:
|
||||
generations_scanned.append(label)
|
||||
for ep in s.get("endpoints", []):
|
||||
key = (ep["protocol"], ep["method"], ep["endpoint_pattern"])
|
||||
cur = endpoint_totals.get(key)
|
||||
if cur is None:
|
||||
endpoint_totals[key] = dict(ep)
|
||||
else:
|
||||
for k_num in ("total_requests", "external_requests", "internal_requests", "status_2xx", "status_304", "status_4xx", "status_5xx", "total_latency_us"):
|
||||
cur[k_num] = int(cur.get(k_num, 0)) + int(ep.get(k_num, 0))
|
||||
cur["max_latency_us"] = max(int(cur.get("max_latency_us", 0)), int(ep.get("max_latency_us", 0)))
|
||||
if str(ep.get("last_called_utc", "")) > str(cur.get("last_called_utc", "")):
|
||||
cur["last_called_utc"] = ep["last_called_utc"]
|
||||
for pr in s.get("parameter_rollups", []):
|
||||
pkey = (pr["param_category"], pr["param_value"])
|
||||
cur_p = param_totals.get(pkey)
|
||||
if cur_p is None:
|
||||
param_totals[pkey] = dict(pr)
|
||||
else:
|
||||
for k_num in ("total_requests", "external_requests", "internal_requests"):
|
||||
cur_p[k_num] = int(cur_p.get(k_num, 0)) + int(pr.get(k_num, 0))
|
||||
if str(pr.get("last_called_utc", "")) > str(cur_p.get("last_called_utc", "")):
|
||||
cur_p["last_called_utc"] = pr["last_called_utc"]
|
||||
for sr in s.get("static_route_rollups", []):
|
||||
rpref = sr["route_prefix"]
|
||||
cur_s = static_totals.get(rpref)
|
||||
if cur_s is None:
|
||||
static_totals[rpref] = dict(sr)
|
||||
else:
|
||||
cur_s["total_hits"] = int(cur_s.get("total_hits", 0)) + int(sr.get("total_hits", 0))
|
||||
if str(sr.get("last_ingested_utc", "")) > str(cur_s.get("last_ingested_utc", "")):
|
||||
cur_s["last_ingested_utc"] = sr["last_ingested_utc"]
|
||||
|
||||
if t_path.is_file():
|
||||
_merge_summary(get_api_telemetry_summary(t_path), str(t_path.name))
|
||||
|
||||
for idx in range(1, max_generations + 1):
|
||||
gz_p = Path(f"{t_path}.{idx}.gz")
|
||||
if not gz_p.is_file():
|
||||
continue
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(suffix=".db", delete=True) as tmp_f:
|
||||
with gzip.open(gz_p, "rb") as f_in:
|
||||
tmp_f.write(f_in.read())
|
||||
tmp_f.flush()
|
||||
_merge_summary(get_api_telemetry_summary(tmp_f.name), gz_p.name)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
tot_reqs = sum(int(v.get("total_requests", 0)) for v in endpoint_totals.values())
|
||||
ext_reqs = sum(int(v.get("external_requests", 0)) for v in endpoint_totals.values())
|
||||
int_reqs = sum(int(v.get("internal_requests", 0)) for v in endpoint_totals.values())
|
||||
confidence_status = (
|
||||
"No data available"
|
||||
if ext_reqs < MIN_EXTERNAL_REQUESTS_FOR_CONFIDENCE
|
||||
else f"Sufficient external production sample (n={ext_reqs})"
|
||||
)
|
||||
return {
|
||||
"base_db_path": str(t_path),
|
||||
"generations_scanned": generations_scanned,
|
||||
"generations_count": len(generations_scanned),
|
||||
"total_requests": tot_reqs,
|
||||
"external_production_requests": ext_reqs,
|
||||
"internal_test_requests": int_reqs,
|
||||
"market_demand_confidence": confidence_status,
|
||||
"endpoints": sorted(endpoint_totals.values(), key=lambda x: (-int(x.get("total_requests", 0)), x["endpoint_pattern"])),
|
||||
"parameter_rollups": sorted(param_totals.values(), key=lambda x: (-int(x.get("total_requests", 0)), x["param_category"], x["param_value"])),
|
||||
"static_route_rollups": sorted(static_totals.values(), key=lambda x: (-int(x.get("total_hits", 0)), x["route_prefix"])),
|
||||
}
|
||||
|
||||
|
||||
def ingest_caddy_route_counts(
|
||||
log_path: Path | str = "/var/log/caddy/hyperstition-access.json",
|
||||
telemetry_db_path: Path | str | None = None,
|
||||
truncate_log: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Ingest zero-IP Caddy JSON access log entries (`Strategy 3A`: `--ingest-caddy-route-counts`)
|
||||
into `static_route_rollups` inside `api-telemetry.db`, mapping URIs onto `CANONICAL_STATIC_ROUTE_PREFIXES`
|
||||
and discarding all client identifiers.
|
||||
"""
|
||||
l_path = Path(log_path)
|
||||
t_path = Path(telemetry_db_path) if telemetry_db_path is not None else get_default_telemetry_db_path()
|
||||
now_utc = dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
if not l_path.is_file():
|
||||
return {"ok": True, "log_path": str(l_path), "ingested_lines": 0, "matched_hits": 0, "status": "log_absent"}
|
||||
|
||||
counts_by_prefix: dict[str, int] = {}
|
||||
lines_read = 0
|
||||
for raw_ln in l_path.read_text(encoding="utf-8", errors="replace").splitlines():
|
||||
ln = raw_ln.strip()
|
||||
if not ln:
|
||||
continue
|
||||
lines_read += 1
|
||||
try:
|
||||
obj = json.loads(ln)
|
||||
except Exception:
|
||||
continue
|
||||
status = int(obj.get("status", 0) or 0)
|
||||
if status not in (200, 304):
|
||||
continue
|
||||
req_obj = obj.get("request") or {}
|
||||
uri = str(req_obj.get("uri") or obj.get("uri") or "").split("?", 1)[0]
|
||||
if not uri or uri.startswith("/api/v1") or uri.startswith("/mcp") or uri.startswith("/assets/"):
|
||||
continue
|
||||
for pref in CANONICAL_STATIC_ROUTE_PREFIXES:
|
||||
if pref == "/":
|
||||
if uri in ("/", "/index.html"):
|
||||
counts_by_prefix["/"] = counts_by_prefix.get("/", 0) + 1
|
||||
break
|
||||
elif uri == pref or uri.startswith(pref):
|
||||
counts_by_prefix[pref] = counts_by_prefix.get(pref, 0) + 1
|
||||
break
|
||||
|
||||
if counts_by_prefix:
|
||||
t_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
conn = sqlite3.connect(str(t_path), timeout=30.0, isolation_level=None)
|
||||
try:
|
||||
conn.execute("PRAGMA busy_timeout = 30000;")
|
||||
conn.executescript(TELEMETRY_SCHEMA_SQL)
|
||||
conn.execute("BEGIN IMMEDIATE;")
|
||||
try:
|
||||
for pref, cnt in counts_by_prefix.items():
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO static_route_rollups (route_prefix, total_hits, last_ingested_utc)
|
||||
VALUES (?, ?, ?)
|
||||
ON CONFLICT(route_prefix) DO UPDATE SET
|
||||
total_hits = total_hits + excluded.total_hits,
|
||||
last_ingested_utc = excluded.last_ingested_utc
|
||||
""",
|
||||
(pref, cnt, now_utc),
|
||||
)
|
||||
conn.execute("COMMIT;")
|
||||
except Exception:
|
||||
conn.execute("ROLLBACK;")
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if truncate_log:
|
||||
try:
|
||||
l_path.write_text("", encoding="utf-8")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"log_path": str(l_path),
|
||||
"db_path": str(t_path),
|
||||
"ingested_lines": lines_read,
|
||||
"matched_hits": sum(counts_by_prefix.values()),
|
||||
"counts_by_prefix": counts_by_prefix,
|
||||
}
|
||||
|
||||
|
||||
def run_logrotate_directive(
|
||||
conf_path: Path | str | None = None,
|
||||
telemetry_db_path: Path | str | None = None,
|
||||
@@ -1161,6 +1492,9 @@ def main(argv: list[str] | None = None) -> int:
|
||||
ap.add_argument("--timeseries", action="store_true", help="Query periodic quant_timeseries_bars.")
|
||||
ap.add_argument("--symbol", default=None, help="Optional ticker symbol filter for --timeseries.")
|
||||
ap.add_argument("--telemetry", action="store_true", help="Print REST/MCP telemetry rollup summary.")
|
||||
ap.add_argument("--telemetry-history", action="store_true", help="Print longitudinal REST/MCP telemetry aggregated across active DB and rotated .1.gz..12.gz snapshots (Strategy 2C).")
|
||||
ap.add_argument("--ingest-caddy-route-counts", action="store_true", help="Ingest zero-IP Caddy JSON access log counts into static_route_rollups (Strategy 3A).")
|
||||
ap.add_argument("--caddy-log", default="/var/log/caddy/hyperstition-access.json", help="Path to zero-IP Caddy access log.")
|
||||
ap.add_argument(
|
||||
"--truncate-quiescent",
|
||||
action="store_true",
|
||||
@@ -1213,6 +1547,14 @@ def main(argv: list[str] | None = None) -> int:
|
||||
print(json.dumps(query_timeseries_bars(symbol=args.symbol, db_path=args.db), indent=2))
|
||||
return 0
|
||||
|
||||
if args.telemetry_history:
|
||||
print(json.dumps(get_longitudinal_telemetry_summary(args.db), indent=2))
|
||||
return 0
|
||||
|
||||
if args.ingest_caddy_route_counts:
|
||||
print(json.dumps(ingest_caddy_route_counts(args.caddy_log, telemetry_db_path=args.db), indent=2))
|
||||
return 0
|
||||
|
||||
if args.telemetry:
|
||||
print(json.dumps(get_api_telemetry_summary(args.db), indent=2))
|
||||
return 0
|
||||
|
||||
@@ -456,6 +456,7 @@ def dispatch_rest_v1(
|
||||
raw_path: str,
|
||||
body_bytes: bytes = b"",
|
||||
if_none_match: str | None = None,
|
||||
traffic_source: str = "internal_test",
|
||||
) -> tuple[int, str, Any]:
|
||||
"""
|
||||
Dispatch an HTTP GET or POST request under `/api/v1/*` and automatically record
|
||||
@@ -475,6 +476,16 @@ def dispatch_rest_v1(
|
||||
status = 304
|
||||
payload = ""
|
||||
elapsed_us = max(1, (time.perf_counter_ns() - t0_ns) // 1000)
|
||||
|
||||
param_events: dict[str, str] = {}
|
||||
if query_str:
|
||||
for k, vals in urllib.parse.parse_qs(query_str, keep_blank_values=False).items():
|
||||
if vals:
|
||||
param_events[k] = vals[0]
|
||||
m_sym = re.match(r"^/api/v1/(?:quant/instruments|zoology/pokedex)/([^/]+)$", path)
|
||||
if m_sym:
|
||||
param_events.setdefault("symbol", urllib.parse.unquote(m_sym.group(1)))
|
||||
|
||||
record_api_telemetry(
|
||||
protocol="rest_v1",
|
||||
method=method.upper(),
|
||||
@@ -482,5 +493,7 @@ def dispatch_rest_v1(
|
||||
status_code=status,
|
||||
latency_us=elapsed_us,
|
||||
isolation_ok=True,
|
||||
traffic_source=traffic_source,
|
||||
param_events=param_events,
|
||||
)
|
||||
return status, ctype, payload
|
||||
@@ -39,12 +39,12 @@ from hyperstitionstud_io.mcp.tools import MCP_TOOLS_SCHEMA, call_mcp_tool # noq
|
||||
|
||||
SERVER_INFO = {
|
||||
"name": "hyperstitionstudio-mcp",
|
||||
"version": "2.7.0",
|
||||
"namespace_urn": "urn:io:hyperstitionstud:mcp:2.7.0",
|
||||
"version": "2.8.0",
|
||||
"namespace_urn": "urn:io:hyperstitionstud:mcp:2.8.0",
|
||||
}
|
||||
|
||||
|
||||
def dispatch_jsonrpc(req: dict[str, Any]) -> dict[str, Any] | None:
|
||||
def dispatch_jsonrpc(req: dict[str, Any], traffic_source: str = "internal_test") -> dict[str, Any] | None:
|
||||
"""
|
||||
Process a single JSON-RPC 2.0 request or notification and return the JSON-RPC 2.0 response
|
||||
(or None for notifications without an 'id').
|
||||
@@ -134,6 +134,14 @@ def dispatch_jsonrpc(req: dict[str, Any]) -> dict[str, Any] | None:
|
||||
}
|
||||
finally:
|
||||
elapsed_us = max(1, (time.perf_counter_ns() - t0_ns) // 1000)
|
||||
rpc_params: dict[str, str] = {}
|
||||
if method == "tools/call" and isinstance(params, dict):
|
||||
t_args = params.get("arguments") or {}
|
||||
if isinstance(t_args, dict):
|
||||
for p_k in ("symbol", "symbol_filter", "lens", "lang", "unit_filter"):
|
||||
if p_k in t_args and t_args[p_k]:
|
||||
norm_k = "symbol" if p_k == "symbol_filter" else p_k
|
||||
rpc_params[norm_k] = str(t_args[p_k])
|
||||
record_api_telemetry(
|
||||
protocol="mcp_jsonrpc",
|
||||
method="POST",
|
||||
@@ -141,6 +149,8 @@ def dispatch_jsonrpc(req: dict[str, Any]) -> dict[str, Any] | None:
|
||||
status_code=status_code,
|
||||
latency_us=elapsed_us,
|
||||
isolation_ok=True,
|
||||
traffic_source=traffic_source,
|
||||
param_events=rpc_params,
|
||||
)
|
||||
|
||||
return {"jsonrpc": "2.0", "id": req_id, "result": result}
|
||||
@@ -215,11 +225,18 @@ class _MCPHTTPHandler(BaseHTTPRequestHandler):
|
||||
self.send_header("Access-Control-Expose-Headers", "ETag")
|
||||
self.end_headers()
|
||||
|
||||
def _classify_traffic_source(self) -> str:
|
||||
ua = (self.headers.get("User-Agent") or "").strip()
|
||||
if "HyperstitionPublicSmoke" in ua or "HyperstitionInternalTest" in ua:
|
||||
return "internal_test"
|
||||
return "external_production"
|
||||
|
||||
def do_GET(self) -> None:
|
||||
try:
|
||||
inm = self.headers.get("If-None-Match")
|
||||
tsrc = self._classify_traffic_source()
|
||||
if self.path.startswith("/api/v1"):
|
||||
status, ctype, payload = dispatch_rest_v1("GET", self.path)
|
||||
status, ctype, payload = dispatch_rest_v1("GET", self.path, traffic_source=tsrc)
|
||||
etag = compute_response_etag(payload) if status == 200 else None
|
||||
if status == 200 and inm and etag and matches_if_none_match(inm, etag):
|
||||
record_api_telemetry(
|
||||
@@ -229,6 +246,7 @@ class _MCPHTTPHandler(BaseHTTPRequestHandler):
|
||||
status_code=304,
|
||||
latency_us=1,
|
||||
isolation_ok=True,
|
||||
traffic_source=tsrc,
|
||||
)
|
||||
self._send_payload(304, ctype, "", etag=etag)
|
||||
return
|
||||
@@ -271,8 +289,9 @@ class _MCPHTTPHandler(BaseHTTPRequestHandler):
|
||||
self._send_json(400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "Invalid content length"}})
|
||||
return
|
||||
raw_bytes = self.rfile.read(length) if length > 0 else b""
|
||||
tsrc = self._classify_traffic_source()
|
||||
if self.path.startswith("/api/v1"):
|
||||
status, ctype, payload = dispatch_rest_v1("POST", self.path, raw_bytes)
|
||||
status, ctype, payload = dispatch_rest_v1("POST", self.path, raw_bytes, traffic_source=tsrc)
|
||||
self._send_payload(status, ctype, payload)
|
||||
return
|
||||
if not raw_bytes:
|
||||
@@ -284,7 +303,7 @@ class _MCPHTTPHandler(BaseHTTPRequestHandler):
|
||||
except json.JSONDecodeError as exc:
|
||||
self._send_json(400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": str(exc)}})
|
||||
return
|
||||
resp = dispatch_jsonrpc(req)
|
||||
resp = dispatch_jsonrpc(req, traffic_source=tsrc)
|
||||
if resp is None:
|
||||
self.send_response(202)
|
||||
self.end_headers()
|
||||
|
||||
@@ -892,6 +892,7 @@ def call_mcp_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]:
|
||||
from hyperstitionstud_io.ci.public_regression import get_default_baseline_cache_path
|
||||
from hyperstitionstud_io.db.sqlite_meta import (
|
||||
get_api_telemetry_summary,
|
||||
get_longitudinal_telemetry_summary,
|
||||
query_coordinate_join,
|
||||
query_fts_catalog,
|
||||
query_registry_manifests,
|
||||
@@ -950,6 +951,8 @@ def call_mcp_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]:
|
||||
}
|
||||
try:
|
||||
out_cat["api_telemetry_summary"] = get_api_telemetry_summary()
|
||||
if arguments.get("include_rotated_history"):
|
||||
out_cat["longitudinal_telemetry_summary"] = get_longitudinal_telemetry_summary()
|
||||
except Exception:
|
||||
out_cat["api_telemetry_summary"] = {"quiescent": True}
|
||||
return out_cat
|
||||
|
||||
@@ -418,7 +418,7 @@ def _render_nav_html(active_slug: str | None, enabled_subpages: list[str], rel_p
|
||||
links.append(_render_polyglot_selector_html())
|
||||
links.append('<span class="nav-donate-sep" aria-hidden="true"></span>')
|
||||
links.append(
|
||||
f'<a class="btn-donate-pill" href="{rel_prefix}../donate/index.html">'
|
||||
f'<a class="btn-donate-pill" href="{rel_prefix}../donate/index.html?from=engineering">'
|
||||
'<span class="donate-pill-emblem" aria-hidden="true">♥</span><span>DONATE</span></a>'
|
||||
)
|
||||
return "\n ".join(links)
|
||||
|
||||
@@ -24,8 +24,59 @@ from hyperstitionstud_io.config import load_workspace_config
|
||||
from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard
|
||||
from hyperstitionstud_io.ipld import compute_dag_json_cidv1
|
||||
from hyperstitionstud_io.mcp.tools import MCP_TOOLS_SCHEMA
|
||||
from hyperstitionstud_io.publishing.archive_rotator import snapshot_gematria_pipeline_richness
|
||||
from hyperstitionstud_io.publishing.engineering_docs import introspect_engineering_manifest
|
||||
from hyperstitionstud_io.publishing.math_docs import introspect_math_manifest
|
||||
from hyperstitionstud_io.version_sync import compute_programmatic_version_bump
|
||||
|
||||
|
||||
def compute_corpus_delta_report(workspace_root: str | Path | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
Compute a deterministic, zero-LLM-token corpus & release delta snapshot (`Strategy 1B`: `--corpus-delta`)
|
||||
comparing current `snapshot_gematria_pipeline_richness()` and `compute_programmatic_version_bump()`
|
||||
against the cached prior richness snapshot (or baseline state).
|
||||
"""
|
||||
cfg = load_workspace_config(workspace_root=workspace_root)
|
||||
cur_snap = snapshot_gematria_pipeline_richness(workspace_root=cfg.workspace_root)
|
||||
bump_info = compute_programmatic_version_bump(ws_root=cfg.workspace_root)
|
||||
|
||||
cache_p = cfg.core_dir / ".cache" / "corpus-richness-baseline.json"
|
||||
prior_snap = cur_snap
|
||||
if cache_p.is_file():
|
||||
try:
|
||||
prior_snap = json.loads(cache_p.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
prior_snap = cur_snap
|
||||
|
||||
numeric_keys = (
|
||||
"dossiers_count",
|
||||
"dated_news_dossiers_count",
|
||||
"glossary_entries_count",
|
||||
"bilingual_specimens_count",
|
||||
"kg_nodes_count",
|
||||
"kg_edges_count",
|
||||
"quant_instruments_count",
|
||||
"real_exchange_bars_count",
|
||||
"fred_macro_series_count",
|
||||
"calc_db_txt_bytes",
|
||||
"cmudict_fallback_entries",
|
||||
)
|
||||
deltas: dict[str, int] = {}
|
||||
for k in numeric_keys:
|
||||
deltas[k] = int(cur_snap.get(k, 0)) - int(prior_snap.get(k, cur_snap.get(k, 0)))
|
||||
|
||||
return {
|
||||
"current_version": CURRENT_VERSION,
|
||||
"baseline_git_tag": bump_info.get("baseline_git_tag"),
|
||||
"recommended_bump_level": bump_info.get("recommended_bump_level"),
|
||||
"next_version": bump_info.get("next_version"),
|
||||
"newly_archived_plans": bump_info.get("signals", {}).get("newly_archived_plans", []),
|
||||
"new_cli_scripts": bump_info.get("signals", {}).get("new_cli_scripts", []),
|
||||
"new_mcp_tools": bump_info.get("signals", {}).get("new_mcp_tools", []),
|
||||
"current_richness": cur_snap,
|
||||
"deltas_since_baseline": deltas,
|
||||
"llm_tokens_used": 0,
|
||||
}
|
||||
|
||||
|
||||
def build_recent_highlights_summary(
|
||||
@@ -33,6 +84,7 @@ def build_recent_highlights_summary(
|
||||
max_chars: int = 1100,
|
||||
out_dir: str | Path | None = None,
|
||||
workspace_root: str | Path | None = None,
|
||||
include_corpus_delta: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Generate the <= 2 paragraph phone-messenger highlights summary for software engineers
|
||||
@@ -146,6 +198,8 @@ def build_recent_highlights_summary(
|
||||
},
|
||||
}
|
||||
payload["ipld_dag_json_cidv1"] = {"/": compute_dag_json_cidv1(payload)}
|
||||
if include_corpus_delta:
|
||||
payload["corpus_delta"] = compute_corpus_delta_report(workspace_root=cfg.workspace_root)
|
||||
|
||||
try:
|
||||
target_untracked.mkdir(parents=True, exist_ok=True)
|
||||
@@ -170,6 +224,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
ap.add_argument("--focus", default="both", choices=["both", "eng", "math"], help="Target audience focus (default: both).")
|
||||
ap.add_argument("--max-chars", type=int, default=1100, help="Maximum total characters (default: 1100).")
|
||||
ap.add_argument("--out-dir", default=None, help="Output directory (defaults to /workspace/untracked/recent-highlights).")
|
||||
ap.add_argument("--corpus-delta", action="store_true", help="Include deterministic corpus richness & Git tag delta report (Strategy 1B).")
|
||||
ap.add_argument("--json", action="store_true", help="Print full JSON payload to stdout instead of plain messenger text.")
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
@@ -177,8 +232,9 @@ def main(argv: list[str] | None = None) -> int:
|
||||
focus=args.focus,
|
||||
max_chars=args.max_chars,
|
||||
out_dir=args.out_dir,
|
||||
include_corpus_delta=args.corpus_delta,
|
||||
)
|
||||
if args.json:
|
||||
if args.json or args.corpus_delta:
|
||||
print(json.dumps(res, indent=2, ensure_ascii=False))
|
||||
else:
|
||||
print(res["messenger_text"])
|
||||
|
||||
@@ -369,7 +369,7 @@ def _render_math_nav_html(active_slug: str | None, enabled_subpages: list[str],
|
||||
links.append(_render_polyglot_selector_html())
|
||||
links.append('<span class="nav-donate-sep" aria-hidden="true"></span>')
|
||||
links.append(
|
||||
f'<a class="btn-donate-pill" href="{rel_prefix}../donate/index.html">'
|
||||
f'<a class="btn-donate-pill" href="{rel_prefix}../donate/index.html?from=math">'
|
||||
'<span class="donate-pill-emblem" aria-hidden="true">♥</span><span>DONATE</span></a>'
|
||||
)
|
||||
return "\n ".join(links)
|
||||
|
||||
@@ -678,7 +678,7 @@ def build_financial_quant_harvest(
|
||||
payload: dict[str, Any] = {
|
||||
"$schema": "./schemas/v1/financial-aq-harvest.schema.json",
|
||||
"$id": "urn:io:hyperstitionstud:schema:v1:financial-aq-harvest",
|
||||
"version": "2.7.0",
|
||||
"version": "2.8.0",
|
||||
"target_date_utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d"),
|
||||
"harvest_mode": harvest_mode,
|
||||
"synthetic_data_eliminated": True,
|
||||
|
||||
@@ -498,9 +498,16 @@ def main(argv: list[str] | None = None) -> int:
|
||||
ap.add_argument("--set", dest="set_version", default=None, help="Set new version X.Y.Z across all site HTML elements, JS bundles, and manifests.")
|
||||
ap.add_argument("--check", action="store_true", help="Verify that all site elements match hyperstitionstud_io.__version__ without modifying files.")
|
||||
ap.add_argument("--explain-bump", action="store_true", help="Evaluate zero-LLM-token change-scope heuristics and print the recommended bump level without modifying files.")
|
||||
ap.add_argument("--corpus-delta", action="store_true", help="Print deterministic corpus richness & Git tag delta report (Strategy 1B, 0 LLM tokens).")
|
||||
ap.add_argument("--auto-bump", action="store_true", help="Programmatically determine the next semantic version via change-scope heuristics (0 LLM tokens) and synchronize all workspace files.")
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
if args.corpus_delta:
|
||||
from hyperstitionstud_io.publishing.highlights import compute_corpus_delta_report
|
||||
|
||||
print(json.dumps(compute_corpus_delta_report(), indent=2, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
if args.explain_bump:
|
||||
report = compute_programmatic_version_bump()
|
||||
print(json.dumps(report, indent=2))
|
||||
|
||||
Reference in new issue
Block a user