diff --git a/README.md b/README.md index 69f5d02..93d561d 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ -# `hyperstitionstudio-core` (`hyperstitionstud_io.*` — `v2.7.0`) +# `hyperstitionstudio-core` (`hyperstitionstud_io.*` — `v2.8.0`) -> **Gitea Commit & Release Telemetry (`v2.7.0` • Namespace `urn:io:hyperstitionstud`)** +> **Gitea Commit & Release Telemetry (`v2.8.0` • Namespace `urn:io:hyperstitionstud`)** > - **Repository Role & Public Route:** Shared PEP 420 Python core library (`hyperstitionstud_io.*`), MCP/REST server, `/quant/`, `/learn/`, `/engineering/`, `/math/`, & `/donate/` webroots → [`https://hyperstitionstud.io/`](https://hyperstitionstud.io/) -> - **Latest Commit Scope (`hyperstitionstudio-core`):** Synchronized v2.7.0 release state across 48 tracked module/artifact surface(s) -> - **Touched Files / Surfaces:** `deploy/run-vps-data-production.sh`, `deploy/sync-vps-repos.sh`, `deploy/test-first-deployment.sh`, `package.json`, `packages-js/ciphers-aq/package.json`, `pyproject.toml`, `scripts/build_gallery_manifest.py`, `site/assets/closeups/quadrant-1-cybermemetics-calc-graph.png` (+40 more) -> - **Live Verified Ecosystem Metrics (`v2.7.0`):** `6` Repositories • `17` CLI Entrypoints • `20` MCP/REST Tools • `14` URN Resources • `63` Verified Web Routes • `388` KG Nodes / `1,282` Edges • `282` Glossary Entries • `4,943` Offline CMUdict Phonetics • `0` Synthetic Data +> - **Latest Commit Scope (`hyperstitionstudio-core`):** Synchronized v2.8.0 release state across 48 tracked module/artifact surface(s) +> - **Touched Files / Surfaces:** `deploy/Caddyfile`, `deploy/run-vps-archive-rotation.sh`, `deploy/sync-vps-repos.sh`, `package.json`, `packages-js/ciphers-aq/package.json`, `pyproject.toml`, `scripts/build_gallery_manifest.py`, `site/assets/closeups/quadrant-1-cybermemetics-calc-graph.png` (+40 more) +> - **Live Verified Ecosystem Metrics (`v2.8.0`):** `6` Repositories • `17` CLI Entrypoints • `20` MCP/REST Tools • `14` URN Resources • `63` Verified Web Routes • `388` KG Nodes / `1,282` Edges • `282` Glossary Entries • `4,943` Offline CMUdict Phonetics • `0` Synthetic Data Shared Python common library (`hyperstitionstud_io.*`), stateless read-only Model Context Protocol (`/mcp`) & OpenAPI 3.1 REST (`/api/v1/*`) server, SQLite FTS5 metadata catalog (`hs-db-build`), offline `URN:` JSON Schema registry (`urn:io:hyperstitionstud:schema:v1:*`), and Group 3 Stealth Basalt web workbenches (`/`, `/learn/`, `/quant/`, `/engineering/`, `/math/`, `/donate/`) with the 4-Ring Hardened Polyglot REPL (`Guile Scheme`, `TypeScript`, `Rust`) and Subtle Cybernetic Code Rain (`hs-matrix-coderain.js`). @@ -50,7 +50,7 @@ python3 hyperstitionstudio-core/tests/test_core_suite.py --- -## Key Architecture & Capabilities (`v2.7.0`) +## Key Architecture & Capabilities (`v2.8.0`) 1. **17 CLI Entrypoints (`pyproject.toml [project.scripts]`):** - `hs-doctor`, `hs-citations`, `hs-pdf-build`, `hs-kg-build`, `hs-quant-harvest`, `hs-macro-harvest`, `hs-daily-brief`, `hs-ticker-card`, `hs-mcp`, `hs-db-build`, `hs-sync-version`, `hs-readme-sync`, `hs-archive-rotate`, `hs-public-smoke`, `hs-eng-docs`, `hs-math-docs`, and `hs-highlights`. diff --git a/deploy/Caddyfile b/deploy/Caddyfile index fdacd5f..a19fc12 100644 --- a/deploy/Caddyfile +++ b/deploy/Caddyfile @@ -12,6 +12,24 @@ www.hyperstitionstud.io { hyperstitionstud.io { encode zstd gzip + # Zero-PII Route Counter Log (Strategy 3A — remote_ip, client_ip, Cookie, User-Agent, and Referer deleted) + log { + output file /var/log/caddy/hyperstition-access.json { + roll_size 50MiB + roll_keep 3 + } + format filter { + wrap json + fields { + request>remote_ip delete + request>client_ip delete + request>headers>Cookie delete + request>headers>User-Agent delete + request>headers>Referer delete + } + } + } + header { Alt-Svc "h3=\":443\"; ma=2592000" Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" diff --git a/deploy/run-vps-archive-rotation.sh b/deploy/run-vps-archive-rotation.sh index 5bd7b9f..62928b9 100755 --- a/deploy/run-vps-archive-rotation.sh +++ b/deploy/run-vps-archive-rotation.sh @@ -56,8 +56,9 @@ else fi echo "${ROTATE_JSON}" -echo "[2/3] Running Quiescent SQLite Telemetry Logrotate Check (100M threshold)..." +echo "[2/3] Ingesting Zero-IP Caddy Route Counts (Strategy 3A) & Running Quiescent SQLite Telemetry Logrotate Check (100M threshold)..." if [[ "${DRY_RUN}" -eq 0 ]]; then + python3 -m hyperstitionstud_io.db.sqlite_meta --ingest-caddy-route-counts python3 -m hyperstitionstud_io.db.sqlite_meta --compress-archive --truncate-quiescent --max-mb 100 fi diff --git a/deploy/sync-vps-repos.sh b/deploy/sync-vps-repos.sh index c9681ba..8f1bed0 100755 --- a/deploy/sync-vps-repos.sh +++ b/deploy/sync-vps-repos.sh @@ -198,6 +198,12 @@ if [[ "${DO_CADDY}" -eq 1 ]]; then if [[ -w "/var/lib" ]] || [[ -n "${SUDO}" ]]; then run_checked "mkdir /var/lib/hyperstitionstud.io" ${SUDO} mkdir -p "/var/lib/hyperstitionstud.io" fi + if [[ -w "/var/log" ]] || [[ -n "${SUDO}" ]]; then + run_checked "mkdir /var/log/caddy" ${SUDO} mkdir -p "/var/log/caddy" + if getent passwd caddy >&2; then + ${SUDO} chown -R caddy:caddy "/var/log/caddy" || true + fi + fi SRC_LOGROTATE="${DEPLOY_DIR}/logrotate.d/hyperstition-sqlite-meta" DST_LOGROTATE="/etc/logrotate.d/hyperstition-sqlite-meta" if [[ -f "${SRC_LOGROTATE}" ]] && [[ -d "/etc/logrotate.d" ]] && { [[ -w "/etc/logrotate.d" ]] || [[ -n "${SUDO}" ]]; }; then diff --git a/package.json b/package.json index 92aa48d..d92042c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@hyperstitionstud.io/workspace-core", - "version": "2.7.0", + "version": "2.8.0", "private": true, "description": "Offline-first ESM & browser global (@hyperstitionstud.io/* / window.HyperstitionStudio.*) packages for Base-36 AQ ciphers and interactive knowledge graph workbenches.", "license": "MIT", diff --git a/packages-js/ciphers-aq/package.json b/packages-js/ciphers-aq/package.json index e2b6805..c4a269d 100644 --- a/packages-js/ciphers-aq/package.json +++ b/packages-js/ciphers-aq/package.json @@ -1,6 +1,6 @@ { "name": "@hyperstitionstud.io/ciphers-aq", - "version": "2.7.0", + "version": "2.8.0", "type": "module", "main": "index.js", "license": "MIT" diff --git a/pyproject.toml b/pyproject.toml index 6c3f447..d112dcf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "hyperstitionstudio-core" -version = "2.7.0" +version = "2.8.0" description = "Shared PEP 420 common library (hyperstitionstud_io.*) for Base-36 AQ ciphers, offline CMUdict Ingglish phonetics, ReportLab/Pillow publishing, SHA-256 glossary isolation guards, local-config citation verification, and multi-format knowledge graphs." readme = "README.md" requires-python = ">=3.10" diff --git a/scripts/build_gallery_manifest.py b/scripts/build_gallery_manifest.py index 1c4431d..70615aa 100755 --- a/scripts/build_gallery_manifest.py +++ b/scripts/build_gallery_manifest.py @@ -144,8 +144,8 @@ def main() -> int: }) manifest = { - "version": "2.7.0", - "namespace_urn": "urn:io:hyperstitionstud:gallery:2.7.0", + "version": "2.8.0", + "namespace_urn": "urn:io:hyperstitionstud:gallery:2.8.0", "total_items": len(items), "items": items, } diff --git a/site/assets/closeups/quadrant-1-cybermemetics-calc-graph.png b/site/assets/closeups/quadrant-1-cybermemetics-calc-graph.png index fe4ff87..cc661d4 100644 Binary files a/site/assets/closeups/quadrant-1-cybermemetics-calc-graph.png and b/site/assets/closeups/quadrant-1-cybermemetics-calc-graph.png differ diff --git a/site/assets/closeups/quadrant-2-esoteric-finance-quant.png b/site/assets/closeups/quadrant-2-esoteric-finance-quant.png index 66b947f..a90538d 100644 Binary files a/site/assets/closeups/quadrant-2-esoteric-finance-quant.png and b/site/assets/closeups/quadrant-2-esoteric-finance-quant.png differ diff --git a/site/assets/closeups/quadrant-3-info-science-novice-learn-polyglot.png b/site/assets/closeups/quadrant-3-info-science-novice-learn-polyglot.png index f55dd73..c775c4f 100644 Binary files a/site/assets/closeups/quadrant-3-info-science-novice-learn-polyglot.png and b/site/assets/closeups/quadrant-3-info-science-novice-learn-polyglot.png differ diff --git a/site/assets/closeups/quadrant-4-operators-deployment-vps.png b/site/assets/closeups/quadrant-4-operators-deployment-vps.png index 6122734..b4e4329 100644 Binary files a/site/assets/closeups/quadrant-4-operators-deployment-vps.png and b/site/assets/closeups/quadrant-4-operators-deployment-vps.png differ diff --git a/site/assets/hs-matrix-coderain.js b/site/assets/hs-matrix-coderain.js index a53927f..abf4ef2 100644 --- a/site/assets/hs-matrix-coderain.js +++ b/site/assets/hs-matrix-coderain.js @@ -308,6 +308,47 @@ applyMode(currentMode); + // Strategy 3B, 4B & 5B: Zero-PII Conditional ETag Surface, Donate-From, Donate-Copy & Export-Action Handshake + try { + if (window.location && (window.location.protocol === "http:" || window.location.protocol === "https:") && typeof window.fetch === "function") { + var pathStr = window.location.pathname || "/"; + var surfSlug = "home"; + if (pathStr.indexOf("/calc") === 0) surfSlug = "calc"; + else if (pathStr.indexOf("/quant") === 0) surfSlug = "quant"; + else if (pathStr.indexOf("/graph") === 0) surfSlug = "graph"; + else if (pathStr.indexOf("/learn") === 0) surfSlug = "learn"; + else if (pathStr.indexOf("/engineering") === 0) surfSlug = "engineering"; + else if (pathStr.indexOf("/math") === 0) surfSlug = "math"; + else if (pathStr.indexOf("/donate") === 0) surfSlug = "donate"; + + var qParts = ["surface=" + encodeURIComponent(surfSlug)]; + if (surfSlug === "donate" && window.location.search) { + var mFrom = window.location.search.match(/[?&]from=([a-z]+)/i); + if (mFrom && mFrom[1]) qParts.push("donate_from=" + encodeURIComponent(mFrom[1].toLowerCase())); + } + window.fetch("/api/v1/status?" + qParts.join("&"), { method: "GET" }).catch(function () {}); + + var exportBindings = [ + ["#btnDownloadState", "learn_state_json"], + ["#exportCsvBtn", "quant_csv"], + ["#exportJsonBtn", "quant_json"], + ["#openTradingViewBtn", "quant_tradingview"], + ["#panel3TvBtn", "quant_tradingview"], + ["#exportPngBtn", "graph_png"] + ]; + exportBindings.forEach(function (pair) { + document.querySelectorAll(pair[0]).forEach(function (el) { + if (!el.__hsExportBound) { + el.__hsExportBound = true; + el.addEventListener("click", function () { + window.fetch("/api/v1/status?export_action=" + pair[1], { method: "GET" }).catch(function () {}); + }); + } + }); + }); + } + } catch (_e) {} + return { applyMode: applyMode, cycleMode: cycleMode, diff --git a/site/donate/index.html b/site/donate/index.html index 2d92b1a..537f4f8 100644 --- a/site/donate/index.html +++ b/site/donate/index.html @@ -4,7 +4,7 @@ Signal Patronage & Open-Instrument Notes — hyperstitionstud.io/donate - + - +

