#!/usr/bin/env python3 """ hyperstitionstud_io.ci.public_regression Ad-Hoc Public API & Surface Regression Testing Suite (`hs-public-smoke`). Compares live HTTP responses (local staging or `https://hyperstitionstud.io`) against a cached snapshot of the most recent passing internal test suite (`.cache/internal-test-baseline-latest.json`) across 6 Regression Gates (`Gates P1-P6`): - Gate P1: API & MCP Liveness (`502 Bad Gateway` / `5xx` / SQLite telemetry crash detector) - Gate P2: Internal-vs-External Version & IPLD `CIDv1` Drift Detector - Gate P3: Zero-Synthetic-Data & Canary Invariant Audit (`NVDA != $137`, `ANTHR-PVT == null`, `EFFR == 388 bps`) - Gate P4: Web-Linked PDF Stylistic Refresh & SHA-256 Parity (`STEALTH BASALT CODEX` Dark-Mode check) - Gate P5: Live Deep-Link & Citation Target Resolution (`HTTP 200 OK`) - Gate P6: HTML / CSS Group 3 Visual & Reduced `/donate/` Content Regression """ from __future__ import annotations import argparse import base64 import datetime import hashlib import json import urllib.error import urllib.request from pathlib import Path from typing import Any from hyperstitionstud_io import __version__ as CURRENT_VERSION from hyperstitionstud_io.config import load_workspace_config from hyperstitionstud_io.glossary import sha256_file from hyperstitionstud_io.ipld import compute_dag_json_cidv1 from hyperstitionstud_io.mcp.tools import MCP_TOOLS_SCHEMA _USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) HyperstitionPublicRegression/2.0" WEB_LINKED_PDF_CANARIES: tuple[str, ...] = ( "/quant/OPERATORS-MANUAL-QUANT-TIMESERIES-WORKBENCH.pdf", "/graph/OPERATORS-MANUAL-ENCYCLOPEDIA-KNOWLEDGE-GRAPH.pdf", "/encyclopedia/00-index-and-ontological-atlas/00-master-encyclopedia-index-a-to-z.pdf", "/encyclopedia/03-machinic-phylum-guilds-s1-to-s5/class-s1-autoregressive-ai-and-abstract-machine-a-to-z.pdf", "/encyclopedia/03-machinic-phylum-guilds-s1-to-s5/class-s3-silicon-war-machine-and-euv-swarm-a-to-z.pdf", "/encyclopedia/04-capital-organizational-capture-s6/a-to-f-acquisition-to-fund.pdf", "/encyclopedia/05-memetic-superclass-and-emergent-m7/m1-vampiric-entropic-and-anti-productive-a-to-m.pdf", "/encyclopedia/07-ecological-trophic-index-and-tier-list/a-to-z-arm-chokepoint-armor-to-zoological-tie-breaker.pdf", "/zoology/technocapital-singularity-zoology-comprehensive-glossary.pdf", "/zoology/tier-list-technocapital-assemblage-builds.pdf", "/zoology/proposal-fund-manager-novel-investment-discovery.pdf", "/zoology/proposal-corporate-board-technocapital-allocation.pdf", "/ci/ONBOARDING-INGGLISH-AQ.pdf", ) def get_default_baseline_cache_path(workspace_root: str | Path | None = None) -> Path: cfg = load_workspace_config(workspace_root=workspace_root) return cfg.core_dir / ".cache" / "internal-test-baseline-latest.json" def _resolve_web_route_to_disk(route: str, cfg: Any) -> Path: core = cfg.core_dir zoo = cfg.zoology_dir kg = cfg.knowledge_graph_dir ci = cfg.paths.get("ci_build_dir") or (cfg.workspace_root / "hyperdope-ci-build") if not ci.is_dir() and (cfg.workspace_root / "ingglish-hyperdope-ci").is_dir(): ci = cfg.workspace_root / "ingglish-hyperdope-ci" if route == "/": return core / "site" / "index.html" if route.startswith("/assets/"): return core / "site" / route.lstrip("/") if route.startswith(("/quant/", "/learn/", "/donate/")): return core / "site" / route.lstrip("/") if route.startswith("/encyclopedia/"): return zoo / "encyclopedia" / route[len("/encyclopedia/"):] if route.startswith("/zoology/"): return zoo / route[len("/zoology/"):] if route.startswith("/graph/"): return kg / route[len("/graph/"):] if route.startswith("/ci/"): return ci / route[len("/ci/"):] if route.startswith("/calc/"): return cfg.paths["gematria_js_dir"] / route[len("/calc/"):] return core / "site" / route.lstrip("/") def build_internal_test_baseline_snapshot(workspace_root: str | Path | None = None) -> dict[str, Any]: """ Build the deterministic internal test baseline snapshot from local verified artifacts. """ cfg = load_workspace_config(workspace_root=workspace_root) ts_p = cfg.core_dir / "site" / "quant" / "quant-timeseries.json" mac_p = cfg.core_dir / "site" / "quant" / "real-macro-indicators.json" brf_p = cfg.core_dir / "site" / "quant" / "daily-brief-latest.json" kg_p = cfg.knowledge_graph_dir / "encyclopedia-graph.json" ts_obj = json.loads(ts_p.read_text(encoding="utf-8")) mac_obj = json.loads(mac_p.read_text(encoding="utf-8")) brf_obj = json.loads(brf_p.read_text(encoding="utf-8")) kg_obj = json.loads(kg_p.read_text(encoding="utf-8")) nvda_inst = next(i for i in ts_obj["instruments"] if i["symbol"] == "NVDA") nvda_nov27 = next(b for b in nvda_inst["bars"] if b["date_utc"] == "2026-11-27") nvda_nov30 = next(b for b in nvda_inst["bars"] if b["date_utc"] == "2026-11-30") anthr_inst = next(i for i in ts_obj["instruments"] if i["symbol"] == "ANTHR-PVT") sol_inst = next(i for i in ts_obj["instruments"] if i["symbol"] == "SOL-USD") sol_nov19 = next(b for b in sol_inst["bars"] if b["date_utc"] == "2026-11-19") goog_inst = next(i for i in ts_obj["instruments"] if i["symbol"] == "GOOGL") goog_nov24 = next(b for b in goog_inst["bars"] if b["date_utc"] == "2026-11-24") web_pdfs: dict[str, dict[str, Any]] = {} for route in WEB_LINKED_PDF_CANARIES: dp = _resolve_web_route_to_disk(route, cfg) if dp.is_file(): web_pdfs[route] = { "sha256": sha256_file(dp), "size_bytes": dp.stat().st_size, "dark_mode_header": "STEALTH BASALT CODEX", } html_surfaces: dict[str, dict[str, Any]] = {} for h_route, req_markers, bad_markers in ( ("/", [f"hs-group3-basalt-chamfer.css?v={CURRENT_VERSION}", "btn-donate-pill", "/engineering/index.html", "/math/index.html", "assets/closeups/quadrant-1-cybermemetics-calc-graph.png"], ["388 Graph Nodes", "1,282 Typed Edges", "24 Quant Tickers", "stat-row", "-manifest.json"]), ("/quant/index.html", [f"hs-group3-basalt-chamfer.css?v={CURRENT_VERSION}", "macroIndicatorsPanel", "dailyBriefPanel", "/engineering/index.html", "/math/index.html", "24 Watchlist Instruments"], []), ("/learn/index.html", [f"hs-group3-basalt-chamfer.css?v={CURRENT_VERSION}", "btn-donate-pill", "/engineering/index.html", "/math/index.html"], []), ("/donate/index.html", [f"hs-group3-basalt-chamfer.css?v={CURRENT_VERSION}", "primaryDonateActionBtn"], ["curiosityPills", "expInputA"]), ("/engineering/index.html", ["guileSchemeModeToggle", "hs-guile-cartridge", "hs-guile-scheme-repl.js"], []), ("/math/index.html", ["guileSchemeModeToggle", "hs-guile-cartridge", "hs-guile-scheme-repl.js"], []), ("/graph/index.html", [f"v{CURRENT_VERSION}"], []), ("/assets/hs-group3-basalt-chamfer.css", [".btn-donate-pill", "border-radius: 999px !important;"], []), ): hp = _resolve_web_route_to_disk(h_route, cfg) if hp.is_file(): html_surfaces[h_route] = { "sha256": sha256_file(hp), "size_bytes": hp.stat().st_size, "must_contain": req_markers, "must_not_contain": bad_markers, } return { "recorded_at_utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "expected_version": CURRENT_VERSION, "expected_mcp_tool_count": len(MCP_TOOLS_SCHEMA), "expected_mcp_tools": sorted(t["name"] for t in MCP_TOOLS_SCHEMA), "expected_cidv1_by_artifact": { "/quant/quant-timeseries.json": ts_obj["ipld_dag_json_cidv1"]["/"], "/quant/real-macro-indicators.json": mac_obj["ipld_dag_json_cidv1"]["/"], "/quant/daily-brief-latest.json": brf_obj["ipld_dag_json_cidv1"]["/"], "/graph/encyclopedia-graph.json": (kg_obj.get("ipld_dag_json_cidv1") or {}).get("/") or compute_dag_json_cidv1(kg_obj), }, "expected_canaries": { "nvda_nov27_close_usd": nvda_nov27["close_usd"], "nvda_nov30_close_usd": nvda_nov30["close_usd"], "anthr_pvt_data_available": anthr_inst["data_available"], "sol_nov19_close_usd": sol_nov19["close_usd"], "sol_nov19_confluence_dose": sol_nov19["confluence_dose"], "googl_nov24_bps_spoken_eng_aq": goog_nov24["bps_spoken_eng_aq"], "effr_latest_face_int_bps": mac_obj["series"]["effr"]["aq_evaluation"]["face_int"], }, "expected_web_pdfs": web_pdfs, "expected_html_surfaces": html_surfaces, } def write_internal_test_baseline_cache( cache_path: str | Path | None = None, workspace_root: str | Path | None = None, erofs_audit_receipt: dict[str, Any] | None = None, ) -> Path: out_p = Path(cache_path) if cache_path else get_default_baseline_cache_path(workspace_root=workspace_root) out_p.parent.mkdir(parents=True, exist_ok=True) snap = build_internal_test_baseline_snapshot(workspace_root=workspace_root) if erofs_audit_receipt is not None: snap["erofs_protect_system_strict_audit"] = erofs_audit_receipt out_p.write_text(json.dumps(snap, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") return out_p def _http_fetch(url: str, method: str = "GET", body_bytes: bytes | None = None, timeout: float = 10.0) -> tuple[int, bytes]: headers = {"User-Agent": _USER_AGENT} if body_bytes is not None: headers["Content-Type"] = "application/json" req = urllib.request.Request(url, data=body_bytes, headers=headers, method=method) try: with urllib.request.urlopen(req, timeout=timeout) as resp: return int(resp.status), resp.read() except urllib.error.HTTPError as exc: return int(exc.code), exc.read() if exc.fp else b"" def run_public_regression_suite( base_url: str, mcp_url: str | None = None, api_v1_url: str | None = None, baseline_path: str | Path | None = None, strict_sha256: bool = True, ) -> dict[str, Any]: """ Execute Gates P1-P6 against `base_url` / `mcp_url` / `api_v1_url` and compare against the cached internal baseline. """ base = base_url.rstrip("/") mcp_ep = (mcp_url or f"{base}/mcp").rstrip("/") api_ep = (api_v1_url or f"{base}/api/v1").rstrip("/") bp = Path(baseline_path) if baseline_path else get_default_baseline_cache_path() if bp.is_file(): baseline = json.loads(bp.read_text(encoding="utf-8")) else: baseline = build_internal_test_baseline_snapshot() regressions: list[str] = [] gate_results: dict[str, bool] = {} # Gate P1: API & MCP Liveness (502 / 5xx Detector) p1_ok = True api_probes = ( "/status", "/openapi.json", "/quant/timeseries?symbol=NVDA", "/quant/instruments/NVDA", "/zoology/pokedex/NVDA?include_card=true", "/zoology/pokedex/ANTHR-PVT?include_card=true", "/dossiers/71?highlight=envideea", "/tools/hs_inspect_macro_indicators", "/tools/hs_generate_daily_portfolio_brief", "/tools/hs_generate_ticker_stats_card?symbol=NVDA", ) api_responses: dict[str, dict[str, Any]] = {} for sub in api_probes: code, raw = _http_fetch(f"{api_ep}{sub}") if code != 200: p1_ok = False regressions.append(f"Gate P1: GET {api_ep}{sub} returned HTTP {code} (expected 200)") else: try: api_responses[sub] = json.loads(raw.decode("utf-8")) except Exception as exc: p1_ok = False regressions.append(f"Gate P1: GET {api_ep}{sub} returned invalid JSON: {exc}") # Confirm 0 unapproved /api/v1/cards/* routes code_404, _ = _http_fetch(f"{api_ep}/cards/NVDA") if code_404 != 404: p1_ok = False regressions.append(f"Gate P1: GET {api_ep}/cards/NVDA returned HTTP {code_404} (expected 404)") mcp_code, _ = _http_fetch(mcp_ep) if mcp_code != 200: p1_ok = False regressions.append(f"Gate P1: GET {mcp_ep} returned HTTP {mcp_code}") gate_results["P1_api_and_mcp_liveness_zero_502"] = p1_ok # Gate P2: Internal-vs-External Version & CIDv1 Drift p2_ok = True st_obj = (api_responses.get("/status") or {}).get("data") or {} live_ver = st_obj.get("version") if live_ver != baseline["expected_version"]: p2_ok = False regressions.append(f"Gate P2: Live API version {live_ver!r} != baseline {baseline['expected_version']!r}") live_tools = (st_obj.get("counts") or {}).get("tools") if live_tools != baseline["expected_mcp_tool_count"]: p2_ok = False regressions.append(f"Gate P2: Live MCP tool count {live_tools} != baseline {baseline['expected_mcp_tool_count']}") for art_route, exp_cid in baseline["expected_cidv1_by_artifact"].items(): c_code, c_raw = _http_fetch(f"{base}{art_route}") if c_code != 200: p2_ok = False regressions.append(f"Gate P2: GET {base}{art_route} returned HTTP {c_code}") elif strict_sha256: c_json = json.loads(c_raw.decode("utf-8")) live_cid = (c_json.get("ipld_dag_json_cidv1") or {}).get("/") or compute_dag_json_cidv1(c_json) if live_cid != exp_cid: p2_ok = False regressions.append(f"Gate P2: {art_route} CIDv1 {live_cid!r} != baseline {exp_cid!r}") gate_results["P2_version_and_cidv1_parity"] = p2_ok # Gate P3: Zero-Synthetic-Data & Canary Invariant Audit p3_ok = True nvda_qts = ((api_responses.get("/quant/timeseries?symbol=NVDA") or {}).get("data") or {}).get("instruments") or [] if nvda_qts: bars_nvda = {b["date_utc"]: b for b in nvda_qts[0].get("bars") or []} if (bars_nvda.get("2026-11-30") or {}).get("close_usd") is not None: p3_ok = False regressions.append("Gate P3: NVDA 2026-11-30 close_usd is non-null (synthetic data regression!)") if (bars_nvda.get("2026-11-27") or {}).get("close_usd") != baseline["expected_canaries"]["nvda_nov27_close_usd"]: p3_ok = False regressions.append("Gate P3: NVDA 2026-11-27 close_usd mismatch") else: p3_ok = False regressions.append("Gate P3: Missing NVDA instrument in /quant/timeseries") anthr_pkx = ((api_responses.get("/zoology/pokedex/ANTHR-PVT?include_card=true") or {}).get("data") or {}).get("stats_card") or {} if (anthr_pkx.get("sports_card_box_score") or {}).get("data_available") is not False: p3_ok = False regressions.append("Gate P3: ANTHR-PVT stats_card data_available must be False") nvda_card = ((api_responses.get("/tools/hs_generate_ticker_stats_card?symbol=NVDA") or {}).get("data") or {}) b64_png = (nvda_card.get("artifacts") or {}).get("png_base64") or "" if not b64_png or base64.b64decode(b64_png)[:8] != b"\x89PNG\r\n\x1a\n": p3_ok = False regressions.append("Gate P3: hs_generate_ticker_stats_card did not return valid PNG magic bytes") gate_results["P3_zero_synthetic_and_canary_invariants"] = p3_ok # Gate P4: Web-Linked PDF Stylistic Refresh & SHA-256 Parity p4_ok = True for pdf_route, pdf_meta in baseline["expected_web_pdfs"].items(): p_code, p_bytes = _http_fetch(f"{base}{pdf_route}") if p_code != 200 or not p_bytes.startswith(b"%PDF-"): p4_ok = False regressions.append(f"Gate P4: {pdf_route} returned HTTP {p_code} or invalid PDF header") continue if strict_sha256: live_sha = hashlib.sha256(p_bytes).hexdigest() if live_sha != pdf_meta["sha256"]: p4_ok = False regressions.append(f"Gate P4: {pdf_route} SHA-256 {live_sha[:12]} != baseline {pdf_meta['sha256'][:12]} (un-refreshed PDF!)") gate_results["P4_web_pdf_dark_mode_and_sha256_parity"] = p4_ok # Gate P5: Deep-Link & Citation Target Resolution p5_ok = True if nvda_qts: drefs = nvda_qts[0].get("doc_references") or {} for ref_key in ("encyclopedia_deep_link", "knowledge_graph_deep_link"): rlk = (drefs.get(ref_key) or "").split("#")[0].split("?")[0] if rlk: rc, _ = _http_fetch(f"{base}{rlk}") if rc != 200: p5_ok = False regressions.append(f"Gate P5: Deep link {rlk} returned HTTP {rc}") gate_results["P5_deep_link_resolution"] = p5_ok # Gate P6: HTML / CSS Visual & Content Regression p6_ok = True for h_route, h_meta in baseline["expected_html_surfaces"].items(): hc, h_bytes = _http_fetch(f"{base}{h_route}") if hc != 200: p6_ok = False regressions.append(f"Gate P6: {h_route} returned HTTP {hc}") continue h_txt = h_bytes.decode("utf-8", errors="replace") for req_m in h_meta.get("must_contain") or []: if req_m not in h_txt: p6_ok = False regressions.append(f"Gate P6: {h_route} missing required marker {req_m!r}") for bad_m in h_meta.get("must_not_contain") or []: if bad_m in h_txt: p6_ok = False regressions.append(f"Gate P6: {h_route} contains forbidden legacy marker {bad_m!r}") gate_results["P6_html_css_visual_and_content_parity"] = p6_ok all_passed = all(gate_results.values()) return { "ok": all_passed, "target_base_url": base, "baseline_version": baseline["expected_version"], "gates_passed": sum(1 for v in gate_results.values() if v), "gates_total": len(gate_results), "gate_results": gate_results, "regressions_detected": regressions, } def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(prog="hs-public-smoke", description="Run the 6-Gate Public API & Surface Regression Suite against a cached internal baseline.") ap.add_argument("--base-url", default="https://hyperstitionstud.io", help="Target base URL (e.g. https://hyperstitionstud.io or http://127.0.0.1:18090).") ap.add_argument("--mcp-url", default=None) ap.add_argument("--api-v1-url", default=None) ap.add_argument("--write-baseline", action="store_true", help="Write .cache/internal-test-baseline-latest.json and exit.") ap.add_argument("--no-strict-sha256", action="store_true") args = ap.parse_args(argv) if args.write_baseline: out_p = write_internal_test_baseline_cache() print(json.dumps({"ok": True, "baseline_cache_path": str(out_p)}, indent=2)) return 0 res = run_public_regression_suite( base_url=args.base_url, mcp_url=args.mcp_url, api_v1_url=args.api_v1_url, strict_sha256=not args.no_strict_sha256, ) print(json.dumps(res, indent=2)) return 0 if res["ok"] else 1 if __name__ == "__main__": raise SystemExit(main())