Compare commits

..
6 Commits
34 changed files with 30429 additions and 18926 deletions

No files matched your search

+4
View File
@@ -7,14 +7,18 @@ Before=caddy.service
[Service]
Type=simple
WorkingDirectory=/srv/hyperstitionstud.io/repos
StateDirectory=hyperstitionstud.io
Environment="HYPERSTITIONSTUDIO_CONFIG=/srv/hyperstitionstud.io/repos/workspace.toml"
Environment="PYTHONPATH=/srv/hyperstitionstud.io/repos/hyperstitionstudio-core/src"
Environment="HYPERSTITION_TELEMETRY_DB_PATH=/var/lib/hyperstitionstud.io/api-telemetry.db"
Environment="HYPERSTITION_SQLITE_MAX_MB=100"
ExecStart=/srv/hyperstitionstud.io/repos/.venv/bin/python3 /srv/hyperstitionstud.io/repos/hyperstitionstudio-core/src/hyperstitionstud_io/mcp/server.py --transport http --host 127.0.0.1 --port 8095
Restart=always
RestartSec=2
NoNewPrivileges=true
ProtectSystem=strict
ReadOnlyPaths=/srv/hyperstitionstud.io/repos
ReadWritePaths=/var/lib/hyperstitionstud.io
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,44 @@
# /etc/logrotate.d/hyperstition-sqlite-meta
# Quiescent size-based compression & truncation for the hyperstitionstud.io SQLite REST/MCP API metadata DB.
#
# Why quiescent snapshot compression + in-place SQLite truncation is used:
# Raw byte truncation (`copytruncate`) on a live SQLite `.db` or `-wal` file while readers or
# writers hold locks corrupts the SQLite B-tree page header and WAL frame index.
# Instead, `prerotate` invokes `hyperstitionstud_io.db.sqlite_meta --truncate-quiescent --compress-archive`, which:
# 1. Sets `PRAGMA busy_timeout = 30000` (waits up to 30s for in-flight requests to finish),
# 2. Flushes committed WAL frames via `PRAGMA wal_checkpoint(TRUNCATE)`,
# 3. Writes a consistent point-in-time SQLite snapshot and compresses it with `gzip -9`
# to `<db_path>.1.gz` (rotating `.1.gz` .. `.12.gz` rather than removing history),
# 4. Acquires `BEGIN EXCLUSIVE` to guarantee 100% SQLite reader/writer quiescence,
# purges the live telemetry tables, and commits cleanly,
# 5. Executes `PRAGMA wal_checkpoint(TRUNCATE)` + `VACUUM` + `PRAGMA optimize` on the live DB, and
# 6. Verifies `PRAGMA integrity_check == 'ok'` on the live DB.
#
# Configurable threshold:
# - Default logrotate trigger: `size 100M` (100 MB)
# - Runtime override: export `HYPERSTITION_SQLITE_MAX_MB` (default `100`) or `HYPERSTITION_SQLITE_MAX_BYTES`.
/var/lib/hyperstitionstud.io/api-telemetry.db {
size 100M
rotate 12
compress
delaycompress
missingok
notifempty
nocreate
sharedscripts
prerotate
TARGET_DB="${1:-${HYPERSTITION_TELEMETRY_DB_PATH:-/var/lib/hyperstitionstud.io/api-telemetry.db}}"
MAX_MB="${HYPERSTITION_SQLITE_MAX_MB:-100}"
MAX_BYTES="${HYPERSTITION_SQLITE_MAX_BYTES:-$((MAX_MB * 1024 * 1024))}"
ROTATE_KEEP="${HYPERSTITION_SQLITE_ROTATE_KEEP:-12}"
PYTHON_BIN="${HYPERSTITION_PYTHON_BIN:-python3}"
PYTHONPATH="${PYTHONPATH:-/srv/hyperstitionstud.io/repos/hyperstitionstudio-core/src:/workspace/hyperstitionstudio-core/src}" \
"${PYTHON_BIN}" -m hyperstitionstud_io.db.sqlite_meta \
--truncate-quiescent \
--compress-archive \
--rotate-keep "${ROTATE_KEEP}" \
--db "${TARGET_DB}" \
--max-bytes "${MAX_BYTES}"
endscript
}
+22 -3
View File
@@ -3,7 +3,8 @@
# Hydrates per-repository install directories from REPOS_ROOT into LIVE_REPOS (tmpfs RAM mount),
# supplies untracked haiperdohp-jemaytreeah/.gitignore files (config.js, db.json, db_lite.json),
# creates top-level route symlinks, pre-compresses (.br / .gz) static assets, and idempotently
# syncs/validates/reloads /etc/caddy/Caddyfile and systemd units by default (negated via --no-caddy).
# syncs/validates/reloads /etc/caddy/Caddyfile, systemd units, and /etc/logrotate.d/hyperstition-sqlite-meta
# by default (negated via --no-caddy).
#
# Usage:
# ./sync-vps-repos.sh [all|<repo-name>] [--no-pull] [--no-caddy|--no-services]
@@ -161,6 +162,7 @@ fi
${LIVE_SUDO} ln -sfn "hyperstitionstudio-core/site/index.html" "${LIVE_REPOS}/index.html"
${LIVE_SUDO} ln -sfn "hyperstitionstudio-core/site/learn" "${LIVE_REPOS}/learn"
${LIVE_SUDO} ln -sfn "hyperstitionstudio-core/site/quant" "${LIVE_REPOS}/quant"
${LIVE_SUDO} ln -sfn "hyperstitionstudio-core/site/donate" "${LIVE_REPOS}/donate"
# Note: /gallery is disabled for now (tracked as a long-term plan in docs/PLAN-MEMETIC-GALLERY-SUBPAGE.pdf)
${LIVE_SUDO} rm -rf "${LIVE_REPOS}/gallery" "${LIVE_REPOS}/hyperstitionstudio-core/site/gallery"
${LIVE_SUDO} ln -sfn "encyclopedia-knowledge-graph" "${LIVE_REPOS}/graph"
@@ -181,9 +183,24 @@ if [[ -n "$(type -P brotli || true)" ]]; then
-exec brotli -q 11 -k -f {} \;
fi
# Step 5: Idempotent systemd unit & /etc/caddy/Caddyfile synchronization (enabled by default; skip with --no-caddy)
# Step 5: Idempotent systemd unit, logrotate.d & /etc/caddy/Caddyfile synchronization (enabled by default; skip with --no-caddy)
if [[ "${DO_CADDY}" -eq 1 ]]; then
DEPLOY_DIR="${REPOS_ROOT}/hyperstitionstudio-core/deploy"
if [[ -w "/var/lib" ]] || [[ -n "${SUDO}" ]]; then
run_checked "mkdir /var/lib/hyperstitionstud.io" ${SUDO} mkdir -p "/var/lib/hyperstitionstud.io"
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
if [[ -f "${DST_LOGROTATE}" ]] && cmp -s "${SRC_LOGROTATE}" "${DST_LOGROTATE}"; then
echo "[5/5] ${DST_LOGROTATE} is already identical to deploy/logrotate.d/hyperstition-sqlite-meta."
else
echo "[5/5] Installing quiescent SQLite logrotate rule to ${DST_LOGROTATE}..."
run_checked "copy hyperstition-sqlite-meta logrotate rule" ${SUDO} cp "${SRC_LOGROTATE}" "${DST_LOGROTATE}"
run_checked "chmod 0644 ${DST_LOGROTATE}" ${SUDO} chmod 0644 "${DST_LOGROTATE}"
fi
fi
if [[ -n "$(type -P systemctl || true)" ]] && [[ -d "/run/systemd/system" ]]; then
UNITS_CHANGED=0
for unit_name in "hyperstition-tmpfs-sync.service" "hyperstition-mcp.service"; do
@@ -202,8 +219,10 @@ if [[ "${DO_CADDY}" -eq 1 ]]; then
run_checked "systemctl enable hyperstition-tmpfs-sync.service" ${SUDO} systemctl enable hyperstition-tmpfs-sync.service
run_checked "systemctl enable --now hyperstition-mcp.service" ${SUDO} systemctl enable --now hyperstition-mcp.service
run_checked "systemctl restart hyperstition-mcp.service" ${SUDO} systemctl restart hyperstition-mcp.service
elif [[ -f "/etc/systemd/system/hyperstition-mcp.service" ]] && ! systemctl is-active --quiet hyperstition-mcp.service; then
elif [[ -f "/etc/systemd/system/hyperstition-mcp.service" ]]; then
echo "[5/5] Restarting hyperstition-mcp.service to load latest MCP & REST API v1 (/api/v1/*) modules..."
run_checked "systemctl enable --now hyperstition-mcp.service" ${SUDO} systemctl enable --now hyperstition-mcp.service
run_checked "systemctl restart hyperstition-mcp.service" ${SUDO} systemctl restart hyperstition-mcp.service
fi
fi
+27 -2
View File
@@ -28,7 +28,8 @@ trap cleanup EXIT
if [[ -z "${TARGET_BASE_URL}" ]]; then
export LIVE_REPOS="${LIVE_REPOS:-/tmp/hyperstition-live-repos}"
rm -rf "${LIVE_REPOS}"
export HYPERSTITION_TELEMETRY_DB_PATH="${HYPERSTITION_TELEMETRY_DB_PATH:-/tmp/hyperstition-deploy-test-telemetry.db}"
rm -rf "${LIVE_REPOS}" "${HYPERSTITION_TELEMETRY_DB_PATH}" "${HYPERSTITION_TELEMETRY_DB_PATH}-wal" "${HYPERSTITION_TELEMETRY_DB_PATH}-shm"
echo "[1/4] Hydrating per-repository webroot at ${LIVE_REPOS} via sync-vps-repos.sh --no-pull..."
"${SCRIPT_DIR}/sync-vps-repos.sh" --no-pull
@@ -51,12 +52,16 @@ fi
echo "[3/4] Verifying all active portal, /learn/, /quant/, graph, encyclopedia, haiperdohp-jemaytreeah (.gitignore artifacts), CI & schema routes against ${TARGET_BASE_URL}..."
ROUTES=(
"/"
"/donate/index.html"
"/learn/index.html"
"/learn/learn-app.js"
"/quant/index.html"
"/quant/quant-app.js"
"/quant/quant-tutorials.js"
"/quant/quant-timeseries-data.js"
"/quant/quant-timeseries.json"
"/quant/real-market-history.json"
"/quant/OPERATORS-MANUAL-QUANT-TIMESERIES-WORKBENCH.pdf"
"/graph/index.html"
"/graph/graph-data.js"
"/graph/encyclopedia-graph.json"
@@ -65,6 +70,8 @@ ROUTES=(
"/graph/docs/cross-repo-dependency-and-audit-flow-diagram.html"
"/graph/docs/cross-repo-dependency-and-audit-flow-diagram.pdf"
"/graph/docs/VPS-AND-GIT-OPERATOR-DEPLOYMENT-GUIDE.pdf"
"/graph/docs/PLAN-QUANT-INTERFACE-INFO-ICONS-AND-GLOSSARY-POPOVERS.pdf"
"/graph/docs/PLAN-LEXICAL-AND-ETYMOLOGICAL-SIMPLIFICATION.pdf"
"/graph/docs/PLAN-LLM-TOKEN-ECONOMIZER-AND-VARIANCE-ROUTING.pdf"
"/graph/docs/PLAN-LLM-TOKEN-ECONOMIZER-DATA-FIDELITY-AND-DEGRADATION-RISK-EVALUATION.pdf"
"/encyclopedia/00-index-and-ontological-atlas/00-master-encyclopedia-index-a-to-z.pdf"
@@ -120,7 +127,7 @@ fi
echo " [200 OK] POST ${MCP_URL} (JSON-RPC 2.0 tools/call hs_evaluate_aq_and_ingglish verified)"
echo "[4b/4] Verifying stateless REST API v1 & OpenAPI 3.1 endpoints (${API_V1_URL})..."
for api_sub in "/status" "/openapi.json" "/quant/instruments/NVDA" "/zoology/pokedex/NVDA"; do
for api_sub in "/status" "/openapi.json" "/quant/timeseries?symbol=NVDA" "/quant/instruments/NVDA" "/zoology/pokedex/NVDA" "/dossiers/71?highlight=envideea"; do
api_code="$(curl -s -o /dev/null -w "%{http_code}" "${API_V1_URL}${api_sub}")"
if [[ "${api_code}" != "200" ]]; then
echo " [FAIL ${api_code}] GET ${API_V1_URL}${api_sub}" >&2
@@ -129,4 +136,22 @@ for api_sub in "/status" "/openapi.json" "/quant/instruments/NVDA" "/zoology/pok
echo " [200 OK] GET ${API_V1_URL}${api_sub}"
done
if [[ -n "${HYPERSTITION_TELEMETRY_DB_PATH:-}" ]] && [[ -f "${LIVE_REPOS}/hyperstitionstudio-core/deploy/logrotate.d/hyperstition-sqlite-meta" ]]; then
echo "[4c/4] Verifying SQLite REST/MCP metadata DB population & quiescent logrotate.d compression + truncation..."
PYTHONPATH="${SCRIPT_DIR}/../src" python3 - <<'PY'
import os
from pathlib import Path
from hyperstitionstud_io.db.sqlite_meta import get_api_telemetry_summary, run_logrotate_directive
tel_db = Path(os.environ["HYPERSTITION_TELEMETRY_DB_PATH"])
conf_p = Path(os.environ["LIVE_REPOS"]) / "hyperstitionstudio-core" / "deploy" / "logrotate.d" / "hyperstition-sqlite-meta"
summary = get_api_telemetry_summary(tel_db)
assert summary["total_requests"] >= 5, f"Expected >= 5 recorded MCP/REST calls, got {summary['total_requests']}"
lr_out = run_logrotate_directive(conf_path=conf_p, telemetry_db_path=tel_db, max_bytes_override=1024)
assert lr_out["truncated"] is True and lr_out["quiescent"] is True and lr_out["integrity_check"] == "ok", lr_out
assert lr_out["compress_enabled"] is True and lr_out["compressed_archive_bytes"] > 0 and Path(lr_out["compressed_archive_path"]).is_file(), lr_out
print(f" [OK] SQLite metadata DB populated ({summary['total_requests']} calls), compressed to {Path(lr_out['compressed_archive_path']).name} ({lr_out['compressed_archive_bytes']} B) & quiescently truncated via {conf_p.name} (default {lr_out['configured_size_directive']}).")
PY
fi
echo "[OK] All ${PASS_COUNT}/${#ROUTES[@]} static routes + 2 MCP HTTP endpoints + 4 REST API v1 endpoints verified (HTTP 200 OK)."
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@hyperstitionstud.io/workspace-core",
"version": "2.0.18",
"version": "2.0.23",
"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",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@hyperstitionstud.io/ciphers-aq",
"version": "2.0.18",
"version": "2.0.23",
"type": "module",
"main": "index.js",
"license": "MIT"
+2 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "hyperstitionstudio-core"
version = "2.0.18"
version = "2.0.23"
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"
@@ -27,6 +27,7 @@ hs-kg-build = "hyperstitionstud_io.graph.cli:main"
hs-quant-harvest = "hyperstitionstud_io.quant.collector:main"
hs-mcp = "hyperstitionstud_io.mcp.server:main"
hs-sync-version = "hyperstitionstud_io.version_sync:main"
hs-db-build = "hyperstitionstud_io.db.sqlite_meta:main"
[tool.setuptools.packages.find]
where = ["src"]
+2 -2
View File
@@ -144,8 +144,8 @@ def main() -> int:
})
manifest = {
"version": "2.0.18",
"namespace_urn": "urn:io:hyperstitionstud:gallery:2.0.18",
"version": "2.0.23",
"namespace_urn": "urn:io:hyperstitionstud:gallery:2.0.23",
"total_items": len(items),
"items": items,
}
+645
View File
@@ -0,0 +1,645 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Signal Patronage &amp; Open-Instrument Notes — hyperstitionstud.io/donate</title>
<style>
:root {
--bg-canvas: #020617;
--bg-panel: #0f172a;
--bg-card: #1e293b;
--bg-deep: #090d16;
--border: #334155;
--text-main: #f8fafc;
--text-muted: #94a3b8;
--cyan: #22d3ee;
--red: #ff4d4d;
--gold: #f5c630;
--emerald: #34d399;
--violet: #a78bfa;
--rose: #fb7185;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
background: var(--bg-canvas);
color: var(--text-main);
font-family: 'DejaVu Sans Mono', 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
min-height: 100vh;
padding: 1.75rem 1.5rem;
line-height: 1.55;
}
.container {
max-width: 1220px;
margin: 0 auto;
display: flex;
flex-direction: column;
gap: 1.35rem;
}
header {
background: var(--bg-panel);
border: 1px solid var(--border);
border-left: 4px solid var(--gold);
border-radius: 10px;
padding: 1.25rem 1.5rem;
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 1rem;
}
.title-row { display: flex; align-items: center; gap: 0.7rem; }
.dot {
width: 11px;
height: 11px;
border-radius: 50%;
background: var(--gold);
box-shadow: 0 0 10px var(--gold);
}
h1 { font-size: 1.24rem; font-weight: 700; letter-spacing: -0.01em; }
.subtitle { font-size: 0.77rem; color: var(--text-muted); margin-top: 0.3rem; }
.top-nav {
margin-left: auto;
display: flex;
align-items: center;
justify-content: flex-end;
gap: 0.5rem;
flex-wrap: wrap;
}
.btn {
text-decoration: none;
background: var(--bg-card);
color: var(--text-main);
border: 1px solid var(--border);
border-radius: 5px;
padding: 0.42rem 0.78rem;
font-size: 0.74rem;
font-weight: 600;
font-family: inherit;
cursor: pointer;
transition: all 0.15s ease;
}
.btn:hover { border-color: var(--cyan); color: var(--cyan); }
.btn.primary { background: var(--cyan); color: #020617; border-color: var(--cyan); }
.hero-panel {
background: linear-gradient(145deg, #0f172a 0%, #131c33 100%);
border: 1px solid var(--border);
border-radius: 12px;
padding: 1.75rem 1.85rem;
display: grid;
grid-template-columns: 1fr auto;
align-items: center;
gap: 2rem;
}
@media (max-width: 900px) {
.hero-panel { grid-template-columns: 1fr; }
}
.hero-tag {
font-size: 0.72rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--gold);
margin-bottom: 0.5rem;
}
.hero-title {
font-size: 1.38rem;
font-weight: 700;
color: var(--text-main);
line-height: 1.35;
margin-bottom: 0.9rem;
}
.hero-copy {
display: flex;
flex-direction: column;
gap: 0.75rem;
font-size: 0.82rem;
color: #cbd5e1;
line-height: 1.65;
}
.hero-copy em { color: var(--cyan); font-style: normal; font-weight: 600; }
.hero-cta-col {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.65rem;
padding: 1.15rem 1.25rem;
background: rgba(9, 13, 22, 0.72);
border: 1px solid rgba(245, 198, 48, 0.35);
border-radius: 12px;
}
/* Prominent Tactile Vector Pill DONATE Button */
.tactile-donate-btn {
position: relative;
width: 260px;
height: 68px;
border-radius: 999px;
background: linear-gradient(180deg, #ffd86b 0%, #f59e0b 48%, #d97706 52%, #b45309 100%);
border: 3px solid #fde68a;
box-shadow:
inset 0 2px 3px rgba(255, 255, 255, 0.65),
0 6px 0 #78350f,
0 12px 24px rgba(245, 158, 11, 0.35);
display: inline-flex;
align-items: center;
gap: 0.85rem;
padding: 0 1.25rem 0 0.65rem;
text-decoration: none;
cursor: pointer;
user-select: none;
transition: transform 0.12s ease, box-shadow 0.12s ease, filter 0.12s ease;
overflow: hidden;
}
.tactile-donate-btn.centerpiece {
width: 280px;
height: 72px;
}
.tactile-donate-btn::before {
content: "";
position: absolute;
top: 2px;
left: 14px;
right: 14px;
height: 44%;
border-radius: 999px 999px 40% 40%;
background: linear-gradient(180deg, rgba(255, 255, 255, 0.42) 0%, rgba(255, 255, 255, 0.06) 100%);
pointer-events: none;
}
.tactile-donate-btn:hover {
filter: brightness(1.05);
transform: translateY(-1px);
box-shadow:
inset 0 2px 3px rgba(255, 255, 255, 0.72),
0 7px 0 #78350f,
0 14px 28px rgba(245, 158, 11, 0.45);
}
.tactile-donate-btn:active {
transform: translateY(3px);
box-shadow:
inset 0 2px 3px rgba(255, 255, 255, 0.45),
0 3px 0 #78350f,
0 6px 14px rgba(245, 158, 11, 0.3);
}
.tactile-emblem {
width: 44px;
height: 44px;
border-radius: 50%;
background: radial-gradient(circle at 32% 30%, #1e293b 0%, #020617 85%);
border: 2px solid #fde68a;
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.75), 0 1px 2px rgba(255, 255, 255, 0.35);
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
z-index: 1;
}
.tactile-label-group {
display: flex;
flex-direction: column;
align-items: flex-start;
z-index: 1;
}
.tactile-main-label {
font-size: 1.22rem;
font-weight: 800;
letter-spacing: 0.08em;
color: #020617;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.48);
line-height: 1.1;
}
.tactile-sub-label {
font-size: 0.62rem;
font-weight: 700;
letter-spacing: 0.06em;
color: #1e293b;
text-transform: uppercase;
margin-top: 0.12rem;
}
.questions-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(340px, 1fr));
gap: 1.15rem;
}
.panel {
background: var(--bg-panel);
border: 1px solid var(--border);
border-radius: 10px;
padding: 1.35rem 1.45rem;
display: flex;
flex-direction: column;
gap: 0.7rem;
}
.q-tag {
font-size: 0.7rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.06em;
}
.panel h2 { font-size: 1.02rem; font-weight: 700; color: var(--text-main); }
.panel p { font-size: 0.79rem; color: var(--text-muted); line-height: 1.6; }
.sandbox-card {
background: var(--bg-panel);
border: 1px solid var(--cyan);
border-radius: 10px;
padding: 1.4rem 1.5rem;
display: flex;
flex-direction: column;
gap: 0.9rem;
}
.pill-row { display: flex; flex-wrap: wrap; gap: 0.5rem; }
.story-pill {
background: var(--bg-deep);
color: var(--cyan);
border: 1px solid var(--border);
border-radius: 999px;
padding: 0.35rem 0.85rem;
font-size: 0.73rem;
font-family: inherit;
font-weight: 600;
cursor: pointer;
transition: all 0.15s ease;
}
.story-pill:hover, .story-pill.active {
background: var(--cyan);
color: #020617;
border-color: var(--cyan);
}
.sandbox-inputs {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.75rem;
}
@media (max-width: 720px) {
.sandbox-inputs { grid-template-columns: 1fr; }
}
.inp-group { display: flex; flex-direction: column; gap: 0.3rem; font-size: 0.73rem; color: var(--text-muted); }
.inp {
background: var(--bg-deep);
color: var(--text-main);
border: 1px solid var(--border);
border-radius: 6px;
padding: 0.5rem 0.75rem;
font-family: inherit;
font-size: 0.8rem;
}
.sandbox-readout {
background: var(--bg-deep);
border: 1px solid var(--border);
border-left: 4px solid var(--emerald);
border-radius: 6px;
padding: 0.85rem 1rem;
font-size: 0.78rem;
color: var(--text-main);
white-space: pre-wrap;
}
.channels-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
gap: 0.9rem;
margin-top: 0.4rem;
}
.channel-card {
background: var(--bg-deep);
border: 1px solid var(--border);
border-radius: 8px;
padding: 0.95rem 1.05rem;
display: flex;
flex-direction: column;
justify-content: space-between;
gap: 0.65rem;
}
.channel-card.selected {
border-color: var(--gold);
box-shadow: 0 0 12px rgba(245, 198, 48, 0.18);
}
.addr-box {
background: #020617;
border: 1px solid var(--border);
border-radius: 4px;
padding: 0.4rem 0.55rem;
font-size: 0.69rem;
color: var(--cyan);
word-break: break-all;
}
footer {
margin-top: 0.75rem;
text-align: center;
font-size: 0.73rem;
color: var(--text-muted);
border-top: 1px solid var(--border);
padding-top: 1rem;
display: flex;
flex-direction: column;
gap: 0.3rem;
}
</style>
</head>
<body>
<div class="container">
<header>
<div>
<div class="title-row">
<span class="dot"></span>
<h1>hyperstitionstud.io/donate — Signal Patronage &amp; Open-Instrument Notes</h1>
</div>
<p class="subtitle">Open-Readout Phonemic, Graph &amp; Closing-Bell Telemetry Workbench &bull; Namespace Authority: urn:io:hyperstitionstud:donate:v2.0.23</p>
</div>
<nav class="top-nav">
<a class="btn" data-donate-route="home" href="/">Portal Home (/)</a>
<a class="btn" data-donate-route="quant" href="/quant/index.html">Time-Series (/quant/)</a>
<a class="btn" data-donate-route="graph" href="/graph/index.html">Knowledge Graph (/graph/)</a>
<a class="btn" data-donate-route="learn" href="/learn/index.html">Learning Track (/learn/)</a>
<a class="btn" data-donate-route="calc" href="/calc/index.html">Calculator (/calc/)</a>
</nav>
</header>
<!-- HERO ESSAY & PROMINENT TACTILE VECTOR DONATE BUTTON -->
<section class="hero-panel">
<div>
<div class="hero-tag">Open-Instrument Field Notes // Signal &amp; Circuitry</div>
<h2 class="hero-title">What If Language, Market Tape, and Breaking News Are Dials on the Same Circuit?</h2>
<div class="hero-copy">
<p>Spend ten minutes exploring the Knowledge Graph, the calculator, or the closing-bell timeline, and you will run into something that makes you pause.</p>
<p>Strip away the silent letters of standard English, and <em>synthetic data</em> and <em>abstract machine</em> land on the exact same coordinate as written <em>asset management</em>. Follow the fault lines of a market selloff, and <em>Dario Amodei</em>, <em>Anthropic</em>, and <em>flash crash</em> lock together across written and spoken scripts&mdash;or a trillion-dollar chipmaker closes at the exact dollar price of its own phonemic name on the night it leads the global news wire.</p>
<p>Most instruments are built to smooth those anomalies away&mdash;to sort the world into tidy, separate compartments where linguistics stays in one room, supply-chain bottlenecks stay in another, and market prices stay in a third.</p>
<p><code>hyperstitionstud.io</code> was built to see what happens when you wire those rooms together. Every evening at the US market close and the midnight UTC news rollover, our collectors harvest live headlines and core technocapital tickers, decode them into spoken phonemes, and map where the circuits cross&mdash;leaving the cover off the machine so anyone curious enough can trace the signal for themselves.</p>
</div>
</div>
<div class="hero-cta-col">
<a class="tactile-donate-btn" href="#fuel-channels" id="heroDonateBtn" aria-label="Donate and jump to contribution channels">
<span class="tactile-emblem" aria-hidden="true">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
<circle cx="12" cy="12" r="10" stroke="#f5c630" stroke-width="1.5" stroke-dasharray="3 2" />
<path d="M12 17.8C12 17.8 6.5 14.2 6.5 10.1C6.5 8.2 8.0 6.8 9.8 6.8C10.9 6.8 11.6 7.4 12 8.1C12.4 7.4 13.1 6.8 14.2 6.8C16.0 6.8 17.5 8.2 17.5 10.1C17.5 14.2 12 17.8 12 17.8Z" fill="#fb7185" stroke="#fde68a" stroke-width="1.2" />
</svg>
</span>
<span class="tactile-label-group">
<span class="tactile-main-label">DONATE &#x2197;</span>
<span class="tactile-sub-label">Toss Fuel in the Reactor</span>
</span>
</a>
<span style="font-size:0.7rem;color:var(--text-muted);text-align:center;">100% Open Readout &bull; Zero Trackers</span>
</div>
</section>
<!-- SECTION 1: THREE QUESTIONS THAT KEEP THIS WORKBENCH RUNNING -->
<section class="questions-grid" aria-label="Three Questions That Keep This Workbench Running">
<article class="panel">
<span class="q-tag" style="color:var(--cyan);">01 // The Ghost in the Spelling</span>
<h2>What is English hiding inside its spelling?</h2>
<p>Written English is an archaeological dig. Every word carries centuries of silent letters, borrowed scribal habits, and visual camouflage. When you decode a sentence into pure spoken sound&mdash;one spelling per phoneme&mdash;the camouflage drops away. Concepts that look miles apart in a press release or an earnings report suddenly collapse onto the exact same coordinate. Is that just a quirk of information compression, or is language acting like a low-level routing protocol for how culture and capital organize themselves? We&rsquo;d rather measure it than guess.</p>
</article>
<article class="panel">
<span class="q-tag" style="color:var(--gold);">02 // The Load-Bearing Chokepoints</span>
<h2>Where are the quiet walls that never move?</h2>
<p>Every technology boom is loud at the edges and silent at the center. Dozens of labs race to build the flashiest model or the fastest trading desk, while the entire spectacle quietly funnels through a handful of physical and legal bottlenecks&mdash;a single extreme-ultraviolet laser builder, a single wafer foundry, a corporate charter, a power grid. In our tables, certain words refuse to drift by a single point between how they are written on paper and how they sound out loud. Watching how the noisy stories orbit those fixed points tells you a lot about where leverage actually sits.</p>
</article>
<article class="panel">
<span class="q-tag" style="color:var(--emerald);">03 // The Discipline of the Room</span>
<h2>What happens when you outlaw dictionary fishing?</h2>
<p>Numerology gets a bad reputation for a simple reason: if you let yourself rummage through a 200,000-word dictionary after the fact, you can connect any number to anything. That&rsquo;s a parlor trick. So we enforce a stricter rule: <em>stay in the room</em>. Only evaluate the words, people, and prices that actually showed up together in the same day&rsquo;s news wire, the same supply chain, or the same closing bell. When the locks still fire under that constraint, the question stops being &ldquo;can you find a pattern?&rdquo; and becomes &ldquo;why did these specific pieces fall into place at the same time?&rdquo;</p>
</article>
</section>
<!-- SECTION 2: TRY A WIRE EXPERIMENT (INTERACTIVE CURIOSITY SANDBOX) -->
<section class="sandbox-card" aria-label="Interactive Curiosity Sandbox">
<div>
<div class="q-tag" style="color:var(--cyan);">04 // Interactive Curiosity Sandbox</div>
<h2 style="font-size:1.06rem;margin-top:0.2rem;">Try a Wire Experiment: Watch Silent Letters Drop Away</h2>
<p style="font-size:0.78rem;color:var(--text-muted);margin-top:0.25rem;">Click a live collision below&mdash;or type two terms of your own&mdash;to see how standard written spelling (<code>Gen 0</code>) and pure spoken sound (<code>Gen 1 Ingglish</code>) score in Base-36 Alphanumeric Qabbala (<code>0&ndash;9 = 0..9, A&ndash;Z = 10..35</code>):</p>
</div>
<div class="pill-row" id="curiosityPills">
<button type="button" class="story-pill active" data-a="Anthropic" data-b="flash crash" data-note="Both spoken forms ('anthropik' and 'flash krash') lock onto 193 (the 44th prime)—matching written 'Dario Amodei' (193).">The Founder &amp; The Flash Crash (193)</button>
<button type="button" class="story-pill" data-a="synthetic data" data-b="abstract machine" data-note="Separated by 41 points in written English (276 vs. 317), both collapse onto 292 in spoken sound—the exact written coordinate of 'asset management' (292).">Synthetic Data &amp; Abstract Machine (292)</button>
<button type="button" class="story-pill" data-a="ASML" data-b="asset" data-note="'ASML' (81) is an isometric lithography chokepoint (Δ = 0) that locks directly onto spoken 'asat' (81) and '+81 bps' closing-bell moves.">The Chip Laser &amp; The Balance Sheet (81)</button>
<button type="button" class="story-pill" data-a="capital" data-b="capture" data-note="'capital' -> 'kapatal' (125, Δ = 0 isometric anchor) and 'capture' -> 'kapcher' (125) converge on the core S6 coordinate 125.">Capital &amp; Capture (125)</button>
</div>
<div class="sandbox-inputs">
<label class="inp-group">Term A (Written English):
<input class="inp" id="expInputA" type="text" value="Anthropic" />
</label>
<label class="inp-group">Term B (Written English):
<input class="inp" id="expInputB" type="text" value="flash crash" />
</label>
</div>
<div class="sandbox-readout" id="expReadout"></div>
</section>
<!-- SECTION 3: BACKING THE SIGNAL -->
<section class="panel">
<span class="q-tag" style="color:var(--violet);">05 // Backing the Signal</span>
<h2>Where Patronage Goes</h2>
<p>Every tool on <code>hyperstitionstud.io</code>&mdash;the 388-node property graph, the 22-volume encyclopedia, the multi-cipher calculator, the closing-bell time-series workbench, and the public API&mdash;is open, downloadable for offline travel, and built to show you the raw readout so you can test your own hypotheses.</p>
<p>Patronage directly fuels the next layer of the instrument: keeping the public HTTP/3 relays fast, expanding the daily midnight wire and closing-bell harvests, synthesizing new full-length episodes of <em>The Encyclopedia Expeditions</em>, and charting new divisions of the archive.</p>
<p>If a lock, a dossier, or an hour spent exploring the graph sparked a new line of thought, you can toss fuel into the reactor via the button or addresses below&mdash;or fork the repositories on <code>git.libre.audio</code> and build an instrument of your own.</p>
</section>
<!-- SECTION 4: FUEL THE REACTOR (DIRECT CONTRIBUTION CHANNELS) -->
<section class="panel" id="fuel-channels">
<div style="display:flex;flex-direction:column;align-items:center;gap:0.65rem;padding:0.6rem 0 0.9rem;border-bottom:1px solid var(--border);">
<span class="q-tag" style="color:var(--gold);">06 // Fuel the Reactor &bull; Direct Contribution Channels</span>
<button type="button" class="tactile-donate-btn centerpiece" id="primaryDonateActionBtn">
<span class="tactile-emblem" aria-hidden="true">
<svg width="26" height="26" viewBox="0 0 24 24" fill="none">
<circle cx="12" cy="12" r="10" stroke="#f5c630" stroke-width="1.5" stroke-dasharray="3 2" />
<path d="M12 17.8C12 17.8 6.5 14.2 6.5 10.1C6.5 8.2 8.0 6.8 9.8 6.8C10.9 6.8 11.6 7.4 12 8.1C12.4 7.4 13.1 6.8 14.2 6.8C16.0 6.8 17.5 8.2 17.5 10.1C17.5 14.2 12 17.8 12 17.8Z" fill="#fb7185" stroke="#fde68a" stroke-width="1.2" />
</svg>
</span>
<span class="tactile-label-group">
<span class="tactile-main-label">DONATE</span>
<span class="tactile-sub-label" id="primaryDonateSubLabel">Copy Active Channel (BTC)</span>
</span>
</button>
<div id="copyFeedbackBanner" style="font-size:0.75rem;color:var(--emerald);min-height:1.15rem;">Select any channel card below or click the DONATE button to copy its address.</div>
</div>
<div class="channels-grid" id="channelCardsGrid">
<div class="channel-card selected" data-channel="BTC" data-addr="bc1qcgkpl0j2ayxd68haeutfvarjgla2lmz30yd23e">
<div>
<div style="display:flex;justify-content:space-between;align-items:center;">
<strong style="color:var(--gold);font-size:0.84rem;">Bitcoin (BTC // Layer-1)</strong>
<span style="font-size:0.68rem;color:var(--text-muted);">AQ(bitcoin) = 152</span>
</div>
<p style="font-size:0.72rem;margin-top:0.25rem;">Direct sovereign settlement for daily wire &amp; closing-bell telemetry harvests.</p>
</div>
<div class="addr-box">bc1qcgkpl0j2ayxd68haeutfvarjgla2lmz30yd23e</div>
<button type="button" class="btn copy-channel-btn" data-channel="BTC" data-addr="bc1qcgkpl0j2ayxd68haeutfvarjgla2lmz30yd23e">Copy BTC Address</button>
</div>
<div class="channel-card" data-channel="XMR" data-addr="83ZCDY7YpUHJRwwj4ETL2THYYWVxWti6sbyxvdJ7kGBoWyKR2Wt4of6YyFjmjZqJCjYSwKdWkBK36dhsNzrnwbnvMajDaEJ">
<div>
<div style="display:flex;justify-content:space-between;align-items:center;">
<strong style="color:var(--rose);font-size:0.84rem;">Monero (XMR // Zero-Trace)</strong>
<span style="font-size:0.68rem;color:var(--text-muted);">44th Prime (193)</span>
</div>
<p style="font-size:0.72rem;margin-top:0.25rem;">Zero-metadata shielded patronage aligned with our zero-tracker architecture.</p>
</div>
<div class="addr-box">83ZCDY7YpUHJRwwj4ETL2THYYWVxWti6sbyxvdJ7kGBoWyKR2Wt4of6YyFjmjZqJCjYSwKdWkBK36dhsNzrnwbnvMajDaEJ</div>
<button type="button" class="btn copy-channel-btn" data-channel="XMR" data-addr="83ZCDY7YpUHJRwwj4ETL2THYYWVxWti6sbyxvdJ7kGBoWyKR2Wt4of6YyFjmjZqJCjYSwKdWkBK36dhsNzrnwbnvMajDaEJ">Copy XMR Address</button>
</div>
</div>
<div style="display:flex;flex-wrap:wrap;gap:0.55rem;justify-content:center;padding-top:0.65rem;">
<a class="btn primary" data-donate-route="quant" href="/quant/index.html">Explore Closing-Bell Time-Series (/quant/)</a>
<a class="btn" data-donate-route="graph" href="/graph/index.html">Trace Bridges in Knowledge Graph (/graph/)</a>
<a class="btn" data-donate-route="calc" href="/calc/index.html">Test Hypotheses in Calculator (/calc/)</a>
<a class="btn" href="https://git.libre.audio/seasharp" target="_blank" rel="noopener noreferrer">Fork Repositories on git.libre.audio &#x2197;</a>
</div>
</section>
<footer>
<div>hyperstitionstud.io/donate v2.0.23 &bull; 100% Static &amp; Offline-Portable &bull; Zero External Trackers</div>
<div class="hs-lemur-credit">Made with <span class="hs-heart" role="img" aria-label="love" style="color:var(--rose);display:inline-block;padding:0 2px;">&#x2665;</span> by Lemurs.</div>
</footer>
</div>
<script>
(function () {
"use strict";
if (window.location.protocol === "file:") {
const routeMap = {
"home": "../index.html",
"quant": "../quant/index.html",
"learn": "../learn/index.html",
"graph": "../../../encyclopedia-knowledge-graph/index.html",
"calc": "../../../haiperdohp-jemaytreeah/index.html"
};
document.querySelectorAll("[data-donate-route]").forEach(function (a) {
const k = a.getAttribute("data-donate-route");
if (routeMap[k]) a.setAttribute("href", routeMap[k]);
});
}
const PHONEMIC_MAP = {
"anthropic": "anthropik",
"flash crash": "flash krash",
"dario amodei": "dario amodei",
"synthetic data": "sinthetik dayta",
"abstract machine": "abstrakt masheen",
"schizoanalysis": "shizohnalizis",
"asset management": "asat manajmant",
"asml": "asml",
"asset": "asat",
"capital": "kapatal",
"capture": "kapcher",
"folds": "fohldz",
"nvidia": "envideea",
"halts": "hawlts",
"inertia": "inersha",
"blackwell": "blakwel",
"charter": "charter",
"sloth": "slawth"
};
function toIngglishApprox(str) {
const key = (str || "").trim().toLowerCase();
if (PHONEMIC_MAP[key]) return PHONEMIC_MAP[key];
return key
.replace(/ph/g, "f")
.replace(/ght/g, "t")
.replace(/kn/g, "n")
.replace(/wr/g, "r")
.replace(/ck/g, "k")
.replace(/qu/g, "kw")
.replace(/c(?=[eiy])/g, "s")
.replace(/c/g, "k");
}
function computeAQ(str) {
const s = (str || "").toUpperCase();
let sum = 0;
for (let i = 0; i < s.length; i++) {
const c = s.charCodeAt(i);
if (c >= 48 && c <= 57) sum += (c - 48);
else if (c >= 65 && c <= 90) sum += (c - 55);
}
return sum;
}
const inpA = document.getElementById("expInputA");
const inpB = document.getElementById("expInputB");
const readout = document.getElementById("expReadout");
let activeNote = "Both spoken forms ('anthropik' and 'flash krash') lock onto 193 (the 44th prime)—matching written 'Dario Amodei' (193).";
function updateSandbox() {
const rawA = inpA.value.trim() || "Anthropic";
const rawB = inpB.value.trim() || "flash crash";
const ingA = toIngglishApprox(rawA);
const ingB = toIngglishApprox(rawB);
const engAqA = computeAQ(rawA);
const engAqB = computeAQ(rawB);
const ingAqA = computeAQ(ingA);
const ingAqB = computeAQ(ingB);
const writtenDelta = Math.abs(engAqA - engAqB);
const spokenDelta = Math.abs(ingAqA - ingAqB);
const statusLine = spokenDelta === 0
? `EXACT SPOKEN LOCK AT COORDINATE ${ingAqA} (Written gap of ${writtenDelta} pts collapses to 0 in spoken sound!)`
: `Written Gap: |${engAqA} - ${engAqB}| = ${writtenDelta} pts | Spoken Gap: |${ingAqA} - ${ingAqB}| = ${spokenDelta} pts`;
readout.textContent =
`Term A: "${rawA}" (Written AQ = ${engAqA}) --> Spoken Ingglish: "${ingA}" (Spoken AQ = ${ingAqA}, Δ = ${ingAqA - engAqA})\n` +
`Term B: "${rawB}" (Written AQ = ${engAqB}) --> Spoken Ingglish: "${ingB}" (Spoken AQ = ${ingAqB}, Δ = ${ingAqB - engAqB})\n` +
`Result: ${statusLine}\n` +
(activeNote ? `Note: ${activeNote}` : "");
}
document.querySelectorAll(".story-pill").forEach(function (btn) {
btn.addEventListener("click", function () {
document.querySelectorAll(".story-pill").forEach(function (b) { b.classList.remove("active"); });
btn.classList.add("active");
inpA.value = btn.getAttribute("data-a") || "";
inpB.value = btn.getAttribute("data-b") || "";
activeNote = btn.getAttribute("data-note") || "";
updateSandbox();
});
});
inpA.addEventListener("input", function () { activeNote = ""; updateSandbox(); });
inpB.addEventListener("input", function () { activeNote = ""; updateSandbox(); });
updateSandbox();
// Channel selection & one-click copy
let selectedChannel = "BTC";
let selectedAddr = "bc1qcgkpl0j2ayxd68haeutfvarjgla2lmz30yd23e";
const subLbl = document.getElementById("primaryDonateSubLabel");
const feedback = document.getElementById("copyFeedbackBanner");
function copyAddress(channel, addr) {
selectedChannel = channel;
selectedAddr = addr;
document.querySelectorAll(".channel-card").forEach(function (card) {
card.classList.toggle("selected", card.getAttribute("data-channel") === channel);
});
if (subLbl) subLbl.textContent = `Copy Active Channel (${channel})`;
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(addr).catch(function () {});
}
if (feedback) {
feedback.textContent = `[COPIED ${channel}] ${addr} — Ready to paste in your wallet.`;
}
}
document.querySelectorAll(".copy-channel-btn").forEach(function (btn) {
btn.addEventListener("click", function () {
copyAddress(btn.getAttribute("data-channel"), btn.getAttribute("data-addr"));
});
});
document.querySelectorAll(".channel-card").forEach(function (card) {
card.addEventListener("click", function (e) {
if (e.target.tagName === "BUTTON") return;
copyAddress(card.getAttribute("data-channel"), card.getAttribute("data-addr"));
});
});
const primaryBtn = document.getElementById("primaryDonateActionBtn");
if (primaryBtn) {
primaryBtn.addEventListener("click", function () {
copyAddress(selectedChannel, selectedAddr);
});
}
})();
</script>
</body>
</html>
+1 -1
View File
@@ -217,7 +217,7 @@
<main class="gallery-grid" id="galleryGrid"></main>
<footer>
<div>hyperstitionstud.io/gallery &bull; Powered by hyperstitionstudio-core (urn:io:hyperstitionstud:gallery:2.0.18)</div>
<div>hyperstitionstud.io/gallery &bull; Powered by hyperstitionstudio-core (urn:io:hyperstitionstud:gallery:2.0.23)</div>
<div class="hs-lemur-credit">Made with <span class="hs-heart" role="img" aria-label="love">&#x2665;</span> by Lemurs.</div>
</footer>
</div>
+65 -3
View File
@@ -52,7 +52,66 @@
}
h1 { font-size: 1.35rem; font-weight: 700; letter-spacing: -0.02em; }
.subtitle { color: var(--text-muted); font-size: 0.8rem; margin-top: 0.35rem; }
.meta-badges { display: flex; gap: 0.5rem; flex-wrap: wrap; }
.meta-badges {
margin-left: auto;
display: flex;
align-items: center;
justify-content: flex-end;
gap: 0.5rem;
flex-wrap: wrap;
}
.nav-donate-sep {
width: 1px;
height: 20px;
background: var(--border);
margin: 0 0.2rem;
display: inline-block;
flex-shrink: 0;
}
.btn-donate-pill {
height: 34px;
border-radius: 999px;
padding: 0.28rem 0.9rem 0.28rem 0.35rem;
background: linear-gradient(180deg, #ffd86b 0%, #f59e0b 52%, #d97706 100%);
color: #020617;
border: 1px solid #f5c630;
box-shadow: inset 0 1px 1px rgba(255, 255, 255, 0.55), 0 2px 8px rgba(245, 158, 11, 0.22);
display: inline-flex;
align-items: center;
gap: 0.45rem;
font-size: 0.74rem;
font-weight: 700;
letter-spacing: 0.05em;
text-decoration: none;
flex-shrink: 0;
transition: transform 0.15s ease, box-shadow 0.15s ease, filter 0.15s ease;
}
.btn-donate-pill:hover {
filter: brightness(1.06);
transform: translateY(-1px);
box-shadow: inset 0 1px 1px rgba(255, 255, 255, 0.65), 0 4px 12px rgba(245, 158, 11, 0.32);
color: #020617;
}
.donate-pill-emblem {
width: 20px;
height: 20px;
border-radius: 50%;
background: #0f172a;
color: var(--rose);
border: 1px solid rgba(245, 198, 48, 0.7);
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 0.68rem;
line-height: 1;
flex-shrink: 0;
}
@media (max-width: 1120px) {
.meta-badges {
margin-left: auto;
justify-content: flex-end;
}
}
.badge {
background: var(--bg-card);
border: 1px solid var(--border);
@@ -131,7 +190,7 @@
<span class="dot"></span>
<h1>HYPERSTITIONSTUD.IO // TECHNOCAPITAL SINGULARITY ZOOLOGY WORKBENCH</h1>
</div>
<p class="subtitle">100% Offline-Portable &amp; HTTP/3 Edge-Ready Research Corpus &bull; Namespace Authority: urn:io:hyperstitionstud (v2.0.18)</p>
<p class="subtitle">100% Offline-Portable &amp; HTTP/3 Edge-Ready Research Corpus &bull; Namespace Authority: urn:io:hyperstitionstud (v2.0.23)</p>
</div>
<div class="meta-badges">
<a class="btn primary" data-route="learn-track" href="/learn/index.html" style="padding:0.35rem 0.75rem;font-size:0.74rem;">Start Learning Track (/learn/)</a>
@@ -139,6 +198,8 @@
<span class="badge">388 Graph Nodes</span>
<span class="badge">1,282 Typed Edges</span>
<span class="badge">24 Quant Tickers</span>
<span class="nav-donate-sep" aria-hidden="true"></span>
<a class="btn-donate-pill" data-route="donate-page" href="/donate/index.html" title="Signal Patronage &amp; Open-Instrument Notes (/donate/)"><span class="donate-pill-emblem" aria-hidden="true">&#x2665;</span><span>DONATE</span></a>
</div>
</header>
@@ -254,7 +315,7 @@
</main>
<footer>
<div>hyperstitionstud.io &bull; Powered by hyperstitionstudio-core (hyperstitionstud_io.* / urn:io:hyperstitionstud v2.0.18) &bull; Zero External Network Dependencies</div>
<div>hyperstitionstud.io &bull; Powered by hyperstitionstudio-core (hyperstitionstud_io.* / urn:io:hyperstitionstud v2.0.23) &bull; Zero External Network Dependencies</div>
<div class="hs-lemur-credit" style="margin-top:0.35rem;color:var(--text-muted);font-size:0.75rem;">Made with <span class="hs-heart" role="img" aria-label="love" style="color:var(--rose);display:inline-block;padding:0 2px;">&#x2665;</span> by Lemurs.</div>
</footer>
</div>
@@ -266,6 +327,7 @@
const map = {
"learn-track": "./learn/index.html",
"quant-app": "./quant/index.html",
"donate-page": "./donate/index.html",
"meme-gallery": "./gallery/index.html",
"graph-index": "../../encyclopedia-knowledge-graph/index.html",
"graph-manual": "../../encyclopedia-knowledge-graph/OPERATORS-MANUAL-ENCYCLOPEDIA-KNOWLEDGE-GRAPH.pdf",
+40 -3
View File
@@ -44,7 +44,41 @@
}
h1 { font-size: 1.25rem; font-weight: 700; }
.subtitle { font-size: 0.78rem; color: var(--text-muted); margin-top: 0.25rem; }
.top-nav { display: flex; gap: 0.5rem; flex-wrap: wrap; }
.top-nav { margin-left: auto; display: flex; gap: 0.5rem; flex-wrap: wrap; align-items: center; justify-content: flex-end; }
.nav-donate-sep { width: 1px; height: 20px; background: var(--border); margin: 0 0.2rem; display: inline-block; flex-shrink: 0; }
.btn-donate-pill {
height: 34px;
border-radius: 999px;
padding: 0.28rem 0.9rem 0.28rem 0.35rem;
background: linear-gradient(180deg, #ffd86b 0%, #f59e0b 52%, #d97706 100%);
color: #020617;
border: 1px solid #f5c630;
box-shadow: inset 0 1px 1px rgba(255, 255, 255, 0.55), 0 2px 8px rgba(245, 158, 11, 0.22);
display: inline-flex;
align-items: center;
gap: 0.45rem;
font-size: 0.74rem;
font-weight: 700;
letter-spacing: 0.05em;
text-decoration: none;
flex-shrink: 0;
transition: transform 0.15s ease, box-shadow 0.15s ease, filter 0.15s ease;
}
.btn-donate-pill:hover { filter: brightness(1.06); transform: translateY(-1px); color: #020617; }
.donate-pill-emblem {
width: 20px;
height: 20px;
border-radius: 50%;
background: #0f172a;
color: var(--rose);
border: 1px solid rgba(245, 198, 48, 0.7);
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 0.68rem;
line-height: 1;
flex-shrink: 0;
}
.btn {
text-decoration: none;
background: var(--bg-card);
@@ -215,8 +249,11 @@
</div>
<nav class="top-nav">
<a class="btn" data-learn-route="nav-home" href="../index.html">&larr; Portal Home</a>
<a class="btn" data-learn-route="nav-quant" href="/quant/index.html">Time-Series (/quant/)</a>
<a class="btn" data-learn-route="nav-graph" href="/graph/index.html">Knowledge Graph</a>
<a class="btn" data-learn-route="nav-calc" href="/calc/index.html">AQ Calculator</a>
<span class="nav-donate-sep" aria-hidden="true"></span>
<a class="btn-donate-pill" data-learn-route="nav-donate" href="/donate/index.html" title="Signal Patronage &amp; Open-Instrument Notes (/donate/)"><span class="donate-pill-emblem" aria-hidden="true">&#x2665;</span><span>DONATE</span></a>
</nav>
</header>
@@ -238,7 +275,7 @@
<option value="replace">Upload Mode: Replace State</option>
<option value="merge">Upload Mode: Merge State</option>
</select>
<button class="btn" id="btnLoadDemoState" type="button">Load 6/6 Demo State</button>
<button class="btn" id="btnLoadDemoState" type="button" style="border-color:var(--gold);color:var(--gold);" title="Loads clearly labeled synthetic example state for UI demonstration">&#x26A0; Load Simulated Demo State (Synthetic Example)</button>
<button class="btn" id="btnResetState" type="button">Reset Local State</button>
</div>
<span id="stateStatusMsg" style="font-size:0.72rem;color:var(--emerald);">Drop a saved .json state file anywhere on this bar to restore progress.</span>
@@ -413,7 +450,7 @@
</main>
<footer>
<div>hyperstitionstud.io/learn &bull; Powered by hyperstitionstudio-core (urn:io:hyperstitionstud:schema:v1:learn-progress-state v2.0.18)</div>
<div>hyperstitionstud.io/learn &bull; Powered by hyperstitionstudio-core (urn:io:hyperstitionstud:schema:v1:learn-progress-state v2.0.23)</div>
<div class="hs-lemur-credit">Made with <span class="hs-heart" role="img" aria-label="love">&#x2665;</span> by Lemurs.</div>
</footer>
</div>
+4 -2
View File
@@ -265,7 +265,7 @@
const base = {
$schema: "../schemas/v1/learn-progress-state.schema.json",
$id: SCHEMA_ID,
version: "2.0.18",
version: "2.0.23",
updated_at_utc: new Date().toISOString(),
preferred_register: "fund_manager",
completed_modules: [],
@@ -427,7 +427,7 @@
M05: "S+ Center (88-100 ETI) radiates outward to Tier D Periphery (44-51 ETI).",
M06: "Fund Manager Uncaptured Gem screen: high COL/VEL + low CAP (<68) in Tiers B & C."
};
saveState(demo, "Loaded 6/6 Demo Completed State — click 'Download State (.json)' to test export!");
saveState(demo, "⚠️ [SIMULATED / SYNTHETIC DEMO DATA] Loaded synthetic example state (not real user progress).");
}
function resetLearnState() {
@@ -625,6 +625,8 @@
if (window.location.protocol !== "file:") return;
const map = {
"nav-home": "../index.html",
"nav-quant": "../quant/index.html",
"nav-donate": "../donate/index.html",
"nav-gallery": "../gallery/index.html",
"nav-graph": "../../../encyclopedia-knowledge-graph/index.html",
"nav-calc": "../../../haiperdohp-jemaytreeah/index.html",
@@ -0,0 +1,50 @@
# Operator's Manual: Quantitative Finance & Memetic Gematria Time-Series Workbench (`/quant/`) (`v2.0.20`)
- **Document ID:** `OPERATORS-MANUAL-QUANT-TIMESERIES-WORKBENCH` (`v2.0.20`)
- **Web Route:** `https://hyperstitionstud.io/quant/` (`/quant/index.html`)
- **Offline `file://` Path:** `/workspace/hyperstitionstudio-core/site/quant/index.html`
- **Schema Contract:** `urn:io:hyperstitionstud:schema:v1:quant-timeseries` (`/schemas/v1/quant-timeseries.schema.json`)
- **Interactive Guided Tour:** Built-in 5-Episode, 25-Scene HTML5 Canvas Choreographer (`/quant/quant-tutorials.js`, `< 45 KB` Git-tracked, zero `.mp4` bloat, Web Speech TTS + WebAudio Telemetry Chime narration ON by default).
---
## 1. Strict Periodicity Qualification Gate
Only data sources that emit discrete, timestamp-indexed periodic observations ($\Delta t \in \{\text{1d US-Closing-Bell at 21:30 UTC}, \text{24h UTC News-Wire Rollover at 00:00 UTC}\}$) enter `/quant/`:
- **Included (`0` Non-Periodic Records):**
1. `30` daily `21:30 UTC` (`16:30 EST`) US closing-bell bars across the `24` canonical `S1–S6` technocapital instruments (`NVDA`, `MSFT`, `GOOGL`, `META`, `PLTR`, `ARM`, `COIN`, `MSTR`, `GS`, `JPM`, `TSM`, `ASML`, `LMT`, `RTX`, `TSLA`, `TMUS`, `EQIX`, `CEG`, `LLY`, `UNH`, `BLK`, `BRK-B`, `BTC-USD`, `ANTHR-PVT`).
2. `21` dated `00:00 UTC` news-wire dossiers (`25..71-dossier-news-YYYY-MM-DD.md`).
3. Daily objective thermodynamic regime state vectors (`M1_ENTROPIC_STAGNATION`, `M2_FLASH_CRASH_TEMPLEX_SURGE`, `M3_LEVIATHAN_TRILLION_CAP_CONCENTRATION`).
4. Dated `quantitative-economic-anchors.json` step revisions (`$83 -> $89` on `2026-11-26` for `ANTHR-PVT`).
- **Excluded Static Corpora:** Static lexicons (`01-ingglish-aq-lexicon.md`), undated dossiers (`10–24`, `26–45`, `65–69`), the 22-volume PDF Encyclopedia, stakeholder proposals, lectures, and `/calc/db.json`.
---
## 2. Visual Figure & Numerical Readout Guide (Panels 1–4)
| Panel & Figure | Visual Encoding | Mathematical & Gematrial Definition | Passage-Encoded Deep Link |
| :--- | :--- | :--- | :--- |
| **Panel 1 (Top Pane): Solid Cyan Curve** | `#22d3ee` polyline across `30` UTC days | Plots `Spoken AQ (Gen 1)`, `Close Price (USD)`, `Move (BPS)`, or `Digit AQ` for the active ticker. | `/encyclopedia/01-cipher-orthography-and-boundaries/a-to-f-alphanumeric-qabbala-to-full-clause-isometry.pdf#page=1&search=Alphanumeric%20Qabbala` |
| **Panel 1 (Top Pane): Dashed Crimson Line (`entity_ing=N`)** | Horizontal `#ff4d4d` dashed threshold | Marks the ticker's intrinsic phonemic identity coordinate $\text{AQ}_{\text{Ing}}(\text{Entity}_i)$ (e.g. `envideea = 137`, `asml = 81`, `anthropik = 193`). | `/encyclopedia/03-machinic-phylum-guilds-s1-to-s5/class-s3-silicon-war-machine-and-euv-swarm-a-to-z.pdf#page=5&search=envideea` |
| **Panel 1 (Top Pane): Gold Beacon Circles (`r = 5.2px`)** | Glowing `#f5c630` vertex circles | **`Scope 1` Self-Lock or Repdigit Attractor (Real Exchange Bars Only):** Fires when a real exchange bar's integer close equals the entity's own `AQ` (`PLTR $159.36 -> 159 == palanter`, `CEG $276.09 -> 276 == konstalayshan`, `RTX $191.88 -> 192 == raytheeon`) or hits a `37 × k` repdigit (`AVGO $333.40 -> 333`, `NVDA $206.69 -> 'too huhndrad siks' = 333`). Missing/closed dates state `"No data available"`. | `/encyclopedia/08-stakeholder-registers-idioms-and-pokedex-semiotics/a-to-h-ai-powered-race-to-hidden-chokepoint-screen.pdf#page=2&search=Room%20Filter` |
| **Panel 1 (Top Pane): Cyan Beacon Circles (`r = 3.8px`)** | `#22d3ee` vertex circles | **`Scope 2` `S1–S6` Ring Migration:** Price, spoken AQ, or bps lands on one of the `30` canonical `S1–S6` signature coordinates (`71, 81, 91, 95, 115, 125, 128, 129, 133, 135, 136, 137, 153, 160, 163, 166, 183, 189, 191, 193, 197, 211, 215, 222, 237, 246, 256, 260, 292`). | `/encyclopedia/06-genealogical-vectors-and-quantitative-repricing/a-to-m-attractors-to-multi-build-flex-singularities.pdf#page=2&search=Flex` |
| **Panel 1 (Middle Pane): Violet vs. Emerald Bars** | Daily `333/666/777` wire equation counts | Violet (`#a78bfa`) = standard wire harvest day; Emerald (`#34d399`) = **`Scope 3` News-Wire Co-Presence ($C_{i,t} = 1$)** where ticker $i$ appeared in that UTC day's breaking wire dossier. | `/archive/71-dossier-news-2026-11-29.md#:~:text=Nvidia` |
| **Panel 1 (Bottom Pane): `Vol20d` Regime Bars** | 20d relative volume ($V_{i,t}/\bar{V}_{20}$) | Gold (`< 0.45x`) = `M1_ENTROPIC_STAGNATION` (`137`); Crimson (`>= 2.5x` or `<= -5%`) = `M2_FLASH_CRASH_TEMPLEX_SURGE` (`193`); Sky-Blue = `M3_LEVIATHAN`. | `/encyclopedia/05-memetic-superclass-and-emergent-m7/m1-vampiric-entropic-and-anti-productive-a-to-m.pdf#page=1&search=M1` |
| **Panel 2: `24 × 30` Spatiotemporal Heatmap** | Interactive grid of `(Ticker, UTC Date)` cells | Gold cell = Scope 1 Self-Lock; Cyan cell = Scope 2 Ring Migration; Emerald outline = Scope 3 Wire Co-Presence; `↗` opens the ticker's TradingView Superchart (`EXCHANGE:SYMBOL`). | `https://www.tradingview.com/chart/?symbol=NASDAQ%3ANVDA` |
| **Panel 3: Lens Projection, Citations & Wire Tape** | Cross-sectional date inspector + `LENS_REGISTRY` + Citation Drawer | Projects lens-neutral `struct_*` and `ts_*` keys through `fund_manager`, `neutral_math`, `corporate_board`, `tierzoo_ecology`, `fantasy_sabermetrics`, or `pokedex_scanner`, and provides passage-encoded links (`#page=N&search=...`, `#:~:text=...`, `/graph/index.html?select=aq:N`, `/api/v1/dossiers/N?highlight=...`). | `/graph/index.html?select=aq:137` |
| **Panel 4: Lead-Lag Correlation Explorer $r(\tau)$** | 11-bar histogram across $\tau \in [-5, +5]$ days | Empirical Pearson correlation between daily wire velocity $M_t$ and unsigned ticker move $|\Delta\text{bps}_{i,t+\tau}|$; Gold bar marks optimal causal lag $\tau^* = \arg\max_\tau |r(\tau)|$. | `/api/v1/quant/timeseries?symbol=NVDA` |
---
## 3. Keyboard Shortcuts & Programmatic REST API v1 Endpoints
- **Keyboard Shortcuts on `/quant/`:**
- `←` / `→`: Step backward or forward one UTC day (`2026-11-01 .. 2026-11-30`).
- `T`: Launch the selected ticker's live TradingView Superchart (`https://www.tradingview.com/chart/?symbol=...`) in a new browser window (`noopener,noreferrer`).
- **REST API v1 Endpoints:**
- `GET /api/v1/quant/timeseries?symbol=NVDA&lens=fund_manager`
- `GET /api/v1/quant/instruments/NVDA`
- `GET /api/v1/zoology/pokedex/NVDA`
- `GET /api/v1/dossiers/71?highlight=envideea`
- `GET /api/v1/openapi.json`
+69 -3
View File
@@ -44,7 +44,41 @@
}
h1 { font-size: 1.18rem; font-weight: 700; color: var(--text-main); }
.subtitle { font-size: 0.74rem; color: var(--text-muted); margin-top: 0.25rem; }
.top-nav { display: flex; gap: 0.45rem; flex-wrap: wrap; align-items: center; }
.top-nav { margin-left: auto; display: flex; gap: 0.45rem; flex-wrap: wrap; align-items: center; justify-content: flex-end; }
.nav-donate-sep { width: 1px; height: 20px; background: var(--border); margin: 0 0.2rem; display: inline-block; flex-shrink: 0; }
.btn-donate-pill {
height: 34px;
border-radius: 999px;
padding: 0.28rem 0.9rem 0.28rem 0.35rem;
background: linear-gradient(180deg, #ffd86b 0%, #f59e0b 52%, #d97706 100%);
color: #020617;
border: 1px solid #f5c630;
box-shadow: inset 0 1px 1px rgba(255, 255, 255, 0.55), 0 2px 8px rgba(245, 158, 11, 0.22);
display: inline-flex;
align-items: center;
gap: 0.45rem;
font-size: 0.74rem;
font-weight: 700;
letter-spacing: 0.05em;
text-decoration: none;
flex-shrink: 0;
transition: transform 0.15s ease, box-shadow 0.15s ease, filter 0.15s ease;
}
.btn-donate-pill:hover { filter: brightness(1.06); transform: translateY(-1px); color: #020617; }
.donate-pill-emblem {
width: 20px;
height: 20px;
border-radius: 50%;
background: #0f172a;
color: var(--rose);
border: 1px solid rgba(245, 198, 48, 0.7);
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 0.68rem;
line-height: 1;
flex-shrink: 0;
}
.btn, select {
text-decoration: none;
background: var(--bg-card);
@@ -159,6 +193,10 @@
display: inline-block;
}
.hm-none { background: #0f172a; }
.hm-nodata {
background: repeating-linear-gradient(45deg, #090d16, #090d16 3px, #1e293b 3px, #1e293b 6px);
opacity: 0.55;
}
.hm-scope1 { background: var(--gold); box-shadow: 0 0 5px rgba(245, 198, 48, 0.6); }
.hm-scope2 { background: var(--cyan); }
.hm-wire { outline: 2px solid var(--emerald); outline-offset: -2px; }
@@ -222,16 +260,41 @@
<header>
<div>
<h1>hyperstitionstud.io/quant — Quantitative Finance &amp; Memetic Gematria Time-Series Workbench</h1>
<p class="subtitle">Strictly Periodic Telemetry (21:30 UTC US Closing Bell &times; 00:00 UTC News-Wire Dossiers) &bull; Lens-Neutral Schema (urn:io:hyperstitionstud:quant-timeseries:v2.0.18)</p>
<p class="subtitle">Strictly Periodic Telemetry (21:30 UTC US Closing Bell &times; 00:00 UTC News-Wire Dossiers) &bull; Lens-Neutral Schema (urn:io:hyperstitionstud:quant-timeseries:v2.0.23)</p>
</div>
<nav class="top-nav">
<a class="btn" id="navHome" href="/">Portal Home (/)</a>
<a class="btn" id="navGraph" href="/graph/index.html">Knowledge Graph (/graph/)</a>
<a class="btn" id="navLearn" href="/learn/index.html">Learning Track (/learn/)</a>
<a class="btn" id="navCalc" href="/calc/index.html">AQ Calculator (/calc/)</a>
<a class="btn" id="navManual" href="/quant/OPERATORS-MANUAL-QUANT-TIMESERIES-WORKBENCH.pdf" target="_blank">Operator's Manual (PDF)</a>
<span class="nav-donate-sep" aria-hidden="true"></span>
<a class="btn-donate-pill" id="navDonate" href="/donate/index.html" title="Signal Patronage &amp; Open-Instrument Notes (/donate/)"><span class="donate-pill-emblem" aria-hidden="true">&#x2665;</span><span>DONATE</span></a>
</nav>
</header>
<!-- INTERACTIVE 5-EPISODE GUIDED CANVAS TUTORIAL PLAYER (Zero-MP4 Option B) -->
<section class="panel" id="quantTutorialBar" aria-label="Interactive Tutorial Series Player">
<div class="panel-header">
<span class="panel-title">INTERACTIVE GUIDED CANVAS TOUR (5 Episodes &times; 5 Scenes = 25 Live Choreographed Walkthroughs &bull; Zero-MP4)</span>
<span class="panel-meta" id="tutStepBadge">Ep 01 &bull; Scene 1/5</span>
</div>
<div class="pill-row" id="tutEpisodeTabs"></div>
<div style="display:flex;flex-wrap:wrap;align-items:center;gap:0.5rem;">
<button type="button" class="btn primary" id="tutPlayPauseBtn">&#x25B6; Play Guided Tour</button>
<button type="button" class="btn" id="tutPrevBtn">&#x23EE; Prev Scene</button>
<input type="range" id="tutScrubber" min="0" max="4" value="0" style="flex:1;min-width:140px;accent-color:var(--gold);cursor:pointer;" aria-label="Scene timeline scrubber" />
<button type="button" class="btn" id="tutNextBtn">Next Scene &#x23ED;</button>
<button type="button" class="btn primary" id="tutSpeechBtn" title="Toggle Web Speech / WebAudio narration (ON by default)">&#x1F50A; Voice: ON</button>
<button type="button" class="btn" id="tutClearSpotlightBtn" title="Clear canvas spotlight overlay">Clear Spotlight</button>
</div>
<div class="stat-box" style="border-left:3px solid var(--gold);">
<div style="font-size:0.76rem;font-weight:700;color:var(--gold);margin-bottom:0.25rem;" id="tutKeyframeTitle"></div>
<div style="font-size:0.75rem;color:var(--text-main);line-height:1.5;" id="tutSubtitleText"></div>
<div class="pill-row" style="margin-top:0.45rem;" id="tutCitationPills"></div>
</div>
</section>
<section class="toolbar" aria-label="Workbench Controls">
<div class="control-group">
<span class="control-label">Guild Filter:</span>
@@ -286,10 +349,12 @@
</div>
<div class="inspector-grid" id="dateMetricsGrid"></div>
<div class="stat-box" id="lensProjectionCard"></div>
<div class="stat-box" id="docReferencesCard" style="border-left:3px solid var(--cyan);"></div>
<div>
<div class="control-label" style="margin-bottom:0.35rem;" id="wireTapeHeader">Dated 00:00 GMT News-Wire Memetic Equations (333 / 666 / 777):</div>
<div class="eq-tape" id="wireEqTape"></div>
</div>
<div class="stat-box" id="passagePreviewBox" style="display:none;border-left:3px solid var(--emerald);font-size:0.69rem;white-space:pre-wrap;"></div>
</section>
</div>
@@ -307,9 +372,10 @@
</section>
<footer>
hyperstitionstud.io/quant v2.0.18 &bull; Made with <span class="hs-heart" style="color:#ff4d4d;">&#x2665;</span> by Lemurs.
hyperstitionstud.io/quant v2.0.23 &bull; Made with <span class="hs-heart" style="color:#ff4d4d;">&#x2665;</span> by Lemurs.
</footer>
</div>
<script src="quant-app.js"></script>
<script src="quant-tutorials.js"></script>
</body>
</html>
+290 -92
View File
@@ -1,5 +1,5 @@
// /workspace/hyperstitionstudio-core/site/quant/quant-app.js
// Interactive Quantitative Finance & Memetic Gematria Time-Series Workbench (v2.0.18)
// Interactive Quantitative Finance & Memetic Gematria Time-Series Workbench (v2.0.23)
(function () {
"use strict";
@@ -15,10 +15,25 @@
const navGraph = document.getElementById("navGraph");
const navLearn = document.getElementById("navLearn");
const navCalc = document.getElementById("navCalc");
const navManual = document.getElementById("navManual");
const navDonate = document.getElementById("navDonate");
if (navHome) navHome.href = "../index.html";
if (navGraph) navGraph.href = "../../../encyclopedia-knowledge-graph/index.html";
if (navLearn) navLearn.href = "../learn/index.html";
if (navCalc) navCalc.href = "../../../haiperdohp-jemaytreeah/index.html";
if (navManual) navManual.href = "./OPERATORS-MANUAL-QUANT-TIMESERIES-WORKBENCH.pdf";
if (navDonate) navDonate.href = "../donate/index.html";
}
let activeSpotlight = null;
function findLatestAvailableDateIdx(sym) {
const inst = DATA.instruments.find((x) => x.symbol === sym) || DATA.instruments[0];
if (!inst || !inst.bars) return DATA.dates_utc.length - 1;
for (let i = inst.bars.length - 1; i >= 0; i--) {
if (inst.bars[i].data_available) return i;
}
return DATA.dates_utc.length - 1;
}
const state = {
@@ -26,7 +41,7 @@
selectedSymbol: "NVDA",
selectedLens: DATA.default_lens || "fund_manager",
metricMode: "spoken_aq", // "spoken_aq" | "close_usd" | "change_bps" | "digit_aq"
selectedDateIdx: DATA.dates_utc.length - 1,
selectedDateIdx: findLatestAvailableDateIdx("NVDA"),
};
const guilds = ["ALL", "S1", "S2", "S3", "S4", "S5", "S6"];
@@ -178,65 +193,95 @@
ctx.stroke();
});
// Top Pane: Selected Metric Trajectory
// Top Pane: Selected Metric Trajectory (strictly over real available bars; never synthesized or interpolated)
const vals = bars.map((b) => {
if (!b || !b.data_available || b.close_usd === null || b.close_usd === undefined) return null;
if (state.metricMode === "close_usd") return Number(b.close_usd);
if (state.metricMode === "change_bps") return Number(b.change_bps);
if (state.metricMode === "digit_aq") return Number(b.close_digit_aq);
return Number(b.close_spoken_ing_aq);
if (state.metricMode === "change_bps") return b.change_bps !== null && b.change_bps !== undefined ? Number(b.change_bps) : null;
if (state.metricMode === "digit_aq") return b.close_digit_aq !== null && b.close_digit_aq !== undefined ? Number(b.close_digit_aq) : null;
return b.close_spoken_ing_aq !== null && b.close_spoken_ing_aq !== undefined ? Number(b.close_spoken_ing_aq) : null;
});
const minV = Math.min.apply(null, vals);
const maxV = Math.max.apply(null, vals);
const spanV = Math.max(1e-3, maxV - minV);
const validVals = vals.filter((v) => v !== null && !Number.isNaN(v));
function yTop(v) {
return topY1 - ((v - minV) / spanV) * (topY1 - topY0 - 14) - 6;
}
if (!inst.data_available || validVals.length === 0) {
ctx.fillStyle = "rgba(15, 23, 42, 0.94)";
ctx.fillRect(padL + 40, topY0 + 36, plotW - 80, 92);
ctx.strokeStyle = "#f5c630";
ctx.strokeRect(padL + 40, topY0 + 36, plotW - 80, 92);
ctx.fillStyle = "#f5c630";
ctx.font = "bold 13px monospace";
ctx.textAlign = "center";
ctx.fillText("NO MARKET DATA AVAILABLE FOR " + inst.symbol, padL + plotW / 2, topY0 + 74);
ctx.fillStyle = "#94a3b8";
ctx.font = "11px monospace";
ctx.fillText(inst.status || "No public exchange feed available (0 synthetic bars generated).", padL + plotW / 2, topY0 + 98);
ctx.textAlign = "left";
} else {
const minV = Math.min.apply(null, validVals);
const maxV = Math.max.apply(null, validVals);
const spanV = Math.max(1e-3, maxV - minV);
// Draw entity AQ horizontal reference line if within range
const refAq = inst.entity_ing_aq;
if (refAq >= minV && refAq <= maxV) {
const ry = yTop(refAq);
ctx.strokeStyle = "rgba(255, 77, 77, 0.45)";
ctx.setLineDash([4, 4]);
ctx.beginPath();
ctx.moveTo(padL, ry);
ctx.lineTo(W - padR, ry);
ctx.stroke();
ctx.setLineDash([]);
ctx.fillStyle = "#ff4d4d";
ctx.font = "10px monospace";
ctx.fillText(inst.entity_ing + "=" + refAq, padL + 6, ry - 4);
}
// Plot curve
ctx.strokeStyle = "#22d3ee";
ctx.lineWidth = 2.2;
ctx.beginPath();
vals.forEach((v, idx) => {
const px = xAt(idx);
const py = yTop(v);
if (idx === 0) ctx.moveTo(px, py);
else ctx.lineTo(px, py);
});
ctx.stroke();
// Lock beacon markers on Top Pane
bars.forEach((b, idx) => {
const px = xAt(idx);
const py = yTop(vals[idx]);
if (b.scope1_locks && b.scope1_locks.length > 0) {
ctx.fillStyle = "#f5c630";
ctx.beginPath();
ctx.arc(px, py, 5.2, 0, Math.PI * 2);
ctx.fill();
} else if (b.scope2_ring_coordinates && b.scope2_ring_coordinates.length > 0) {
ctx.fillStyle = "#22d3ee";
ctx.beginPath();
ctx.arc(px, py, 3.8, 0, Math.PI * 2);
ctx.fill();
function yTop(v) {
return topY1 - ((v - minV) / spanV) * (topY1 - topY0 - 14) - 6;
}
});
// Draw entity AQ horizontal reference line if within range
const refAq = inst.entity_ing_aq;
if (refAq >= minV && refAq <= maxV) {
const ry = yTop(refAq);
ctx.strokeStyle = "rgba(255, 77, 77, 0.45)";
ctx.setLineDash([4, 4]);
ctx.beginPath();
ctx.moveTo(padL, ry);
ctx.lineTo(W - padR, ry);
ctx.stroke();
ctx.setLineDash([]);
ctx.fillStyle = "#ff4d4d";
ctx.font = "10px monospace";
ctx.fillText(inst.entity_ing + "=" + refAq, padL + 6, ry - 4);
}
// Plot curve across available trading days
ctx.strokeStyle = "#22d3ee";
ctx.lineWidth = 2.2;
ctx.beginPath();
let started = false;
vals.forEach((v, idx) => {
if (v === null || Number.isNaN(v)) return;
const px = xAt(idx);
const py = yTop(v);
if (!started) {
ctx.moveTo(px, py);
started = true;
} else {
ctx.lineTo(px, py);
}
});
ctx.stroke();
// Lock beacon markers on Top Pane
bars.forEach((b, idx) => {
if (vals[idx] === null || Number.isNaN(vals[idx])) return;
const px = xAt(idx);
const py = yTop(vals[idx]);
if (b.scope1_locks && b.scope1_locks.length > 0) {
ctx.fillStyle = "#f5c630";
ctx.beginPath();
ctx.arc(px, py, 5.2, 0, Math.PI * 2);
ctx.fill();
} else if (b.scope2_ring_coordinates && b.scope2_ring_coordinates.length > 0) {
ctx.fillStyle = "#22d3ee";
ctx.beginPath();
ctx.arc(px, py, 3.8, 0, Math.PI * 2);
ctx.fill();
}
});
ctx.fillStyle = "#94a3b8";
ctx.font = "10px monospace";
ctx.fillText(maxV.toFixed(1), 6, topY0 + 8);
ctx.fillText(minV.toFixed(1), 6, topY1 - 4);
}
// Middle Pane: 00:00 GMT News Wire Equation Counts + Co-Presence Diamonds
const wireTotals = DATA.daily_wire_series.map((d) => Number(d.equation_counts.total || 0));
@@ -251,21 +296,22 @@
});
// Bottom Pane: 20-Day Volume Ratio & Regime Color Strip
const vols = bars.map((b) => Number(b.volume_ratio_20d));
const maxVol = Math.max(2.6, Math.max.apply(null, vols));
const vols = bars.map((b) => (b && b.data_available && b.volume_ratio_20d !== null && b.volume_ratio_20d !== undefined) ? Number(b.volume_ratio_20d) : null);
const validVols = vols.filter((v) => v !== null && v > 0);
const maxVol = validVols.length > 0 ? Math.max(2.6, Math.max.apply(null, validVols)) : 2.6;
vols.forEach((vr, idx) => {
if (vr === null) return;
const px = xAt(idx);
const bh = (vr / maxVol) * (botY1 - botY0 - 8);
const b = bars[idx];
ctx.fillStyle = b.change_pct <= -5.0 || vr >= 2.5 ? "#ff4d4d" : (vr < 0.45 ? "#f5c630" : "#38bdf8");
const chgP = b.change_pct !== null && b.change_pct !== undefined ? Number(b.change_pct) : 0.0;
ctx.fillStyle = chgP <= -5.0 || vr >= 2.5 ? "#ff4d4d" : (vr < 0.45 ? "#f5c630" : "#38bdf8");
ctx.fillRect(px - barW / 2, botY1 - bh, barW, bh);
});
// Axis labels
ctx.fillStyle = "#94a3b8";
ctx.font = "10px monospace";
ctx.fillText(maxV.toFixed(1), 6, topY0 + 8);
ctx.fillText(minV.toFixed(1), 6, topY1 - 4);
ctx.fillText("Wire Eq", 6, midY0 + 12);
ctx.fillText("Vol20d", 6, botY0 + 12);
@@ -273,6 +319,36 @@
for (let i = 0; i < N; i += 4) {
ctx.fillText(DATA.dates_utc[i].slice(5), xAt(i) - 14, H - 4);
}
// Optional Tutorial Spotlight Ring & Callout Banner on Canvas
if (activeSpotlight && activeSpotlight.target === "canvas") {
const spX = padL + (activeSpotlight.xRatio || 0.9) * plotW;
const spY = (activeSpotlight.yRatio || 0.25) * H;
ctx.save();
ctx.strokeStyle = "#f5c630";
ctx.lineWidth = 2.5;
ctx.beginPath();
ctx.arc(spX, spY, 18, 0, Math.PI * 2);
ctx.stroke();
ctx.strokeStyle = "rgba(251, 113, 133, 0.85)";
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.arc(spX, spY, 25, 0, Math.PI * 2);
ctx.stroke();
const lbl = activeSpotlight.label || "Spotlight";
ctx.font = "bold 11px monospace";
const tw = ctx.measureText(lbl).width + 16;
const bx = Math.max(padL + 6, Math.min(W - tw - 12, spX - tw - 24));
const by = Math.max(18, spY - 14);
ctx.fillStyle = "rgba(2, 6, 23, 0.92)";
ctx.fillRect(bx, by, tw, 24);
ctx.strokeStyle = "#f5c630";
ctx.strokeRect(bx, by, tw, 24);
ctx.fillStyle = "#f5c630";
ctx.fillText(lbl, bx + 8, by + 16);
ctx.restore();
}
}
function renderHeatmap() {
@@ -293,11 +369,14 @@
html += "</th>";
inst.bars.forEach((b, dIdx) => {
let cls = "hm-cell hm-none";
if (b.scope1_locks && b.scope1_locks.length > 0) cls = "hm-cell hm-scope1";
if (!b.data_available) cls = "hm-cell hm-nodata";
else if (b.scope1_locks && b.scope1_locks.length > 0) cls = "hm-cell hm-scope1";
else if (b.scope2_ring_coordinates && b.scope2_ring_coordinates.length > 0) cls = "hm-cell hm-scope2";
if (b.co_present_in_news_wire) cls += " hm-wire";
if (inst.symbol === state.selectedSymbol && dIdx === state.selectedDateIdx) cls += " hm-selected";
const tip = inst.symbol + " (" + b.date_utc + "): $" + b.close_usd + " (" + b.change_bps + " bps) | Spoken AQ=" + b.close_spoken_ing_aq;
const tip = !b.data_available
? (inst.symbol + " (" + b.date_utc + "): No data available")
: (inst.symbol + " (" + b.date_utc + "): $" + b.close_usd + " (" + (b.change_bps !== null ? b.change_bps + " bps" : "No bps data") + ") | Spoken AQ=" + b.close_spoken_ing_aq);
html += "<td><span class='" + cls + "' data-sym='" + inst.symbol + "' data-didx='" + dIdx + "' title='" + tip + "'></span></td>";
});
html += "</tr>";
@@ -330,17 +409,38 @@
"PANEL 3: " + inst.symbol + " (" + inst.entity_eng + " \u2192 " + inst.entity_ing + "=" + inst.entity_ing_aq + ") @ " + dt;
const metricsGrid = document.getElementById("dateMetricsGrid");
const lockSummary = (bar.scope1_locks || []).concat((bar.scope2_ring_coordinates || []).map((c) => "Ring " + c)).join(", ") || "None";
metricsGrid.innerHTML = [
{ l: "Close USD (Change)", v: "$" + bar.close_usd + " (" + (bar.change_bps >= 0 ? "+" : "") + bar.change_bps + " bps)" },
{ l: "Spoken Close (Gen 1 AQ)", v: bar.close_spoken_ing + " (" + bar.close_spoken_ing_aq + ")" },
{ l: "Scaled Cap (Gen 1 AQ)", v: bar.market_cap_str + " (" + bar.scaled_cap_spoken_ing_aq + ")" },
{ l: "BPS Spoken AQ / Vol20d", v: bar.bps_spoken_ing_aq + " / " + bar.volume_ratio_20d + "x" },
{ l: "Active Contingent Locks", v: lockSummary },
{ l: "00:00 GMT Wire Co-Present", v: bar.co_present_in_news_wire ? "YES (Scope 3 Lock)" : "No" },
]
.map((m) => "<div class='stat-box'><div class='stat-label'>" + m.l + "</div><div class='stat-val'>" + m.v + "</div></div>")
.join("");
if (!bar.data_available || bar.close_usd === null || bar.close_usd === undefined) {
metricsGrid.innerHTML = [
{ l: "Close USD (Change)", v: "No data available" },
{ l: "Spoken Close (Gen 1 AQ)", v: "No data available" },
{ l: "Scaled Cap (Gen 1 AQ)", v: "No data available" },
{ l: "BPS Spoken AQ / Vol20d", v: "No data available" },
{ l: "Active Contingent Locks", v: "No data available" },
{ l: "00:00 GMT Wire Co-Present", v: bar.co_present_in_news_wire ? "YES (Scope 3 Lock)" : "No" },
]
.map((m) => "<div class='stat-box'><div class='stat-label'>" + m.l + "</div><div class='stat-val' style='color:var(--text-muted);'>" + m.v + "</div></div>")
.join("");
} else {
const lockSummary = (bar.scope1_locks || []).concat((bar.scope2_ring_coordinates || []).map((c) => "Ring " + c)).join(", ") || "None";
const chgStr = bar.change_bps !== null && bar.change_bps !== undefined
? (" (" + (bar.change_bps >= 0 ? "+" : "") + bar.change_bps + " bps)")
: " (No prior day data)";
const capDisp = (bar.market_cap_str && bar.market_cap_str !== "No data available" && bar.scaled_cap_spoken_ing_aq !== null)
? (bar.market_cap_str + " (" + bar.scaled_cap_spoken_ing_aq + ")")
: "No data available";
const bpsDisp = bar.bps_spoken_ing_aq !== null && bar.bps_spoken_ing_aq !== undefined ? String(bar.bps_spoken_ing_aq) : "No data available";
const volDisp = bar.volume_ratio_20d !== null && bar.volume_ratio_20d !== undefined ? (bar.volume_ratio_20d + "x") : "No data available";
metricsGrid.innerHTML = [
{ l: "Close USD (Change)", v: "$" + bar.close_usd + chgStr },
{ l: "Spoken Close (Gen 1 AQ)", v: bar.close_spoken_ing + " (" + bar.close_spoken_ing_aq + ")" },
{ l: "Scaled Cap (Gen 1 AQ)", v: capDisp },
{ l: "BPS Spoken AQ / Vol20d", v: bpsDisp + " / " + volDisp },
{ l: "Active Contingent Locks", v: lockSummary },
{ l: "00:00 GMT Wire Co-Present", v: bar.co_present_in_news_wire ? "YES (Scope 3 Lock)" : "No" },
]
.map((m) => "<div class='stat-box'><div class='stat-label'>" + m.l + "</div><div class='stat-val'>" + m.v + "</div></div>")
.join("");
}
// Render Active Lens Projection Card (LENS_REGISTRY)
const lensCard = document.getElementById("lensProjectionCard");
@@ -348,40 +448,108 @@
let rowsHtml = "";
Object.keys(proj.labeled_timeseries || {}).forEach((k) => {
const val = proj.labeled_timeseries[k];
const disp = typeof val === "object" ? JSON.stringify(val) : String(val);
let disp = "No data available";
if (val !== null && val !== undefined) {
if (typeof val === "object") {
const nonNull = Object.values(val).some((x) => x !== null && x !== undefined);
disp = nonNull ? JSON.stringify(val) : "No data available";
} else {
disp = String(val);
}
}
rowsHtml += "<div style='display:flex;justify-content:space-between;font-size:0.69rem;border-bottom:1px solid #162032;padding:0.18rem 0;'>" +
"<span style='color:var(--text-muted);'>" + k + ":</span><span style='color:var(--text-main);font-weight:600;'>" + disp + "</span></div>";
});
const archDisp = (proj.qualitative_profile && proj.qualitative_profile.archetype) || "No data available";
const regDisp = (proj.qualitative_profile && proj.qualitative_profile.regime_specialization) || "No data available";
const sparkDisp = inst.timeseries_moments.ts_sparkline_30d || "No data available";
lensCard.innerHTML =
"<div style='display:flex;justify-content:space-between;align-items:center;margin-bottom:0.4rem;'>" +
"<span style='font-size:0.76rem;font-weight:700;color:var(--gold);'>Lens: " + proj.lens_title + "</span>" +
"<span style='font-size:0.7rem;color:var(--cyan);'>" + proj.tier_classification + "</span></div>" +
"<div style='font-size:0.71rem;color:var(--emerald);margin-bottom:0.4rem;'>" +
"Archetype: " + proj.qualitative_profile.archetype + " &bull; " + proj.qualitative_profile.regime_specialization +
" &bull; 30d: " + inst.timeseries_moments.ts_sparkline_30d + "</div>" +
"Archetype: " + archDisp + " &bull; " + regDisp +
" &bull; 30d: " + sparkDisp + "</div>" +
rowsHtml;
}
// Render Knowledge-Graph-Modeled Documentation & Cited Passages Card
const docCard = document.getElementById("docReferencesCard");
if (docCard && inst.doc_references) {
const dr = inst.doc_references;
const resolveUrl = (window.HyperstitionStudio.QuantTutorials && window.HyperstitionStudio.QuantTutorials.adaptHrefForFileProtocol) || function (u) { return u; };
const encUrl = resolveUrl(dr.encyclopedia_deep_link);
const kgUrl = resolveUrl(dr.knowledge_graph_deep_link);
const dosUrl = resolveUrl(dr.exemplar_dossier_deep_link);
const apiUrl = dr.rest_api_deep_link;
docCard.innerHTML =
"<div style='font-size:0.74rem;font-weight:700;color:var(--cyan);margin-bottom:0.3rem;'>Documentation &amp; Passage-Encoded Deep Citations</div>" +
"<div style='font-size:0.68rem;color:var(--text-muted);margin-bottom:0.4rem;'>" + (dr.verbatim_citation_passage || "") + "</div>" +
"<div style='display:flex;flex-wrap:wrap;gap:0.35rem;'>" +
"<a class='pill' style='text-decoration:none;color:var(--gold);border-color:var(--gold);' href='" + encUrl + "' target='_blank' rel='noopener noreferrer'>\uD83D\uDCC4 Encyclopedia PDF (#page &amp; search) \u2197</a>" +
"<a class='pill' style='text-decoration:none;color:var(--cyan);border-color:var(--cyan);' href='" + kgUrl + "' target='_blank' rel='noopener noreferrer'>\uD83D\uDD78\uFE0F Knowledge Graph (aq:" + inst.entity_ing_aq + ") \u2197</a>" +
"<a class='pill' style='text-decoration:none;color:var(--emerald);border-color:var(--emerald);' href='" + dosUrl + "' target='_blank' rel='noopener noreferrer'>\uD83D\uDCDC Dossier Passage (#:~:text=) \u2197</a>" +
"<button type='button' class='pill preview-api-btn' data-api='" + apiUrl + "' style='color:var(--violet);border-color:var(--violet);'>\uD83D\uDD0D Inline Passage Preview</button>" +
"</div>";
}
// Render Dated 00:00 GMT News-Wire Equation Tape
const wireDay = DATA.daily_wire_series[state.selectedDateIdx];
const tapeEl = document.getElementById("wireEqTape");
const hdrEl = document.getElementById("wireTapeHeader");
const resolveUrl = (window.HyperstitionStudio.QuantTutorials && window.HyperstitionStudio.QuantTutorials.adaptHrefForFileProtocol) || function (u) { return u; };
if (wireDay && wireDay.dossier_file) {
hdrEl.innerHTML =
"Dated 00:00 GMT Wire Dossier (<a href='" + wireDay.archive_route + "' style='color:var(--cyan);'>" +
"Dated 00:00 GMT Wire Dossier (<a href='" + resolveUrl(wireDay.archive_route) + "' target='_blank' style='color:var(--cyan);'>" +
wireDay.dossier_file + "</a> &bull; " + wireDay.equation_counts.total + " Verified Equations):";
tapeEl.innerHTML = (wireDay.sample_equations || [])
.map(
(eq) =>
"<div class='eq-item'><div><strong style='color:var(--gold);'>[" + eq.target + "]</strong> " +
"<code>" + eq.ing + "</code> (\"" + eq.eng + "\")</div>" +
"<div style='color:var(--text-muted);font-size:0.65rem;'>" + eq.breakdown + " = " + eq.target + "</div></div>"
(eq) => {
const dLink = resolveUrl(eq.dossier_deep_link || wireDay.archive_route);
const gLink = resolveUrl((eq.graph_hub_links && eq.graph_hub_links[0]) || ("/graph/index.html?select=aq:" + eq.target));
const aLink = eq.api_highlight_link || ("/api/v1/dossiers/" + wireDay.dossier_number + "?highlight=" + encodeURIComponent(eq.ing.slice(0, 20)));
return "<div class='eq-item'><div><strong style='color:var(--gold);'>[" + eq.target + "]</strong> " +
"<code>" + eq.ing + "</code> (\"" + eq.eng + "\")</div>" +
"<div style='color:var(--text-muted);font-size:0.65rem;margin-bottom:0.2rem;'>" + eq.breakdown + " = " + eq.target + "</div>" +
"<div style='display:flex;flex-wrap:wrap;gap:0.3rem;'>" +
"<a class='pill' style='text-decoration:none;font-size:0.62rem;padding:0.12rem 0.4rem;color:var(--emerald);' href='" + dLink + "' target='_blank'>Passage #:~:text= \u2197</a>" +
"<a class='pill' style='text-decoration:none;font-size:0.62rem;padding:0.12rem 0.4rem;color:var(--cyan);' href='" + gLink + "' target='_blank'>Graph Hub \u2197</a>" +
"<button type='button' class='pill preview-api-btn' data-api='" + aLink + "' data-fallback='" + eq.ing + " (\"" + eq.eng + "\") = " + eq.target + "' style='font-size:0.62rem;padding:0.12rem 0.4rem;color:var(--violet);'>Preview Passage</button>" +
"</div></div>";
}
)
.join("");
} else {
hdrEl.textContent = "Dated 00:00 GMT Wire Dossier (" + dt + "):";
tapeEl.innerHTML = "<div style='color:var(--text-muted);'>No separate dated news dossier archived on " + dt + " (US Closing-Bell Market Telemetry Bar active).</div>";
}
document.querySelectorAll(".preview-api-btn").forEach(function (btn) {
btn.onclick = function () {
const apiTarget = btn.getAttribute("data-api");
const fallbackTxt = btn.getAttribute("data-fallback") || (inst.doc_references && inst.doc_references.verbatim_citation_passage) || "";
const previewBox = document.getElementById("passagePreviewBox");
if (!previewBox) return;
previewBox.style.display = "block";
previewBox.textContent = "Loading passage preview from " + apiTarget + " ...";
fetch(apiTarget)
.then(function (r) { return r.json(); })
.then(function (j) {
const d = (j && j.data) || j || {};
const matches = d.matched_passages || [];
if (matches.length > 0) {
previewBox.textContent =
"[REST API Passage Match in " + (d.uri || apiTarget) + " — Line " + matches[0].line_number + "]\n" +
matches[0].context;
} else {
previewBox.textContent = "[Passage Preview]\n" + fallbackTxt;
}
})
.catch(function () {
previewBox.textContent = "[Offline Passage Preview]\n" + fallbackTxt;
});
};
});
}
function renderLagExplorer() {
@@ -391,22 +559,32 @@
const container = document.getElementById("lagBarsContainer");
let html = "";
for (let tau = -5; tau <= 5; tau++) {
const r = Number(curve[String(tau)] || 0);
const hPct = Math.max(6, Math.round(Math.abs(r) * 85));
const color = tau === optLag ? "var(--gold)" : (r >= 0 ? "var(--cyan)" : "var(--rose)");
html +=
"<div class='lag-col' title='Lag tau=" + tau + "d: r=" + r.toFixed(3) + "'>" +
"<div style='font-size:0.62rem;color:var(--text-main);'>" + r.toFixed(2) + "</div>" +
"<div class='lag-bar' style='height:" + hPct + "px;background:" + color + ";'></div>" +
"<div class='lag-lbl'>&tau;=" + (tau >= 0 ? "+" + tau : tau) + "d</div></div>";
const rawR = curve[String(tau)];
if (rawR === null || rawR === undefined) {
html +=
"<div class='lag-col' title='Lag tau=" + tau + "d: No data available'>" +
"<div style='font-size:0.62rem;color:var(--text-muted);'>N/A</div>" +
"<div class='lag-bar' style='height:4px;background:#334155;'></div>" +
"<div class='lag-lbl'>&tau;=" + (tau >= 0 ? "+" + tau : tau) + "d</div></div>";
} else {
const r = Number(rawR);
const hPct = Math.max(6, Math.round(Math.abs(r) * 85));
const color = tau === optLag ? "var(--gold)" : (r >= 0 ? "var(--cyan)" : "var(--rose)");
html +=
"<div class='lag-col' title='Lag tau=" + tau + "d: r=" + r.toFixed(3) + "'>" +
"<div style='font-size:0.62rem;color:var(--text-main);'>" + r.toFixed(2) + "</div>" +
"<div class='lag-bar' style='height:" + hPct + "px;background:" + color + ";'></div>" +
"<div class='lag-lbl'>&tau;=" + (tau >= 0 ? "+" + tau : tau) + "d</div></div>";
}
}
container.innerHTML = html;
const pGate = DATA.periodicity_gate || {};
const optLagDisp = optLag !== null && optLag !== undefined ? ((optLag >= 0 ? "+" + optLag : optLag) + "d") : "No data available";
document.getElementById("periodicityAuditFooter").textContent =
"Periodicity Gate Enforced: " + pGate.dated_news_dossiers_ingested + " dated 00:00 UTC news dossiers + 30 daily 21:30 UTC closing-bell bars (" +
pGate.non_periodic_records_ingested + " non-periodic/static records ingested) | Optimal Lag tau* = " +
(optLag >= 0 ? "+" + optLag : optLag) + "d | CIDv1: " + (DATA.ipld_dag_json_cidv1 && DATA.ipld_dag_json_cidv1["/"]);
"Periodicity Gate Enforced: " + pGate.dated_news_dossiers_ingested + " dated 00:00 UTC news dossiers + real exchange closing-bell bars (" +
pGate.non_periodic_records_ingested + " non-periodic/static records ingested; missing bars = null / No data available) | Optimal Lag tau* = " +
optLagDisp + " | CIDv1: " + (DATA.ipld_dag_json_cidv1 && DATA.ipld_dag_json_cidv1["/"]);
}
function renderAll() {
@@ -478,5 +656,25 @@
a.click();
};
window.HyperstitionStudio = window.HyperstitionStudio || {};
window.HyperstitionStudio.QuantWorkbenchApp = {
getState: function () { return Object.assign({}, state); },
setStateAndRender: function (nextState, spotlight) {
if (nextState) {
if (nextState.guildFilter) state.guildFilter = nextState.guildFilter;
if (nextState.selectedSymbol) state.selectedSymbol = nextState.selectedSymbol;
if (nextState.selectedLens && DATA.lens_registry_meta[nextState.selectedLens]) {
state.selectedLens = nextState.selectedLens;
}
if (nextState.metricMode) state.metricMode = nextState.metricMode;
if (typeof nextState.selectedDateIdx === "number") {
state.selectedDateIdx = Math.max(0, Math.min(DATA.dates_utc.length - 1, nextState.selectedDateIdx));
}
}
activeSpotlight = spotlight || null;
renderAll();
}
};
renderAll();
})();
+1 -1
View File
@@ -1,3 +1,3 @@
// Auto-generated synchronous time-series bundle for file:// and https:// portability
window.HyperstitionStudio = window.HyperstitionStudio || {};
window.HyperstitionStudio.QuantTimeSeries = {"$schema": "./schemas/v1/quant-timeseries.schema.json", "$id": "urn:io:hyperstitionstud:schema:v1:quant-timeseries", "version": "2.0.18", "namespace_urn": "urn:io:hyperstitionstud:quant-timeseries:2.0.18", "generated_at_utc": "2026-11-30T05:40:45Z", "periodicity_gate": {"enforced": true, "allowed_cadences": ["1d-us-closing-bell-2130-utc", "24h-news-wire-rollover-0000-utc"], "dated_news_dossiers_ingested": 21, "excluded_non_periodic_sources": ["01-ingglish-aq-lexicon.md", "10-19-ledger-*.md", "20-24-dossier-*.md", "26-45-dossier-*.md", "65-69-dossier-technocapital-singularity-*.md", "technocapital-singularity-zoology/encyclopedia/*", "proposal-*.md", "lecture-*.md", "podcast-ep*.md", "haiperdohp-jemaytreeah/db.json"], "non_periodic_records_ingested": 0}, "enabled_lenses": ["fund_manager", "neutral_math", "corporate_board", "tierzoo_ecology", "fantasy_sabermetrics", "pokedex_scanner"], "default_lens": "fund_manager", "lens_registry_meta": {"fund_manager": {"lens_id": "fund_manager", "title": "Quantitative Hedge Fund & Factor Risk", "short_label": "Quant Factor", "structural_labels": {"struct_isometric_armor": "Chokepoint Moat", "struct_drift_velocity": "Signal Velocity", "struct_variance_collapse": "Convergence Power", "struct_trophic_capture": "Institutional Coupling", "struct_prime_density": "Idiosyncratic Asymmetry", "struct_repricing_resilience": "Regime Robustness"}, "timeseries_labels": {"ts_duty_cycle_pct": "Signal Duty Cycle / Hit Rate (%)", "ts_weighted_resonance": "Conviction-Weighted Exposure (0-100)", "ts_excess_over_replacement": "Information Ratio / Alpha Over Benchmark", "ts_quantile_profile": "Downside VaR_20 / Upside P90 / Convexity CV", "ts_optimal_lag_days": "Granger Lead-Lag Horizon τ* (Days)", "ts_regime_splits": "Regime-Conditional Beta Split (M1/M2/M3)"}}, "neutral_math": {"lens_id": "neutral_math", "title": "Neutral Mathematical & Statistical Invariants", "short_label": "Neutral Math", "structural_labels": {"struct_isometric_armor": "G4 Isometric Ratio (Δ=0)", "struct_drift_velocity": "G3 Inverse Phonemic Drift", "struct_variance_collapse": "G1 Log Variance Collapse", "struct_trophic_capture": "Bipartite S×S6 Coupling Degree", "struct_prime_density": "G5 Prime & Twin-Prime Density", "struct_repricing_resilience": "Repricing Counter-Swap Closure"}, "timeseries_labels": {"ts_duty_cycle_pct": "Active Duty Cycle Pr[X_t > 0] (%)", "ts_weighted_resonance": "Weighted Resonance Index (0-100)", "ts_excess_over_replacement": "Excess Value Over Baseline (σ-Units)", "ts_quantile_profile": "Quantile Spread (P20 / P90 / CV)", "ts_optimal_lag_days": "Peak Cross-Correlation Lag τ* (Days)", "ts_regime_splits": "Conditional Regime Delta E[X|S_t] - μ"}}, "corporate_board": {"lens_id": "corporate_board", "title": "Corporate Strategy & Balance-Sheet Governance", "short_label": "Corporate Board", "structural_labels": {"struct_isometric_armor": "Supply-Chain Moat", "struct_drift_velocity": "Execution Agility", "struct_variance_collapse": "Cross-Unit Synergy", "struct_trophic_capture": "Governance & Balance-Sheet Integration", "struct_prime_density": "Proprietary IP Density", "struct_repricing_resilience": "Stress-Test Resilience"}, "timeseries_labels": {"ts_duty_cycle_pct": "Operational Utilization Cadence (%)", "ts_weighted_resonance": "Strategic Capital Share (0-100)", "ts_excess_over_replacement": "Net Economic Value Added (EVA)", "ts_quantile_profile": "Base-Case Floor / Upside Case / Variance", "ts_optimal_lag_days": "Guidance-to-Market Lead Time τ* (Days)", "ts_regime_splits": "Macro Stress-Scenario Delta (Halt/Surge/Cap)"}}, "tierzoo_ecology": {"lens_id": "tierzoo_ecology", "title": "TierZoo Ecological Trophic Index (ETI)", "short_label": "TierZoo (ETI)", "structural_labels": {"struct_isometric_armor": "ARM (G4 Isometric Chokepoint Armor)", "struct_drift_velocity": "VEL (Teleoplexic Escape Velocity)", "struct_variance_collapse": "COL (G1 Variance-Collapse Compression)", "struct_trophic_capture": "CAP (S×S6 Double-Articulation & Capture)", "struct_prime_density": "PRM (Prime & G5 Twin-Prime Mutation IQ)", "struct_repricing_resilience": "RES (Tri-Modal Repricing & State Resilience)"}, "timeseries_labels": {"ts_duty_cycle_pct": "Foraging Activity Duty Cycle (%)", "ts_weighted_resonance": "Trophic Dominance Rating (0-100)", "ts_excess_over_replacement": "Apex Surplus Over Extinction Floor", "ts_quantile_profile": "Metabolic Floor / Burst Ceiling / Niche CV", "ts_optimal_lag_days": "Predator-Prey Phase Lead τ* (Days)", "ts_regime_splits": "Biome Weather Adaptation Split (M1/M2/M3)"}}, "fantasy_sabermetrics": {"lens_id": "fantasy_sabermetrics", "title": "Fantasy Football & Sabermetric Roster Engine", "short_label": "Fantasy Sabermetrics", "structural_labels": {"struct_isometric_armor": "Pass Protection (OL Chokepoint Block)", "struct_drift_velocity": "Breakaway Speed (Open-Field Velocity)", "struct_variance_collapse": "Stack Power (Multi-Asset CorrelatiLine truncated
window.HyperstitionStudio.QuantTimeSeries = {"$schema": "./schemas/v1/quant-timeseries.schema.json", "$id": "urn:io:hyperstitionstud:schema:v1:quant-timeseries", "version": "2.0.23", "namespace_urn": "urn:io:hyperstitionstud:quant-timeseries:2.0.23", "generated_at_utc": "2026-11-30T08:33:23Z", "synthetic_data_eliminated": true, "periodicity_gate": {"enforced": true, "allowed_cadences": ["1d-us-closing-bell-2130-utc", "24h-news-wire-rollover-0000-utc"], "dated_news_dossiers_ingested": 21, "excluded_non_periodic_sources": ["01-ingglish-aq-lexicon.md", "10-19-ledger-*.md", "20-24-dossier-*.md", "26-45-dossier-*.md", "65-69-dossier-technocapital-singularity-*.md", "technocapital-singularity-zoology/encyclopedia/*", "proposal-*.md", "lecture-*.md", "podcast-ep*.md", "haiperdohp-jemaytreeah/db.json"], "non_periodic_records_ingested": 0, "missing_data_policy": "No data available (never synthesized or interpolated)"}, "enabled_lenses": ["fund_manager", "neutral_math", "corporate_board", "tierzoo_ecology", "fantasy_sabermetrics", "pokedex_scanner"], "default_lens": "fund_manager", "lens_registry_meta": {"fund_manager": {"lens_id": "fund_manager", "title": "Quantitative Hedge Fund & Factor Risk", "short_label": "Quant Factor", "structural_labels": {"struct_isometric_armor": "Chokepoint Moat", "struct_drift_velocity": "Signal Velocity", "struct_variance_collapse": "Convergence Power", "struct_trophic_capture": "Institutional Coupling", "struct_prime_density": "Idiosyncratic Asymmetry", "struct_repricing_resilience": "Regime Robustness"}, "timeseries_labels": {"ts_duty_cycle_pct": "Signal Duty Cycle / Hit Rate (%)", "ts_weighted_resonance": "Conviction-Weighted Exposure (0-100)", "ts_excess_over_replacement": "Information Ratio / Alpha Over Benchmark", "ts_quantile_profile": "Downside VaR_20 / Upside P90 / Convexity CV", "ts_optimal_lag_days": "Granger Lead-Lag Horizon τ* (Days)", "ts_regime_splits": "Regime-Conditional Beta Split (M1/M2/M3)"}}, "neutral_math": {"lens_id": "neutral_math", "title": "Neutral Mathematical & Statistical Invariants", "short_label": "Neutral Math", "structural_labels": {"struct_isometric_armor": "G4 Isometric Ratio (Δ=0)", "struct_drift_velocity": "G3 Inverse Phonemic Drift", "struct_variance_collapse": "G1 Log Variance Collapse", "struct_trophic_capture": "Bipartite S×S6 Coupling Degree", "struct_prime_density": "G5 Prime & Twin-Prime Density", "struct_repricing_resilience": "Repricing Counter-Swap Closure"}, "timeseries_labels": {"ts_duty_cycle_pct": "Active Duty Cycle Pr[X_t > 0] (%)", "ts_weighted_resonance": "Weighted Resonance Index (0-100)", "ts_excess_over_replacement": "Excess Value Over Baseline (σ-Units)", "ts_quantile_profile": "Quantile Spread (P20 / P90 / CV)", "ts_optimal_lag_days": "Peak Cross-Correlation Lag τ* (Days)", "ts_regime_splits": "Conditional Regime Delta E[X|S_t] - μ"}}, "corporate_board": {"lens_id": "corporate_board", "title": "Corporate Strategy & Balance-Sheet Governance", "short_label": "Corporate Board", "structural_labels": {"struct_isometric_armor": "Supply-Chain Moat", "struct_drift_velocity": "Execution Agility", "struct_variance_collapse": "Cross-Unit Synergy", "struct_trophic_capture": "Governance & Balance-Sheet Integration", "struct_prime_density": "Proprietary IP Density", "struct_repricing_resilience": "Stress-Test Resilience"}, "timeseries_labels": {"ts_duty_cycle_pct": "Operational Utilization Cadence (%)", "ts_weighted_resonance": "Strategic Capital Share (0-100)", "ts_excess_over_replacement": "Net Economic Value Added (EVA)", "ts_quantile_profile": "Base-Case Floor / Upside Case / Variance", "ts_optimal_lag_days": "Guidance-to-Market Lead Time τ* (Days)", "ts_regime_splits": "Macro Stress-Scenario Delta (Halt/Surge/Cap)"}}, "tierzoo_ecology": {"lens_id": "tierzoo_ecology", "title": "TierZoo Ecological Trophic Index (ETI)", "short_label": "TierZoo (ETI)", "structural_labels": {"struct_isometric_armor": "ARM (G4 Isometric Chokepoint Armor)", "struct_drift_velocity": "VEL (Teleoplexic Escape Velocity)", "struct_variance_collapse": "COL (G1 Variance-Collapse Compression)", "struct_trophic_capture": "CAP (S×S6 Double-Articulation & Capture)", "struct_prime_density": "PRM (Prime & G5 Twin-Prime Mutation IQ)", "struct_repricing_resilience": "RES (Tri-Modal Repricing & State Resilience)"}, "timeseries_labels": {"ts_duty_cycle_pct": "Foraging Activity Duty Cycle (%)", "ts_weighted_resonance": "Trophic Dominance Rating (0-100)", "ts_excess_over_replacement": "Apex Surplus Over Extinction Floor", "ts_quantile_profile": "Metabolic Floor / Burst Ceiling / Niche CV", "ts_optimal_lag_days": "Predator-Prey Phase Lead τ* (Days)", "ts_regime_splits": "Biome Weather Adaptation Split (M1/M2/M3)"}}, "fantasy_sabermetrics": {"lens_id": "fantasy_sabermetrics", "title": "Fantasy Football & Sabermetric Roster Engine", "short_label": "Fantasy Sabermetrics", "structural_labels": {"struct_isometric_armor": "Pass Protection (OL Chokepoint Block)", "struct_drift_Line truncated
+21718 -18355
View File
File diff suppressed because it is too large. Load diff
+647
View File
@@ -0,0 +1,647 @@
// /workspace/hyperstitionstudio-core/site/quant/quant-tutorials.js
// Option B Zero-MP4 Interactive HTML5 Canvas Tutorial Player & Deep-Link Choreographer (v2.0.23)
(function () {
"use strict";
window.HyperstitionStudio = window.HyperstitionStudio || {};
const EPISODES = [
{
id: "ep01",
code: "Ep 01",
title: "The Strict Periodicity Gate & Watchlist Topology",
keyframes: [
{
title: "1.1 Strict Periodicity Gate (21:30 UTC Close x 00:00 UTC Wire)",
state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 29 },
spotlight: { target: "canvas", pane: "top", xRatio: 0.96, yRatio: 0.22, label: "Strict Periodicity Gate: 30 UTC Days x 24 Tickers" },
subtitle: "Only periodic timestamp-indexed sources (21:30 UTC US Closing-Bell bars and 00:00 UTC dated news dossiers) enter this workbench. Static lexicons and undated ledgers are strictly excluded (0 non-periodic records).",
citations: [
{ label: "Vol 08A PDF (Room Filter)", href: "/encyclopedia/08-stakeholder-registers-idioms-and-pokedex-semiotics/a-to-h-ai-powered-race-to-hidden-chokepoint-screen.pdf#page=2&search=Room%20Filter" },
{ label: "Archive Methodology", href: "/archive/00-index-and-methodology.md#:~:text=closing-bell" },
{ label: "Graph Hub aq:137", href: "/graph/index.html?select=aq:137" }
]
},
{
title: "1.2 Guild S1 — Autoregressive AI Syndicate (Coordinate 292)",
state: { guildFilter: "S1", selectedSymbol: "MSFT", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 28 },
spotlight: { target: "canvas", pane: "top", xRatio: 0.90, yRatio: 0.28, label: "S1 AI Guild Filter Active (292 Singularity)" },
subtitle: "Filtering by Guild S1 isolates the Autoregressive AI Syndicate anchored on Coordinate 292 (shizohnalizis == abstrakt masheen == sinthetik dayta == asset management [Gen 0]).",
citations: [
{ label: "Vol 03A PDF (S1 AI)", href: "/encyclopedia/03-machinic-phylum-guilds-s1-to-s5/class-s1-autoregressive-ai-and-abstract-machine-a-to-z.pdf#page=1&search=292" },
{ label: "Dossier 65 (292 Lock)", href: "/zoology/dossiers/65-dossier-technocapital-singularity-autoregressive-ai.md#:~:text=292" },
{ label: "Graph Build S1", href: "/graph/index.html?select=build:S1" }
]
},
{
title: "1.3 Guild S3 — Silicon-Photonic War Machine (137 & 81)",
state: { guildFilter: "S3", selectedSymbol: "ASML", selectedLens: "corporate_board", metricMode: "close_usd", selectedDateIdx: 29 },
spotlight: { target: "canvas", pane: "top", xRatio: 0.95, yRatio: 0.30, label: "S3 Isometric Chokepoint: ASML = asml = 81 (Δ = 0)" },
subtitle: "Guild S3 maps physical wafer and EUV lithography chokepoints: ASML (81, Δ = 0 isometric), TSMC (95, Δ = 0), and Nvidia (envideea = 137 [33rd Prime]).",
citations: [
{ label: "Vol 03C PDF (p.5 ASML/envideea)", href: "/encyclopedia/03-machinic-phylum-guilds-s1-to-s5/class-s3-silicon-war-machine-and-euv-swarm-a-to-z.pdf#page=5&search=envideea" },
{ label: "Dossier 67 (Silicon War Machine)", href: "/zoology/dossiers/67-dossier-technocapital-singularity-silicon-war-machine.md#:~:text=137" },
{ label: "Graph Hub aq:81", href: "/graph/index.html?select=aq:81" }
]
},
{
title: "1.4 Guild S6 — Apparatus of Capture (Coordinate 125)",
state: { guildFilter: "S6", selectedSymbol: "BLK", selectedLens: "corporate_board", metricMode: "spoken_aq", selectedDateIdx: 27 },
spotlight: { target: "canvas", pane: "top", xRatio: 0.86, yRatio: 0.26, label: "S6 Capture Ring: kapatal == kapcher == fohldz = 125" },
subtitle: "Guild S6 tracks sovereign and balance-sheet capture around Coordinate 125 (kapatal == kapcher == fohldz = 125) and charter/sloth (136).",
citations: [
{ label: "Vol 04A PDF (S6 Capture)", href: "/encyclopedia/04-capital-organizational-capture-s6/a-to-f-acquisition-to-fund.pdf#page=1&search=125" },
{ label: "Dossier 68 (Capture)", href: "/zoology/dossiers/68-dossier-technocapital-singularity-apparatus-of-capture.md#:~:text=125" },
{ label: "Graph Hub aq:125", href: "/graph/index.html?select=aq:125" }
]
},
{
title: "1.5 Periodicity Audit Footer & IPLD dag-json CIDv1",
state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 29 },
spotlight: { target: "panel4", xRatio: 0.50, yRatio: 0.85, label: "Cryptographic CIDv1 & Periodicity Audit Footer" },
subtitle: "The bottom footer verifies 21 dated 00:00 UTC dossiers + 30 closing-bell bars, 0 non-periodic records, and the deterministic IPLD dag-json CIDv1 digest (baguqeera...).",
citations: [
{ label: "Static Bundle quant-timeseries.json", href: "/quant/quant-timeseries.json" },
{ label: "REST API /api/v1/quant/timeseries", href: "/api/v1/quant/timeseries?symbol=NVDA" },
{ label: "Schema quant-timeseries.schema.json", href: "/schemas/v1/quant-timeseries.schema.json" }
]
}
]
},
{
id: "ep02",
code: "Ep 02",
title: "Reading Panel 1: Spoken AQ Curves, Gold/Cyan Beacons & Regimes",
keyframes: [
{
title: "2.1 Top Pane: Dashed Crimson Identity Line & Real Scope 1 Self-Lock (PLTR)",
state: { guildFilter: "ALL", selectedSymbol: "PLTR", selectedLens: "fund_manager", metricMode: "close_usd", selectedDateIdx: 22 },
spotlight: { target: "canvas", pane: "top", xRatio: 0.76, yRatio: 0.25, label: "Real Scope 1 Self-Lock: PLTR Close $159.36 (159 == palanter)" },
subtitle: "On 2026-11-23, Palantir (PLTR) closed at $159.36 on the exchange: its rounded integer price (159) lands directly on the dashed crimson threshold marking its own Gen 1 Ingglish name (palanter = 159), firing a real Scope 1 Gold Beacon.",
citations: [
{ label: "Vol 03C PDF (S3 War Machine)", href: "/encyclopedia/03-machinic-phylum-guilds-s1-to-s5/class-s3-silicon-war-machine-and-euv-swarm-a-to-z.pdf#page=5&search=palanter" },
{ label: "Dossier 67 (Silicon War Machine)", href: "/zoology/dossiers/67-dossier-technocapital-singularity-silicon-war-machine.md#:~:text=137" },
{ label: "Graph Hub aq:159", href: "/graph/index.html?select=aq:159" }
]
},
{
title: "2.2 Move (BPS) Mode: TSMC (TSM) +81 bps Ring Migration & Microsoft -125 bps",
state: { guildFilter: "ALL", selectedSymbol: "TSM", selectedLens: "fund_manager", metricMode: "change_bps", selectedDateIdx: 17 },
spotlight: { target: "canvas", pane: "top", xRatio: 0.59, yRatio: 0.24, label: "Real Exchange Move: TSM +81 bps on 2026-11-18 (Ring 81 == asml)" },
subtitle: "Switching Metric Mode to Move (BPS) on 2026-11-18 shows TSMC (TSM) moving +81 bps ($359.70 -> $362.62), landing on the S3 lithography coordinate 81 (asml = 81).",
citations: [
{ label: "Vol 03C PDF (ASML = 81)", href: "/encyclopedia/03-machinic-phylum-guilds-s1-to-s5/class-s3-silicon-war-machine-and-euv-swarm-a-to-z.pdf#page=1&search=ASML" },
{ label: "Graph Hub aq:81", href: "/graph/index.html?select=aq:81" }
]
},
{
title: "2.3 Real Repdigit Attractor Lock: Broadcom (AVGO) at $333.40 & NVDA Spoken 333",
state: { guildFilter: "ALL", selectedSymbol: "AVGO", selectedLens: "fund_manager", metricMode: "close_usd", selectedDateIdx: 15 },
spotlight: { target: "canvas", pane: "top", xRatio: 0.52, yRatio: 0.20, label: "Real Exchange Repdigit Lock: AVGO $333.40 on 2026-11-16 (333 = 3 x 111)" },
subtitle: "On 2026-11-16, Broadcom (AVGO) closed at $333.40 (rounded integer 333 = 3 x 111), and on 2026-11-03 Nvidia (NVDA) closed at $206.69 ('too huhndrad siks' = 333), firing real Scope 1 Repdigit Gold Beacons.",
citations: [
{ label: "Vol 03C PDF (S3 Guild)", href: "/encyclopedia/03-machinic-phylum-guilds-s1-to-s5/class-s3-silicon-war-machine-and-euv-swarm-a-to-z.pdf#page=1&search=333" },
{ label: "Graph Hub aq:333", href: "/graph/index.html?select=aq:333" }
]
},
{
title: "2.4 Middle Pane: 00:00 GMT Wire Velocity & Emerald Scope 3 Bars",
state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 28 },
spotlight: { target: "canvas", pane: "mid", xRatio: 0.93, yRatio: 0.63, label: "Emerald Bar = Scope 3 News-Wire Co-Presence" },
subtitle: "In the middle pane, Violet bars show daily 333/666/777 equation counts; Emerald bars highlight UTC dates where the selected ticker co-occurred in breaking 00:00 GMT news headlines.",
citations: [
{ label: "Dossier 71 (2026-11-29)", href: "/archive/71-dossier-news-2026-11-29.md#:~:text=333" },
{ label: "REST Highlight Preview", href: "/api/v1/dossiers/71?highlight=envideea" }
]
},
{
title: "2.5 Bottom Pane: 20-Day Volume Ratio & M1/M2/M3 Thermodynamic Regimes",
state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 25 },
spotlight: { target: "canvas", pane: "bot", xRatio: 0.83, yRatio: 0.86, label: "Thermodynamic Regime Color Coding (M1 Gold / M2 Crimson / M3 Sky)" },
subtitle: "The bottom pane color-codes 20d relative volume by objective thermodynamic state: Gold (<0.45x) = M1 Stagnation (137), Crimson (>=2.5x or <=-5%) = M2 Flash-Crash Surge (193), Sky-Blue = M3 Leviathan.",
citations: [
{ label: "Vol 05A PDF (Subclass M1)", href: "/encyclopedia/05-memetic-superclass-and-emergent-m7/m1-vampiric-entropic-and-anti-productive-a-to-m.pdf#page=1&search=M1" },
{ label: "Vol 05C PDF (M2-M6)", href: "/encyclopedia/05-memetic-superclass-and-emergent-m7/m2-to-m6-kinetic-leviathan-mimetic-oracle-abyssal-a-to-z.pdf#page=1&search=M2" }
]
}
]
},
{
id: "ep03",
code: "Ep 03",
title: "Panels 2 & 3: The 24x30 Lock Heatmap, TradingView & Deep Citations",
keyframes: [
{
title: "3.1 Panel 2: 24x30 Heatmap & Explicit 'No Data Available' Handling (ANTHR-PVT & Weekends)",
state: { guildFilter: "ALL", selectedSymbol: "ANTHR-PVT", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 17 },
spotlight: { target: "panel2", xRatio: 0.50, yRatio: 0.40, label: "Zero Synthetic Data: ANTHR-PVT & Closed Market Days Show 'No data available'" },
subtitle: "This workbench never synthesizes or interpolates missing market data. Because Anthropic (ANTHR-PVT) is a private entity with no public exchange feed (and US stock markets close on weekends and Thanksgiving), those cells explicitly state 'No data available'.",
citations: [
{ label: "Vol 06A PDF (Anchor Revision)", href: "/encyclopedia/06-genealogical-vectors-and-quantitative-repricing/a-to-m-attractors-to-multi-build-flex-singularities.pdf#page=1&search=193" },
{ label: "Dossier 66 (193 Flash Crash)", href: "/zoology/dossiers/66-dossier-technocapital-singularity-flash-crash-liquidity.md#:~:text=193" },
{ label: "Graph Hub aq:193", href: "/graph/index.html?select=aq:193" }
]
},
{
title: "3.2 TradingView Superchart Launcher (Shortcut: T)",
state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 29 },
spotlight: { target: "panel3", xRatio: 0.85, yRatio: 0.12, label: "Open TradingView Chart ↗ (Zero External Script Embeds)" },
subtitle: "Every ticker resolves deterministically to EXCHANGE:SYMBOL (e.g. NASDAQ:NVDA). Clicking 'TradingView ↗' or pressing 'T' opens the live Superchart in a new window while keeping 0 external scripts embedded.",
citations: [
{ label: "Launch TradingView (NASDAQ:NVDA)", href: "https://www.tradingview.com/chart/?symbol=NASDAQ%3ANVDA" },
{ label: "Operator's Manual (PDF)", href: "/quant/OPERATORS-MANUAL-QUANT-TIMESERIES-WORKBENCH.pdf#page=1&search=TradingView" }
]
},
{
title: "3.3 Panel 3: Knowledge-Graph-Modeled Documentation & Cited Passages Card",
state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 28 },
spotlight: { target: "docCard", xRatio: 0.50, yRatio: 0.50, label: "Passage-Encoded PDF (#page & search) + Dossier (#:~:text=) Links" },
subtitle: "Modeled directly on the Knowledge Graph's inspector drawer, the Documentation Card links every ticker to its exact Encyclopedia PDF page (#page=N&search=...), Dossier passage (#:~:text=...), and Graph node (?select=aq:N).",
citations: [
{ label: "Vol 03C PDF (#page=5&search=envideea)", href: "/encyclopedia/03-machinic-phylum-guilds-s1-to-s5/class-s3-silicon-war-machine-and-euv-swarm-a-to-z.pdf#page=5&search=envideea" },
{ label: "Graph Deep Link (?select=aq:137)", href: "/graph/index.html?select=aq:137" },
{ label: "REST API Highlight (/api/v1/dossiers/67?highlight=137)", href: "/api/v1/dossiers/67?highlight=137" }
]
},
{
title: "3.4 Panel 3: Verbatim Dated Memetic Equation Tape & Inline Passage Preview",
state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 28 },
spotlight: { target: "wireTape", xRatio: 0.50, yRatio: 0.50, label: "Dated 333 / 666 / 777 Equations with Scroll-to-Text Deep Links" },
subtitle: "Every equation in the Dated Wire Tape includes a WICG scroll-to-text link (#:~:text=...), a Knowledge Graph coordinate link, and an inline REST passage preview button.",
citations: [
{ label: "Dossier 71 Scroll-to-Text", href: "/archive/71-dossier-news-2026-11-29.md#:~:text=333" },
{ label: "REST Dossier 71 JSON", href: "/api/v1/dossiers/71?highlight=333" }
]
},
{
title: "3.5 Bidirectional Graph & Dossier Cross-Verification",
state: { guildFilter: "ALL", selectedSymbol: "COIN", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 27 },
spotlight: { target: "docCard", xRatio: 0.50, yRatio: 0.50, label: "Cross-Corpus Coordinate Verification" },
subtitle: "Clicking any coordinate pill jumps straight to the Encyclopedia Knowledge Graph with that node centered and isolated in the right-hand drawer.",
citations: [
{ label: "Graph Node aq:211", href: "/graph/index.html?select=aq:211" },
{ label: "Dossier 68 (S6 Capture)", href: "/zoology/dossiers/68-dossier-technocapital-singularity-apparatus-of-capture.md#:~:text=125" }
]
}
]
},
{
id: "ep04",
code: "Ep 04",
title: "Hot-Swapping Projection Lenses (LENS_REGISTRY Reversibility)",
keyframes: [
{
title: "4.1 Lens 1: Neutral Mathematical Substrate (neutral_math)",
state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "neutral_math", metricMode: "spoken_aq", selectedDateIdx: 29 },
spotlight: { target: "lensCard", xRatio: 0.50, yRatio: 0.50, label: "Pure Lens-Neutral Keys (struct_* & ts_*)" },
subtitle: "Under the hood, quant-timeseries.json stores 100% lens-neutral mathematical keys (struct_isometric_armor, ts_duty_cycle_pct, ts_weighted_resonance, ts_excess_over_replacement, ts_optimal_lag_days).",
citations: [
{ label: "Schema quant-timeseries.schema.json", href: "/schemas/v1/quant-timeseries.schema.json" },
{ label: "Vol 08A PDF (Stakeholder Registers)", href: "/encyclopedia/08-stakeholder-registers-idioms-and-pokedex-semiotics/a-to-h-ai-powered-race-to-hidden-chokepoint-screen.pdf#page=1&search=Register" }
]
},
{
title: "4.2 Lens 2: Out-of-Sample Quantitative Factor Register (fund_manager)",
state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 29 },
spotlight: { target: "lensCard", xRatio: 0.50, yRatio: 0.50, label: "Fund Manager Register: Signal Duty Cycle & Alpha Over Benchmark" },
subtitle: "Switching to 'Quant Factor (fund_manager)' translates the exact same 6 numbers into institutional factor terminology (Chokepoint Moat, Signal Duty Cycle %, Composite Resonance Load).",
citations: [
{ label: "Fund Manager Proposal (PDF)", href: "/zoology/proposal-fund-manager-novel-investment-discovery.pdf#page=1&search=Uncaptured" },
{ label: "REST Tier List (fund_manager)", href: "/api/v1/zoology/tier-list?register=fund_manager" }
]
},
{
title: "4.3 Lens 3: Corporate Board & Supply-Chain Governance (corporate_board)",
state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "corporate_board", metricMode: "spoken_aq", selectedDateIdx: 29 },
spotlight: { target: "lensCard", xRatio: 0.50, yRatio: 0.50, label: "Corporate Board Register: Supply-Chain Moat & Stress-Test Delta" },
subtitle: "Switching to 'Corporate Board' frames those identical invariants as Supply-Chain Structural Moat, Cross-Unit Synergy, and Stress-Test Regime Delta.",
citations: [
{ label: "Corporate Board Proposal (PDF)", href: "/zoology/proposal-corporate-board-technocapital-allocation.pdf#page=1&search=Moat" },
{ label: "REST Tier List (corporate_board)", href: "/api/v1/zoology/tier-list?register=corporate_board" }
]
},
{
title: "4.4 Lens 4 & 5: TierZoo Ecology (ETI) & Fantasy Sabermetrics (SNAP% / WOPR / WAR)",
state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fantasy_sabermetrics", metricMode: "spoken_aq", selectedDateIdx: 29 },
spotlight: { target: "lensCard", xRatio: 0.50, yRatio: 0.50, label: "Fantasy Sabermetrics: SNAP%, WOPR, WAR (30d) & Matchup Splits" },
subtitle: "Switching to 'Fantasy Sabermetrics' projects SNAP% (Active Lock Share), WOPR (1.5x Target Share + 0.7x Air-Yards Share), and WAR (30d Wins Above Tier D Replacement).",
citations: [
{ label: "ETI Tier List Scorecard (PDF)", href: "/zoology/tier-list-technocapital-assemblage-builds.pdf#page=1&search=ETI" },
{ label: "Vol 07A PDF (ETI Ontology)", href: "/encyclopedia/07-ecological-trophic-index-and-tier-list/a-to-z-arm-chokepoint-armor-to-zoological-tie-breaker.pdf#page=1&search=ETI" }
]
},
{
title: "4.5 Lens 6: Gen IV Pokédex Field-Scanner (DEX #137)",
state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "pokedex_scanner", metricMode: "spoken_aq", selectedDateIdx: 29 },
spotlight: { target: "lensCard", xRatio: 0.50, yRatio: 0.50, label: "Gen IV Pokédex Scanner: DEX #137, Nature, Ability & EV Yield" },
subtitle: "Switching to 'Pokédex Scanner' deterministically derives Gen IV attributes (DEX #137, Nature, Passive Ability, EV Yield) from the 30-day time-series moments—and remains 100% removable via ENABLED_LENSES.",
citations: [
{ label: "REST Pokédex Endpoint (/api/v1/zoology/pokedex/NVDA)", href: "/api/v1/zoology/pokedex/NVDA" },
{ label: "Vol 08B PDF (Pokédex Semiotics)", href: "/encyclopedia/08-stakeholder-registers-idioms-and-pokedex-semiotics/i-to-z-idiosyncratic-prime-screen-to-united-fidelity.pdf#page=1&search=Pokedex" }
]
}
]
},
{
id: "ep05",
code: "Ep 05",
title: "Panel 4: Lead-Lag Cross-Correlation r(tau), Exports & REST APIs",
keyframes: [
{
title: "5.1 Panel 4: Lead-Lag Cross-Correlation Curve r(tau) across [-5 .. +5] Days",
state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 29 },
spotlight: { target: "panel4", xRatio: 0.50, yRatio: 0.45, label: "Pearson Cross-Correlation r(tau) & Gold Optimal Causal Lag tau*" },
subtitle: "Panel 4 computes the empirical Pearson cross-correlation r(tau) between daily 00:00 GMT news-wire equation velocity M_t and unsigned basis-point displacement |Δbps_{i, t+tau}| across lags tau in [-5, +5] days.",
citations: [
{ label: "Operator's Manual (Panel 4 Math)", href: "/quant/OPERATORS-MANUAL-QUANT-TIMESERIES-WORKBENCH.pdf#page=2&search=Correlation" },
{ label: "Graph Mode 2 Concentric Radar", href: "/graph/index.html?select=aq:137&mode=mode2_radar" }
]
},
{
title: "5.2 Interpreting Optimal Causal Lag tau* (Leader vs. Synchronizer vs. Follower)",
state: { guildFilter: "ALL", selectedSymbol: "ASML", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 29 },
spotlight: { target: "panel4", xRatio: 0.58, yRatio: 0.45, label: "Gold Bar Marks argmax |r(tau)|" },
subtitle: "The Gold bar highlights tau* = argmax |r(tau)|: tau* > 0 indicates a Teleoplexic Wire Leader (midnight wire velocity leads market volatility), tau* = 0 an Instantaneous Synchronizer, and tau* < 0 a Narrative Follower.",
citations: [
{ label: "Vol 03C PDF (ASML)", href: "/encyclopedia/03-machinic-phylum-guilds-s1-to-s5/class-s3-silicon-war-machine-and-euv-swarm-a-to-z.pdf#page=1&search=ASML" },
{ label: "Graph Node aq:81", href: "/graph/index.html?select=aq:81" }
]
},
{
title: "5.3 Portable .CSV & Lens-Neutral .JSON Slice Exports",
state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "neutral_math", metricMode: "spoken_aq", selectedDateIdx: 29 },
spotlight: { target: "panel4", xRatio: 0.82, yRatio: 0.14, label: "One-Click .CSV & Lens-Neutral .JSON Export" },
subtitle: "Click 'Export Filtered Series (.CSV)' or 'Export Lens-Neutral Slice (.JSON)' in the Panel 4 header to download any ticker's 30-day periodic bar table and structural/time-series vectors for offline research.",
citations: [
{ label: "Raw Bundle quant-timeseries.json", href: "/quant/quant-timeseries.json" },
{ label: "Schema quant-timeseries.schema.json", href: "/schemas/v1/quant-timeseries.schema.json" }
]
},
{
title: "5.4 Unified Stateless REST API v1 (/api/v1/*) & OpenAPI 3.1.0",
state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 29 },
spotlight: { target: "docCard", xRatio: 0.50, yRatio: 0.50, label: "Programmatic REST API v1 & OpenAPI 3.1.0" },
subtitle: "Every readout on /quant/ is also queryable over HTTP GET/POST via /api/v1/quant/timeseries, /api/v1/quant/instruments/{symbol}, /api/v1/dossiers/{number}?highlight=..., and /api/v1/openapi.json.",
citations: [
{ label: "OpenAPI 3.1.0 Spec (/api/v1/openapi.json)", href: "/api/v1/openapi.json" },
{ label: "REST Status (/api/v1/status)", href: "/api/v1/status" },
{ label: "REST NVDA Instrument", href: "/api/v1/quant/instruments/NVDA" }
]
},
{
title: "5.5 Complete Tour Summary & Companion Operator's Manual",
state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 29 },
spotlight: { target: "canvas", pane: "top", xRatio: 0.96, yRatio: 0.25, label: "Tour Complete — Explore Any Ticker, Lens, or Deep Citation" },
subtitle: "You have completed all 5 episodes of the /quant/ guided walkthrough. Open the Companion Operator's Manual (PDF) or click any heatmap cell, lens, or deep citation link to continue exploring.",
citations: [
{ label: "Operator's Manual (PDF)", href: "/quant/OPERATORS-MANUAL-QUANT-TIMESERIES-WORKBENCH.pdf" },
{ label: "Interactive Knowledge Graph (/graph/)", href: "/graph/index.html?select=aq:137" },
{ label: "Self-Paced Learning Track (/learn/)", href: "/learn/index.html" }
]
}
]
}
];
function adaptHrefForFileProtocol(href) {
if (!href || window.location.protocol !== "file:") return href;
if (href.startsWith("https://")) return href;
if (href.startsWith("/encyclopedia/")) {
return "../../../technocapital-singularity-zoology/encyclopedia/" + href.slice("/encyclopedia/".length);
}
if (href.startsWith("/zoology/")) {
return "../../../technocapital-singularity-zoology/" + href.slice("/zoology/".length);
}
if (href.startsWith("/archive/")) {
return "../../../ingglish-hyperdope-gematria/ingglish-aq-archive/" + href.slice("/archive/".length);
}
if (href.startsWith("/graph/")) {
return "../../../encyclopedia-knowledge-graph/" + href.slice("/graph/".length);
}
if (href.startsWith("/learn/")) {
return "../learn/" + href.slice("/learn/".length);
}
if (href.startsWith("/quant/")) {
return "./" + href.slice("/quant/".length);
}
if (href.startsWith("/schemas/")) {
return "../../schemas/" + href.slice("/schemas/".length);
}
if (href.startsWith("/api/v1/quant/")) {
return "./quant-timeseries.json";
}
if (href.startsWith("/api/v1/zoology/tier-list")) {
return "../../../technocapital-singularity-zoology/taxonomy/assemblage-builds-tier-list.json";
}
if (href.startsWith("/api/v1/dossiers/")) {
return "../../../ingglish-hyperdope-gematria/ingglish-aq-archive/71-dossier-news-2026-11-29.md";
}
return href;
}
let curEpIdx = 0;
let curStepIdx = 0;
let isPlaying = false;
let playTimer = null;
let speechEnabled = true; // Enabled by default so tour playback narrates immediately
let cachedVoices = [];
let audioCtx = null;
function refreshVoices() {
if (typeof window.speechSynthesis === "undefined") return;
try {
cachedVoices = window.speechSynthesis.getVoices() || [];
} catch (_) {
cachedVoices = [];
}
}
if (typeof window.speechSynthesis !== "undefined") {
refreshVoices();
if (typeof window.speechSynthesis.onvoiceschanged !== "undefined") {
window.speechSynthesis.onvoiceschanged = refreshVoices;
}
}
function playWebAudioTelemetryChime(stepIdx) {
try {
const Ctx = window.AudioContext || window.webkitAudioContext;
if (!Ctx) return;
if (!audioCtx) audioCtx = new Ctx();
if (audioCtx.state === "suspended") audioCtx.resume();
const baseFreqs = [292.0, 333.0, 394.0, 444.0, 528.0];
const f0 = baseFreqs[stepIdx % baseFreqs.length];
const now = audioCtx.currentTime;
[f0, f0 * 1.25, f0 * 1.5].forEach(function (freq, i) {
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
osc.type = i === 0 ? "triangle" : "sine";
osc.frequency.setValueAtTime(freq, now + i * 0.09);
gain.gain.setValueAtTime(0.001, now + i * 0.09);
gain.gain.exponentialRampToValueAtTime(0.06, now + i * 0.09 + 0.03);
gain.gain.exponentialRampToValueAtTime(0.0001, now + i * 0.09 + 0.45);
osc.connect(gain);
gain.connect(audioCtx.destination);
osc.start(now + i * 0.09);
osc.stop(now + i * 0.09 + 0.48);
});
} catch (_) {}
}
function scheduleNextStep(delayMs) {
if (playTimer) clearTimeout(playTimer);
if (!isPlaying) return;
playTimer = setTimeout(function () {
if (isPlaying) stepNext();
}, delayMs);
}
function speakSubtitle(text, onDoneCallback) {
if (!speechEnabled) {
if (onDoneCallback) scheduleNextStep(7000);
return;
}
// Always play a subtle harmonic telemetry cue at scene start so audio feedback is immediate even if OS TTS voices are absent
playWebAudioTelemetryChime(curStepIdx);
refreshVoices();
if (typeof window.speechSynthesis === "undefined" || cachedVoices.length === 0) {
if (onDoneCallback) scheduleNextStep(7500);
return;
}
try {
window.speechSynthesis.cancel();
window.speechSynthesis.resume();
setTimeout(function () {
if (!speechEnabled) return;
const u = new SpeechSynthesisUtterance(text);
const preferred = cachedVoices.find(function (v) {
return /en(-|_)(US|GB)/i.test(v.lang) && /natural|neural|google|english/i.test(v.name);
}) || cachedVoices.find(function (v) {
return /^en/i.test(v.lang);
}) || cachedVoices[0];
if (preferred) u.voice = preferred;
u.rate = 1.03;
u.pitch = 1.0;
u.volume = 1.0;
let settled = false;
const finish = function () {
if (settled) return;
settled = true;
if (onDoneCallback && isPlaying) {
scheduleNextStep(1800);
}
};
u.onend = finish;
u.onerror = finish;
window.speechSynthesis.speak(u);
// Safety fallback timer in case browser TTS engine stalls without firing onend
const estMs = Math.max(8500, Math.min(20000, text.split(/\s+/).length * 420));
if (onDoneCallback && isPlaying) {
scheduleNextStep(estMs);
}
}, 60);
} catch (_) {
if (onDoneCallback) scheduleNextStep(7500);
}
}
function getActiveKeyframe() {
const ep = EPISODES[curEpIdx] || EPISODES[0];
return ep.keyframes[curStepIdx] || ep.keyframes[0];
}
function highlightDomTarget(targetId) {
["heatmapTable", "lensProjectionCard", "docReferencesCard", "wireEqTape", "lagBarsContainer"].forEach(function (id) {
const el = document.getElementById(id);
if (el) el.style.boxShadow = "";
});
const map = {
panel2: "heatmapTable",
lensCard: "lensProjectionCard",
docCard: "docReferencesCard",
wireTape: "wireEqTape",
panel4: "lagBarsContainer"
};
const domId = map[targetId];
if (domId) {
const el = document.getElementById(domId);
if (el) {
el.style.boxShadow = "0 0 0 2px #f5c630, 0 0 18px rgba(245, 198, 48, 0.35)";
}
}
}
function applyCurrentKeyframe(narrateNow) {
const kf = getActiveKeyframe();
const app = window.HyperstitionStudio.QuantWorkbenchApp;
if (app && typeof app.setStateAndRender === "function") {
app.setStateAndRender(kf.state, kf.spotlight);
}
highlightDomTarget(kf.spotlight && kf.spotlight.target);
renderTutorialUI();
if (narrateNow || isPlaying) {
speakSubtitle(kf.subtitle, isPlaying);
}
}
function stepNext() {
const ep = EPISODES[curEpIdx];
if (curStepIdx < ep.keyframes.length - 1) {
curStepIdx++;
} else if (curEpIdx < EPISODES.length - 1) {
curEpIdx++;
curStepIdx = 0;
} else {
stopPlayback();
return;
}
applyCurrentKeyframe(true);
}
function stepPrev() {
if (curStepIdx > 0) {
curStepIdx--;
} else if (curEpIdx > 0) {
curEpIdx--;
curStepIdx = EPISODES[curEpIdx].keyframes.length - 1;
}
applyCurrentKeyframe(true);
}
function startPlayback() {
isPlaying = true;
if (playTimer) clearTimeout(playTimer);
applyCurrentKeyframe(true);
renderTutorialUI();
}
function stopPlayback() {
isPlaying = false;
if (playTimer) {
clearTimeout(playTimer);
playTimer = null;
}
if (typeof window.speechSynthesis !== "undefined") {
try { window.speechSynthesis.cancel(); } catch (_) {}
}
renderTutorialUI();
}
function renderTutorialUI() {
const epTabs = document.getElementById("tutEpisodeTabs");
const stepBadge = document.getElementById("tutStepBadge");
const scrubber = document.getElementById("tutScrubber");
const playBtn = document.getElementById("tutPlayPauseBtn");
const speechBtn = document.getElementById("tutSpeechBtn");
const titleEl = document.getElementById("tutKeyframeTitle");
const subEl = document.getElementById("tutSubtitleText");
const citesEl = document.getElementById("tutCitationPills");
if (!epTabs) return;
const ep = EPISODES[curEpIdx];
const kf = getActiveKeyframe();
epTabs.innerHTML = EPISODES.map(function (e, idx) {
const cls = "pill" + (idx === curEpIdx ? " active" : "");
return "<button type='button' class='" + cls + "' data-ep-idx='" + idx + "'>" + e.code + ": " + e.title + "</button>";
}).join("");
epTabs.querySelectorAll("[data-ep-idx]").forEach(function (b) {
b.onclick = function () {
curEpIdx = parseInt(b.getAttribute("data-ep-idx"), 10);
curStepIdx = 0;
applyCurrentKeyframe(speechEnabled);
};
});
if (playBtn) {
playBtn.textContent = isPlaying ? "\u23F8 Pause Tour" : "\u25B6 Play Guided Tour";
playBtn.className = isPlaying ? "btn tv-btn" : "btn primary";
}
if (speechBtn) {
speechBtn.textContent = speechEnabled ? "\uD83D\uDD0A Voice: ON" : "\uD83D\uDD07 Voice: OFF";
speechBtn.className = speechEnabled ? "btn primary" : "btn";
}
if (stepBadge) {
stepBadge.textContent = ep.code + " \u2022 Scene " + (curStepIdx + 1) + "/" + ep.keyframes.length;
}
if (scrubber) {
scrubber.max = String(ep.keyframes.length - 1);
scrubber.value = String(curStepIdx);
}
if (titleEl) {
titleEl.textContent = kf.title;
}
if (subEl) {
subEl.textContent = kf.subtitle;
}
if (citesEl) {
citesEl.innerHTML = (kf.citations || []).map(function (c) {
const resolved = adaptHrefForFileProtocol(c.href);
return "<a class='pill tut-cite-link' data-raw-href='" + c.href + "' style='text-decoration:none;color:var(--cyan);border-color:var(--cyan);' href='" +
resolved + "' target='_blank' rel='noopener noreferrer'>\uD83D\uDCC4 " + c.label + " \u2197</a>";
}).join("");
}
}
function initTutorials() {
const playBtn = document.getElementById("tutPlayPauseBtn");
const prevBtn = document.getElementById("tutPrevBtn");
const nextBtn = document.getElementById("tutNextBtn");
const clearBtn = document.getElementById("tutClearSpotlightBtn");
const speechBtn = document.getElementById("tutSpeechBtn");
const scrubber = document.getElementById("tutScrubber");
if (playBtn) {
playBtn.onclick = function () {
if (isPlaying) stopPlayback();
else startPlayback();
};
}
if (prevBtn) prevBtn.onclick = function () { stopPlayback(); stepPrev(); };
if (nextBtn) nextBtn.onclick = function () { stopPlayback(); stepNext(); };
if (clearBtn) {
clearBtn.onclick = function () {
stopPlayback();
highlightDomTarget(null);
const app = window.HyperstitionStudio.QuantWorkbenchApp;
if (app && typeof app.setStateAndRender === "function") {
app.setStateAndRender({}, null);
}
};
}
if (speechBtn) {
speechBtn.onclick = function () {
speechEnabled = !speechEnabled;
if (speechEnabled) speakSubtitle(getActiveKeyframe().subtitle, isPlaying);
else if (typeof window.speechSynthesis !== "undefined") {
try { window.speechSynthesis.cancel(); } catch (_) {}
}
renderTutorialUI();
};
}
if (scrubber) {
scrubber.oninput = function () {
stopPlayback();
curStepIdx = parseInt(scrubber.value, 10) || 0;
applyCurrentKeyframe(speechEnabled);
};
}
renderTutorialUI();
}
window.HyperstitionStudio.QuantTutorials = {
version: "2.0.23",
episodes: EPISODES,
adaptHrefForFileProtocol: adaptHrefForFileProtocol,
init: initTutorials
};
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", initTutorials);
} else {
initTutorials();
}
})();
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -1,3 +1,3 @@
"""hyperstitionstud_io — Shared Common Library for the hyperstitionstud.io workspace (v2.0.18)."""
__version__ = "2.0.18"
"""hyperstitionstud_io — Shared Common Library for the hyperstitionstud.io workspace (v2.0.23)."""
__version__ = "2.0.23"
NAMESPACE_URN = "urn:io:hyperstitionstud"
+22
View File
@@ -57,11 +57,27 @@ def run_diagnostics(workspace_root: str | Path | None = None) -> dict[str, Any]:
fb_path = Path(__file__).resolve().parent.parent / "phonetics" / "cmudict_fallback.json"
fb_count = len(json.loads(fb_path.read_text(encoding="utf-8"))) if fb_path.is_file() else 0
lr_path = cfg.core_dir / "deploy" / "logrotate.d" / "hyperstition-sqlite-meta"
lr_txt = lr_path.read_text(encoding="utf-8") if lr_path.is_file() else ""
lr_ok = (
lr_path.is_file()
and "/var/lib/hyperstitionstud.io/api-telemetry.db" in lr_txt
and "/tmp/" not in lr_txt
and "size 100M" in lr_txt
and "compress" in lr_txt
and "nocompress" not in lr_txt
and "rotate 0" not in lr_txt
and "--truncate-quiescent" in lr_txt
and "--compress-archive" in lr_txt
and "prerotate" in lr_txt
)
all_ok = (
pkgs.get("Pillow") is not None
and all(dirs_ok.values())
and all(v["matches_baseline"] for v in isolation_checks.values())
and fb_count >= 190
and lr_ok
)
return {
@@ -74,6 +90,12 @@ def run_diagnostics(workspace_root: str | Path | None = None) -> dict[str, Any]:
"truetype_fonts": fonts_resolved,
"workspace_directories": dirs_ok,
"offline_cmudict_fallback_entries": fb_count,
"sqlite_logrotate_config": {
"path": str(lr_path),
"exists": lr_path.is_file(),
"default_size_limit": "100M",
"quiescent_truncation_configured": lr_ok,
},
"citation_path_mounts": cfg.citation_path_mounts,
"isolation_locks": isolation_checks,
}
+41
View File
@@ -0,0 +1,41 @@
"""
hyperstitionstud_io.db — Standalone SQLite + FTS5 Catalog & REST/MCP Telemetry Database Engine.
"""
from __future__ import annotations
from hyperstitionstud_io.db.sqlite_meta import (
DEFAULT_MAX_TELEMETRY_BYTES,
DEFAULT_MAX_TELEMETRY_MB,
build_catalog_sqlite_db,
ensure_catalog_sqlite_db,
get_api_telemetry_summary,
get_default_catalog_db_path,
get_default_telemetry_db_path,
parse_size_spec_bytes,
query_coordinate_join,
query_fts_catalog,
query_registry_manifests,
query_timeseries_bars,
record_api_telemetry,
run_logrotate_directive,
truncate_telemetry_db_quiescent,
)
__all__ = [
"DEFAULT_MAX_TELEMETRY_BYTES",
"DEFAULT_MAX_TELEMETRY_MB",
"build_catalog_sqlite_db",
"ensure_catalog_sqlite_db",
"get_api_telemetry_summary",
"get_default_catalog_db_path",
"get_default_telemetry_db_path",
"parse_size_spec_bytes",
"query_coordinate_join",
"query_fts_catalog",
"query_registry_manifests",
"query_timeseries_bars",
"record_api_telemetry",
"run_logrotate_directive",
"truncate_telemetry_db_quiescent",
]
File diff suppressed because it is too large. Load diff
+17 -9
View File
@@ -233,21 +233,29 @@ def classify_qualitative_archetype(
structural_vector: dict[str, float],
timeseries_moments: dict[str, Any],
lens_id: str,
) -> dict[str, str]:
) -> dict[str, str | None]:
"""
Deterministically map lens-neutral structural + time-series moments into qualitative
archetype tags, roles, and abilities under the requested lens.
Returns `None` (`null` in JSON) when time-series data is unavailable.
"""
if timeseries_moments.get("ts_duty_cycle_pct") is None:
return {
"archetype": None,
"causal_role": None,
"regime_specialization": None,
}
qp = timeseries_moments.get("ts_quantile_profile") or {}
p20 = float(qp.get("p20_floor", 50.0))
p90 = float(qp.get("p90_ceiling", 75.0))
cv = float(qp.get("cv", 0.5))
duty = float(timeseries_moments.get("ts_duty_cycle_pct", 50.0))
lag = int(timeseries_moments.get("ts_optimal_lag_days", 0))
p20 = float(qp["p20_floor"]) if qp.get("p20_floor") is not None else 0.0
p90 = float(qp["p90_ceiling"]) if qp.get("p90_ceiling") is not None else 0.0
cv = float(qp["cv"]) if qp.get("cv") is not None else 0.5
duty = float(timeseries_moments["ts_duty_cycle_pct"])
lag_raw = timeseries_moments.get("ts_optimal_lag_days")
lag = int(lag_raw) if lag_raw is not None else 0
splits = timeseries_moments.get("ts_regime_splits") or {}
m1_split = float(splits.get("M1_ENTROPIC", 0.0))
m2_split = float(splits.get("M2_FLASH_CRASH", 0.0))
m3_split = float(splits.get("M3_LEVIATHAN", 0.0))
m1_split = float(splits["M1_ENTROPIC"]) if splits.get("M1_ENTROPIC") is not None else -999.0
m2_split = float(splits["M2_FLASH_CRASH"]) if splits.get("M2_FLASH_CRASH") is not None else -999.0
m3_split = float(splits["M3_LEVIATHAN"]) if splits.get("M3_LEVIATHAN") is not None else -999.0
if m1_split >= max(m2_split, m3_split) and m1_split > 3.0:
peak_regime = "M1_ENTROPIC"
+74 -11
View File
@@ -10,11 +10,13 @@ from __future__ import annotations
import json
import re
import time
import urllib.parse
from typing import Any
from hyperstitionstud_io import __version__ as CURRENT_VERSION
from hyperstitionstud_io.config import load_workspace_config
from hyperstitionstud_io.db.sqlite_meta import record_api_telemetry
from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard
from hyperstitionstud_io.mcp.prompts import MCP_PROMPTS, get_mcp_prompt
from hyperstitionstud_io.mcp.resources import (
@@ -193,19 +195,30 @@ def _error_response(status: int, code: str, message: str) -> tuple[int, str, dic
)
def dispatch_rest_v1(
def _normalize_rest_endpoint_pattern(path: str) -> str:
if re.match(r"^/api/v1/graph/nodes/.+$", path):
return "/api/v1/graph/nodes/{node_id}"
if re.match(r"^/api/v1/quant/instruments/[^/]+$", path):
return "/api/v1/quant/instruments/{symbol}"
if re.match(r"^/api/v1/zoology/pokedex/[^/]+$", path):
return "/api/v1/zoology/pokedex/{symbol}"
if re.match(r"^/api/v1/resources/[a-z0-9-]+$", path):
return "/api/v1/resources/{slug}"
if re.match(r"^/api/v1/dossiers/\d+$", path):
return "/api/v1/dossiers/{number}"
if re.match(r"^/api/v1/schemas/[a-z0-9-]+$", path):
return "/api/v1/schemas/{schema_slug}"
if re.match(r"^/api/v1/prompts/[a-z0-9_]+$", path):
return "/api/v1/prompts/{prompt_name}"
return path
def _dispatch_rest_v1_inner(
method: str,
raw_path: str,
path: str,
query_str: str,
body_bytes: bytes = b"",
) -> tuple[int, str, Any]:
"""
Dispatch an HTTP GET or POST request under `/api/v1/*`.
Returns `(http_status_code, content_type, response_payload_or_text)`.
"""
parsed_url = urllib.parse.urlsplit(raw_path)
path = parsed_url.path.rstrip("/") or "/api/v1"
query_str = parsed_url.query
cfg = load_workspace_config()
try:
with ReadOnlyIsolationGuard(cfg.read_only_files) as guard:
@@ -299,9 +312,32 @@ def dispatch_rest_v1(
md_text = r_out["contents"][0]["text"]
if q_args.get("format") == "raw":
return 200, "text/markdown; charset=utf-8", md_text
dos_payload: dict[str, Any] = {
"dossier_number": num,
"uri": uri,
"mime_type": "text/markdown",
"markdown": md_text,
}
hl_q = str(q_args.get("highlight", "")).strip()
if hl_q:
hl_low = hl_q.lower()
lines = md_text.splitlines()
matched_passages: list[dict[str, Any]] = []
for l_idx, ln in enumerate(lines):
if hl_low in ln.lower():
start_i = max(0, l_idx - 1)
end_i = min(len(lines), l_idx + 2)
matched_passages.append({
"line_number": l_idx + 1,
"line": ln,
"context": "\n".join(lines[start_i:end_i]),
})
dos_payload["highlight_query"] = hl_q
dos_payload["match_count"] = len(matched_passages)
dos_payload["matched_passages"] = matched_passages[:25]
return 200, "application/json; charset=utf-8", _wrap_response(
path,
{"dossier_number": num, "uri": uri, "mime_type": "text/markdown", "markdown": md_text},
dos_payload,
unwrap=unwrap,
)
@@ -363,3 +399,30 @@ def dispatch_rest_v1(
return _error_response(status, "VALIDATION_ERROR", msg)
except Exception as exc:
return _error_response(500, "INTERNAL_ERROR", str(exc))
def dispatch_rest_v1(
method: str,
raw_path: str,
body_bytes: bytes = b"",
) -> tuple[int, str, Any]:
"""
Dispatch an HTTP GET or POST request under `/api/v1/*` and automatically record
the request metadata and latency in the SQLite REST API metadata database (`api-telemetry.db`).
Returns `(http_status_code, content_type, response_payload_or_text)`.
"""
parsed_url = urllib.parse.urlsplit(raw_path)
path = parsed_url.path.rstrip("/") or "/api/v1"
query_str = parsed_url.query
t0_ns = time.perf_counter_ns()
status, ctype, payload = _dispatch_rest_v1_inner(method, path, query_str, body_bytes)
elapsed_us = max(1, (time.perf_counter_ns() - t0_ns) // 1000)
record_api_telemetry(
protocol="rest_v1",
method=method.upper(),
endpoint_pattern=_normalize_rest_endpoint_pattern(path),
status_code=status,
latency_us=elapsed_us,
isolation_ok=True,
)
return status, ctype, payload
+82 -52
View File
@@ -12,6 +12,7 @@ from __future__ import annotations
import argparse
import json
import sys
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from typing import Any
@@ -21,6 +22,7 @@ if _SRC_DIR.is_dir() and str(_SRC_DIR) not in sys.path:
sys.path.insert(0, str(_SRC_DIR))
from hyperstitionstud_io.config import load_workspace_config # noqa: E402
from hyperstitionstud_io.db.sqlite_meta import record_api_telemetry # noqa: E402
from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard # noqa: E402
from hyperstitionstud_io.mcp.prompts import MCP_PROMPTS, get_mcp_prompt # noqa: E402
from hyperstitionstud_io.mcp.resources import ( # noqa: E402
@@ -33,8 +35,8 @@ from hyperstitionstud_io.mcp.tools import MCP_TOOLS_SCHEMA, call_mcp_tool # noq
SERVER_INFO = {
"name": "hyperstitionstudio-mcp",
"version": "2.0.18",
"namespace_urn": "urn:io:hyperstitionstud:mcp:2.0.18",
"version": "2.0.23",
"namespace_urn": "urn:io:hyperstitionstud:mcp:2.0.23",
}
@@ -50,6 +52,14 @@ def dispatch_jsonrpc(req: dict[str, Any]) -> dict[str, Any] | None:
if method.startswith("notifications/"):
return None
t0_ns = time.perf_counter_ns()
rpc_pattern = method
if method == "tools/call":
rpc_pattern = f"tools/call:{params.get('name', '')}"
elif method == "prompts/get":
rpc_pattern = f"prompts/get:{params.get('name', '')}"
status_code = 200
cfg = load_workspace_config()
try:
with ReadOnlyIsolationGuard(cfg.read_only_files):
@@ -96,12 +106,14 @@ def dispatch_jsonrpc(req: dict[str, Any]) -> dict[str, Any] | None:
p_args = params.get("arguments") or {}
result = get_mcp_prompt(p_name, p_args)
else:
status_code = 404
return {
"jsonrpc": "2.0",
"id": req_id,
"error": {"code": -32601, "message": f"Method not found: {method}"},
}
except Exception as exc:
status_code = 422
if method == "tools/call":
return {
"jsonrpc": "2.0",
@@ -116,6 +128,16 @@ def dispatch_jsonrpc(req: dict[str, Any]) -> dict[str, Any] | None:
"id": req_id,
"error": {"code": -32602, "message": str(exc)},
}
finally:
elapsed_us = max(1, (time.perf_counter_ns() - t0_ns) // 1000)
record_api_telemetry(
protocol="mcp_jsonrpc",
method="POST",
endpoint_pattern=rpc_pattern or "unknown",
status_code=status_code,
latency_us=elapsed_us,
isolation_ok=True,
)
return {"jsonrpc": "2.0", "id": req_id, "result": result}
@@ -173,57 +195,65 @@ class _MCPHTTPHandler(BaseHTTPRequestHandler):
self.end_headers()
def do_GET(self) -> None:
if self.path.startswith("/api/v1"):
status, ctype, payload = dispatch_rest_v1("GET", self.path)
self._send_payload(status, ctype, payload)
return
manifest = {
"serverInfo": SERVER_INFO,
"protocols": ["2025-03-26", "2024-11-05"],
"transport": "streamable-http",
"endpoints": {
"jsonrpc_post": "/mcp",
"manifest_get": "/mcp",
"rest_api_v1": "/api/v1",
"openapi_3_1": "/api/v1/openapi.json",
},
"counts": {
"tools": len(MCP_TOOLS_SCHEMA),
"static_resources": len(STATIC_RESOURCES),
"resource_templates": len(RESOURCE_TEMPLATES),
"prompts": len(MCP_PROMPTS),
},
"tools": [t["name"] for t in MCP_TOOLS_SCHEMA],
"resources": [r["uri"] for r in STATIC_RESOURCES],
"prompts": [p["name"] for p in MCP_PROMPTS],
}
self._send_json(200, manifest)
def do_POST(self) -> None:
length = int(self.headers.get("Content-Length", "0"))
if length < 0 or length > 65536:
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""
if self.path.startswith("/api/v1"):
status, ctype, payload = dispatch_rest_v1("POST", self.path, raw_bytes)
self._send_payload(status, ctype, payload)
return
if not raw_bytes:
self._send_json(400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "Invalid content length"}})
return
raw = raw_bytes.decode("utf-8")
try:
req = json.loads(raw)
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)
if resp is None:
self.send_response(202)
self.end_headers()
return
self._send_json(200, resp)
if self.path.startswith("/api/v1"):
status, ctype, payload = dispatch_rest_v1("GET", self.path)
self._send_payload(status, ctype, payload)
return
manifest = {
"serverInfo": SERVER_INFO,
"protocols": ["2025-03-26", "2024-11-05"],
"transport": "streamable-http",
"endpoints": {
"jsonrpc_post": "/mcp",
"manifest_get": "/mcp",
"rest_api_v1": "/api/v1",
"openapi_3_1": "/api/v1/openapi.json",
},
"counts": {
"tools": len(MCP_TOOLS_SCHEMA),
"static_resources": len(STATIC_RESOURCES),
"resource_templates": len(RESOURCE_TEMPLATES),
"prompts": len(MCP_PROMPTS),
},
"tools": [t["name"] for t in MCP_TOOLS_SCHEMA],
"resources": [r["uri"] for r in STATIC_RESOURCES],
"prompts": [p["name"] for p in MCP_PROMPTS],
}
self._send_json(200, manifest)
except Exception as exc:
self._send_json(500, {"ok": False, "error": {"code": "INTERNAL_ERROR", "status": 500, "message": str(exc)}})
# 7. Stateless Read-Only MCP (/mcp) & REST API v1 (/api/v1/*) HTTP Server -> 127.0.0.1:8095
# Note: Do NOT call dispatch_jsonrpc or dispatch_rest_v1 inside do_POST without top-level try/except
def do_POST(self) -> None:
try:
length = int(self.headers.get("Content-Length", "0"))
if length < 0 or length > 65536:
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""
if self.path.startswith("/api/v1"):
status, ctype, payload = dispatch_rest_v1("POST", self.path, raw_bytes)
self._send_payload(status, ctype, payload)
return
if not raw_bytes:
self._send_json(400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "Invalid content length"}})
return
raw = raw_bytes.decode("utf-8")
try:
req = json.loads(raw)
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)
if resp is None:
self.send_response(202)
self.end_headers()
return
self._send_json(200, resp)
except Exception as exc:
self._send_json(500, {"ok": False, "error": {"code": "INTERNAL_ERROR", "status": 500, "message": str(exc)}})
def run_http_server(host: str, port: int) -> int:
+7 -1
View File
@@ -383,6 +383,8 @@ def call_mcp_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]:
d_dig = new_dig_aq - old_dig_aq
d_sp = new_sp_aq - old_sp_aq
return {
"is_simulated": True,
"simulation_warning": "SIMULATED COUNTERFACTUAL ANCHOR REVISION — NOT LIVE MARKET DATA",
"anchor_id": aid,
"entity": anchor["entity"],
"old_digit": {"str": anchor["q_digit"], "aq": old_dig_aq},
@@ -475,7 +477,11 @@ def call_mcp_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]:
sym_q = str(arguments.get("symbol", "")).strip().upper()
lens_q = str(arguments.get("lens", "fund_manager")).strip()
bundle = build_quant_timeseries_bundle(write_files=False)
ts_json_path = cfg.core_dir / "site" / "quant" / "quant-timeseries.json"
if ts_json_path.is_file():
bundle = json.loads(ts_json_path.read_text(encoding="utf-8"))
else:
bundle = build_quant_timeseries_bundle(write_files=False)
if sym_q:
matched = [
inst
+312 -170
View File
@@ -2,10 +2,13 @@
"""
hyperstitionstud_io.quant.collector — Periodic Quantitative Financial Telemetry & Contingent Meaning Collector (`hs-quant-harvest`).
Evaluates quantitative financial telemetry across 3 anti-pareidolia contingent meaning scopes:
1. Scope 1 (Intra-Instrument Self-Lock): Entity/Ticker AQ locks or closes 333/666/777 with its own price, cap, or bps move.
2. Scope 2 (Causal S1-S6 Supply-Chain Ring Migration): Repriced metric migrates across S1-S6 signature coordinates.
3. Scope 3 (Objective Numerical State-Gate Activation): VIX, drawdown %, volume ratio, and cap thresholds trigger M1-M6.
Strict Data Integrity Policy:
- Never synthesizes or hardcodes fake market prices, basis-point moves, or market caps.
- Uses only real market observations from Yahoo Finance v8, Stooq CSV, CoinGecko v3, or
the verified real exchange history cache (`site/quant/real-market-history.json`).
- Whenever market data is unavailable for an instrument (e.g. private entity `ANTHR-PVT`
or missing feed fields like `market_cap_str`), explicitly reports `"No data available"`
(`data_available = False`, numeric fields `None`).
"""
from __future__ import annotations
@@ -47,6 +50,8 @@ os.environ["TZ"] = "UTC"
if hasattr(time, "tzset"):
time.tzset()
NO_DATA_AVAILABLE = "No data available"
S1_S6_SIGNATURE_RINGS: dict[int, list[str]] = {
292: ["S1: shizohnalizis / abstrakt masheen / sinthetik dayta", "S6: asset management [Gen 0]"],
260: ["S3: teknohkapital / kiler rohbots"],
@@ -80,31 +85,32 @@ S1_S6_SIGNATURE_RINGS: dict[int, list[str]] = {
71: ["S3: gpu [Iso]"],
}
# Static watchlist metadata ONLY — zero hardcoded or synthesized prices/moves/caps.
CANONICAL_WATCHLIST_24: list[dict[str, Any]] = [
{"symbol": "NVDA", "entity_eng": "Nvidia", "guilds": ["S1", "S3"], "close_usd": 137.00, "change_pct": -1.45, "change_bps": -145, "volume_ratio_20d": 1.18, "market_cap_str": "$3.35T"},
{"symbol": "ASML", "entity_eng": "ASML", "guilds": ["S3", "S6"], "close_usd": 710.00, "change_pct": 0.81, "change_bps": 81, "volume_ratio_20d": 1.05, "market_cap_str": "$280B"},
{"symbol": "TSM", "entity_eng": "TSMC", "guilds": ["S3", "S6"], "close_usd": 191.00, "change_pct": 1.25, "change_bps": 125, "volume_ratio_20d": 1.12, "market_cap_str": "$990B"},
{"symbol": "ANTHR-PVT", "entity_eng": "Anthropic", "guilds": ["S1", "S2"], "close_usd": 89.00, "change_pct": 7.23, "change_bps": 723, "volume_ratio_20d": 1.60, "market_cap_str": "$61B"},
{"symbol": "MSFT", "entity_eng": "Microsoft", "guilds": ["S1", "S6"], "close_usd": 425.00, "change_pct": 0.40, "change_bps": 40, "volume_ratio_20d": 0.92, "market_cap_str": "$3.16T"},
{"symbol": "GOOGL", "entity_eng": "Alphabet", "guilds": ["S1", "S6"], "close_usd": 183.00, "change_pct": -0.95, "change_bps": -95, "volume_ratio_20d": 0.98, "market_cap_str": "$2.25T"},
{"symbol": "META", "entity_eng": "Meta", "guilds": ["S1", "S6"], "close_usd": 592.00, "change_pct": 1.33, "change_bps": 133, "volume_ratio_20d": 1.04, "market_cap_str": "$1.49T"},
{"symbol": "ORCL", "entity_eng": "Oracle", "guilds": ["S1", "S6"], "close_usd": 189.00, "change_pct": 1.60, "change_bps": 160, "volume_ratio_20d": 1.15, "market_cap_str": "$520B"},
{"symbol": "AVGO", "entity_eng": "Broadcom", "guilds": ["S3", "S6"], "close_usd": 163.00, "change_pct": 0.91, "change_bps": 91, "volume_ratio_20d": 1.01, "market_cap_str": "$760B"},
{"symbol": "ARM", "entity_eng": "Arm", "guilds": ["S3", "S1"], "close_usd": 135.00, "change_pct": -1.28, "change_bps": -128, "volume_ratio_20d": 0.88, "market_cap_str": "$142B"},
{"symbol": "AMD", "entity_eng": "AMD", "guilds": ["S3", "S1"], "close_usd": 137.00, "change_pct": -0.71, "change_bps": -71, "volume_ratio_20d": 0.94, "market_cap_str": "$222B"},
{"symbol": "PLTR", "entity_eng": "Palantir", "guilds": ["S3", "S6"], "close_usd": 66.00, "change_pct": 2.60, "change_bps": 260, "volume_ratio_20d": 1.45, "market_cap_str": "$150B"},
{"symbol": "LMT", "entity_eng": "Lockheed", "guilds": ["S3"], "close_usd": 534.00, "change_pct": 0.39, "change_bps": 39, "volume_ratio_20d": 0.85, "market_cap_str": "$127B"},
{"symbol": "RTX", "entity_eng": "Raytheon", "guilds": ["S3"], "close_usd": 121.00, "change_pct": 0.41, "change_bps": 41, "volume_ratio_20d": 0.82, "market_cap_str": "$161B"},
{"symbol": "HG=F", "entity_eng": "Copper", "guilds": ["S3", "S2"], "close_usd": 4.15, "change_pct": 2.11, "change_bps": 211, "volume_ratio_20d": 1.22, "market_cap_str": "$211B"},
{"symbol": "^VIX", "entity_eng": "VIX", "guilds": ["S2"], "close_usd": 14.20, "change_pct": -5.33, "change_bps": -533, "volume_ratio_20d": 1.10, "market_cap_str": "$0B"},
{"symbol": "BTC-USD", "entity_eng": "Bitcoin", "guilds": ["S2", "S6"], "close_usd": 96000.00, "change_pct": 1.93, "change_bps": 193, "volume_ratio_20d": 1.35, "market_cap_str": "$1.90T"},
{"symbol": "ETH-USD", "entity_eng": "Ethereum", "guilds": ["S2"], "close_usd": 3600.00, "change_pct": 1.83, "change_bps": 183, "volume_ratio_20d": 1.20, "market_cap_str": "$433B"},
{"symbol": "SOL-USD", "entity_eng": "Solana", "guilds": ["S2"], "close_usd": 244.00, "change_pct": 1.29, "change_bps": 129, "volume_ratio_20d": 1.18, "market_cap_str": "$116B"},
{"symbol": "COIN", "entity_eng": "Coinbase", "guilds": ["S2", "S6"], "close_usd": 292.00, "change_pct": 2.56, "change_bps": 256, "volume_ratio_20d": 1.40, "market_cap_str": "$73B"},
{"symbol": "CEG", "entity_eng": "Constellation", "guilds": ["S4", "S3"], "close_usd": 256.00, "change_pct": 1.16, "change_bps": 116, "volume_ratio_20d": 1.08, "market_cap_str": "$80B"},
{"symbol": "LLY", "entity_eng": "Eli Lilly", "guilds": ["S5", "S6"], "close_usd": 777.00, "change_pct": 0.84, "change_bps": 84, "volume_ratio_20d": 0.96, "market_cap_str": "$740B"},
{"symbol": "^TNX", "entity_eng": "Treasury", "guilds": ["S6", "S2"], "close_usd": 4.18, "change_pct": -0.71, "change_bps": -71, "volume_ratio_20d": 1.00, "market_cap_str": "$28T"},
{"symbol": "BLK", "entity_eng": "BlackRock", "guilds": ["S6"], "close_usd": 1025.00, "change_pct": 1.25, "change_bps": 125, "volume_ratio_20d": 1.02, "market_cap_str": "$153B"},
{"symbol": "NVDA", "entity_eng": "Nvidia", "guilds": ["S1", "S3"]},
{"symbol": "ASML", "entity_eng": "ASML", "guilds": ["S3", "S6"]},
{"symbol": "TSM", "entity_eng": "TSMC", "guilds": ["S3", "S6"]},
{"symbol": "ANTHR-PVT", "entity_eng": "Anthropic", "guilds": ["S1", "S2"]},
{"symbol": "MSFT", "entity_eng": "Microsoft", "guilds": ["S1", "S6"]},
{"symbol": "GOOGL", "entity_eng": "Alphabet", "guilds": ["S1", "S6"]},
{"symbol": "META", "entity_eng": "Meta", "guilds": ["S1", "S6"]},
{"symbol": "ORCL", "entity_eng": "Oracle", "guilds": ["S1", "S6"]},
{"symbol": "AVGO", "entity_eng": "Broadcom", "guilds": ["S3", "S6"]},
{"symbol": "ARM", "entity_eng": "Arm", "guilds": ["S3", "S1"]},
{"symbol": "AMD", "entity_eng": "AMD", "guilds": ["S3", "S1"]},
{"symbol": "PLTR", "entity_eng": "Palantir", "guilds": ["S3", "S6"]},
{"symbol": "LMT", "entity_eng": "Lockheed", "guilds": ["S3"]},
{"symbol": "RTX", "entity_eng": "Raytheon", "guilds": ["S3"]},
{"symbol": "HG=F", "entity_eng": "Copper", "guilds": ["S3", "S2"]},
{"symbol": "^VIX", "entity_eng": "VIX", "guilds": ["S2"]},
{"symbol": "BTC-USD", "entity_eng": "Bitcoin", "guilds": ["S2", "S6"]},
{"symbol": "ETH-USD", "entity_eng": "Ethereum", "guilds": ["S2"]},
{"symbol": "SOL-USD", "entity_eng": "Solana", "guilds": ["S2"]},
{"symbol": "COIN", "entity_eng": "Coinbase", "guilds": ["S2", "S6"]},
{"symbol": "CEG", "entity_eng": "Constellation", "guilds": ["S4", "S3"]},
{"symbol": "LLY", "entity_eng": "Eli Lilly", "guilds": ["S5", "S6"]},
{"symbol": "^TNX", "entity_eng": "Treasury", "guilds": ["S6", "S2"]},
{"symbol": "BLK", "entity_eng": "BlackRock", "guilds": ["S6"]},
]
_USER_AGENT = "Mozilla/5.0 (compatible; HyperstitionStudioQuantCollector/2.0; +urn:io:hyperstitionstud)"
@@ -116,18 +122,26 @@ _STOOQ_MAP = {
"RTX": "rtx.us", "COIN": "coin.us", "CEG": "ceg.us", "LLY": "lly.us", "BLK": "blk.us",
}
# Precomputed 2-word (noun + prep or verb + article) closures for 333 / 666 / 777intra-instrument verified equations
_EQ_CLOSURES_333: dict[int, list[str]] = {
137: [
71: [
"envideea (137) + fohldz (125) + gpu (71) = 333",
"daireeoh (137) + fohldz (125) + gpu (71) = 333",
],
81: [
"asml (81) + akselerayshan (256) - 4 = 333",
"asml (81) + chaildz (126) + chaildz (126) = 333",
],
91: [
"tsmc (91) + fohldz (125) +ekst (117) = 333",
"tsmc (91) + fohldz (125) + tekst (117) = 333",
],
125: [
"envideea (137) + fohldz (125) + gpu (71) = 333",
],
137: [
"envideea (137) + fohldz (125) + gpu (71) = 333",
"daireeoh (137) + fohldz (125) + gpu (71) = 333",
],
163: [
"manopalee (163) + in (41) + blakwel (129) = 333",
],
191: [
"derivativ (191) + aiern (92) + tab (50) = 333",
@@ -153,7 +167,9 @@ _EQ_CLOSURES_333: dict[int, list[str]] = {
def _fetch_yahoo_chart(symbol: str, timeout: float = 6.0) -> dict[str, Any] | None:
"""Source 1: Keyless Yahoo Finance v8 Chart JSON API."""
"""Source 1: Keyless Yahoo Finance v8 Chart JSON API (using actual prior trading day close)."""
if symbol == "ANTHR-PVT":
return None
enc_sym = urllib.parse.quote(symbol, safe="")
url = f"https://query1.finance.yahoo.com/v8/finance/chart/{enc_sym}?range=1mo&interval=1d"
req = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT, "Accept": "application/json"})
@@ -162,26 +178,46 @@ def _fetch_yahoo_chart(symbol: str, timeout: float = 6.0) -> dict[str, Any] | No
res_list = (data.get("chart") or {}).get("result") or []
if not res_list:
return None
meta = res_list[0].get("meta") or {}
ts_list = res_list[0].get("timestamp") or []
quotes = (((res_list[0].get("indicators") or {}).get("quote") or [{}])[0])
closes = [float(x) for x in (quotes.get("close") or []) if x is not None]
vols = [float(x) for x in (quotes.get("volume") or []) if x is not None and x > 0]
close_usd = float(meta.get("regularMarketPrice") or (closes[-1] if closes else 0.0))
raw_closes = quotes.get("close") or []
raw_vols = quotes.get("volume") or []
valid_pairs = [
(ts_list[i], float(raw_closes[i]), float(raw_vols[i]) if i < len(raw_vols) and raw_vols[i] is not None else None)
for i in range(min(len(ts_list), len(raw_closes)))
if raw_closes[i] is not None
]
if not valid_pairs:
return None
last_ts, close_usd, last_vol = valid_pairs[-1]
if close_usd <= 0:
return None
prev_close = float(meta.get("chartPreviousClose") or (closes[-2] if len(closes) >= 2 else close_usd))
chg_pct = ((close_usd - prev_close) / prev_close * 100.0) if prev_close > 0 else 0.0
chg_bps = int(round(chg_pct * 100.0))
vol_ratio = 1.0
if len(vols) >= 2:
avg_v = sum(vols[:-1][-20:]) / max(1, len(vols[:-1][-20:]))
obs_date = datetime.datetime.fromtimestamp(last_ts, datetime.timezone.utc).strftime("%Y-%m-%d")
prev_close = valid_pairs[-2][1] if len(valid_pairs) >= 2 else None
if prev_close and prev_close > 0:
chg_pct: float | None = round((close_usd - prev_close) / prev_close * 100.0, 2)
chg_bps: int | None = int(round(chg_pct * 100.0))
else:
chg_pct = None
chg_bps = None
vol_ratio: float | None = None
prior_vols = [x[2] for x in valid_pairs[:-1][-20:] if x[2] is not None and x[2] > 0]
if last_vol is not None and last_vol > 0 and prior_vols:
avg_v = sum(prior_vols) / len(prior_vols)
if avg_v > 0:
vol_ratio = round(vols[-1] / avg_v, 2)
vol_ratio = round(last_vol / avg_v, 2)
return {
"observation_date_utc": obs_date,
"close_usd": round(close_usd, 2),
"change_pct": round(chg_pct, 2),
"change_pct": chg_pct,
"change_bps": chg_bps,
"volume_ratio_20d": vol_ratio,
"market_cap_str": None,
"feed_source": "yahoo_v8_json",
}
@@ -199,20 +235,22 @@ def _fetch_stooq_csv(symbol: str, timeout: float = 6.0) -> dict[str, Any] | None
if not rows or "Close" not in rows[-1] or rows[-1]["Close"] in ("", "N/D", None):
return None
close_usd = float(rows[-1]["Close"])
prev_close = float(rows[-2]["Close"]) if len(rows) >= 2 and rows[-2].get("Close") not in ("", "N/D", None) else close_usd
chg_pct = ((close_usd - prev_close) / prev_close * 100.0) if prev_close > 0 else 0.0
chg_bps = int(round(chg_pct * 100.0))
prev_close = float(rows[-2]["Close"]) if len(rows) >= 2 and rows[-2].get("Close") not in ("", "N/D", None) else None
chg_pct = round((close_usd - prev_close) / prev_close * 100.0, 2) if (prev_close and prev_close > 0) else None
chg_bps = int(round(chg_pct * 100.0)) if chg_pct is not None else None
vols = [float(r["Volume"]) for r in rows[-21:] if r.get("Volume") and r["Volume"].replace(".", "").isdigit()]
vol_ratio = 1.0
vol_ratio = None
if len(vols) >= 2:
avg_v = sum(vols[:-1]) / max(1, len(vols[:-1]))
if avg_v > 0:
vol_ratio = round(vols[-1] / avg_v, 2)
return {
"observation_date_utc": rows[-1].get("Date"),
"close_usd": round(close_usd, 2),
"change_pct": round(chg_pct, 2),
"change_pct": chg_pct,
"change_bps": chg_bps,
"volume_ratio_20d": vol_ratio,
"market_cap_str": None,
"feed_source": "stooq_csv",
}
@@ -228,51 +266,109 @@ def _fetch_coingecko_crypto(timeout: float = 6.0) -> dict[str, dict[str, Any]]:
for sym, cg_id in _COINGECKO_MAP.items():
if cg_id in data and "usd" in data[cg_id]:
c_usd = float(data[cg_id]["usd"])
chg_pct = float(data[cg_id].get("usd_24h_change") or 0.0)
chg_raw = data[cg_id].get("usd_24h_change")
chg_pct = round(float(chg_raw), 2) if chg_raw is not None else None
mcap = float(data[cg_id].get("usd_market_cap") or 0.0)
mcap_str = f"${mcap / 1e12:.2f}T" if mcap >= 1e12 else (f"${int(round(mcap / 1e9))}B" if mcap >= 1e9 else "$0B")
mcap_str = f"${mcap / 1e12:.2f}T" if mcap >= 1e12 else (f"${int(round(mcap / 1e9))}B" if mcap >= 1e9 else None)
out[sym] = {
"close_usd": round(c_usd, 2),
"change_pct": round(chg_pct, 2),
"change_bps": int(round(chg_pct * 100.0)),
"change_pct": chg_pct,
"change_bps": int(round(chg_pct * 100.0)) if chg_pct is not None else None,
"market_cap_str": mcap_str,
"feed_source": "coingecko_v3_json",
}
return out
def _load_real_history_latest_bars() -> dict[str, dict[str, Any]]:
"""
Read the latest real exchange bar per symbol from `site/quant/real-market-history.json`
(populated strictly from real Yahoo Finance v8 / CoinGecko responses; never synthesized).
"""
cfg = load_workspace_config()
hist_path = cfg.core_dir / "site" / "quant" / "real-market-history.json"
if not hist_path.is_file():
return {}
try:
raw = json.loads(hist_path.read_text(encoding="utf-8"))
out: dict[str, dict[str, Any]] = {}
for sym, sym_obj in (raw.get("instruments") or {}).items():
bars_by_date = sym_obj.get("bars_by_date") or {}
if bars_by_date:
latest_dt = sorted(bars_by_date.keys())[-1]
bar = dict(bars_by_date[latest_dt])
bar["observation_date_utc"] = latest_dt
out[sym] = bar
return out
except Exception:
return {}
def fetch_live_watchlist(
base_watchlist: list[dict[str, Any]] | None = None,
timeout: float = 6.0,
allow_live_network: bool = True,
) -> list[dict[str, Any]]:
"""
Attempt multi-source keyless HTTP ingestion (Yahoo Finance v8 -> Stooq CSV -> CoinGecko JSON),
falling back deterministically per instrument to CANONICAL_WATCHLIST_24 if offline or rate-limited.
Resolve real market observations for the 24 watchlist instruments.
Never invents or synthesizes missing data: if an instrument has no real exchange observation
(e.g. private company `ANTHR-PVT`), its numeric fields remain `None` and `status` is
`"No data available"`.
"""
watchlist = [dict(x) for x in (base_watchlist or CANONICAL_WATCHLIST_24)]
cached_latest = _load_real_history_latest_bars()
cg_quotes: dict[str, dict[str, Any]] = {}
try:
cg_quotes = _fetch_coingecko_crypto(timeout=timeout)
except Exception:
cg_quotes = {}
if allow_live_network:
try:
cg_quotes = _fetch_coingecko_crypto(timeout=timeout)
except Exception:
cg_quotes = {}
def _resolve_one(item: dict[str, Any]) -> dict[str, Any]:
sym = item["symbol"]
merged = dict(item)
merged["feed_source"] = "canonical_snapshot"
merged = {
"symbol": sym,
"entity_eng": item["entity_eng"],
"guilds": list(item["guilds"]),
"data_available": False,
"status": NO_DATA_AVAILABLE,
"feed_source": None,
"observation_date_utc": None,
"close_usd": None,
"change_pct": None,
"change_bps": None,
"volume_ratio_20d": None,
"market_cap_str": None,
}
if sym == "ANTHR-PVT":
merged["status"] = "No data available (private entity — not publicly traded)"
return merged
if sym in cg_quotes:
merged.update(cg_quotes[sym])
if allow_live_network:
for fetcher in (_fetch_yahoo_chart, _fetch_stooq_csv):
try:
q = fetcher(sym, timeout=timeout)
if q and q.get("close_usd") is not None:
merged.update(q)
if sym in cg_quotes and cg_quotes[sym].get("market_cap_str"):
merged["market_cap_str"] = cg_quotes[sym]["market_cap_str"]
merged["data_available"] = True
merged["status"] = "ok"
return merged
except Exception:
continue
if sym in cg_quotes and cg_quotes[sym].get("close_usd") is not None:
merged.update(cg_quotes[sym])
merged["data_available"] = True
merged["status"] = "ok"
return merged
if sym in cached_latest and cached_latest[sym].get("close_usd") is not None:
merged.update(cached_latest[sym])
merged["data_available"] = True
merged["status"] = "ok"
return merged
for fetcher in (_fetch_yahoo_chart, _fetch_stooq_csv):
try:
q = fetcher(sym, timeout=timeout)
if q:
merged.update(q)
return merged
except Exception:
continue
return merged
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
@@ -289,26 +385,27 @@ def build_financial_quant_harvest(
with ReadOnlyIsolationGuard(cfg.read_only_files) as guard:
if snapshot_path and Path(snapshot_path).is_file():
raw_watchlist = json.loads(Path(snapshot_path).read_text(encoding="utf-8"))
elif live_fetch:
raw_watchlist = fetch_live_watchlist(CANONICAL_WATCHLIST_24)
else:
raw_watchlist = [dict(x) for x in CANONICAL_WATCHLIST_24]
raw_watchlist = fetch_live_watchlist(
CANONICAL_WATCHLIST_24,
allow_live_network=bool(live_fetch),
)
# Batch translate entity names and all 4 quantitative normalization modes:
# Mode 1: q_digit, Mode 2: q_spoken_int, Mode 3: q_spoken_scaled, Mode 4: q_delta_bps
phrases_to_translate: list[str] = []
for item in raw_watchlist:
phrases_to_translate.append(item["entity_eng"])
close_int = int(round(float(item["close_usd"])))
bps_abs = abs(int(item["change_bps"]))
mcap_sp_eng = expand_quant_spoken(str(item.get("market_cap_str", "$0B")))
phrases_to_translate.append(int_to_spoken_words(close_int))
phrases_to_translate.append(int_to_spoken_words(bps_abs))
phrases_to_translate.append(mcap_sp_eng)
if item.get("close_usd") is not None:
close_int = int(round(float(item["close_usd"])))
phrases_to_translate.append(int_to_spoken_words(close_int))
if item.get("change_bps") is not None:
bps_abs = abs(int(item["change_bps"]))
phrases_to_translate.append(int_to_spoken_words(bps_abs))
mcap_raw = item.get("market_cap_str")
if mcap_raw and mcap_raw != NO_DATA_AVAILABLE:
phrases_to_translate.append(expand_quant_spoken(str(mcap_raw)))
ing_map = translate_batch(phrases_to_translate)
# Resolve same-day news headlines for cross-join (Check 4 in PLAN-QUANTITATIVE-FINANCIAL-TELEMETRY-PIPELINE)
effective_news_path = Path(join_news_path) if join_news_path else (cfg.archive_dir / "news-aq-harvest-latest.json")
news_entities: dict[str, list[str]] = {}
if effective_news_path.is_file():
@@ -350,48 +447,103 @@ def build_financial_quant_harvest(
instruments_out: list[dict[str, Any]] = []
active_memetic_states: set[str] = set()
emergent_m7_quant_triggers: list[dict[str, Any]] = []
vix_close_val = 14.2
us10y_yield_val = 4.18
vix_close_val: float | None = None
us10y_yield_val: float | None = None
for item in raw_watchlist:
sym = item["symbol"]
if sym == "^VIX":
vix_close_val = float(item["close_usd"])
elif sym == "^TNX":
us10y_yield_val = float(item["close_usd"])
ent_eng = item["entity_eng"]
ent_ing = ing_map.get(ent_eng, ent_eng.lower())
ent_eng_aq = compute_aq(ent_eng)
ent_ing_aq = compute_aq(ent_ing)
close_int = int(round(float(item["close_usd"])))
bps_abs = abs(int(item["change_bps"]))
mcap_s = str(item.get("market_cap_str", "$0B"))
close_sp_eng = int_to_spoken_words(close_int)
close_sp_ing = ing_map.get(close_sp_eng, close_sp_eng)
bps_sp_eng = int_to_spoken_words(bps_abs)
bps_sp_ing = ing_map.get(bps_sp_eng, bps_sp_eng)
mcap_sp_eng = expand_quant_spoken(mcap_s)
mcap_sp_ing = ing_map.get(mcap_sp_eng, mcap_sp_eng)
close_dig_aq = compute_aq(str(close_int))
close_sp_aq = compute_aq(close_sp_ing)
bps_dig_aq = compute_aq(str(bps_abs))
bps_sp_aq = compute_aq(bps_sp_ing)
mcap_sp_aq = compute_aq(mcap_sp_ing)
locks: list[dict[str, Any]] = []
co_present = sym in news_entities
# Scope 1: Intra-Instrument Self-Locks & Repdigit Attractors
has_price = item.get("close_usd") is not None
if not has_price:
instruments_out.append({
"symbol": sym,
"entity_eng": ent_eng,
"entity_ing": ent_ing,
"entity_eng_aq": ent_eng_aq,
"entity_ing_aq": ent_ing_aq,
"guilds": item["guilds"],
"data_available": False,
"status": item.get("status") or NO_DATA_AVAILABLE,
"feed_source": None,
"observation_date_utc": None,
"co_present_in_news_wire": co_present,
"metrics": {
"close_usd": None,
"change_pct": None,
"change_bps": None,
"volume_ratio_20d": None,
"market_cap_str": NO_DATA_AVAILABLE,
},
"quant_encodings": {
"status": NO_DATA_AVAILABLE,
"close_digit_aq": None,
"close_spoken_eng": NO_DATA_AVAILABLE,
"close_spoken_ing": NO_DATA_AVAILABLE,
"close_spoken_ing_aq": None,
"close_spoken_prime_rank": None,
"scaled_cap_spoken_eng": NO_DATA_AVAILABLE,
"scaled_cap_spoken_ing": NO_DATA_AVAILABLE,
"scaled_cap_spoken_ing_aq": None,
"bps_digit_aq": None,
"bps_spoken_eng": NO_DATA_AVAILABLE,
"bps_spoken_ing": NO_DATA_AVAILABLE,
"bps_spoken_ing_aq": None,
},
"contingent_locks": [],
})
continue
close_val = float(item["close_usd"])
if sym == "^VIX":
vix_close_val = close_val
elif sym == "^TNX":
us10y_yield_val = close_val
close_int = int(round(close_val))
close_sp_eng = int_to_spoken_words(close_int)
close_sp_ing = ing_map.get(close_sp_eng, close_sp_eng)
close_dig_aq = compute_aq(str(close_int))
close_sp_aq = compute_aq(close_sp_ing)
chg_bps_raw = item.get("change_bps")
chg_pct_raw = item.get("change_pct")
if chg_bps_raw is not None:
bps_abs: int | None = abs(int(chg_bps_raw))
bps_sp_eng = int_to_spoken_words(bps_abs)
bps_sp_ing = ing_map.get(bps_sp_eng, bps_sp_eng)
bps_dig_aq: int | None = compute_aq(str(bps_abs))
bps_sp_aq: int | None = compute_aq(bps_sp_ing)
else:
bps_abs = None
bps_sp_eng = NO_DATA_AVAILABLE
bps_sp_ing = NO_DATA_AVAILABLE
bps_dig_aq = None
bps_sp_aq = None
mcap_raw = item.get("market_cap_str")
if mcap_raw and mcap_raw != NO_DATA_AVAILABLE:
mcap_s = str(mcap_raw)
mcap_sp_eng = expand_quant_spoken(mcap_s)
mcap_sp_ing = ing_map.get(mcap_sp_eng, mcap_sp_eng)
mcap_sp_aq: int | None = compute_aq(mcap_sp_ing)
else:
mcap_s = NO_DATA_AVAILABLE
mcap_sp_eng = NO_DATA_AVAILABLE
mcap_sp_ing = NO_DATA_AVAILABLE
mcap_sp_aq = None
locks: list[dict[str, Any]] = []
if close_int == ent_ing_aq or close_int == ent_eng_aq:
eqs = list(_EQ_CLOSURES_333.get(close_int, []))
locks.append({
"scope": "SCOPE1_INTRA_INSTRUMENT_SELF_LOCK",
"description": f"{sym} integer close (${close_int}) equals its own AQ coordinate ({ent_ing}={ent_ing_aq}).",
"verified_equations": eqs,
"verified_equations": list(_EQ_CLOSURES_333.get(close_int, [])),
})
if is_repdigit_37(close_sp_aq) or is_repdigit_37(close_int):
rep_val = close_sp_aq if is_repdigit_37(close_sp_aq) else close_int
@@ -400,15 +552,21 @@ def build_financial_quant_harvest(
"description": f"{sym} close ${close_int} ('{close_sp_ing}') locks onto repdigit attractor {rep_val}.",
"verified_equations": [f"{close_sp_ing} = {close_sp_aq}"],
})
if bps_abs == ent_ing_aq or bps_abs == ent_eng_aq:
if bps_abs is not None and (bps_abs == ent_ing_aq or bps_abs == ent_eng_aq):
locks.append({
"scope": "SCOPE1_BPS_ISOMETRIC_SELF_LOCK",
"description": f"{sym} basis-point move ({bps_abs} bps) equals its own isometric AQ coordinate ({ent_ing}={ent_ing_aq}).",
"verified_equations": list(_EQ_CLOSURES_333.get(bps_abs, [])),
})
# Scope 2: S1-S6 Signature Ring Migrations
for coord_val, label_mode in ((close_int, "close_int"), (close_sp_aq, "close_spoken_aq"), (bps_abs, "change_bps")):
coord_checks: list[tuple[int, str]] = [
(close_int, "close_int"),
(close_sp_aq, "close_spoken_aq"),
]
if bps_abs is not None:
coord_checks.append((bps_abs, "change_bps"))
for coord_val, label_mode in coord_checks:
if coord_val in S1_S6_SIGNATURE_RINGS:
locks.append({
"scope": "SCOPE2_S1_S6_RING_MIGRATION",
@@ -425,17 +583,15 @@ def build_financial_quant_harvest(
"partners": S1_S6_SIGNATURE_RINGS[129],
})
# Scope 3: Objective Numerical State-Gate Activation
vol_ratio = float(item.get("volume_ratio_20d", 1.0))
chg_pct = float(item.get("change_pct", 0.0))
if vol_ratio < 0.45 and abs(chg_pct) < 0.10:
vol_ratio = float(item["volume_ratio_20d"]) if item.get("volume_ratio_20d") is not None else None
chg_pct = float(chg_pct_raw) if chg_pct_raw is not None else None
if vol_ratio is not None and chg_pct is not None and vol_ratio < 0.45 and abs(chg_pct) < 0.10:
active_memetic_states.add("M1_ENTROPIC_STAGNATION")
if chg_pct <= -5.0 or vol_ratio >= 2.5 or (sym == "^VIX" and close_int >= 25):
if (chg_pct is not None and chg_pct <= -5.0) or (vol_ratio is not None and vol_ratio >= 2.5) or (sym == "^VIX" and close_int >= 25):
active_memetic_states.add("M2_FLASH_CRASH_TEMPLEX_SURGE")
if mcap_s.endswith("T"):
active_memetic_states.add("M3_LEVIATHAN_TRILLION_CAP_CONCENTRATION")
# Scope 4 / News-Wire Co-Presence Lock (when entity is in news wire AND triggers Scope 1-2 lock)
if co_present and locks:
locks.append({
"scope": "SCOPE3_NEWS_WIRE_CO_PRESENCE_LOCK",
@@ -450,15 +606,20 @@ def build_financial_quant_harvest(
"entity_eng_aq": ent_eng_aq,
"entity_ing_aq": ent_ing_aq,
"guilds": item["guilds"],
"data_available": True,
"status": "ok",
"feed_source": item.get("feed_source") or "real_market_cache",
"observation_date_utc": item.get("observation_date_utc"),
"co_present_in_news_wire": co_present,
"metrics": {
"close_usd": item["close_usd"],
"close_usd": close_val,
"change_pct": chg_pct,
"change_bps": item["change_bps"],
"change_bps": int(chg_bps_raw) if chg_bps_raw is not None else None,
"volume_ratio_20d": vol_ratio,
"market_cap_str": mcap_s,
},
"quant_encodings": {
"status": "ok",
"close_digit_aq": close_dig_aq,
"close_spoken_eng": close_sp_eng,
"close_spoken_ing": close_sp_ing,
@@ -475,41 +636,29 @@ def build_financial_quant_harvest(
"contingent_locks": locks,
})
# Evaluate registered anchor revisions against taxonomy/quantitative-economic-anchors.json
anc_revs = [
{
"anchor_id": "anthropic_ipo_price_83",
"q_old_digit": "$83",
"q_new_digit": "$89",
"q_old_spoken_ing": "aytee three (202)",
"q_new_spoken_ing": "aytee nain (193 [44th PRIME])",
"migration": "Migrates into 193 == anthropik == flash krash == Dario Amodei [Gen 0] (Scope 1 + Scope 2 Exact Self-Lock).",
"counter_substitutions": {
"path_a_verb_swap": "hohldz (127) ->iksprest / +9 shift",
"path_b_tail_chokepoint": "tab (50) -> 59 (arm [Iso]) in 'aytee nain in dha arm = 333'",
"verified_333": "aytee nain (193) + koinbays (140) = 333",
},
}
]
receipt = guard.audit_receipt()
available_count = sum(1 for x in instruments_out if x.get("data_available"))
unavailable_syms = [x["symbol"] for x in instruments_out if not x.get("data_available")]
payload: dict[str, Any] = {
"$schema": "./schemas/v1/financial-aq-harvest.schema.json",
"$id": "urn:io:hyperstitionstud:schema:v1:financial-aq-harvest",
"version": "2.0.18",
"version": "2.0.23",
"target_date_utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d"),
"harvest_mode": harvest_mode,
"synthetic_data_eliminated": True,
"regime_summary": {
"instrument_count": len(instruments_out),
"instruments_with_data_count": available_count,
"instruments_without_data": unavailable_syms,
"total_contingent_locks": sum(len(x["contingent_locks"]) for x in instruments_out),
"vix_close": vix_close_val,
"us10y_yield_pct": us10y_yield_val,
"vix_close": vix_close_val if vix_close_val is not None else NO_DATA_AVAILABLE,
"us10y_yield_pct": us10y_yield_val if us10y_yield_val is not None else NO_DATA_AVAILABLE,
"news_wire_co_present_symbols": sorted(news_entities.keys()),
"active_memetic_states": sorted(active_memetic_states),
"emergent_m7_quant_triggers": emergent_m7_quant_triggers,
},
"instruments": instruments_out,
"anchor_revisions_detected": anc_revs,
"anchor_revisions_detected": [],
"isolation_receipt": receipt,
}
payload["ipld_dag_json_cidv1"] = {"/": compute_dag_json_cidv1(payload)}
@@ -517,7 +666,7 @@ def build_financial_quant_harvest(
def synthesize_quant_dossier_markdown(payload: dict[str, Any]) -> str:
"""Synthesize a verified 7X-dossier-quant-YYYY-MM-DD.md Markdown dossier from a harvest payload."""
"""Format a Markdown report strictly from real observed harvest data (stating 'No data available' when absent)."""
dt = payload["target_date_utc"]
mode = payload["harvest_mode"]
cid = payload["ipld_dag_json_cidv1"]["/"]
@@ -527,43 +676,35 @@ def synthesize_quant_dossier_markdown(payload: dict[str, Any]) -> str:
"",
f"- **Target Date (UTC):** `{dt}`",
f"- **Harvest Mode:** `{mode}`",
f"- **Instruments Audited:** `{reg['instrument_count']}` (`S1–S6` Canonical Watchlist)",
f"- **Instruments Audited:** `{reg['instrument_count']}` (`{reg.get('instruments_with_data_count', 0)}` with market data; `{', '.join(reg.get('instruments_without_data', [])) or 'none'}`: No data available)",
f"- **Total Contingent Locks:** `{reg['total_contingent_locks']}`",
f"- **Active Memetic States:** `{', '.join(reg['active_memetic_states'])}`",
f"- **Active Memetic States:** `{', '.join(reg['active_memetic_states']) or 'None'}`",
f"- **IPLD `dag-json` `CIDv1`:** `{cid}`",
"",
"## 1. Scope 1 & Scope 2 Instrument Locks",
"## 1. Instrument Telemetry & Observed Locks",
"",
"| Symbol | Entity (`Gen 0 -> Gen 1`) | Close (USD) | Spoken Close (`Gen 1` AQ) | Change (bps) | Active Contingent Locks |",
"| Symbol | Entity (`Gen 0 -> Gen 1`) | Close (USD) | Spoken Close (`Gen 1` AQ) | Change (bps) | Status / Active Contingent Locks |",
"| :--- | :--- | :---: | :--- | :---: | :--- |",
]
for inst in payload["instruments"]:
if not inst["contingent_locks"]:
if not inst.get("data_available"):
lines.append(
f"| `{inst['symbol']}` | `{inst['entity_eng']} -> {inst['entity_ing']}` (`{inst['entity_eng_aq']}->{inst['entity_ing_aq']}`) | "
f"*{NO_DATA_AVAILABLE}* | *{NO_DATA_AVAILABLE}* | *{NO_DATA_AVAILABLE}* | {inst.get('status', NO_DATA_AVAILABLE)} |"
)
continue
q = inst["quant_encodings"]
lock_strs = "; ".join(
l.get("description") or f"{l['scope']} ({l.get('coordinate')} -> {', '.join(l.get('ring_partners', []))})"
for l in inst["contingent_locks"]
)
) or "No locks triggered"
bps_disp = inst["metrics"]["change_bps"] if inst["metrics"]["change_bps"] is not None else NO_DATA_AVAILABLE
lines.append(
f"| `{inst['symbol']}` | `{inst['entity_eng']} -> {inst['entity_ing']}` (`{inst['entity_eng_aq']}->{inst['entity_ing_aq']}`) | "
f"`${inst['metrics']['close_usd']}` | `{q['close_spoken_ing']}` (`{q['close_spoken_ing_aq']}`) | "
f"`{inst['metrics']['change_bps']}` | {lock_strs} |"
f"`{bps_disp}` | {lock_strs} |"
)
lines.extend([
"",
"## 2. Verified Multi-Scale (`333 / 666 / 777`) Quantitative Equations",
"",
"- `envideea fohldz gpu` (\"Nvidia folds GPU\") — `envideea (137) + fohldz (125) + gpu (71) = 333`",
"- `daireeoh fohldz gpu` (\"Dario folds GPU\") — `daireeoh (137) + fohldz (125) + gpu (71) = 333`",
"- `anthropik koinbays` (\"Anthropic Coinbase\") — `anthropik (193) + koinbays (140) = 333`",
"- `flash krash koinbays` (\"flash crash Coinbase\") — `flash krash (193) + koinbays (140) = 333`",
"- `lap for siks bilyan` (\"lap for six billion\") — `lap (56) + for (66) + siks bilyan (211) = 333`",
"- `lap for koper waier` (\"lap for copper wire\") — `lap (56) + for (66) + koper waier (211) = 333`",
"- `aytee nain in dha arm` (\"eighty nine in the Arm\") — `aytee (98) + nain (95) + in (41) + dha (40) + arm (59) = 333`",
"- `siks bilyan hohldz dha kohld asml in gpu` (\"six billion holds the cold ASML in GPU\") — `siks (76) + bilyan (135) + hohldz (127) + dha (40) + kohld (95) + asml (81) + in (41) + gpu (71) = 666`",
"",
])
lines.append("")
return "\n".join(lines)
@@ -571,9 +712,9 @@ def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(prog="hs-quant-harvest", description="Periodic Quantitative Financial Telemetry & Contingent Meaning Collector.")
ap.add_argument("--mode", choices=["us-closing-bell", "utc-rollover"], default="us-closing-bell")
ap.add_argument("--from-snapshot", default=None, help="Optional offline JSON snapshot file.")
ap.add_argument("--live", action="store_true", help="Attempt live keyless HTTP fetch (Yahoo v8 / Stooq CSV / CoinGecko) with snapshot fallback.")
ap.add_argument("--live", action="store_true", help="Attempt live keyless HTTP fetch (Yahoo v8 / Stooq CSV / CoinGecko).")
ap.add_argument("--join-news", default=None, help="Optional path to news-aq-harvest-latest.json.")
ap.add_argument("--write-dossier", default=None, help="Optional path to emit synthesized Markdown quant dossier.")
ap.add_argument("--write-dossier", default=None, help="Optional path to emit Markdown quant report.")
ap.add_argument("--out", default=None, help="Output JSON path (default: <archive_dir>/financial-aq-harvest-latest.json).")
args = ap.parse_args(argv)
@@ -593,7 +734,6 @@ def main(argv: list[str] | None = None) -> int:
d_path.parent.mkdir(parents=True, exist_ok=True)
d_path.write_text(synthesize_quant_dossier_markdown(payload), encoding="utf-8")
# Refresh the periodic time-series bundle (/quant/) whenever hs-quant-harvest runs
from hyperstitionstud_io.quant.timeseries import build_quant_timeseries_bundle
ts_bundle = build_quant_timeseries_bundle(write_files=True)
@@ -603,6 +743,8 @@ def main(argv: list[str] | None = None) -> int:
"output_path": str(out_path),
"harvest_mode": payload["harvest_mode"],
"instrument_count": payload["regime_summary"]["instrument_count"],
"instruments_with_data_count": payload["regime_summary"]["instruments_with_data_count"],
"instruments_without_data": payload["regime_summary"]["instruments_without_data"],
"total_contingent_locks": payload["regime_summary"]["total_contingent_locks"],
"news_wire_co_present_symbols": payload["regime_summary"]["news_wire_co_present_symbols"],
"active_memetic_states": payload["regime_summary"]["active_memetic_states"],
+310 -202
View File
@@ -19,6 +19,7 @@ import hashlib
import json
import math
import re
import urllib.parse
from pathlib import Path
from typing import Any
@@ -33,15 +34,11 @@ from hyperstitionstud_io.ciphers import (
from hyperstitionstud_io.config import load_workspace_config
from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard
from hyperstitionstud_io.ipld import compute_dag_json_cidv1, write_pretty_and_dag_json
from hyperstitionstud_io.lenses import (
DEFAULT_LENS,
ENABLED_LENSES,
LENS_REGISTRY,
apply_all_lenses,
)
from hyperstitionstud_io.lenses import DEFAULT_LENS, ENABLED_LENSES, LENS_REGISTRY, apply_all_lenses
from hyperstitionstud_io.phonetics import translate_batch
from hyperstitionstud_io.quant.collector import (
CANONICAL_WATCHLIST_24,
NO_DATA_AVAILABLE,
S1_S6_SIGNATURE_RINGS,
)
@@ -91,6 +88,51 @@ _DATED_NEWS_RE = re.compile(r"^(\d+)-dossier-news-(\d{4}-\d{2}-\d{2})\.md$")
_EQ_LINE_RE = re.compile(r"^-\s+`([^`]+)`\s+\(\"([^\"]+)\"\)\s+—\s+`([^`]+)=\s*(333|666|777)`")
GUILD_ENCYCLOPEDIA_VOLUME_MAP: dict[str, tuple[str, int, int, str]] = {
"S1": ("03-machinic-phylum-guilds-s1-to-s5/class-s1-autoregressive-ai-and-abstract-machine-a-to-z.pdf", 1, 65, "292"),
"S2": ("03-machinic-phylum-guilds-s1-to-s5/class-s2-flash-crash-and-templex-liquidity-a-to-z.pdf", 1, 66, "193"),
"S3": ("03-machinic-phylum-guilds-s1-to-s5/class-s3-silicon-war-machine-and-euv-swarm-a-to-z.pdf", 5, 67, "137"),
"S4": ("03-machinic-phylum-guilds-s1-to-s5/class-s4-and-s5-nomad-carrier-wave-and-cutaneous-bwo-a-to-z.pdf", 1, 67, "211"),
"S5": ("03-machinic-phylum-guilds-s1-to-s5/class-s4-and-s5-nomad-carrier-wave-and-cutaneous-bwo-a-to-z.pdf", 3, 69, "777"),
"S6": ("04-capital-organizational-capture-s6/a-to-f-acquisition-to-fund.pdf", 1, 68, "125"),
}
def build_instrument_doc_references(
sym: str,
ent_eng: str,
ent_ing: str,
ent_ing_aq: int,
guilds: list[str],
) -> dict[str, Any]:
primary_g = guilds[0] if guilds else "S1"
vol_rel, pg_num, dos_num, fallback_q = GUILD_ENCYCLOPEDIA_VOLUME_MAP.get(
primary_g,
("03-machinic-phylum-guilds-s1-to-s5/class-s1-autoregressive-ai-and-abstract-machine-a-to-z.pdf", 1, 65, "292"),
)
dos_file_map = {
65: "65-dossier-technocapital-singularity-autoregressive-ai.md",
66: "66-dossier-technocapital-singularity-flash-crash-liquidity.md",
67: "67-dossier-technocapital-singularity-silicon-war-machine.md",
68: "68-dossier-technocapital-singularity-apparatus-of-capture.md",
69: "69-dossier-technocapital-singularity-vampiric-memetics.md",
}
dos_fname = dos_file_map.get(dos_num, "71-dossier-news-2026-11-29.md")
dos_prefix = "/zoology/dossiers" if dos_num in dos_file_map else "/archive"
q_enc = urllib.parse.quote(ent_ing)
return {
"encyclopedia_volume_rel": vol_rel,
"encyclopedia_deep_link": f"/encyclopedia/{vol_rel}#page={pg_num}&search={q_enc}",
"knowledge_graph_deep_link": f"/graph/index.html?select=aq:{ent_ing_aq}",
"exemplar_dossier_deep_link": f"{dos_prefix}/{dos_fname}#:~:text={urllib.parse.quote(fallback_q)}",
"rest_api_deep_link": f"/api/v1/dossiers/{dos_num}?highlight={urllib.parse.quote(fallback_q)}",
"verbatim_citation_passage": (
f"{sym} ({ent_eng} -> `{ent_ing}` = {ent_ing_aq}) indexed in Guilds [{', '.join(guilds)}] "
f"and Volume `{vol_rel.split('/')[-1]}` (p.{pg_num}, Dossier {dos_num})."
),
}
def resolve_tradingview_target(symbol: str) -> dict[str, str]:
tv_sym, tv_url = TRADINGVIEW_SYMBOL_MAP.get(
symbol.upper(),
@@ -99,29 +141,35 @@ def resolve_tradingview_target(symbol: str) -> dict[str, str]:
return {"tradingview_symbol": tv_sym, "tradingview_url": tv_url}
def _make_sparkline(values: list[float]) -> str:
if not values:
return ""
lo, hi = min(values), max(values)
def _make_sparkline(values: list[float | None]) -> str | None:
valid = [v for v in values if v is not None]
if not valid:
return None
lo, hi = min(valid), max(valid)
span = (hi - lo) if hi > lo else 1.0
out = []
for v in values:
idx = int(round((v - lo) / span * (len(_SPARK_BLOCKS) - 1)))
out.append(_SPARK_BLOCKS[max(0, min(len(_SPARK_BLOCKS) - 1, idx))])
if v is None:
out.append("·")
else:
idx = int(round((v - lo) / span * (len(_SPARK_BLOCKS) - 1)))
out.append(_SPARK_BLOCKS[max(0, min(len(_SPARK_BLOCKS) - 1, idx))])
return "".join(out)
def _pearson_corr(xs: list[float], ys: list[float]) -> float:
n = min(len(xs), len(ys))
def _pearson_corr(xs: list[float | None], ys: list[float | None]) -> float | None:
m = min(len(xs), len(ys))
pairs = [(float(xs[i]), float(ys[i])) for i in range(m) if xs[i] is not None and ys[i] is not None]
n = len(pairs)
if n < 3:
return 0.0
mx = sum(xs[:n]) / n
my = sum(ys[:n]) / n
num = sum((xs[i] - mx) * (ys[i] - my) for i in range(n))
dx = math.sqrt(sum((xs[i] - mx) ** 2 for i in range(n)))
dy = math.sqrt(sum((ys[i] - my) ** 2 for i in range(n)))
return None
mx = sum(p[0] for p in pairs) / n
my = sum(p[1] for p in pairs) / n
num = sum((p[0] - mx) * (p[1] - my) for p in pairs)
dx = math.sqrt(sum((p[0] - mx) ** 2 for p in pairs))
dy = math.sqrt(sum((p[1] - my) ** 2 for p in pairs))
if dx < 1e-9 or dy < 1e-9:
return 0.0
return None
return round(num / (dx * dy), 3)
@@ -155,12 +203,16 @@ def _extract_dated_news_dossiers(archive_dir: Path) -> dict[str, dict[str, Any]]
for tv in token_vals:
if tv in S1_S6_SIGNATURE_RINGS:
coords_hit.add(tv)
ring_hits = sorted(set(tv for tv in token_vals if tv in S1_S6_SIGNATURE_RINGS))
eqs.append({
"ing": ing_p,
"eng": eng_p,
"breakdown": breakdown.strip(),
"target": tgt_s,
"ring_coordinates": sorted(set(tv for tv in token_vals if tv in S1_S6_SIGNATURE_RINGS)),
"ring_coordinates": ring_hits,
"dossier_deep_link": f"/archive/{p.name}#:~:text={urllib.parse.quote(ing_p[:32])}",
"api_highlight_link": f"/api/v1/dossiers/{dos_num}?highlight={urllib.parse.quote(ing_p[:24])}",
"graph_hub_links": [f"/graph/index.html?select=aq:{c}" for c in ring_hits] + [f"/graph/index.html?select=aq:{tgt_s}"],
})
for c_ring in S1_S6_SIGNATURE_RINGS:
@@ -193,144 +245,123 @@ def _extract_dated_news_dossiers(archive_dir: Path) -> dict[str, dict[str, Any]]
return dossiers_by_date
def _generate_deterministic_bar_for_date(
item: dict[str, Any],
dt_str: str,
day_index: int,
total_days: int,
) -> dict[str, Any]:
def _load_real_market_history_bars(cfg: Any) -> dict[str, dict[str, dict[str, Any]]]:
"""
Generate the deterministic daily closing-bell bar for date `dt_str` anchored to the
canonical 2026-11-30 closing-bell telemetry snapshot so the final bar (t = N-1) equals
CANONICAL_WATCHLIST_24 exactly and earlier bars trace a reproducible trajectory.
Load real daily OHLCV bars from `site/quant/real-market-history.json`.
Never synthesizes or interpolates missing dates or private-entity prices:
any `(symbol, date_utc)` not present in the real exchange history returns `None`
and is reported as `"No data available"`.
"""
sym = item["symbol"]
base_close = float(item["close_usd"])
base_chg_pct = float(item["change_pct"])
base_bps = int(item["change_bps"])
base_vol = float(item["volume_ratio_20d"])
mcap_s = str(item["market_cap_str"])
if day_index == total_days - 1:
return {
"close_usd": base_close,
"change_pct": base_chg_pct,
"change_bps": base_bps,
"volume_ratio_20d": base_vol,
"market_cap_str": mcap_s,
}
# Special step-series handling for ANTHR-PVT ($83 pre-Nov 18 -> $89 from Nov 18 onward)
if sym == "ANTHR-PVT":
close_v = 83.0 if dt_str < "2026-11-18" else (89.0 if dt_str >= "2026-11-26" else 86.0)
bps_v = 0 if dt_str < "2026-11-18" else (723 if dt_str == "2026-11-26" else 125)
return {
"close_usd": close_v,
"change_pct": round(bps_v / 100.0, 2),
"change_bps": bps_v,
"volume_ratio_20d": 1.60 if bps_v >= 200 else 1.05,
"market_cap_str": "$57B" if close_v < 89 else "$61B",
}
seed_bytes = hashlib.sha256(f"{sym}:{dt_str}:v2".encode("utf-8")).digest()
wave_a = ((seed_bytes[0] / 255.0) - 0.5) * 2.0
wave_b = ((seed_bytes[1] / 255.0) - 0.5) * 2.0
rem = (total_days - 1 - day_index) / float(max(1, total_days - 1))
if base_close >= 20.0:
# Step integer prices across nearby coordinates including occasional signature ring hits
offset_int = int(round(wave_a * 6.0 * rem + 3.0 * math.sin(day_index * 0.55)))
close_v = float(max(1, int(round(base_close)) + offset_int))
else:
close_v = round(max(0.5, base_close * (1.0 + 0.04 * wave_a * rem)), 2)
bps_v = int(round(base_bps * 0.35 + wave_b * 185.0))
# Periodically snap basis-point moves onto canonical S1-S6 signature ring integers on resonant days
ring_candidates = (71, 81, 91, 95, 115, 125, 128, 129, 133, 135, 137, 153, 160, 163, 183, 189, 191, 193, 211, 256, 260)
if seed_bytes[2] % 4 == 0:
chosen_ring = ring_candidates[seed_bytes[3] % len(ring_candidates)]
bps_v = chosen_ring if wave_b >= 0 else -chosen_ring
vol_v = round(max(0.32, min(3.10, base_vol + 0.45 * wave_a)), 2)
return {
"close_usd": close_v,
"change_pct": round(bps_v / 100.0, 2),
"change_bps": bps_v,
"volume_ratio_20d": vol_v,
"market_cap_str": mcap_s,
}
hist_path = cfg.core_dir / "site" / "quant" / "real-market-history.json"
if not hist_path.is_file():
return {}
try:
raw = json.loads(hist_path.read_text(encoding="utf-8"))
out: dict[str, dict[str, dict[str, Any]]] = {}
for sym, sym_obj in (raw.get("instruments") or {}).items():
out[sym] = dict(sym_obj.get("bars_by_date") or {})
return out
except Exception:
return {}
def compute_timeseries_moments(
daily_points: list[float],
daily_points: list[float | None],
active_flags: list[bool],
wire_shares: list[float],
cap_shares: list[float],
expected_null_locks: float,
observed_locks: int,
wire_vel_series: list[float],
abs_bps_series: list[float],
wire_shares: list[float | None],
cap_shares: list[float | None],
expected_null_locks: float | None,
observed_locks: int | None,
wire_vel_series: list[float | None],
abs_bps_series: list[float | None],
regime_series: list[set[str]],
baseline_replacement_pts: float = 18.0,
available_trading_days: int | None = None,
) -> dict[str, Any]:
"""
Compute the 6 canonical lens-neutral longitudinal time-series moments (`ts_*`).
Returns `None` (`null` in JSON) for unavailable metrics rather than defaulting to `0.0`.
"""
n = max(1, len(daily_points))
duty_pct = round(100.0 * sum(1 for f in active_flags if f) / n, 1)
valid_pts = [float(p) for p in daily_points if p is not None]
avail_cnt = available_trading_days if available_trading_days is not None else len(valid_pts)
if avail_cnt <= 0 or not valid_pts:
return {
"ts_duty_cycle_pct": None,
"ts_weighted_resonance": None,
"ts_excess_over_null": None,
"ts_excess_over_replacement": None,
"ts_quantile_profile": {
"p20_floor": None,
"p90_ceiling": None,
"boom_pct": None,
"bust_pct": None,
"cv": None,
},
"ts_optimal_lag_days": None,
"ts_lag_correlation_curve": {str(tau): None for tau in range(-5, 6)},
"ts_regime_splits": {
"M1_ENTROPIC": None,
"M2_FLASH_CRASH": None,
"M3_LEVIATHAN": None,
},
"ts_sparkline_30d": None,
}
mean_wire_sh = sum(wire_shares) / n if wire_shares else 0.0
mean_cap_sh = sum(cap_shares) / n if cap_shares else 0.0
n_total = max(1, len(daily_points))
n_valid = max(1, len(valid_pts))
duty_pct = round(100.0 * sum(1 for f in active_flags if f) / n_valid, 1)
valid_wire = [float(w) for w in wire_shares if w is not None]
valid_cap = [float(c) for c in cap_shares if c is not None]
mean_wire_sh = sum(valid_wire) / len(valid_wire) if valid_wire else 0.0
mean_cap_sh = sum(valid_cap) / len(valid_cap) if valid_cap else 0.0
weighted_res = min(99.0, round(100.0 * (1.5 * mean_wire_sh + 0.7 * mean_cap_sh), 1))
loe = round(observed_locks - expected_null_locks, 2)
tot_pts = sum(daily_points)
loe = round((observed_locks or 0) - (expected_null_locks or 0.0), 2) if (observed_locks is not None and expected_null_locks is not None) else None
tot_pts = sum(valid_pts)
excess_over_repl = round((tot_pts - baseline_replacement_pts) / 6.5, 2)
sorted_pts = sorted(daily_points)
p20_idx = min(n - 1, max(0, int(0.20 * n)))
p90_idx = min(n - 1, max(0, int(0.90 * n)))
mean_pt = tot_pts / n
var_pt = sum((x - mean_pt) ** 2 for x in daily_points) / n
sorted_pts = sorted(valid_pts)
p20_idx = min(n_valid - 1, max(0, int(0.20 * n_valid)))
p90_idx = min(n_valid - 1, max(0, int(0.90 * n_valid)))
mean_pt = tot_pts / n_valid
var_pt = sum((x - mean_pt) ** 2 for x in valid_pts) / n_valid
std_pt = math.sqrt(var_pt)
cv = round(std_pt / max(0.25, mean_pt), 2)
cv = round(std_pt / mean_pt, 2) if mean_pt > 0 else None
# Normalize P20 floor and P90 ceiling onto a 0-100 diagnostic scale for cross-lens comparability
p20_norm = min(98.0, round(42.0 + 14.0 * sorted_pts[p20_idx], 1))
p90_norm = min(99.0, round(48.0 + 11.5 * sorted_pts[p90_idx], 1))
boom_pct = round(100.0 * sum(1 for x in daily_points if x >= 3.5) / n, 1)
bust_pct = round(100.0 * sum(1 for x in daily_points if x <= 0.01) / n, 1)
boom_pct = round(100.0 * sum(1 for x in valid_pts if x >= 3.5) / n_valid, 1)
bust_pct = round(100.0 * sum(1 for x in valid_pts if x <= 0.01) / n_valid, 1)
# Lead-lag cross-correlation profile across tau in [-5 .. +5] days
lag_corrs: dict[str, float] = {}
best_lag = 0
lag_corrs: dict[str, float | None] = {}
best_lag: int | None = None
best_abs_r = -1.0
for tau in range(-5, 6):
if tau >= 0:
xs = wire_vel_series[: n - tau]
xs = wire_vel_series[: n_total - tau]
ys = abs_bps_series[tau:]
else:
k = -tau
xs = wire_vel_series[k:]
ys = abs_bps_series[: n - k]
ys = abs_bps_series[: n_total - k]
r_val = _pearson_corr(xs, ys)
lag_corrs[str(tau)] = r_val
if abs(r_val) > best_abs_r:
if r_val is not None and abs(r_val) > best_abs_r:
best_abs_r = abs(r_val)
best_lag = tau
# Conditional regime splits
regime_splits: dict[str, float] = {}
regime_splits: dict[str, float | None] = {}
for r_key, r_full in (
("M1_ENTROPIC", "M1_ENTROPIC_STAGNATION"),
("M2_FLASH_CRASH", "M2_FLASH_CRASH_TEMPLEX_SURGE"),
("M3_LEVIATHAN", "M3_LEVIATHAN_TRILLION_CAP_CONCENTRATION"),
):
sub_pts = [daily_points[i] for i in range(n) if r_full in regime_series[i]]
sub_pts = [float(daily_points[i]) for i in range(n_total) if daily_points[i] is not None and r_full in regime_series[i]]
if sub_pts:
regime_splits[r_key] = round((sum(sub_pts) / len(sub_pts) - mean_pt) * 4.0, 1)
else:
regime_splits[r_key] = 0.0
regime_splits[r_key] = None
return {
"ts_duty_cycle_pct": duty_pct,
@@ -357,6 +388,7 @@ def derive_pokedex_specimen_profile(
) -> dict[str, Any]:
"""
Project a lens-neutral instrument record into a Gen IV INFO Pokedex specimen card.
Uses `None` (`null` in JSON) when time-series data is unavailable.
"""
sv = inst_record["structural_vector"]
tm = inst_record["timeseries_moments"]
@@ -365,13 +397,19 @@ def derive_pokedex_specimen_profile(
)["pokedex_scanner"]
qual = proj["qualitative_profile"]
duty = float(tm["ts_duty_cycle_pct"])
level = max(12, min(99, int(round(0.55 * inst_record["composite_score"] + 0.45 * float(tm["ts_weighted_resonance"])))))
rarity = (
"Common Keystone Encounter (21:30 UTC Closing Bell)"
if duty >= 60.0
else ("Uncommon Regime Encounter (00:00 UTC Rollover)" if duty >= 25.0 else "Legendary Roaming Anomaly (<5% Rate)")
)
duty_raw = tm.get("ts_duty_cycle_pct")
w_res_raw = tm.get("ts_weighted_resonance")
if duty_raw is None or w_res_raw is None:
level: int | None = None
rarity: str | None = None
else:
duty = float(duty_raw)
level = max(12, min(99, int(round(0.55 * inst_record["composite_score"] + 0.45 * float(w_res_raw)))))
rarity = (
"Common Keystone Encounter (21:30 UTC Closing Bell)"
if duty >= 60.0
else ("Uncommon Regime Encounter (00:00 UTC Rollover)" if duty >= 25.0 else "Legendary Roaming Anomaly (<5% Rate)")
)
return {
"dex_number": f"DEX #{inst_record['entity_ing_aq']:03d}",
"symbol": symbol,
@@ -408,29 +446,34 @@ def build_quant_timeseries_bundle(
with ReadOnlyIsolationGuard(cfg.read_only_files) as guard:
dated_dossiers = _extract_dated_news_dossiers(cfg.archive_dir)
real_history = _load_real_market_history_bars(cfg)
dates_utc = [f"2026-11-{d:02d}" for d in range(1, 31)]
num_days = len(dates_utc)
# Pre-collect all phrases needed for batch Ingglish translation
raw_bars_by_sym: dict[str, list[dict[str, Any]]] = {}
# Pre-collect all phrases needed for batch Ingglish translation from real observations only
raw_bars_by_sym: dict[str, list[dict[str, Any] | None]] = {}
phrases_to_translate: set[str] = set()
for item in CANONICAL_WATCHLIST_24:
sym = item["symbol"]
phrases_to_translate.add(item["entity_eng"])
bars = []
for d_idx, dt_s in enumerate(dates_utc):
b = _generate_deterministic_bar_for_date(item, dt_s, d_idx, num_days)
sym_hist = real_history.get(sym) or {}
bars: list[dict[str, Any] | None] = []
for dt_s in dates_utc:
b = sym_hist.get(dt_s)
bars.append(b)
phrases_to_translate.add(int_to_spoken_words(int(round(float(b["close_usd"])))))
phrases_to_translate.add(int_to_spoken_words(abs(int(b["change_bps"]))))
phrases_to_translate.add(expand_quant_spoken(str(b["market_cap_str"])))
if b and b.get("close_usd") is not None:
phrases_to_translate.add(int_to_spoken_words(int(round(float(b["close_usd"])))))
if b and b.get("change_bps") is not None:
phrases_to_translate.add(int_to_spoken_words(abs(int(b["change_bps"]))))
if b and b.get("market_cap_str") and b["market_cap_str"] != NO_DATA_AVAILABLE:
phrases_to_translate.add(expand_quant_spoken(str(b["market_cap_str"])))
raw_bars_by_sym[sym] = bars
ing_map = translate_batch(sorted(phrases_to_translate))
# Build daily wire summary series (2026-11-01 .. 2026-11-30)
daily_wire_series: list[dict[str, Any]] = []
wire_vel_global: list[float] = []
wire_vel_global: list[float | None] = []
for dt_s in dates_utc:
dos = dated_dossiers.get(dt_s)
if dos:
@@ -442,12 +485,12 @@ def build_quant_timeseries_bundle(
"dossier_number": None,
"dossier_file": None,
"archive_route": None,
"equation_counts": {"eq_333": 0, "eq_666": 0, "eq_777": 0, "total": 0},
"equation_counts": {"eq_333": None, "eq_666": None, "eq_777": None, "total": None},
"active_ring_coordinates": [],
"co_present_symbols": [],
"sample_equations": [],
})
wire_vel_global.append(0.0)
wire_vel_global.append(None)
# Compute per-day regime states and total volume-weighted locked bps for WOPR share
daily_regimes: list[set[str]] = [set() for _ in range(num_days)]
@@ -464,24 +507,71 @@ def build_quant_timeseries_bundle(
for d_idx, dt_s in enumerate(dates_utc):
b = raw_bars_by_sym[sym][d_idx]
close_int = int(round(float(b["close_usd"])))
bps_abs = abs(int(b["change_bps"]))
mcap_s = str(b["market_cap_str"])
vol_r = float(b["volume_ratio_20d"])
chg_pct = float(b["change_pct"])
dos = dated_dossiers.get(dt_s)
co_present = bool(dos and sym in dos["co_present_symbols"])
if b is None or b.get("close_usd") is None:
series_rows.append({
"date_utc": dt_s,
"data_available": False,
"status": NO_DATA_AVAILABLE,
"feed_source": None,
"close_usd": None,
"change_pct": None,
"change_bps": None,
"volume_ratio_20d": None,
"market_cap_str": NO_DATA_AVAILABLE,
"close_digit_aq": None,
"close_spoken_ing": NO_DATA_AVAILABLE,
"close_spoken_ing_aq": None,
"scaled_cap_spoken_ing": NO_DATA_AVAILABLE,
"scaled_cap_spoken_ing_aq": None,
"bps_digit_aq": None,
"bps_spoken_ing": NO_DATA_AVAILABLE,
"bps_spoken_ing_aq": None,
"scope1_locks": [],
"scope2_ring_coordinates": [],
"co_present_in_news_wire": co_present,
"contingent_points": 1.0 if co_present else None,
"_locked_disp": None,
})
continue
close_val = float(b["close_usd"])
close_int = int(round(close_val))
close_sp_eng = int_to_spoken_words(close_int)
close_sp_ing = ing_map.get(close_sp_eng, close_sp_eng)
bps_sp_eng = int_to_spoken_words(bps_abs)
bps_sp_ing = ing_map.get(bps_sp_eng, bps_sp_eng)
mcap_sp_eng = expand_quant_spoken(mcap_s)
mcap_sp_ing = ing_map.get(mcap_sp_eng, mcap_sp_eng)
close_dig_aq = compute_aq(str(close_int))
close_sp_aq = compute_aq(close_sp_ing)
bps_dig_aq = compute_aq(str(bps_abs))
bps_sp_aq = compute_aq(bps_sp_ing)
mcap_sp_aq = compute_aq(mcap_sp_ing)
chg_bps_raw = b.get("change_bps")
chg_pct_raw = b.get("change_pct")
if chg_bps_raw is not None:
bps_abs: int | None = abs(int(chg_bps_raw))
bps_sp_eng = int_to_spoken_words(bps_abs)
bps_sp_ing = ing_map.get(bps_sp_eng, bps_sp_eng)
bps_dig_aq: int | None = compute_aq(str(bps_abs))
bps_sp_aq: int | None = compute_aq(bps_sp_ing)
else:
bps_abs = None
bps_sp_ing = NO_DATA_AVAILABLE
bps_dig_aq = None
bps_sp_aq = None
mcap_raw = b.get("market_cap_str")
if mcap_raw and mcap_raw != NO_DATA_AVAILABLE:
mcap_s = str(mcap_raw)
mcap_sp_eng = expand_quant_spoken(mcap_s)
mcap_sp_ing = ing_map.get(mcap_sp_eng, mcap_sp_eng)
mcap_sp_aq: int | None = compute_aq(mcap_sp_ing)
else:
mcap_s = NO_DATA_AVAILABLE
mcap_sp_ing = NO_DATA_AVAILABLE
mcap_sp_aq = None
vol_r_raw = b.get("volume_ratio_20d")
vol_r = float(vol_r_raw) if vol_r_raw is not None else None
chg_pct = float(chg_pct_raw) if chg_pct_raw is not None else None
scope1_locks: list[str] = []
scope2_coords: list[int] = []
@@ -490,19 +580,19 @@ def build_quant_timeseries_bundle(
scope1_locks.append(f"CLOSE_SELF_LOCK ({close_int}=={ent_ing})")
if is_repdigit_37(close_sp_aq) or is_repdigit_37(close_int):
scope1_locks.append(f"REPDIGIT_ATTRACTOR ({close_int if is_repdigit_37(close_int) else close_sp_aq})")
if bps_abs == ent_ing_aq or bps_abs == ent_eng_aq:
if bps_abs is not None and (bps_abs == ent_ing_aq or bps_abs == ent_eng_aq):
scope1_locks.append(f"BPS_SELF_LOCK ({bps_abs}=={ent_ing})")
for c_val in (close_int, close_sp_aq, bps_abs):
cand_coords = [close_int, close_sp_aq]
if bps_abs is not None:
cand_coords.append(bps_abs)
for c_val in cand_coords:
if c_val in S1_S6_SIGNATURE_RINGS and c_val not in scope2_coords:
scope2_coords.append(c_val)
dos = dated_dossiers.get(dt_s)
co_present = bool(dos and sym in dos["co_present_symbols"])
if vol_r < 0.45 and abs(chg_pct) < 0.15:
if vol_r is not None and chg_pct is not None and vol_r < 0.45 and abs(chg_pct) < 0.15:
daily_regimes[d_idx].add("M1_ENTROPIC_STAGNATION")
if chg_pct <= -5.0 or vol_r >= 2.5 or (sym == "^VIX" and close_int >= 25):
if (chg_pct is not None and chg_pct <= -5.0) or (vol_r is not None and vol_r >= 2.5) or (sym == "^VIX" and close_int >= 25):
daily_regimes[d_idx].add("M2_FLASH_CRASH_TEMPLEX_SURGE")
if mcap_s.endswith("T"):
daily_regimes[d_idx].add("M3_LEVIATHAN_TRILLION_CAP_CONCENTRATION")
@@ -512,14 +602,17 @@ def build_quant_timeseries_bundle(
+ 1.5 * len(scope2_coords)
+ (2.5 if (co_present and (scope1_locks or scope2_coords)) else (1.0 if co_present else 0.0))
)
locked_disp = (bps_abs * vol_r) if (scope1_locks or scope2_coords) else 0.0
locked_disp = ((bps_abs or 0) * (vol_r or 1.0)) if (scope1_locks or scope2_coords) else 0.0
daily_total_locked_displacement[d_idx] += locked_disp
series_rows.append({
"date_utc": dt_s,
"close_usd": b["close_usd"],
"data_available": True,
"status": "ok",
"feed_source": b.get("feed_source") or "yahoo_v8_json",
"close_usd": close_val,
"change_pct": chg_pct,
"change_bps": b["change_bps"],
"change_bps": int(chg_bps_raw) if chg_bps_raw is not None else None,
"volume_ratio_20d": vol_r,
"market_cap_str": mcap_s,
"close_digit_aq": close_dig_aq,
@@ -547,26 +640,30 @@ def build_quant_timeseries_bundle(
ent_eng_aq = compute_aq(ent_eng)
ent_ing_aq = compute_aq(ent_ing)
s_rows = per_sym_series[sym]
avail_rows = [r for r in s_rows if r.get("data_available")]
daily_pts = [float(r["contingent_points"]) for r in s_rows]
active_flags = [bool(r["scope1_locks"] or r["scope2_ring_coordinates"] or r["co_present_in_news_wire"]) for r in s_rows]
abs_bps = [float(abs(int(r["change_bps"]))) for r in s_rows]
daily_pts: list[float | None] = [float(r["contingent_points"]) if r.get("contingent_points") is not None else None for r in s_rows]
active_flags = [bool(r["scope1_locks"] or r["scope2_ring_coordinates"] or r["co_present_in_news_wire"]) for r in s_rows if r.get("data_available")]
abs_bps: list[float | None] = [float(abs(int(r["change_bps"]))) if r.get("change_bps") is not None else None for r in s_rows]
wire_shares: list[float] = []
cap_shares: list[float] = []
wire_shares: list[float | None] = []
cap_shares: list[float | None] = []
tot_locks = 0
for d_idx, r in enumerate(s_rows):
tot_locks += len(r["scope1_locks"]) + len(r["scope2_ring_coordinates"])
dos = dated_dossiers.get(dates_utc[d_idx])
if dos and dos["active_ring_coordinates"]:
hit = 1.0 if (ent_ing_aq in dos["active_ring_coordinates"] or sym in dos["co_present_symbols"]) else 0.15
hit = 1.0 if (ent_ing_aq in dos["active_ring_coordinates"] or sym in dos["co_present_symbols"]) else 0.0
wire_shares.append(hit / max(1, len(CANONICAL_WATCHLIST_24) * 0.35))
else:
wire_shares.append(0.0)
denom = max(1.0, daily_total_locked_displacement[d_idx])
cap_shares.append(float(r.pop("_locked_disp", 0.0)) / denom)
wire_shares.append(None)
ld_val = r.pop("_locked_disp", None)
if ld_val is not None:
denom = max(1.0, daily_total_locked_displacement[d_idx])
cap_shares.append(float(ld_val) / denom)
else:
cap_shares.append(None)
# Structural 6-vector for the instrument
is_iso = ent_eng_aq == ent_ing_aq
is_p_ing = prime_rank(ent_ing_aq) is not None
is_p_eng = prime_rank(ent_eng_aq) is not None
@@ -593,13 +690,19 @@ def build_quant_timeseries_bundle(
active_flags=active_flags,
wire_shares=wire_shares,
cap_shares=cap_shares,
expected_null_locks=round(num_days * 0.32, 2),
observed_locks=tot_locks,
expected_null_locks=round(len(avail_rows) * 0.32, 2) if avail_rows else None,
observed_locks=tot_locks if avail_rows else None,
wire_vel_series=wire_vel_global,
abs_bps_series=abs_bps,
regime_series=daily_regimes,
available_trading_days=len(avail_rows),
)
ts_moments["available_trading_days"] = len(avail_rows)
ts_moments["missing_trading_days"] = num_days - len(avail_rows)
ts_moments["market_data_status"] = "ok" if avail_rows else NO_DATA_AVAILABLE
tv_info = resolve_tradingview_target(sym)
doc_refs = build_instrument_doc_references(sym, ent_eng, ent_ing, ent_ing_aq, item["guilds"])
inst_obj: dict[str, Any] = {
"symbol": sym,
"entity_eng": ent_eng,
@@ -608,8 +711,12 @@ def build_quant_timeseries_bundle(
"entity_ing_aq": ent_ing_aq,
"isometric_entity": is_iso,
"guilds": item["guilds"],
"data_available": len(avail_rows) > 0,
"status": "ok" if avail_rows else f"{NO_DATA_AVAILABLE} (private entity — no public exchange feed)",
"available_trading_days": len(avail_rows),
"tradingview_symbol": tv_info["tradingview_symbol"],
"tradingview_url": tv_info["tradingview_url"],
"doc_references": doc_refs,
"composite_score": comp_score,
"structural_vector": struct_vec,
"timeseries_moments": ts_moments,
@@ -641,17 +748,16 @@ def build_quant_timeseries_bundle(
if not matching_insts:
matching_insts = instruments_out[:3]
b_daily_pts = [
round(sum(inst["bars"][d_i]["contingent_points"] for inst in matching_insts) / len(matching_insts), 2)
for d_i in range(num_days)
]
b_active = [any(inst["bars"][d_i]["contingent_points"] > 0 for inst in matching_insts) for d_i in range(num_days)]
b_abs_bps = [
round(sum(abs(int(inst["bars"][d_i]["change_bps"])) for inst in matching_insts) / len(matching_insts), 1)
for d_i in range(num_days)
]
b_wire_sh = [0.18 if b_active[d_i] else 0.02 for d_i in range(num_days)]
b_cap_sh = [0.16 if b_daily_pts[d_i] >= 2.0 else 0.04 for d_i in range(num_days)]
b_daily_pts: list[float | None] = []
b_abs_bps: list[float | None] = []
for d_i in range(num_days):
pts_d = [float(inst["bars"][d_i]["contingent_points"]) for inst in matching_insts if inst["bars"][d_i]["contingent_points"] is not None]
b_daily_pts.append(round(sum(pts_d) / len(pts_d), 2) if pts_d else None)
bps_d = [abs(int(inst["bars"][d_i]["change_bps"])) for inst in matching_insts if inst["bars"][d_i]["change_bps"] is not None]
b_abs_bps.append(round(sum(bps_d) / len(bps_d), 1) if bps_d else None)
b_active = [any((inst["bars"][d_i]["contingent_points"] or 0) > 0 for inst in matching_insts) for d_i in range(num_days)]
b_wire_sh: list[float | None] = [None for _ in range(num_days)]
b_cap_sh: list[float | None] = [None for _ in range(num_days)]
b_locks = sum(
len(inst["bars"][d_i]["scope1_locks"]) + len(inst["bars"][d_i]["scope2_ring_coordinates"])
for inst in matching_insts
@@ -670,12 +776,11 @@ def build_quant_timeseries_bundle(
regime_series=daily_regimes,
)
base_eti = float(row.get("curve_score", 75))
live_eti = max(
40.0,
min(
99.0,
round(base_eti + 0.35 * b_ts["ts_excess_over_replacement"], 1),
),
eor_val = b_ts.get("ts_excess_over_replacement")
live_eti = (
max(40.0, min(99.0, round(base_eti + 0.35 * float(eor_val), 1)))
if eor_val is not None
else base_eti
)
builds_out.append({
"rank": row.get("rank"),
@@ -684,6 +789,13 @@ def build_quant_timeseries_bundle(
"roster_slot": row.get("roster_slot"),
"base_composite_score": base_eti,
"live_timeseries_score": live_eti,
"doc_references": {
"encyclopedia_volume_rel": "07-ecological-trophic-index-and-tier-list/a-to-z-arm-chokepoint-armor-to-zoological-tie-breaker.pdf",
"encyclopedia_deep_link": f"/encyclopedia/07-ecological-trophic-index-and-tier-list/a-to-z-arm-chokepoint-armor-to-zoological-tie-breaker.pdf#page=1&search={urllib.parse.quote(g_prefix)}",
"knowledge_graph_deep_link": f"/graph/index.html?select=build:{g_prefix}",
"exemplar_dossier_deep_link": f"/zoology/tier-list-technocapital-assemblage-builds.pdf#page=1&search={urllib.parse.quote(g_prefix)}",
"rest_api_deep_link": f"/api/v1/zoology/tier-list?build_filter={urllib.parse.quote(g_prefix)}",
},
"structural_vector": b_struct,
"timeseries_moments": b_ts,
"lens_projections": apply_all_lenses(b_struct, b_ts, live_eti, active_lenses),
@@ -697,34 +809,28 @@ def build_quant_timeseries_bundle(
"q_old_digit": "$6B",
"q_new_digit": "$6B",
"coordinate": 211,
"description": "Lazarus $6B heist ('siks bilyan' = 211 [47th PRIME] == wor masheen == koper waier).",
"source_dossier": "25-dossier-news-2026-11-01.md",
"description": "Lazarus $6B heist ('siks bilyan' = 211 [47th PRIME] == wor masheen == koper waier) in Dossier 25.",
},
{
"anchor_id": "anthropic_ipo_price_83_baseline",
"anchor_id": "anthropic_ipo_price_83",
"date_utc": "2026-11-18",
"symbol": "ANTHR-PVT",
"q_old_digit": "$83",
"q_new_digit": "$83",
"coordinate": 202,
"description": "Anthropic initial valuation share anchor $83 ('aytee three' = 202) in Dossier 55.",
"source_dossier": "55-dossier-news-2026-11-18.md",
"description": "Anthropic valuation share anchor $83 ('aytee three' = 202) in Dossier 55 (no public exchange market data available).",
},
{
"anchor_id": "bangladesh_factories_481",
"date_utc": "2026-11-24",
"symbol": "TSM",
"q_old_digit": "481",
"q_new_digit": "841",
"q_new_digit": "481",
"coordinate": 13,
"description": "481 halted factories ('4+8+1 = 13' Iso-Digital conservation with 841 = 29^2) in Dossier 62.",
},
{
"anchor_id": "anthropic_ipo_price_83_repricing",
"date_utc": "2026-11-26",
"symbol": "ANTHR-PVT",
"q_old_digit": "$83",
"q_new_digit": "$89",
"coordinate": 193,
"description": "Repriced $83 -> $89 ('aytee nain' = 193 [44th PRIME] == anthropik == flash krash == Dario Amodei [Gen 0]).",
"source_dossier": "62-dossier-news-2026-11-24.md",
"description": "481 halted garment factories ('4+8+1 = 13') in Dossier 62.",
},
]
@@ -735,12 +841,14 @@ def build_quant_timeseries_bundle(
"version": CURRENT_VERSION,
"namespace_urn": f"urn:io:hyperstitionstud:quant-timeseries:{CURRENT_VERSION}",
"generated_at_utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"synthetic_data_eliminated": True,
"periodicity_gate": {
"enforced": True,
"allowed_cadences": ["1d-us-closing-bell-2130-utc", "24h-news-wire-rollover-0000-utc"],
"dated_news_dossiers_ingested": len(dated_dossiers),
"excluded_non_periodic_sources": EXCLUDED_NON_PERIODIC_SOURCES,
"non_periodic_records_ingested": 0,
"missing_data_policy": "No data available (never synthesized or interpolated)",
},
"enabled_lenses": list(active_lenses),
"default_lens": DEFAULT_LENS if DEFAULT_LENS in active_lenses else active_lenses[0],
+14
View File
@@ -88,6 +88,20 @@ def get_version_targets(ws_root: Path | None = None) -> list[tuple[Path, list[tu
(rf'Time-Series Workbench \(v{SEMVER_RE}\)', "Time-Series Workbench (v{V})"),
],
),
(
core / "site" / "quant" / "quant-tutorials.js",
[
(rf'Deep-Link Choreographer \(v{SEMVER_RE}\)', "Deep-Link Choreographer (v{V})"),
(rf'version:\s*"{SEMVER_RE}"', 'version: "{V}"'),
],
),
(
core / "site" / "donate" / "index.html",
[
(rf'urn:io:hyperstitionstud:donate:v{SEMVER_RE}', "urn:io:hyperstitionstud:donate:v{V}"),
(rf'hyperstitionstud\.io/donate v{SEMVER_RE}', "hyperstitionstud.io/donate v{V}"),
],
),
(
core / "site" / "gallery" / "index.html",
[
+268 -8
View File
@@ -45,6 +45,7 @@ def test_offline_urn_namespaces_and_no_external_https_fonts() -> None:
cfg = load_workspace_config()
for html_p in (
cfg.core_dir / "site" / "index.html",
cfg.core_dir / "site" / "donate" / "index.html",
cfg.core_dir / "site" / "learn" / "index.html",
cfg.core_dir / "site" / "quant" / "index.html",
cfg.core_dir / "site" / "gallery" / "index.html",
@@ -58,6 +59,17 @@ def test_offline_urn_namespaces_and_no_external_https_fonts() -> None:
assert "by Lemurs." in txt, f"Missing global Lemurs footer in {html_p}"
assert ("&#x2665;" in txt or "♥" in txt), f"Missing Unicode heart in {html_p}"
for nav_p in (
cfg.core_dir / "site" / "index.html",
cfg.core_dir / "site" / "learn" / "index.html",
cfg.core_dir / "site" / "quant" / "index.html",
):
nav_txt = nav_p.read_text(encoding="utf-8")
assert "btn-donate-pill" in nav_txt, f"Missing distinct stadium-pill Donate button in {nav_p}"
assert "donate-pill-emblem" in nav_txt, f"Missing circular 1:2 Donate emblem in {nav_p}"
assert "nav-donate-sep" in nav_txt, f"Missing vertical divider before Donate pill in {nav_p}"
assert "margin-left: auto" in nav_txt, f"Missing right-justification margin-left: auto in {nav_p}"
schemas_dir = cfg.core_dir / "schemas" / "v1"
for sp in schemas_dir.glob("*.schema.json"):
s_obj = json.loads(sp.read_text(encoding="utf-8"))
@@ -164,19 +176,36 @@ def test_ipld_quant_and_mcp_server() -> None:
cid = compute_dag_json_cidv1({"a": 1, "b": 2})
assert cid.startswith("baguqeera")
# 2. Quantitative Financial Telemetry Collector
q_harvest = build_financial_quant_harvest()
# 2. Quantitative Financial Telemetry Collector (100% Real Exchange Observations — Zero Synthesized Data)
from hyperstitionstud_io.quant.collector import CANONICAL_WATCHLIST_24, NO_DATA_AVAILABLE
assert all("close_usd" not in item for item in CANONICAL_WATCHLIST_24), "Watchlist metadata must not hardcode fake prices"
q_harvest = build_financial_quant_harvest(live_fetch=False)
assert q_harvest["harvest_mode"] == "us-closing-bell"
assert q_harvest["synthetic_data_eliminated"] is True
assert q_harvest["regime_summary"]["instrument_count"] == 24
assert q_harvest["regime_summary"]["total_contingent_locks"] >= 20
assert q_harvest["regime_summary"]["instruments_with_data_count"] == 23
assert q_harvest["regime_summary"]["instruments_without_data"] == ["ANTHR-PVT"]
assert q_harvest["isolation_receipt"]["all_unchanged"] is True
assert q_harvest["ipld_dag_json_cidv1"]["/"].startswith("baguqeera")
nvda_inst = next(x for x in q_harvest["instruments"] if x["symbol"] == "NVDA")
assert nvda_inst["quant_encodings"]["close_spoken_ing"] == "wuhn huhndrad therdee sevan"
assert nvda_inst["quant_encodings"]["scaled_cap_spoken_ing"] == "three point three faiv trilyan"
assert any(l["scope"] == "SCOPE1_INTRA_INSTRUMENT_SELF_LOCK" for l in nvda_inst["contingent_locks"])
q_rollover = build_financial_quant_harvest(harvest_mode="utc-rollover")
anthr_inst = next(x for x in q_harvest["instruments"] if x["symbol"] == "ANTHR-PVT")
assert anthr_inst["data_available"] is False
assert NO_DATA_AVAILABLE in anthr_inst["status"]
assert anthr_inst["metrics"]["close_usd"] is None
assert anthr_inst["quant_encodings"]["close_spoken_ing"] == NO_DATA_AVAILABLE
nvda_inst = next(x for x in q_harvest["instruments"] if x["symbol"] == "NVDA")
assert nvda_inst["data_available"] is True
assert nvda_inst["metrics"]["close_usd"] == 150.49
assert nvda_inst["metrics"]["market_cap_str"] == NO_DATA_AVAILABLE
sol_inst = next(x for x in q_harvest["instruments"] if x["symbol"] == "SOL-USD")
assert sol_inst["data_available"] is True
assert sol_inst["metrics"]["close_usd"] == 71.71
assert sol_inst["metrics"]["market_cap_str"] == "$43B"
q_rollover = build_financial_quant_harvest(harvest_mode="utc-rollover", live_fetch=False)
assert q_rollover["harvest_mode"] == "utc-rollover"
assert q_rollover["isolation_receipt"]["all_unchanged"] is True
@@ -228,20 +257,56 @@ def test_ipld_quant_and_mcp_server() -> None:
from hyperstitionstud_io.quant.timeseries import build_quant_timeseries_bundle
ts_full = build_quant_timeseries_bundle(write_files=False)
assert ts_full["synthetic_data_eliminated"] is True
assert ts_full["periodicity_gate"]["enforced"] is True
assert ts_full["periodicity_gate"]["non_periodic_records_ingested"] == 0
assert ts_full["periodicity_gate"]["dated_news_dossiers_ingested"] >= 20
assert len(ts_full["dates_utc"]) == 30
assert all(re.match(r"^\d{4}-\d{2}-\d{2}$", d) for d in ts_full["dates_utc"])
assert len(ts_full["instruments"]) == 24
anthr_ts = next(x for x in ts_full["instruments"] if x["symbol"] == "ANTHR-PVT")
assert anthr_ts["data_available"] is False
assert anthr_ts["available_trading_days"] == 0
assert all(b["data_available"] is False and b["status"] == NO_DATA_AVAILABLE and b["close_usd"] is None for b in anthr_ts["bars"])
assert all(b["contingent_points"] is None for b in anthr_ts["bars"] if not b["co_present_in_news_wire"])
assert anthr_ts["timeseries_moments"]["ts_duty_cycle_pct"] is None
assert anthr_ts["timeseries_moments"]["ts_weighted_resonance"] is None
assert anthr_ts["timeseries_moments"]["ts_excess_over_replacement"] is None
assert anthr_ts["timeseries_moments"]["ts_optimal_lag_days"] is None
assert anthr_ts["timeseries_moments"]["ts_sparkline_30d"] is None
assert anthr_ts["timeseries_moments"]["ts_quantile_profile"]["p20_floor"] is None
assert all(v is None for v in anthr_ts["timeseries_moments"]["ts_lag_correlation_curve"].values())
assert all(v is None for v in anthr_ts["timeseries_moments"]["ts_regime_splits"].values())
assert anthr_ts["pokedex_profile"]["level"] is None
assert anthr_ts["pokedex_profile"]["nature"] is None
pltr_ts = next(x for x in ts_full["instruments"] if x["symbol"] == "PLTR")
assert pltr_ts["data_available"] is True
assert any("CLOSE_SELF_LOCK (159==palanter)" in (b["scope1_locks"] or []) for b in pltr_ts["bars"])
nvda_ts = next(x for x in ts_full["instruments"] if x["symbol"] == "NVDA")
assert nvda_ts["data_available"] is True
assert nvda_ts["available_trading_days"] == 19
assert sum(1 for b in nvda_ts["bars"] if not b["data_available"] and b["status"] == NO_DATA_AVAILABLE) == 11
assert nvda_ts["tradingview_symbol"] == "NASDAQ:NVDA"
assert "tradingview.com/chart/?symbol=NASDAQ%3ANVDA" in nvda_ts["tradingview_url"]
assert "doc_references" in nvda_ts
assert "#page=" in nvda_ts["doc_references"]["encyclopedia_deep_link"]
assert "search=" in nvda_ts["doc_references"]["encyclopedia_deep_link"]
assert "?select=aq:137" in nvda_ts["doc_references"]["knowledge_graph_deep_link"]
assert "#:~:text=" in nvda_ts["doc_references"]["exemplar_dossier_deep_link"]
assert "struct_isometric_armor" in nvda_ts["structural_vector"]
assert "ts_duty_cycle_pct" in nvda_ts["timeseries_moments"]
assert "fund_manager" in nvda_ts["lens_projections"]
assert "pokedex_scanner" in nvda_ts["lens_projections"]
sample_wire_day = next(d for d in ts_full["daily_wire_series"] if d["sample_equations"])
sample_eq = sample_wire_day["sample_equations"][0]
assert "#:~:text=" in sample_eq["dossier_deep_link"]
assert "?highlight=" in sample_eq["api_highlight_link"]
assert any("?select=aq:" in gl for gl in sample_eq["graph_hub_links"])
# Verify 100% lens-removal invariance when pokedex_scanner, tierzoo_ecology, and fantasy_sabermetrics are disabled
ts_stripped = build_quant_timeseries_bundle(enabled_lenses=("neutral_math", "fund_manager"), write_files=False)
assert ts_stripped["enabled_lenses"] == ["neutral_math", "fund_manager"]
@@ -272,9 +337,204 @@ def test_ipld_quant_and_mcp_server() -> None:
d_code, d_ctype, d_body = dispatch_rest_v1("GET", "/api/v1/dossiers/65?format=raw")
assert d_code == 200 and "text/markdown" in d_ctype and "292" in d_body
hl_code, _, hl_body = dispatch_rest_v1("GET", "/api/v1/dossiers/65?highlight=292")
assert hl_code == 200 and hl_body["data"]["match_count"] >= 1 and len(hl_body["data"]["matched_passages"]) >= 1
qts_code, _, qts_body = dispatch_rest_v1("GET", "/api/v1/quant/timeseries?symbol=NVDA")
assert qts_code == 200 and qts_body["ok"] is True and len(qts_body["data"]["instruments"]) == 1
# Verify every single link in quant-tutorials.js, doc_references, and OPERATORS-MANUAL-QUANT-TIMESERIES-WORKBENCH.md resolves cleanly
cfg = load_workspace_config()
tut_js_path = cfg.core_dir / "site" / "quant" / "quant-tutorials.js"
tut_js_txt = tut_js_path.read_text(encoding="utf-8")
assert "let speechEnabled = true;" in tut_js_txt, "Tutorial voice narration must be enabled by default"
assert "playWebAudioTelemetryChime" in tut_js_txt, "WebAudio fallback chime must be present when OS TTS voices are absent"
all_quant_links: set[str] = set(re.findall(r'href:\s*"([^"]+)"', tut_js_txt))
for inst in ts_full["instruments"]:
for v in (inst.get("doc_references") or {}).values():
if isinstance(v, str) and v.startswith("/"):
all_quant_links.add(v)
for b_item in ts_full["builds"]:
for v in (b_item.get("doc_references") or {}).values():
if isinstance(v, str) and v.startswith("/"):
all_quant_links.add(v)
route_prefix_map = {
"/encyclopedia/": cfg.zoology_dir / "encyclopedia",
"/zoology/": cfg.zoology_dir,
"/archive/": cfg.archive_dir / "ingglish-aq-archive",
"/graph/": cfg.knowledge_graph_dir,
"/learn/": cfg.core_dir / "site" / "learn",
"/quant/": cfg.core_dir / "site" / "quant",
"/donate/": cfg.core_dir / "site" / "donate",
"/schemas/": cfg.core_dir / "schemas",
}
for link in sorted(all_quant_links):
if link.startswith("https://"):
continue
no_frag = link.split("#")[0]
base_p = no_frag.split("?")[0]
if base_p.startswith("/api/v1"):
l_code, _, _ = dispatch_rest_v1("GET", no_frag)
assert l_code == 200, f"Broken tutorial/doc_references REST API link: {link} (status {l_code})"
else:
matched_fs = None
for pref, fs_dir in route_prefix_map.items():
if base_p.startswith(pref):
matched_fs = fs_dir / base_p[len(pref):]
break
assert matched_fs is not None and matched_fs.is_file(), f"Broken tutorial/doc_references static link: {link} -> {matched_fs}"
err_code, _, err_body = dispatch_rest_v1("GET", "/api/v1/ciphers/evaluate")
assert err_code == 422 and err_body["ok"] is False
# 5. SQLite + FTS5 Catalog, Automatic REST/MCP Telemetry Population, Inactive Plan Isolation & Quiescent Logrotate Truncation
import os
import sqlite3
import tempfile
from hyperstitionstud_io.db.sqlite_meta import (
DEFAULT_MAX_TELEMETRY_BYTES,
build_catalog_sqlite_db,
get_api_telemetry_summary,
get_default_telemetry_db_path,
parse_size_spec_bytes,
query_coordinate_join,
query_fts_catalog,
query_registry_manifests,
query_timeseries_bars,
run_logrotate_directive,
truncate_telemetry_db_quiescent,
)
assert DEFAULT_MAX_TELEMETRY_BYTES == 100 * 1024 * 1024
assert parse_size_spec_bytes("100M") == 100 * 1024 * 1024
assert parse_size_spec_bytes("100MB") == 100 * 1024 * 1024
prev_env_chk = os.environ.pop("HYPERSTITION_TELEMETRY_DB_PATH", None)
try:
def_tel_p = get_default_telemetry_db_path()
assert str(def_tel_p) == "/var/lib/hyperstitionstud.io/api-telemetry.db" or ".cache/hyperstitionstud.io" in str(def_tel_p)
finally:
if prev_env_chk is not None:
os.environ["HYPERSTITION_TELEMETRY_DB_PATH"] = prev_env_chk
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_path = Path(tmp_dir)
cat_db = tmp_path / "test-catalog.db"
tel_db = tmp_path / "test-telemetry.db"
cat_res = build_catalog_sqlite_db(cat_db)
assert cat_res["isolation_receipt"]["all_unchanged"] is True
assert cat_res["counts"]["registry_manifests"] >= 7
assert cat_res["counts"]["glossary_entries"] >= 282
assert cat_res["counts"]["kg_nodes"] == 388
assert cat_res["counts"]["kg_edges"] == 1282
assert cat_res["counts"]["dossiers"] >= 71
assert cat_res["counts"]["quant_timeseries_bars"] == 720
manifests = query_registry_manifests(cat_db)
assert any(m["registry_slug"] == "encyclopedia-graph" and m["dag_json_cidv1"].startswith("baguqeera") for m in manifests)
fts_res = query_fts_catalog("envideea", db_path=cat_db)
assert fts_res["match_count"] >= 1
coord_163 = query_coordinate_join(163, db_path=cat_db)
assert coord_163["coordinate_aq"] == 163
assert len(coord_163["kg_nodes"]) >= 1
assert len(coord_163["quant_timeseries_bars"]) >= 1
nvda_bars = query_timeseries_bars(symbol="NVDA", min_points=None, db_path=cat_db)
assert len(nvda_bars) == 30 and sum(1 for b in nvda_bars if b["data_available"] == 1) == 19
assert any(b["contingent_points"] is None for b in nvda_bars if b["data_available"] == 0)
# Verify MCP and REST API calls automatically populate the SQLite REST API metadata database
prev_tel_env = os.environ.get("HYPERSTITION_TELEMETRY_DB_PATH")
os.environ["HYPERSTITION_TELEMETRY_DB_PATH"] = str(tel_db)
try:
s1, _, _ = dispatch_rest_v1("GET", "/api/v1/status")
s2, _, _ = dispatch_rest_v1("GET", "/api/v1/quant/instruments/NVDA")
m1 = dispatch_jsonrpc({"jsonrpc": "2.0", "id": 99, "method": "tools/list"})
assert s1 == 200 and s2 == 200 and m1 is not None
# Verify inactive plan routes (/api/v1/meta/*, hs_query_sqlite_catalog) remain unexposed (404)
inact_meta_code, _, _ = dispatch_rest_v1("GET", "/api/v1/meta/manifests")
inact_tool_code, _, _ = dispatch_rest_v1("GET", "/api/v1/tools/hs_query_sqlite_catalog")
assert inact_meta_code == 404
assert inact_tool_code == 404
summary_before = get_api_telemetry_summary(tel_db)
assert summary_before["total_requests"] == 5
assert summary_before["ringbuffer_count"] == 5
protocols_seen = {ep["protocol"] for ep in summary_before["endpoints"]}
assert protocols_seen == {"rest_v1", "mcp_jsonrpc"}
patterns_seen = {ep["endpoint_pattern"] for ep in summary_before["endpoints"]}
assert "/api/v1/status" in patterns_seen
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"])
# Verify logrotate.d file configuration (default 100M = 100MB, compress enabled, rotate >= 12) & no-op when below limit
import gzip
lr_noop = run_logrotate_directive(telemetry_db_path=tel_db)
assert lr_noop["configured_size_directive"].upper() == "100M"
assert lr_noop["configured_default_bytes"] == 100 * 1024 * 1024
assert lr_noop["compress_enabled"] is True
assert lr_noop["rotate_count"] >= 12
assert lr_noop["truncated"] is False
assert get_api_telemetry_summary(tel_db)["total_requests"] == 5
# Verify logrotate.d quiescent compression + truncation when DB size >= configured limit
lr_trunc = run_logrotate_directive(telemetry_db_path=tel_db, max_bytes_override=1024)
assert lr_trunc["truncated"] is True
assert lr_trunc["quiescent"] is True
assert lr_trunc["integrity_check"] == "ok"
assert lr_trunc["compressed_archive_path"] == f"{tel_db}.1.gz"
assert lr_trunc["compressed_archive_bytes"] > 0
assert Path(lr_trunc["compressed_archive_path"]).is_file()
# Verify the compressed .1.gz archive preserved all 5 pre-truncation requests & passes SQLite integrity_check
restored_db = tmp_path / "restored-from-gz.db"
with gzip.open(lr_trunc["compressed_archive_path"], "rb") as f_gz:
restored_db.write_bytes(f_gz.read())
with sqlite3.connect(str(restored_db)) as r_conn:
assert r_conn.execute("PRAGMA integrity_check;").fetchone()[0] == "ok"
assert get_api_telemetry_summary(restored_db)["total_requests"] == 5
summary_after = get_api_telemetry_summary(tel_db)
assert summary_after["total_requests"] == 0
assert summary_after["ringbuffer_count"] == 0
# Verify SQLite integrity_check == 'ok' and continued automatic population after quiescent truncation
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")
assert s_post == 200
assert get_api_telemetry_summary(tel_db)["total_requests"] == 1
# Also verify second rotation shifts .1.gz -> .2.gz and writes new .1.gz
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
assert direct_trunc["integrity_check"] == "ok"
assert Path(f"{tel_db}.1.gz").is_file()
assert Path(f"{tel_db}.2.gz").is_file()
# 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")
assert ro_code == 200 and ro_body["ok"] is True
ro_mcp = dispatch_jsonrpc({"jsonrpc": "2.0", "id": 100, "method": "ping"})
assert ro_mcp is not None and "result" in ro_mcp
finally:
if prev_tel_env is None:
os.environ.pop("HYPERSTITION_TELEMETRY_DB_PATH", None)
else:
os.environ["HYPERSTITION_TELEMETRY_DB_PATH"] = prev_tel_env
if __name__ == "__main__":
test_offline_urn_namespaces_and_no_external_https_fonts()
+1 -1
View File
@@ -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.0.18"
schema_version = "2.0.23"
namespace_urn = "urn:io:hyperstitionstud"
[paths]