hyperstitionstud.io/quant — Quantitative Finance & Memetic Gematria Time-Series Workbench

-

Strictly Periodic Telemetry (21:30 UTC US Closing Bell × 00:00 UTC News-Wire Dossiers • 24 Watchlist Instruments • 14 FRED Macro Series) • Lens-Neutral Schema (urn:io:hyperstitionstud:quant-timeseries:v2.7.0)

+

Strictly Periodic Telemetry (21:30 UTC US Closing Bell × 00:00 UTC News-Wire Dossiers • 24 Watchlist Instruments • 14 FRED Macro Series) • Lens-Neutral Schema (urn:io:hyperstitionstud:quant-timeseries:v2.8.0)

@@ -443,13 +443,13 @@
- - - - - + + + + + diff --git a/site/quant/quant-app.js b/site/quant/quant-app.js index 67b8ac8..ad32f8e 100644 --- a/site/quant/quant-app.js +++ b/site/quant/quant-app.js @@ -1,5 +1,5 @@ // /workspace/hyperstitionstudio-core/site/quant/quant-app.js -// Interactive Quantitative Finance & Memetic Gematria Time-Series Workbench (v2.7.0) +// Interactive Quantitative Finance & Memetic Gematria Time-Series Workbench (v2.8.0) (function () { "use strict"; diff --git a/site/quant/quant-tutorials.js b/site/quant/quant-tutorials.js index 6c151d9..be4017a 100644 --- a/site/quant/quant-tutorials.js +++ b/site/quant/quant-tutorials.js @@ -1,5 +1,5 @@ // /workspace/hyperstitionstudio-core/site/quant/quant-tutorials.js -// Option B Zero-MP4 Interactive HTML5 Canvas Tutorial Player & Deep-Link Choreographer (v2.7.0) +// Option B Zero-MP4 Interactive HTML5 Canvas Tutorial Player & Deep-Link Choreographer (v2.8.0) (function () { "use strict"; @@ -633,7 +633,7 @@ } window.HyperstitionStudio.QuantTutorials = { - version: "2.7.0", + version: "2.8.0", episodes: EPISODES, adaptHrefForFileProtocol: adaptHrefForFileProtocol, init: initTutorials diff --git a/src/hyperstitionstud_io/__init__.py b/src/hyperstitionstud_io/__init__.py index 3c7a0d2..e1199c2 100644 --- a/src/hyperstitionstud_io/__init__.py +++ b/src/hyperstitionstud_io/__init__.py @@ -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" diff --git a/src/hyperstitionstud_io/db/sqlite_meta.py b/src/hyperstitionstud_io/db/sqlite_meta.py index 99f03c2..7ec0e9c 100644 --- a/src/hyperstitionstud_io/db/sqlite_meta.py +++ b/src/hyperstitionstud_io/db/sqlite_meta.py @@ -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 diff --git a/src/hyperstitionstud_io/mcp/rest.py b/src/hyperstitionstud_io/mcp/rest.py index 3ac8a18..f6cdff1 100644 --- a/src/hyperstitionstud_io/mcp/rest.py +++ b/src/hyperstitionstud_io/mcp/rest.py @@ -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 diff --git a/src/hyperstitionstud_io/mcp/server.py b/src/hyperstitionstud_io/mcp/server.py index d3af41a..7206842 100755 --- a/src/hyperstitionstud_io/mcp/server.py +++ b/src/hyperstitionstud_io/mcp/server.py @@ -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() diff --git a/src/hyperstitionstud_io/mcp/tools.py b/src/hyperstitionstud_io/mcp/tools.py index 45cffcc..3fa76d4 100644 --- a/src/hyperstitionstud_io/mcp/tools.py +++ b/src/hyperstitionstud_io/mcp/tools.py @@ -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 diff --git a/src/hyperstitionstud_io/publishing/engineering_docs.py b/src/hyperstitionstud_io/publishing/engineering_docs.py index 3150d07..82bbe4c 100644 --- a/src/hyperstitionstud_io/publishing/engineering_docs.py +++ b/src/hyperstitionstud_io/publishing/engineering_docs.py @@ -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('') links.append( - f'' + f'' 'DONATE' ) return "\n ".join(links) diff --git a/src/hyperstitionstud_io/publishing/highlights.py b/src/hyperstitionstud_io/publishing/highlights.py index c2d96f6..811b285 100644 --- a/src/hyperstitionstud_io/publishing/highlights.py +++ b/src/hyperstitionstud_io/publishing/highlights.py @@ -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"]) diff --git a/src/hyperstitionstud_io/publishing/math_docs.py b/src/hyperstitionstud_io/publishing/math_docs.py index 105333f..5fa3cda 100644 --- a/src/hyperstitionstud_io/publishing/math_docs.py +++ b/src/hyperstitionstud_io/publishing/math_docs.py @@ -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('') links.append( - f'' + f'' 'DONATE' ) return "\n ".join(links) diff --git a/src/hyperstitionstud_io/quant/collector.py b/src/hyperstitionstud_io/quant/collector.py index f955871..869e0c0 100755 --- a/src/hyperstitionstud_io/quant/collector.py +++ b/src/hyperstitionstud_io/quant/collector.py @@ -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, diff --git a/src/hyperstitionstud_io/version_sync.py b/src/hyperstitionstud_io/version_sync.py index 0eed75c..4c820fe 100755 --- a/src/hyperstitionstud_io/version_sync.py +++ b/src/hyperstitionstud_io/version_sync.py @@ -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)) diff --git a/tests/test_core_suite.py b/tests/test_core_suite.py index b0ede06..1adca37 100644 --- a/tests/test_core_suite.py +++ b/tests/test_core_suite.py @@ -542,6 +542,9 @@ def test_ipld_quant_and_mcp_server() -> None: summary_before = get_api_telemetry_summary(tel_db) assert summary_before["total_requests"] == 5 + assert summary_before["internal_test_requests"] == 5 + assert summary_before["external_production_requests"] == 0 + assert summary_before["market_demand_confidence"] == "No data available" assert summary_before["ringbuffer_count"] == 5 protocols_seen = {ep["protocol"] for ep in summary_before["endpoints"]} assert protocols_seen == {"rest_v1", "mcp_jsonrpc"} @@ -550,6 +553,7 @@ def test_ipld_quant_and_mcp_server() -> None: assert "/api/v1/quant/instruments/{symbol}" in patterns_seen assert "tools/list" in patterns_seen assert all(ev["isolation_ok"] == 1 for ev in summary_before["recent_audit_events"]) + assert all(ev["traffic_source"] == "internal_test" for ev in summary_before["recent_audit_events"]) # Verify logrotate.d file configuration (default 100M = 100MB, compress enabled, rotate >= 12) & no-op when below limit import gzip @@ -587,11 +591,43 @@ def test_ipld_quant_and_mcp_server() -> None: with sqlite3.connect(str(tel_db)) as check_conn: assert check_conn.execute("PRAGMA integrity_check;").fetchone()[0] == "ok" - s_post, _, _ = dispatch_rest_v1("GET", "/api/v1/status") + s_post, _, _ = dispatch_rest_v1( + "GET", + "/api/v1/status?surface=quant&donate_from=quant&donate_copy=BTC&export_action=quant_csv&free_text_ignored=secret123", + traffic_source="external_production", + ) assert s_post == 200 - assert get_api_telemetry_summary(tel_db)["total_requests"] == 1 + summary_ext = get_api_telemetry_summary(tel_db) + assert summary_ext["total_requests"] == 1 + assert summary_ext["external_production_requests"] == 1 + assert summary_ext["internal_test_requests"] == 0 + assert summary_ext["market_demand_confidence"] == "No data available" + assert summary_ext["recent_audit_events"][0]["traffic_source"] == "external_production" + param_map = {(r["param_category"], r["param_value"]): r["external_requests"] for r in summary_ext["parameter_rollups"]} + assert param_map.get(("surface", "quant")) == 1 + assert param_map.get(("donate_from", "quant")) == 1 + assert param_map.get(("donate_copy", "BTC")) == 1 + assert param_map.get(("export_action", "quant_csv")) == 1 + assert all(k[0] != "free_text_ignored" for k in param_map) - # Also verify second rotation shifts .1.gz -> .2.gz and writes new .1.gz + # Verify Strategy 3A (ingest_caddy_route_counts) & Strategy 2C (get_longitudinal_telemetry_summary) + from hyperstitionstud_io.db.sqlite_meta import ( + get_longitudinal_telemetry_summary, + ingest_caddy_route_counts, + ) + + sample_caddy_log = tmp_path / "sample-caddy-access.json" + sample_caddy_log.write_text( + '{"status":200,"request":{"uri":"/quant/index.html"}}\n' + '{"status":200,"request":{"uri":"/zoology/proposal-fund-manager-novel-investment-discovery.pdf"}}\n' + '{"status":304,"request":{"uri":"/"}}\n', + encoding="utf-8", + ) + c_ing = ingest_caddy_route_counts(sample_caddy_log, telemetry_db_path=tel_db) + assert c_ing["matched_hits"] == 3 + assert sample_caddy_log.read_text(encoding="utf-8") == "" + + # Also verify second rotation shifts .1.gz -> .2.gz and writes new .1.gz, and Strategy 2C aggregates across generations direct_trunc = truncate_telemetry_db_quiescent(tel_db, max_bytes=512, force=False) assert direct_trunc["truncated"] is True assert direct_trunc["quiescent"] is True @@ -599,6 +635,19 @@ def test_ipld_quant_and_mcp_server() -> None: assert Path(f"{tel_db}.1.gz").is_file() assert Path(f"{tel_db}.2.gz").is_file() + long_sum = get_longitudinal_telemetry_summary(tel_db) + assert long_sum["generations_count"] >= 2 + assert long_sum["total_requests"] == 6 + assert long_sum["external_production_requests"] == 1 + assert long_sum["internal_test_requests"] == 5 + + # Verify Strategy 1B (compute_corpus_delta_report / --corpus-delta) + from hyperstitionstud_io.publishing.highlights import compute_corpus_delta_report + + cdelta = compute_corpus_delta_report() + assert cdelta["llm_tokens_used"] == 0 + assert "deltas_since_baseline" in cdelta and "dossiers_count" in cdelta["deltas_since_baseline"] + # Verify regression guard: read-only / unwritable SQLite path (sqlite3.OperationalError) never causes 502/crash os.environ["HYPERSTITION_TELEMETRY_DB_PATH"] = "/sys/hyperstition-readonly-telemetry.db" ro_code, _, ro_body = dispatch_rest_v1("GET", "/api/v1/quant/timeseries?symbol=NVDA") diff --git a/workspace.example.toml b/workspace.example.toml index 68c8175..4f957db 100644 --- a/workspace.example.toml +++ b/workspace.example.toml @@ -1,6 +1,6 @@ # workspace.example.toml — Location-Independent Workspace Configuration Template (v1.2.0) # Copy to your parent workspace folder: cp hyperstitionstudio-core/workspace.example.toml ./workspace.toml -schema_version = "2.7.0" +schema_version = "2.8.0" namespace_urn = "urn:io:hyperstitionstud" [paths]