Compare commits

...
3 Commits
27 changed files with 31122 additions and 38 deletions

No files matched your search

+3 -3
View File
@@ -81,9 +81,9 @@ hyperstitionstud.io {
}
redir /ci /ci/ permanent
# 6. Stateless Read-Only Model Context Protocol (MCP) Streamable HTTP Endpoint -> /mcp & /mcp/*
@mcp_route path /mcp /mcp/*
handle @mcp_route {
# 6. Stateless Read-Only MCP (/mcp) & REST API v1 (/api/v1/*) HTTP Server -> 127.0.0.1:8095
@mcp_and_rest_api path /mcp /mcp/* /api/v1 /api/v1/*
handle @mcp_and_rest_api {
reverse_proxy 127.0.0.1:8095
}
+17 -4
View File
@@ -20,9 +20,10 @@ trap 'on_error ${LINENO}' ERR
run_checked() {
local label="$1"
shift
local out
if ! out="$("$@" 2>&1)"; then
local rc=$?
local out=""
local rc=0
out="$("$@" 2>&1)" || rc=$?
if [[ "${rc}" -ne 0 ]]; then
echo "[ERROR] ${label} failed (exit code ${rc}): $*" >&2
if [[ -n "${out}" ]]; then
echo "${out}" >&2
@@ -101,8 +102,15 @@ if [[ "${DO_PULL}" -eq 1 ]]; then
remote_name="downstream"
fi
echo "[1/5] Updating ${REPOS_ROOT}/${repo} (${remote_name}/${branch})..."
prev_head="$(git -C "${REPOS_ROOT}/${repo}" rev-parse HEAD)"
run_checked "git fetch ${repo}" git -C "${REPOS_ROOT}/${repo}" fetch --force "${remote_name}" "${branch}" --tags
run_checked "git merge ${repo}" git -C "${REPOS_ROOT}/${repo}" merge --ff-only "${remote_name}/${branch}"
new_head="$(git -C "${REPOS_ROOT}/${repo}" rev-parse HEAD)"
if [[ "${repo}" == "hyperstitionstudio-core" && "${prev_head}" != "${new_head}" && -z "${HYPERSTITION_SYNC_REEXEC:-}" ]]; then
echo "[1/5] hyperstitionstudio-core updated (${prev_head:0:7} -> ${new_head:0:7}); re-executing updated sync-vps-repos.sh..."
export HYPERSTITION_SYNC_REEXEC=1
exec "${REPOS_ROOT}/hyperstitionstudio-core/deploy/sync-vps-repos.sh" "$@"
fi
fi
done
fi
@@ -119,7 +127,11 @@ if [[ -d "${REPOS_ROOT}/haiperdohp-jemaytreeah" ]]; then
fi
fi
echo "[2/5] Running hs-doctor, version_sync --check, and 6-Gate Knowledge Graph Verification..."
echo "[2/5] Synchronizing local workspace.toml version and running hs-doctor, version_sync --check, and 6-Gate Knowledge Graph Verification..."
if [[ -f "${REPOS_ROOT}/workspace.toml" ]] && [[ -f "${REPOS_ROOT}/hyperstitionstudio-core/workspace.example.toml" ]]; then
# Sync schema_version in untracked parent workspace.toml with hyperstitionstud_io.__version__
run_checked "version_sync (sync untracked workspace.toml)" "${PYTHON_BIN}" -m hyperstitionstud_io.version_sync
fi
run_checked "version_sync --check" "${PYTHON_BIN}" -m hyperstitionstud_io.version_sync --check
run_checked "hs-doctor" "${PYTHON_BIN}" -m hyperstitionstud_io.ci.doctor
run_checked "build_encyclopedia_knowledge_graph.py --verify-only" "${PYTHON_BIN}" "${REPOS_ROOT}/encyclopedia-knowledge-graph/scripts/build_encyclopedia_knowledge_graph.py" --verify-only
@@ -148,6 +160,7 @@ fi
# Create relative route symlinks inside LIVE_REPOS so both Caddy and standalone HTTP servers resolve all active routes
${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"
# 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"
+19 -2
View File
@@ -42,15 +42,21 @@ if [[ -z "${TARGET_BASE_URL}" ]]; then
sleep 0.6
TARGET_BASE_URL="http://127.0.0.1:${PORT}"
MCP_URL="http://127.0.0.1:${MCP_PORT}/mcp"
API_V1_URL="http://127.0.0.1:${MCP_PORT}/api/v1"
else
MCP_URL="${TARGET_BASE_URL%/}/mcp"
API_V1_URL="${TARGET_BASE_URL%/}/api/v1"
fi
echo "[3/4] Verifying all 32 active portal, /learn/, graph, encyclopedia, haiperdohp-jemaytreeah (.gitignore artifacts), CI & schema routes against ${TARGET_BASE_URL}..."
echo "[3/4] Verifying all active portal, /learn/, /quant/, graph, encyclopedia, haiperdohp-jemaytreeah (.gitignore artifacts), CI & schema routes against ${TARGET_BASE_URL}..."
ROUTES=(
"/"
"/learn/index.html"
"/learn/learn-app.js"
"/quant/index.html"
"/quant/quant-app.js"
"/quant/quant-timeseries-data.js"
"/quant/quant-timeseries.json"
"/graph/index.html"
"/graph/graph-data.js"
"/graph/encyclopedia-graph.json"
@@ -82,6 +88,7 @@ ROUTES=(
"/schemas/v1/encyclopedia-graph.schema.json"
"/schemas/v1/learn-progress-state.schema.json"
"/schemas/v1/financial-aq-harvest.schema.json"
"/schemas/v1/quant-timeseries.schema.json"
)
PASS_COUNT=0
@@ -112,4 +119,14 @@ if ! grep -q 'exact_gen1_singularity.*true' <<<"${mcp_post_out}"; then
fi
echo " [200 OK] POST ${MCP_URL} (JSON-RPC 2.0 tools/call hs_evaluate_aq_and_ingglish verified)"
echo "[OK] All ${PASS_COUNT}/${#ROUTES[@]} static routes + 2 MCP HTTP endpoints verified (HTTP 200 OK)."
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
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
exit 1
fi
echo " [200 OK] GET ${API_V1_URL}${api_sub}"
done
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.15",
"version": "2.0.18",
"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.15",
"version": "2.0.18",
"type": "module",
"main": "index.js",
"license": "MIT"
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "hyperstitionstudio-core"
version = "2.0.15"
version = "2.0.18"
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"
+20
View File
@@ -0,0 +1,20 @@
{
"$schema": "urn:ietf:params:scim:schemas:core:2.0",
"$id": "urn:io:hyperstitionstud:schema:v1:quant-timeseries",
"title": "Lens-Neutral Periodic Quantitative Financial & Memetic Gematria Time-Series Schema (v2.0)",
"type": "object",
"required": [
"$id",
"version",
"namespace_urn",
"periodicity_gate",
"enabled_lenses",
"default_lens",
"dates_utc",
"instruments",
"builds",
"daily_wire_series",
"anchor_revision_series",
"isolation_receipt"
]
}
+2 -2
View File
@@ -144,8 +144,8 @@ def main() -> int:
})
manifest = {
"version": "2.0.15",
"namespace_urn": "urn:io:hyperstitionstud:gallery:2.0.15",
"version": "2.0.18",
"namespace_urn": "urn:io:hyperstitionstud:gallery:2.0.18",
"total_items": len(items),
"items": items,
}
+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.15)</div>
<div>hyperstitionstud.io/gallery &bull; Powered by hyperstitionstudio-core (urn:io:hyperstitionstud:gallery:2.0.18)</div>
<div class="hs-lemur-credit">Made with <span class="hs-heart" role="img" aria-label="love">&#x2665;</span> by Lemurs.</div>
</footer>
</div>
+6 -4
View File
@@ -131,13 +131,14 @@
<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.15)</p>
<p class="subtitle">100% Offline-Portable &amp; HTTP/3 Edge-Ready Research Corpus &bull; Namespace Authority: urn:io:hyperstitionstud (v2.0.18)</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>
<a class="btn" data-route="quant-app" href="/quant/index.html" style="padding:0.35rem 0.75rem;font-size:0.74rem;border-color:var(--gold);color:var(--gold);">Quant Time-Series (/quant/)</a>
<span class="badge">388 Graph Nodes</span>
<span class="badge">1,282 Typed Edges</span>
<span class="badge">22 PDF Volumes</span>
<span class="badge">24 Quant Tickers</span>
</div>
</header>
@@ -246,14 +247,14 @@
</div>
<div class="actions">
<a class="btn primary" data-route="dep-html" href="/graph/docs/cross-repo-dependency-and-audit-flow-diagram.html">Interactive Flow Diagram</a>
<a class="btn" data-route="dep-pdf" href="/graph/docs/cross-repo-dependency-and-audit-flow-diagram.pdf">Flow Diagram (PDF)</a>
<a class="btn" data-route="quant-app" href="/quant/index.html">Quant Time-Series (/quant/)</a>
<a class="btn" data-route="vps-guide" href="/graph/docs/VPS-AND-GIT-OPERATOR-DEPLOYMENT-GUIDE.pdf">VPS &amp; Git Guide (PDF)</a>
</div>
</section>
</main>
<footer>
<div>hyperstitionstud.io &bull; Powered by hyperstitionstudio-core (hyperstitionstud_io.* / urn:io:hyperstitionstud v2.0.15) &bull; Zero External Network Dependencies</div>
<div>hyperstitionstud.io &bull; Powered by hyperstitionstudio-core (hyperstitionstud_io.* / urn:io:hyperstitionstud v2.0.18) &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>
@@ -264,6 +265,7 @@
if (window.location.protocol !== "file:") return;
const map = {
"learn-track": "./learn/index.html",
"quant-app": "./quant/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",
+1 -1
View File
@@ -413,7 +413,7 @@
</main>
<footer>
<div>hyperstitionstud.io/learn &bull; Powered by hyperstitionstudio-core (urn:io:hyperstitionstud:schema:v1:learn-progress-state v2.0.15)</div>
<div>hyperstitionstud.io/learn &bull; Powered by hyperstitionstudio-core (urn:io:hyperstitionstud:schema:v1:learn-progress-state v2.0.18)</div>
<div class="hs-lemur-credit">Made with <span class="hs-heart" role="img" aria-label="love">&#x2665;</span> by Lemurs.</div>
</footer>
</div>
+1 -1
View File
@@ -265,7 +265,7 @@
const base = {
$schema: "../schemas/v1/learn-progress-state.schema.json",
$id: SCHEMA_ID,
version: "2.0.15",
version: "2.0.18",
updated_at_utc: new Date().toISOString(),
preferred_register: "fund_manager",
completed_modules: [],
+315
View File
@@ -0,0 +1,315 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Quantitative Finance &amp; Memetic Gematria Time-Series Workbench — hyperstitionstud.io/quant</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.25rem;
line-height: 1.45;
}
.container { max-width: 1380px; margin: 0 auto; display: flex; flex-direction: column; gap: 1rem; }
header {
background: var(--bg-panel);
border: 1px solid var(--border);
border-left: 4px solid var(--gold);
border-radius: 10px;
padding: 1.1rem 1.4rem;
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 0.9rem;
}
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; }
.btn, select {
text-decoration: none;
background: var(--bg-card);
color: var(--text-main);
border: 1px solid var(--border);
border-radius: 5px;
padding: 0.42rem 0.72rem;
font-size: 0.73rem;
font-weight: 600;
font-family: inherit;
cursor: pointer;
transition: all 0.15s ease;
}
.btn:hover, select:hover { border-color: var(--cyan); color: var(--cyan); }
.btn.primary { background: var(--cyan); color: #020617; border-color: var(--cyan); }
.btn.tv-btn { background: rgba(245, 198, 48, 0.15); color: var(--gold); border-color: var(--gold); }
.btn.tv-btn:hover { background: var(--gold); color: #020617; }
.toolbar {
background: var(--bg-panel);
border: 1px solid var(--border);
border-radius: 10px;
padding: 0.85rem 1.1rem;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
gap: 0.75rem;
}
.control-group { display: flex; align-items: center; gap: 0.45rem; flex-wrap: wrap; }
.control-label { font-size: 0.68rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.05em; }
.pill-row { display: flex; gap: 0.3rem; flex-wrap: wrap; }
.pill {
background: var(--bg-deep);
color: var(--text-muted);
border: 1px solid var(--border);
border-radius: 4px;
padding: 0.25rem 0.55rem;
font-size: 0.69rem;
cursor: pointer;
font-family: inherit;
}
.pill.active { background: var(--cyan); color: #020617; border-color: var(--cyan); font-weight: 700; }
.panel {
background: var(--bg-panel);
border: 1px solid var(--border);
border-radius: 10px;
padding: 1rem 1.15rem;
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.panel-header {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 0.5rem;
border-bottom: 1px solid var(--border);
padding-bottom: 0.55rem;
}
.panel-title { font-size: 0.86rem; font-weight: 700; color: var(--cyan); }
.panel-meta { font-size: 0.7rem; color: var(--text-muted); }
canvas#tsCanvas {
width: 100%;
height: 410px;
background: var(--bg-deep);
border: 1px solid var(--border);
border-radius: 8px;
cursor: crosshair;
display: block;
}
.split-grid {
display: grid;
grid-template-columns: 1.25fr 1fr;
gap: 1rem;
}
@media (max-width: 1024px) {
.split-grid { grid-template-columns: 1fr; }
}
.heatmap-wrap {
overflow-x: auto;
background: var(--bg-deep);
border: 1px solid var(--border);
border-radius: 8px;
padding: 0.6rem;
}
table.heatmap {
width: 100%;
border-collapse: collapse;
font-size: 0.65rem;
}
table.heatmap th, table.heatmap td {
padding: 0.2rem 0.18rem;
text-align: center;
border: 1px solid #162032;
}
table.heatmap th.sym-col {
text-align: left;
padding-left: 0.4rem;
padding-right: 0.5rem;
white-space: nowrap;
position: sticky;
left: 0;
background: var(--bg-deep);
z-index: 2;
}
.hm-cell {
width: 18px;
height: 18px;
border-radius: 3px;
cursor: pointer;
display: inline-block;
}
.hm-none { background: #0f172a; }
.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; }
.hm-selected { outline: 2px solid #ffffff; }
.inspector-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(145px, 1fr));
gap: 0.5rem;
}
.stat-box {
background: var(--bg-deep);
border: 1px solid var(--border);
border-radius: 6px;
padding: 0.5rem 0.65rem;
}
.stat-label { font-size: 0.63rem; color: var(--text-muted); }
.stat-val { font-size: 0.84rem; font-weight: 700; color: var(--text-main); margin-top: 0.15rem; }
.eq-tape {
background: var(--bg-deep);
border: 1px solid var(--border);
border-radius: 6px;
padding: 0.65rem;
max-height: 220px;
overflow-y: auto;
font-size: 0.71rem;
display: flex;
flex-direction: column;
gap: 0.45rem;
}
.eq-item {
border-left: 3px solid var(--violet);
padding-left: 0.55rem;
}
.lag-bars {
display: grid;
grid-template-columns: repeat(11, 1fr);
gap: 0.4rem;
align-items: end;
height: 120px;
background: var(--bg-deep);
border: 1px solid var(--border);
border-radius: 8px;
padding: 0.75rem;
}
.lag-col { display: flex; flex-direction: column; align-items: center; gap: 0.25rem; height: 100%; justify-content: flex-end; }
.lag-bar { width: 100%; max-width: 34px; border-radius: 3px 3px 0 0; background: var(--cyan); min-height: 4px; }
.lag-lbl { font-size: 0.63rem; color: var(--text-muted); }
footer {
margin-top: 1rem;
text-align: center;
font-size: 0.72rem;
color: var(--text-muted);
border-top: 1px solid var(--border);
padding-top: 1rem;
}
</style>
<script src="quant-timeseries-data.js"></script>
</head>
<body>
<div class="container">
<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>
</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>
</nav>
</header>
<section class="toolbar" aria-label="Workbench Controls">
<div class="control-group">
<span class="control-label">Guild Filter:</span>
<div class="pill-row" id="guildFilterPills"></div>
</div>
<div class="control-group">
<label class="control-label" for="tickerSelect">Ticker:</label>
<select id="tickerSelect"></select>
<a class="btn tv-btn" id="openTradingViewBtn" href="https://www.tradingview.com/chart/?symbol=NASDAQ%3ANVDA" target="_blank" rel="noopener noreferrer" title="Shortcut: Press T to open TradingView Superchart in a new browser window">Open TradingView Chart &#x2197;</a>
</div>
<div class="control-group">
<label class="control-label" for="lensSelect">Projection Lens:</label>
<select id="lensSelect"></select>
</div>
<div class="control-group">
<span class="control-label">Metric Mode:</span>
<div class="pill-row" id="metricModePills"></div>
</div>
<div class="control-group">
<button class="btn" id="prevDateBtn" title="Shortcut: Left Arrow">&larr; Prev Day</button>
<span id="activeDateBadge" style="font-size:0.76rem;font-weight:700;color:var(--gold);padding:0 0.35rem;">2026-11-30</span>
<button class="btn" id="nextDateBtn" title="Shortcut: Right Arrow">Next Day &rarr;</button>
</div>
</section>
<!-- PANEL 1: 3-Pane Synchronized Time-Series Canvas -->
<section class="panel">
<div class="panel-header">
<span class="panel-title" id="panel1Title">PANEL 1: Synchronized 3-Pane Time-Series Trajectory (Price/BPS &times; Spoken/Digit AQ &times; 00:00 GMT Wire Velocity &times; M1-M3 Regimes)</span>
<span class="panel-meta" id="panel1Meta">Click or drag across canvas to scrub UTC dates &bull; Gold = Scope 1 Self-Lock &bull; Cyan = Scope 2 Ring Migration &bull; Emerald = News Wire Co-Presence</span>
</div>
<canvas id="tsCanvas" width="1320" height="410"></canvas>
</section>
<div class="split-grid">
<!-- PANEL 2: 24 Tickers x 30 UTC Days Contingent Lock Heatmap -->
<section class="panel">
<div class="panel-header">
<span class="panel-title">PANEL 2: Spatiotemporal Contingent Lock Heatmap (24 S1-S6 Tickers &times; 30 UTC Days)</span>
<span class="panel-meta">Click any (Ticker, Date) cell to inspect &bull; &#x2197; launches TradingView</span>
</div>
<div class="heatmap-wrap">
<table class="heatmap" id="heatmapTable"></table>
</div>
</section>
<!-- PANEL 3: Cross-Sectional Date Inspector, Lens Projection & Memetic Equation Tape -->
<section class="panel">
<div class="panel-header">
<span class="panel-title" id="panel3Title">PANEL 3: Cross-Sectional Date Inspector &amp; Lens Projection</span>
<a class="btn tv-btn" id="panel3TvBtn" href="https://www.tradingview.com/chart/?symbol=NASDAQ%3ANVDA" target="_blank" rel="noopener noreferrer">TradingView &#x2197;</a>
</div>
<div class="inspector-grid" id="dateMetricsGrid"></div>
<div class="stat-box" id="lensProjectionCard"></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>
</section>
</div>
<!-- PANEL 4: Lead-Lag Cross-Correlation Explorer & Portable CSV/JSON Export -->
<section class="panel">
<div class="panel-header">
<span class="panel-title">PANEL 4: Lead-Lag Cross-Correlation Explorer r(&tau;) (&tau; &in; [-5 .. +5] Days) &amp; Time-Series Export</span>
<div class="control-group">
<button class="btn" id="exportCsvBtn">Export Filtered Series (.CSV)</button>
<button class="btn" id="exportJsonBtn">Export Lens-Neutral Slice (.JSON)</button>
</div>
</div>
<div class="lag-bars" id="lagBarsContainer"></div>
<p class="panel-meta" id="periodicityAuditFooter"></p>
</section>
<footer>
hyperstitionstud.io/quant v2.0.18 &bull; Made with <span class="hs-heart" style="color:#ff4d4d;">&#x2665;</span> by Lemurs.
</footer>
</div>
<script src="quant-app.js"></script>
</body>
</html>
+482
View File
@@ -0,0 +1,482 @@
// /workspace/hyperstitionstudio-core/site/quant/quant-app.js
// Interactive Quantitative Finance & Memetic Gematria Time-Series Workbench (v2.0.18)
(function () {
"use strict";
const DATA = (window.HyperstitionStudio && window.HyperstitionStudio.QuantTimeSeries) || null;
if (!DATA) {
console.error("QuantTimeSeries bundle missing.");
return;
}
// Resolve file:// vs https:// navigation links automatically
if (window.location.protocol === "file:") {
const navHome = document.getElementById("navHome");
const navGraph = document.getElementById("navGraph");
const navLearn = document.getElementById("navLearn");
const navCalc = document.getElementById("navCalc");
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";
}
const state = {
guildFilter: "ALL",
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,
};
const guilds = ["ALL", "S1", "S2", "S3", "S4", "S5", "S6"];
const modes = [
{ id: "spoken_aq", label: "Spoken AQ (Gen 1)" },
{ id: "close_usd", label: "Close Price (USD)" },
{ id: "change_bps", label: "Move (BPS)" },
{ id: "digit_aq", label: "Digit AQ" },
];
const elGuildPills = document.getElementById("guildFilterPills");
const elTickerSelect = document.getElementById("tickerSelect");
const elLensSelect = document.getElementById("lensSelect");
const elModePills = document.getElementById("metricModePills");
const elDateBadge = document.getElementById("activeDateBadge");
const elTvBtn = document.getElementById("openTradingViewBtn");
const elPanel3TvBtn = document.getElementById("panel3TvBtn");
const canvas = document.getElementById("tsCanvas");
const ctx = canvas.getContext("2d");
function getFilteredInstruments() {
if (state.guildFilter === "ALL") return DATA.instruments;
return DATA.instruments.filter((inst) => inst.guilds.indexOf(state.guildFilter) !== -1);
}
function getSelectedInstrument() {
return (
DATA.instruments.find((inst) => inst.symbol === state.selectedSymbol) ||
DATA.instruments[0]
);
}
function updateTradingViewLinks() {
const inst = getSelectedInstrument();
const url = inst.tradingview_url || ("https://www.tradingview.com/chart/?symbol=" + encodeURIComponent(inst.symbol));
const label = "Open TradingView (" + (inst.tradingview_symbol || inst.symbol) + ") \u2197";
if (elTvBtn) {
elTvBtn.href = url;
elTvBtn.textContent = label;
}
if (elPanel3TvBtn) {
elPanel3TvBtn.href = url;
elPanel3TvBtn.textContent = (inst.tradingview_symbol || inst.symbol) + " on TradingView \u2197";
}
}
function renderControls() {
// Guild Pills
elGuildPills.innerHTML = "";
guilds.forEach((g) => {
const btn = document.createElement("button");
btn.className = "pill" + (state.guildFilter === g ? " active" : "");
btn.textContent = g;
btn.onclick = function () {
state.guildFilter = g;
const list = getFilteredInstruments();
if (list.length && !list.some((x) => x.symbol === state.selectedSymbol)) {
state.selectedSymbol = list[0].symbol;
}
renderAll();
};
elGuildPills.appendChild(btn);
});
// Ticker Select
const filtered = getFilteredInstruments();
elTickerSelect.innerHTML = "";
filtered.forEach((inst) => {
const opt = document.createElement("option");
opt.value = inst.symbol;
opt.textContent = inst.symbol + " — " + inst.entity_eng + " [" + inst.guilds.join(",") + "] (AQ " + inst.entity_ing_aq + ")";
if (inst.symbol === state.selectedSymbol) opt.selected = true;
elTickerSelect.appendChild(opt);
});
elTickerSelect.onchange = function () {
state.selectedSymbol = elTickerSelect.value;
renderAll();
};
// Lens Select (populated dynamically from DATA.enabled_lenses)
elLensSelect.innerHTML = "";
(DATA.enabled_lenses || []).forEach((lid) => {
const meta = (DATA.lens_registry_meta && DATA.lens_registry_meta[lid]) || { short_label: lid, title: lid };
const opt = document.createElement("option");
opt.value = lid;
opt.textContent = meta.short_label + " — " + meta.title;
if (lid === state.selectedLens) opt.selected = true;
elLensSelect.appendChild(opt);
});
elLensSelect.onchange = function () {
state.selectedLens = elLensSelect.value;
renderAll();
};
// Metric Mode Pills
elModePills.innerHTML = "";
modes.forEach((m) => {
const btn = document.createElement("button");
btn.className = "pill" + (state.metricMode === m.id ? " active" : "");
btn.textContent = m.label;
btn.onclick = function () {
state.metricMode = m.id;
renderAll();
};
elModePills.appendChild(btn);
});
elDateBadge.textContent = DATA.dates_utc[state.selectedDateIdx];
updateTradingViewLinks();
}
function drawCanvas() {
const inst = getSelectedInstrument();
const bars = inst.bars;
const N = bars.length;
const W = canvas.width;
const H = canvas.height;
ctx.clearRect(0, 0, W, H);
const padL = 62;
const padR = 28;
const plotW = W - padL - padR;
// 3 Panes: Top (20..195), Middle (215..310), Bottom (330..385)
const topY0 = 22, topY1 = 192;
const midY0 = 216, midY1 = 306;
const botY0 = 328, botY1 = 382;
function xAt(i) {
return padL + (i / Math.max(1, N - 1)) * plotW;
}
// Selected date vertical crosshair
const selX = xAt(state.selectedDateIdx);
ctx.strokeStyle = "rgba(245, 198, 48, 0.45)";
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.moveTo(selX, 10);
ctx.lineTo(selX, H - 18);
ctx.stroke();
// Pane dividers
ctx.strokeStyle = "#1e293b";
ctx.lineWidth = 1;
[topY1, midY1, botY1].forEach((yLine) => {
ctx.beginPath();
ctx.moveTo(padL, yLine);
ctx.lineTo(W - padR, yLine);
ctx.stroke();
});
// Top Pane: Selected Metric Trajectory
const vals = bars.map((b) => {
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);
});
const minV = Math.min.apply(null, vals);
const maxV = Math.max.apply(null, vals);
const spanV = Math.max(1e-3, maxV - minV);
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
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();
}
});
// 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));
const maxW = Math.max(10, Math.max.apply(null, wireTotals));
const barW = Math.max(6, Math.floor(plotW / N) - 5);
wireTotals.forEach((wt, idx) => {
const px = xAt(idx);
const bh = (wt / maxW) * (midY1 - midY0 - 14);
ctx.fillStyle = bars[idx].co_present_in_news_wire ? "#34d399" : "#a78bfa";
ctx.fillRect(px - barW / 2, midY1 - bh, barW, bh);
});
// 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));
vols.forEach((vr, idx) => {
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");
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);
// Date ticks along bottom
for (let i = 0; i < N; i += 4) {
ctx.fillText(DATA.dates_utc[i].slice(5), xAt(i) - 14, H - 4);
}
}
function renderHeatmap() {
const tbl = document.getElementById("heatmapTable");
const filtered = getFilteredInstruments();
let html = "<thead><tr><th class='sym-col'>Ticker (TV)</th>";
DATA.dates_utc.forEach((dt, idx) => {
const selStyle = idx === state.selectedDateIdx ? "color:var(--gold);font-weight:700;" : "color:var(--text-muted);";
html += "<th style='" + selStyle + "'>" + dt.slice(8) + "</th>";
});
html += "</tr></thead><tbody>";
filtered.forEach((inst) => {
const rowSel = inst.symbol === state.selectedSymbol ? "background:rgba(34,211,238,0.12);" : "";
html += "<tr style='" + rowSel + "'><th class='sym-col'>";
html += "<span style='cursor:pointer;color:var(--text-main);' data-sym='" + inst.symbol + "' class='hm-sym-pick'>" + inst.symbol + "</span> ";
html += "<a href='" + inst.tradingview_url + "' target='_blank' rel='noopener noreferrer' style='color:var(--gold);text-decoration:none;' title='Open " + inst.tradingview_symbol + " on TradingView'>\u2197</a>";
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";
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;
html += "<td><span class='" + cls + "' data-sym='" + inst.symbol + "' data-didx='" + dIdx + "' title='" + tip + "'></span></td>";
});
html += "</tr>";
});
html += "</tbody>";
tbl.innerHTML = html;
tbl.querySelectorAll(".hm-cell").forEach((cell) => {
cell.addEventListener("click", function () {
state.selectedSymbol = cell.getAttribute("data-sym");
state.selectedDateIdx = parseInt(cell.getAttribute("data-didx"), 10);
renderAll();
});
});
tbl.querySelectorAll(".hm-sym-pick").forEach((sp) => {
sp.addEventListener("click", function () {
state.selectedSymbol = sp.getAttribute("data-sym");
renderAll();
});
});
}
function renderInspectorAndLens() {
const inst = getSelectedInstrument();
const bar = inst.bars[state.selectedDateIdx];
const dt = bar.date_utc;
const proj = (inst.lens_projections && inst.lens_projections[state.selectedLens]) || null;
document.getElementById("panel3Title").textContent =
"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("");
// Render Active Lens Projection Card (LENS_REGISTRY)
const lensCard = document.getElementById("lensProjectionCard");
if (proj) {
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);
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>";
});
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>" +
rowsHtml;
}
// 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");
if (wireDay && wireDay.dossier_file) {
hdrEl.innerHTML =
"Dated 00:00 GMT Wire Dossier (<a href='" + wireDay.archive_route + "' 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>"
)
.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>";
}
}
function renderLagExplorer() {
const inst = getSelectedInstrument();
const curve = inst.timeseries_moments.ts_lag_correlation_curve || {};
const optLag = inst.timeseries_moments.ts_optimal_lag_days;
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>";
}
container.innerHTML = html;
const pGate = DATA.periodicity_gate || {};
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["/"]);
}
function renderAll() {
renderControls();
drawCanvas();
renderHeatmap();
renderInspectorAndLens();
renderLagExplorer();
}
// Canvas scrub interaction
canvas.addEventListener("click", function (ev) {
const rect = canvas.getBoundingClientRect();
const relX = ((ev.clientX - rect.left) / rect.width) * canvas.width;
const padL = 62, padR = 28;
const ratio = (relX - padL) / (canvas.width - padL - padR);
const idx = Math.round(ratio * (DATA.dates_utc.length - 1));
state.selectedDateIdx = Math.max(0, Math.min(DATA.dates_utc.length - 1, idx));
renderAll();
});
document.getElementById("prevDateBtn").onclick = function () {
state.selectedDateIdx = Math.max(0, state.selectedDateIdx - 1);
renderAll();
};
document.getElementById("nextDateBtn").onclick = function () {
state.selectedDateIdx = Math.min(DATA.dates_utc.length - 1, state.selectedDateIdx + 1);
renderAll();
};
// Keyboard shortcuts: Left/Right arrows step UTC dates; 'T' opens TradingView chart in new window
window.addEventListener("keydown", function (ev) {
if (ev.target && (ev.target.tagName === "INPUT" || ev.target.tagName === "SELECT" || ev.target.tagName === "TEXTAREA")) {
return;
}
if (ev.key === "ArrowLeft") {
state.selectedDateIdx = Math.max(0, state.selectedDateIdx - 1);
renderAll();
} else if (ev.key === "ArrowRight") {
state.selectedDateIdx = Math.min(DATA.dates_utc.length - 1, state.selectedDateIdx + 1);
renderAll();
} else if (ev.key === "t" || ev.key === "T") {
const inst = getSelectedInstrument();
window.open(inst.tradingview_url, "_blank", "noopener,noreferrer");
}
});
// CSV & JSON Exports
document.getElementById("exportCsvBtn").onclick = function () {
const inst = getSelectedInstrument();
const headers = ["date_utc", "symbol", "close_usd", "change_bps", "volume_ratio_20d", "close_spoken_ing_aq", "bps_spoken_ing_aq", "co_present_in_news_wire", "contingent_points"];
const lines = [headers.join(",")];
inst.bars.forEach((b) => {
lines.push([b.date_utc, inst.symbol, b.close_usd, b.change_bps, b.volume_ratio_20d, b.close_spoken_ing_aq, b.bps_spoken_ing_aq, b.co_present_in_news_wire, b.contingent_points].join(","));
});
const blob = new Blob([lines.join("\n") + "\n"], { type: "text/csv;charset=utf-8" });
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = inst.symbol + "-quant-timeseries.csv";
a.click();
};
document.getElementById("exportJsonBtn").onclick = function () {
const inst = getSelectedInstrument();
const blob = new Blob([JSON.stringify(inst, null, 2) + "\n"], { type: "application/json;charset=utf-8" });
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = inst.symbol + "-lens-neutral-slice.json";
a.click();
};
renderAll();
})();
+3
View File
@@ -0,0 +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
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.15)."""
__version__ = "2.0.15"
"""hyperstitionstud_io — Shared Common Library for the hyperstitionstud.io workspace (v2.0.18)."""
__version__ = "2.0.18"
NAMESPACE_URN = "urn:io:hyperstitionstud"
+391
View File
@@ -0,0 +1,391 @@
"""
hyperstitionstud_io.lenses — Declarative Lens-Neutral Mathematical Substrate & Hot-Swappable Projection Registry (`LENS_REGISTRY`).
Projects the 6 canonical structural combine invariants (`struct_*`) and 6 longitudinal time-series
moments (`ts_*`) into interchangeable domain registers without coupling core time-series schemas or
calculators to any specific metaphor.
"""
from __future__ import annotations
from typing import Any
DEFAULT_LENS = "fund_manager"
ENABLED_LENSES: tuple[str, ...] = (
"fund_manager",
"neutral_math",
"corporate_board",
"tierzoo_ecology",
"fantasy_sabermetrics",
"pokedex_scanner",
)
# 12 Canonical Lens-Neutral Mathematical Keys:
# Structural Combine (6):
# 1. struct_isometric_armor (G4 Isometric Chokepoint Ratio, 0-100)
# 2. struct_drift_velocity (G3 Inverse Phonemic Drift & Quantized Steps, 0-100)
# 3. struct_variance_collapse (G1 Log Gen 0 -> Gen 1 Variance Collapse, 0-100)
# 4. struct_trophic_capture (S[1-5]xS6 Double-Articulation & Cross-Guild Degree, 0-100)
# 5. struct_prime_density (G5 Prime & Twin-Prime Mutation Density, 0-100)
# 6. struct_repricing_resilience (Tri-Modal Repricing & State-Gate Closure, 0-100)
# Longitudinal Time-Series Moments (6):
# 7. ts_duty_cycle_pct (Pr[X_t > 0] Active Lock/Wire Duty Cycle %)
# 8. ts_weighted_resonance (1.5*Wire_Share + 0.7*Vol_Weighted_Lock_Share, 0-100)
# 9. ts_excess_over_replacement (Value Over Baseline Tier D Replacement)
# 10. ts_quantile_profile ({p20_floor, p90_ceiling, boom_pct, bust_pct, cv})
# 11. ts_optimal_lag_days (Peak Cross-Correlation Lead-Lag tau* in [-5..+5] days)
# 12. ts_regime_splits (Conditional Regime Delta {M1, M2, M3})
LENS_REGISTRY: dict[str, dict[str, Any]] = {
"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] - μ",
},
"tier_bands": [
(88, "Q1+ (Top Decile Attractor)"),
(80, "Q1 (High-Coupling Hub)"),
(72, "Q2 (State-Gated Subsystem)"),
(60, "Q3 (Uncoupled Specialist)"),
(52, "Q4 (Provisional Cluster)"),
(44, "Q5 (Episodic Point Anchor)"),
(0, "Null / Rejected"),
],
},
"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)",
},
"tier_bands": [
(88, "Core Overweight (Apex Conviction)"),
(80, "Structural Overweight (Keystone Moat)"),
(72, "Tactical Regime Hedge (Counter-Cyclical)"),
(60, "Uncaptured Venture Alpha (Pre-Institutional)"),
(52, "Early Theme Watchlist (Seed Nucleation)"),
(44, "Event-Driven Flyer (Single Catalyst)"),
(0, "Underweight / Filtered"),
],
},
"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)",
},
"tier_bands": [
(88, "Tier 1 Core Operating Platform"),
(80, "Tier 1 Strategic Infrastructure"),
(72, "Tier 2 Defensive Balance-Sheet Buffer"),
(60, "Tier 2 R&D Business Unit"),
(52, "Tier 3 Exploratory Incubator"),
(44, "Tier 4 Contractual Contingency"),
(0, "Non-Core / Divest"),
],
},
"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)",
},
"tier_bands": [
(88, "Tier S+ (Apex Predator)"),
(80, "Tier S (Keystone Guild)"),
(72, "Tier A (Symbiont Lock)"),
(60, "Tier B (Nomad Specialist)"),
(52, "Tier C (Nucleation Stub)"),
(44, "Tier D (Episodic Anchor)"),
(0, "Tier F (Extinct / CI-Rejected)"),
],
},
"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 Correlation)",
"struct_trophic_capture": "Front-Office Cap Reach",
"struct_prime_density": "Playbook IQ (Audible Density)",
"struct_repricing_resilience": "All-Weather Durability",
},
"timeseries_labels": {
"ts_duty_cycle_pct": "SNAP% (Active Wire & Lock Snap Share)",
"ts_weighted_resonance": "WOPR (Weighted Opportunity & Resonance)",
"ts_excess_over_replacement": "WAR_30d (Wins Above Waiver Replacement)",
"ts_quantile_profile": "Floor P20 / Ceiling P90 / Boom% Profile",
"ts_optimal_lag_days": "Pace & Leverage Lead-Lag τ* (Days)",
"ts_regime_splits": "Weather & SOS Matchup Split (M1/M2/M3)",
},
"tier_bands": [
(88, "Tier S+ (Matchup-Proof Franchise Starter)"),
(80, "Tier S (Every-Week Pro-Bowl Trench/Cap)"),
(72, "Tier A (Situational Bad-Weather Defense)"),
(60, "Tier B (High-Upside Bench Flex)"),
(52, "Tier C (Practice-Squad / Dynasty Stash)"),
(44, "Tier D (Waiver-Wire Streaming Flyer)"),
(0, "Tier F (Cut List / IR)"),
],
},
"pokedex_scanner": {
"lens_id": "pokedex_scanner",
"title": "Gen IV INFO Pokédex Field Scanner",
"short_label": "Pokédex Scanner",
"structural_labels": {
"struct_isometric_armor": "Base DEF (Isometric Shield)",
"struct_drift_velocity": "Base SPE (Teleoplexic Speed)",
"struct_variance_collapse": "Base ATK (Variance-Collapse Strike)",
"struct_trophic_capture": "Base HP (Apparatus Mass)",
"struct_prime_density": "Base SPA (Special Prime Resonance)",
"struct_repricing_resilience": "Base SPD (Repricing Ward)",
},
"timeseries_labels": {
"ts_duty_cycle_pct": "Wild Encounter Rate (%) & Route Biome",
"ts_weighted_resonance": "Specimen Combat Level (Lv. 1-100)",
"ts_excess_over_replacement": "Effort Value (EV) Yield (+1..+3 Stats)",
"ts_quantile_profile": "Specimen Nature (+10% Boost / -10% Cut)",
"ts_optimal_lag_days": "Move Priority Bracket (Lead-Lag τ*)",
"ts_regime_splits": "Passive Weather/Terrain Ability Trigger",
},
"tier_bands": [
(88, "Stage 3 (Apex Mythical / Box-Art Legendary)"),
(80, "Stage 3 (Keystone Pseudo-Legendary)"),
(72, "Stage 2 (Weather-Gated Specialist)"),
(60, "Stage 2 (Uncaptured Roaming Nomad)"),
(52, "Stage 1 (Confirmed Run-2 Nucleation)"),
(44, "Stage 1 (Wild Tall-Grass Pre-Evolution)"),
(0, "Fossil / Unhatched Egg"),
],
},
}
def resolve_tier_band(score: float, lens_id: str) -> str:
spec = LENS_REGISTRY.get(lens_id, LENS_REGISTRY[DEFAULT_LENS])
for cutoff, label in spec["tier_bands"]:
if score >= cutoff:
return str(label)
return str(spec["tier_bands"][-1][1])
def classify_qualitative_archetype(
structural_vector: dict[str, float],
timeseries_moments: dict[str, Any],
lens_id: str,
) -> dict[str, str]:
"""
Deterministically map lens-neutral structural + time-series moments into qualitative
archetype tags, roles, and abilities under the requested lens.
"""
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))
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))
if m1_split >= max(m2_split, m3_split) and m1_split > 3.0:
peak_regime = "M1_ENTROPIC"
elif m2_split >= m3_split and m2_split > 3.0:
peak_regime = "M2_FLASH_CRASH"
else:
peak_regime = "M3_LEVIATHAN"
if lens_id == "neutral_math":
dist_class = (
"High-Floor Low-CV Stationary Attractor"
if (p20 >= 65.0 and cv < 0.48)
else ("Right-Skewed Impulse Process" if cv >= 0.70 else "Balanced Ergodic Process")
)
lag_class = f"Lead τ*={lag:+d}d (Wire->Market)" if lag > 0 else (f"Lag τ*={lag:+d}d (Market->Wire)" if lag < 0 else "Synchronous τ*=0d")
return {
"archetype": dist_class,
"causal_role": lag_class,
"regime_specialization": f"Peak Conditional Gain in {peak_regime}",
}
if lens_id == "fund_manager":
arch = (
"Core Compounding Moat (High-Floor / Low-Beta)"
if (p20 >= 65.0 and cv < 0.48)
else ("Convex Tail-Surge Alpha" if (p90 >= 82.0 and cv >= 0.65) else "Balanced Multi-Factor Core")
)
lag_role = "Pre-Price Signal Leader" if lag > 0 else ("Synchronous Tape Confirm" if lag == 0 else "Post-Repricing Momentum")
reg_note = {
"M1_ENTROPIC": "Counter-Cyclical Halt / Stagnation Hedge (+Beta in M1)",
"M2_FLASH_CRASH": "Long-Volatility Gamma Scalper (+Beta in M2)",
"M3_LEVIATHAN": "Mega-Cap Balance-Sheet Compounder (+Beta in M3)",
}[peak_regime]
return {"archetype": arch, "causal_role": lag_role, "regime_specialization": reg_note}
if lens_id == "corporate_board":
arch = (
"Mission-Critical Chokepoint Infrastructure"
if p20 >= 65.0
else ("High-Growth Strategic Initiative" if p90 >= 80.0 else "Modular Operating Unit")
)
lag_role = "Leading Strategic Indicator" if lag >= 0 else "Downstream Accounting Reflection"
reg_note = {
"M1_ENTROPIC": "Supply-Chain Continuity & Halt Buffer",
"M2_FLASH_CRASH": "Liquidity Treasury Shock Absorber",
"M3_LEVIATHAN": "Consortium & Cap-Table Consolidation Engine",
}[peak_regime]
return {"archetype": arch, "causal_role": lag_role, "regime_specialization": reg_note}
if lens_id == "tierzoo_ecology":
arch = (
"Apex Generalist (All-Biome Dominance)"
if (p20 >= 68.0 and p90 >= 85.0)
else ("Armored Trench Keystone" if cv < 0.48 else "Opportunistic Burst Predator")
)
lag_role = "Teleoplexic Carrier-Wave Leader" if lag > 0 else ("Phase-Locked Synchronizer" if lag == 0 else "Detritivore Capture Follower")
reg_note = {
"M1_ENTROPIC": "Vampiric Siphon (Thrives in Entropic Stagnation)",
"M2_FLASH_CRASH": "Templex Swarm Fever (Thrives in Volatility Surges)",
"M3_LEVIATHAN": "Leviathan Gravity (Thrives in Trillion-Cap Capture)",
}[peak_regime]
return {"archetype": arch, "causal_role": lag_role, "regime_specialization": reg_note}
if lens_id == "fantasy_sabermetrics":
if p20 >= 68.0 and p90 >= 85.0:
arch = "Matchup-Proof League-Winner (Every-Down Bellcow)"
elif p20 >= 64.0 and cv < 0.48:
arch = "Ironclad Cash-Game Floor Anchor (OL/Blocker)"
elif p90 >= 80.0 and cv >= 0.62:
arch = "Boom/Bust Tournament Week-Winner (Deep Threat)"
elif duty >= 45.0:
arch = "Multi-Position Flex Pivot"
else:
arch = "Priority Waiver-Wire Breakout Stash"
lag_role = f"Play-Caller Audible Leader ({lag:+d}d)" if lag > 0 else ("Snap-Count Synchronizer (0d)" if lag == 0 else f"Garbage-Time Catch-Up ({lag:+d}d)")
reg_note = {
"M1_ENTROPIC": "Bad-Weather / Supply-Halt Defense Boost (+14 ETI in M1)",
"M2_FLASH_CRASH": "Two-Minute Drill Shootout Boost (+12 ETI in M2)",
"M3_LEVIATHAN": "Front-Office Cap-Space Multiplier (M3)",
}[peak_regime]
return {"archetype": arch, "causal_role": lag_role, "regime_specialization": reg_note}
# Default / pokedex_scanner
arm = float(structural_vector.get("struct_isometric_armor", 70))
vel = float(structural_vector.get("struct_drift_velocity", 70))
col = float(structural_vector.get("struct_variance_collapse", 70))
cap = float(structural_vector.get("struct_trophic_capture", 70))
if vel >= arm and lag > 0:
nature = "Timid (+SPE / -DEF • Teleoplexic Acceleration)"
elif arm > vel and cv < 0.48:
nature = "Relaxed (+DEF / -SPE • Isometric Trench Shield)"
elif col >= 88 and m2_split > 0:
nature = "Rash (+ATK / -SPD • Templex Surge Striker)"
elif cap >= 90:
nature = "Quiet (+HP / -SPE • Sovereign Apparatus Accumulator)"
else:
nature = "Modest (+SPA / -ATK • Prime Harmonic Resonator)"
ability = {
"M1_ENTROPIC": "Supply-Halt Pivot (Converts M1 Freeze into +DEF)",
"M2_FLASH_CRASH": "Templex Surge (Doubles Lock Rate in M2 Volatility)",
"M3_LEVIATHAN": "Apparatus Gravity (Pulls S1-S3 Partners into S6 Ring)",
}[peak_regime]
ev_yield = "+2 SPA, +1 DEF" if arm >= 85 else ("+2 HP, +1 ATK" if cap >= 85 else "+2 SPE, +1 ATK")
return {"archetype": nature, "causal_role": ev_yield, "regime_specialization": ability}
def apply_lens(
structural_vector: dict[str, float],
timeseries_moments: dict[str, Any],
composite_score: float,
lens_id: str = DEFAULT_LENS,
) -> dict[str, Any]:
spec = LENS_REGISTRY.get(lens_id, LENS_REGISTRY[DEFAULT_LENS])
qual = classify_qualitative_archetype(structural_vector, timeseries_moments, spec["lens_id"])
return {
"lens_id": spec["lens_id"],
"lens_title": spec["title"],
"short_label": spec["short_label"],
"tier_classification": resolve_tier_band(composite_score, spec["lens_id"]),
"qualitative_profile": qual,
"labeled_structural": {
spec["structural_labels"][k]: v for k, v in structural_vector.items() if k in spec["structural_labels"]
},
"labeled_timeseries": {
spec["timeseries_labels"][k]: v for k, v in timeseries_moments.items() if k in spec["timeseries_labels"]
},
}
def apply_all_lenses(
structural_vector: dict[str, float],
timeseries_moments: dict[str, Any],
composite_score: float,
enabled_lenses: tuple[str, ...] | list[str] = ENABLED_LENSES,
) -> dict[str, dict[str, Any]]:
return {
lid: apply_lens(structural_vector, timeseries_moments, composite_score, lid)
for lid in enabled_lenses
if lid in LENS_REGISTRY
}
+365
View File
@@ -0,0 +1,365 @@
"""
hyperstitionstud_io.mcp.rest — Unified Stateless REST API & OpenAPI 3.1.0 Adapter (`/api/v1/*`).
Exposes all tools in `MCP_TOOLS_SCHEMA`, static resources in `STATIC_RESOURCES`, templates in
`RESOURCE_TEMPLATES`, and guided prompts in `MCP_PROMPTS` over standard HTTP GET/POST REST
endpoints on the existing `hs-mcp` (`127.0.0.1:8095`) server, guarded by `ReadOnlyIsolationGuard`.
"""
from __future__ import annotations
import json
import re
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.glossary import ReadOnlyIsolationGuard
from hyperstitionstud_io.mcp.prompts import MCP_PROMPTS, get_mcp_prompt
from hyperstitionstud_io.mcp.resources import (
RESOURCE_TEMPLATES,
STATIC_RESOURCES,
read_mcp_resource,
)
from hyperstitionstud_io.mcp.tools import MCP_TOOLS_SCHEMA, call_mcp_tool
# Domain-specific REST aliases mapped to (tool_name, default_arg_overrides)
REST_DOMAIN_ALIASES: dict[str, str] = {
"/api/v1/doctor": "hs_run_doctor_and_audit",
"/api/v1/ciphers/evaluate": "hs_evaluate_aq_and_ingglish",
"/api/v1/zoology/classify": "hs_classify_singularity",
"/api/v1/zoology/tier-list": "hs_inspect_eti_tier_list",
"/api/v1/zoology/anchor-revision": "hs_simulate_anchor_revision",
"/api/v1/graph/query": "hs_query_knowledge_graph",
"/api/v1/glossary/search": "hs_search_glossary_encyclopedia",
"/api/v1/archive/equations": "hs_search_archive_equations",
"/api/v1/quant/harvest": "hs_scan_financial_quant_harvest",
"/api/v1/quant/timeseries": "hs_inspect_quant_timeseries",
"/api/v1/ipld/cid": "hs_compute_ipld_dag_json_cid",
"/api/v1/citations/verify": "hs_verify_grounded_citations",
}
def _find_tool_schema(tool_name: str) -> dict[str, Any] | None:
for t in MCP_TOOLS_SCHEMA:
if t["name"] == tool_name:
return t
return None
def coerce_query_params(query_str: str, input_schema: dict[str, Any] | None = None) -> tuple[dict[str, Any], bool]:
"""
Parse URL query string and coerce values according to `input_schema["properties"]`.
Returns `(coerced_args, unwrap_raw_flag)`.
"""
parsed = urllib.parse.parse_qs(query_str, keep_blank_values=False)
props = ((input_schema or {}).get("properties") or {})
out: dict[str, Any] = {}
unwrap = False
for k, vals in parsed.items():
if k in ("raw", "unwrap") and vals and vals[-1].lower() in ("1", "true", "yes"):
unwrap = True
continue
p_spec = props.get(k) or {}
p_type = p_spec.get("type", "string")
if p_type == "array":
arr: list[str] = []
for v in vals:
arr.extend(x.strip() for x in v.split(",") if x.strip())
out[k] = arr
elif p_type == "integer":
out[k] = int(vals[-1])
elif p_type == "number":
out[k] = float(vals[-1])
elif p_type == "boolean":
out[k] = vals[-1].lower() in ("1", "true", "yes")
else:
out[k] = vals[-1]
return out, unwrap
def build_openapi_v1_spec() -> dict[str, Any]:
"""
Dynamically compile an OpenAPI 3.1.0 specification from MCP_TOOLS_SCHEMA,
STATIC_RESOURCES, RESOURCE_TEMPLATES, and MCP_PROMPTS.
"""
paths: dict[str, Any] = {
"/api/v1/status": {
"get": {
"operationId": "getStatus",
"summary": "Server status, endpoint directory, and ReadOnlyIsolationGuard verification.",
"responses": {"200": {"description": "OK"}},
}
},
"/api/v1/openapi.json": {
"get": {
"operationId": "getOpenApiSpec",
"summary": "OpenAPI 3.1.0 schema for all REST and MCP capabilities.",
"responses": {"200": {"description": "OK"}},
}
},
"/api/v1/tools": {
"get": {
"operationId": "listTools",
"summary": "List all registered MCP/REST tools and their JSON inputSchemas.",
"responses": {"200": {"description": "OK"}},
}
},
"/api/v1/resources": {
"get": {
"operationId": "listResources",
"summary": "List all static URN resources and URI templates.",
"responses": {"200": {"description": "OK"}},
}
},
"/api/v1/prompts": {
"get": {
"operationId": "listPrompts",
"summary": "List all guided workflow prompt templates.",
"responses": {"200": {"description": "OK"}},
}
},
}
for tool in MCP_TOOLS_SCHEMA:
t_name = tool["name"]
schema = tool.get("inputSchema", {"type": "object"})
op_spec = {
"summary": tool.get("description", ""),
"responses": {"200": {"description": "Successful tool execution"}},
}
paths[f"/api/v1/tools/{t_name}"] = {
"get": {"operationId": f"get_{t_name}", **op_spec},
"post": {
"operationId": f"post_{t_name}",
"requestBody": {"content": {"application/json": {"schema": schema}}},
**op_spec,
},
}
for alias_path, t_name in REST_DOMAIN_ALIASES.items():
tool = _find_tool_schema(t_name) or {}
paths[alias_path] = {
"get": {
"operationId": f"alias_get_{t_name}",
"summary": f"REST alias for {t_name}: {tool.get('description', '')}",
"responses": {"200": {"description": "OK"}},
},
"post": {
"operationId": f"alias_post_{t_name}",
"summary": f"REST alias for {t_name}",
"responses": {"200": {"description": "OK"}},
},
}
return {
"openapi": "3.1.0",
"info": {
"title": "hyperstitionstud.io Unified REST & MCP API",
"version": CURRENT_VERSION,
"description": "Stateless read-only REST API (/api/v1/*) and MCP Streamable HTTP (/mcp) interface.",
},
"servers": [{"url": "/"}],
"paths": paths,
}
def _wrap_response(endpoint: str, data: Any, unwrap: bool = False, tool_name: str | None = None) -> dict[str, Any]:
if unwrap and isinstance(data, dict):
return data
resp: dict[str, Any] = {
"ok": True,
"version": CURRENT_VERSION,
"endpoint": endpoint,
}
if tool_name:
resp["tool"] = tool_name
resp["data"] = data
resp["isolation_verified"] = True
return resp
def _error_response(status: int, code: str, message: str) -> tuple[int, str, dict[str, Any]]:
return (
status,
"application/json; charset=utf-8",
{
"ok": False,
"version": CURRENT_VERSION,
"error": {"code": code, "status": status, "message": message},
},
)
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/*`.
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:
# 1. Discovery & OpenAPI
if path in ("/api/v1", "/api/v1/status") and method == "GET":
_, unwrap = coerce_query_params(query_str)
status_data = {
"name": "hyperstitionstudio-rest-api",
"version": CURRENT_VERSION,
"namespace_urn": f"urn:io:hyperstitionstud:api:v1:{CURRENT_VERSION}",
"protocols": {"rest_v1": "/api/v1", "openapi_3_1": "/api/v1/openapi.json", "mcp_jsonrpc": "/mcp"},
"counts": {
"tools": len(MCP_TOOLS_SCHEMA),
"static_resources": len(STATIC_RESOURCES),
"resource_templates": len(RESOURCE_TEMPLATES),
"prompts": len(MCP_PROMPTS),
"domain_aliases": len(REST_DOMAIN_ALIASES),
},
"domain_endpoints": sorted(REST_DOMAIN_ALIASES.keys()),
"isolation_receipt": guard.audit_receipt(),
}
return 200, "application/json; charset=utf-8", _wrap_response(path, status_data, unwrap=unwrap)
if path == "/api/v1/openapi.json" and method == "GET":
return 200, "application/json; charset=utf-8", build_openapi_v1_spec()
if path == "/api/v1/tools" and method == "GET":
_, unwrap = coerce_query_params(query_str)
return 200, "application/json; charset=utf-8", _wrap_response(path, {"tools": MCP_TOOLS_SCHEMA}, unwrap=unwrap)
if path == "/api/v1/resources" and method == "GET":
_, unwrap = coerce_query_params(query_str)
return 200, "application/json; charset=utf-8", _wrap_response(
path,
{"resources": STATIC_RESOURCES, "resourceTemplates": RESOURCE_TEMPLATES},
unwrap=unwrap,
)
if path == "/api/v1/prompts" and method == "GET":
_, unwrap = coerce_query_params(query_str)
return 200, "application/json; charset=utf-8", _wrap_response(path, {"prompts": MCP_PROMPTS}, unwrap=unwrap)
# 2. Parameterized Path Shorthands:
# - /api/v1/graph/nodes/{node_id}
# - /api/v1/quant/instruments/{symbol}
# - /api/v1/zoology/pokedex/{symbol}
# - /api/v1/resources/{slug}
# - /api/v1/dossiers/{number}
# - /api/v1/schemas/{schema_slug}
# - /api/v1/prompts/{prompt_name}
m_node = re.match(r"^/api/v1/graph/nodes/(.+)$", path)
if m_node and method == "GET":
node_id = urllib.parse.unquote(m_node.group(1))
q_args, unwrap = coerce_query_params(query_str, _find_tool_schema("hs_query_knowledge_graph")["inputSchema"])
q_args["query"] = node_id
res = call_mcp_tool("hs_query_knowledge_graph", q_args)
return 200, "application/json; charset=utf-8", _wrap_response(path, res, unwrap=unwrap, tool_name="hs_query_knowledge_graph")
m_inst = re.match(r"^/api/v1/quant/instruments/([^/]+)$", path)
if m_inst and method == "GET":
sym = urllib.parse.unquote(m_inst.group(1))
q_args, unwrap = coerce_query_params(query_str, _find_tool_schema("hs_scan_financial_quant_harvest")["inputSchema"])
q_args["symbol_filter"] = sym
res = call_mcp_tool("hs_scan_financial_quant_harvest", q_args)
return 200, "application/json; charset=utf-8", _wrap_response(path, res, unwrap=unwrap, tool_name="hs_scan_financial_quant_harvest")
m_pkx = re.match(r"^/api/v1/zoology/pokedex/([^/]+)$", path)
if m_pkx and method == "GET":
sym = urllib.parse.unquote(m_pkx.group(1))
q_args, unwrap = coerce_query_params(query_str, _find_tool_schema("hs_inspect_quant_timeseries")["inputSchema"])
q_args["symbol"] = sym
q_args["lens"] = "pokedex_scanner"
res = call_mcp_tool("hs_inspect_quant_timeseries", q_args)
return 200, "application/json; charset=utf-8", _wrap_response(path, res, unwrap=unwrap, tool_name="hs_inspect_quant_timeseries")
m_res = re.match(r"^/api/v1/resources/([a-z0-9-]+)$", path)
if m_res and method == "GET":
slug = m_res.group(1)
_, unwrap = coerce_query_params(query_str)
uri = f"urn:io:hyperstitionstud:resource:{slug}"
r_out = read_mcp_resource(uri)
parsed_json = json.loads(r_out["contents"][0]["text"])
return 200, "application/json; charset=utf-8", _wrap_response(path, parsed_json, unwrap=unwrap)
m_dos = re.match(r"^/api/v1/dossiers/(\d+)$", path)
if m_dos and method == "GET":
num = int(m_dos.group(1))
q_args, unwrap = coerce_query_params(query_str)
uri = f"urn:io:hyperstitionstud:dossier:{num}"
r_out = read_mcp_resource(uri)
md_text = r_out["contents"][0]["text"]
if q_args.get("format") == "raw":
return 200, "text/markdown; charset=utf-8", md_text
return 200, "application/json; charset=utf-8", _wrap_response(
path,
{"dossier_number": num, "uri": uri, "mime_type": "text/markdown", "markdown": md_text},
unwrap=unwrap,
)
m_sch = re.match(r"^/api/v1/schemas/([a-z0-9-]+)$", path)
if m_sch and method == "GET":
slug = m_sch.group(1)
uri = f"urn:io:hyperstitionstud:schema:v1:{slug}"
r_out = read_mcp_resource(uri)
return 200, "application/schema+json; charset=utf-8", json.loads(r_out["contents"][0]["text"])
m_prm = re.match(r"^/api/v1/prompts/([a-z0-9_]+)$", path)
if m_prm:
p_name = m_prm.group(1)
p_args, unwrap = coerce_query_params(query_str)
if method == "POST" and body_bytes:
p_args.update(json.loads(body_bytes.decode("utf-8")))
p_out = get_mcp_prompt(p_name, p_args)
return 200, "application/json; charset=utf-8", _wrap_response(path, p_out, unwrap=unwrap)
# 3. Generic /api/v1/tools/{tool_name} or Domain Alias Execution
target_tool: str | None = None
if path in REST_DOMAIN_ALIASES:
target_tool = REST_DOMAIN_ALIASES[path]
else:
m_tool = re.match(r"^/api/v1/tools/([a-z0-9_]+)$", path)
if m_tool:
target_tool = m_tool.group(1)
if target_tool:
t_schema = _find_tool_schema(target_tool)
if t_schema is None:
return _error_response(404, "UNKNOWN_TOOL", f"Unknown tool: {target_tool}")
in_schema = t_schema.get("inputSchema") or {}
t_args, unwrap = coerce_query_params(query_str, in_schema)
if method == "POST" and body_bytes:
body_obj = json.loads(body_bytes.decode("utf-8"))
if isinstance(body_obj, dict):
if body_obj.pop("raw", False) or body_obj.pop("unwrap", False):
unwrap = True
t_args.update(body_obj)
required_fields = in_schema.get("required") or []
missing = [req_f for req_f in required_fields if req_f not in t_args]
if missing:
return _error_response(
422,
"MISSING_REQUIRED_PARAMETER",
f"Missing required parameter(s) {missing} for tool '{target_tool}'.",
)
out = call_mcp_tool(target_tool, t_args)
return 200, "application/json; charset=utf-8", _wrap_response(path, out, unwrap=unwrap, tool_name=target_tool)
return _error_response(404, "ENDPOINT_NOT_FOUND", f"Unknown REST API v1 endpoint: {path}")
except ValueError as exc:
msg = str(exc)
status = 404 if ("Unknown" in msg or "No dossier" in msg) else 422
return _error_response(status, "VALIDATION_ERROR", msg)
except Exception as exc:
return _error_response(500, "INTERNAL_ERROR", str(exc))
+32 -8
View File
@@ -28,12 +28,13 @@ from hyperstitionstud_io.mcp.resources import ( # noqa: E402
STATIC_RESOURCES,
read_mcp_resource,
)
from hyperstitionstud_io.mcp.rest import dispatch_rest_v1 # noqa: E402
from hyperstitionstud_io.mcp.tools import MCP_TOOLS_SCHEMA, call_mcp_tool # noqa: E402
SERVER_INFO = {
"name": "hyperstitionstudio-mcp",
"version": "2.0.15",
"namespace_urn": "urn:io:hyperstitionstud:mcp:2.0.15",
"version": "2.0.18",
"namespace_urn": "urn:io:hyperstitionstud:mcp:2.0.18",
}
@@ -147,10 +148,13 @@ class _MCPHTTPHandler(BaseHTTPRequestHandler):
def log_message(self, format: str, *args: Any) -> None:
return
def _send_json(self, status: int, payload: Any) -> None:
body = (json.dumps(payload, indent=2, ensure_ascii=False) + "\n").encode("utf-8")
def _send_payload(self, status: int, content_type: str, payload: Any) -> None:
if isinstance(payload, str):
body = payload.encode("utf-8")
else:
body = (json.dumps(payload, indent=2, ensure_ascii=False) + "\n").encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
@@ -158,6 +162,9 @@ class _MCPHTTPHandler(BaseHTTPRequestHandler):
self.end_headers()
self.wfile.write(body)
def _send_json(self, status: int, payload: Any) -> None:
self._send_payload(status, "application/json; charset=utf-8", payload)
def do_OPTIONS(self) -> None:
self.send_response(204)
self.send_header("Access-Control-Allow-Origin", "*")
@@ -166,11 +173,20 @@ 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"},
"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),
@@ -185,10 +201,18 @@ class _MCPHTTPHandler(BaseHTTPRequestHandler):
def do_POST(self) -> None:
length = int(self.headers.get("Content-Length", "0"))
if length <= 0 or length > 65536:
if length < 0 or length > 65536:
self._send_json(400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "Invalid content length"}})
return
raw = self.rfile.read(length).decode("utf-8")
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:
+47
View File
@@ -191,6 +191,21 @@ MCP_TOOLS_SCHEMA: list[dict[str, Any]] = [
},
},
},
{
"name": "hs_inspect_quant_timeseries",
"description": "Inspect the lens-neutral periodic quantitative financial & memetic gematria time-series bundle (30 UTC days x 24 S1-S6 tickers x 21 dated news dossiers), TradingView Superchart URLs, and pluggable LENS_REGISTRY projections.",
"inputSchema": {
"type": "object",
"properties": {
"symbol": {"type": "string", "default": "", "description": "Optional ticker symbol or DEX coordinate (e.g. 'NVDA', '137', 'ASML')."},
"lens": {
"type": "string",
"enum": ["fund_manager", "neutral_math", "corporate_board", "tierzoo_ecology", "fantasy_sabermetrics", "pokedex_scanner"],
"default": "fund_manager",
},
},
},
},
]
@@ -455,4 +470,36 @@ def call_mcp_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]:
payload["instruments"] = [x for x in payload["instruments"] if sym_f in x["symbol"].upper() or sym_f in x["entity_eng"].upper()]
return payload
if name == "hs_inspect_quant_timeseries":
from hyperstitionstud_io.quant.timeseries import build_quant_timeseries_bundle
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)
if sym_q:
matched = [
inst
for inst in bundle["instruments"]
if inst["symbol"].upper() == sym_q
or inst["entity_eng"].upper() == sym_q
or str(inst["entity_ing_aq"]) == sym_q.lstrip("#DEX ")
]
return {
"version": bundle["version"],
"periodicity_gate": bundle["periodicity_gate"],
"selected_lens": lens_q,
"instruments": matched,
"ipld_dag_json_cidv1": bundle["ipld_dag_json_cidv1"],
}
return {
"version": bundle["version"],
"periodicity_gate": bundle["periodicity_gate"],
"enabled_lenses": bundle["enabled_lenses"],
"dates_utc": bundle["dates_utc"],
"instrument_count": len(bundle["instruments"]),
"builds": bundle["builds"],
"anchor_revision_series": bundle["anchor_revision_series"],
"ipld_dag_json_cidv1": bundle["ipld_dag_json_cidv1"],
}
raise ValueError(f"Unknown MCP tool: {name}")
+14
View File
@@ -9,11 +9,25 @@ from hyperstitionstud_io.quant.collector import (
main,
synthesize_quant_dossier_markdown,
)
from hyperstitionstud_io.quant.timeseries import (
EXCLUDED_NON_PERIODIC_SOURCES,
TRADINGVIEW_SYMBOL_MAP,
build_quant_timeseries_bundle,
compute_timeseries_moments,
derive_pokedex_specimen_profile,
resolve_tradingview_target,
)
__all__ = [
"CANONICAL_WATCHLIST_24",
"EXCLUDED_NON_PERIODIC_SOURCES",
"TRADINGVIEW_SYMBOL_MAP",
"build_financial_quant_harvest",
"build_quant_timeseries_bundle",
"compute_timeseries_moments",
"derive_pokedex_specimen_profile",
"fetch_live_watchlist",
"main",
"resolve_tradingview_target",
"synthesize_quant_dossier_markdown",
]
+6 -1
View File
@@ -496,7 +496,7 @@ def build_financial_quant_harvest(
payload: dict[str, Any] = {
"$schema": "./schemas/v1/financial-aq-harvest.schema.json",
"$id": "urn:io:hyperstitionstud:schema:v1:financial-aq-harvest",
"version": "2.0.15",
"version": "2.0.18",
"target_date_utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d"),
"harvest_mode": harvest_mode,
"regime_summary": {
@@ -593,6 +593,10 @@ 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)
print(
json.dumps(
{
@@ -603,6 +607,7 @@ def main(argv: list[str] | None = None) -> int:
"news_wire_co_present_symbols": payload["regime_summary"]["news_wire_co_present_symbols"],
"active_memetic_states": payload["regime_summary"]["active_memetic_states"],
"dag_json_cidv1": info["cidv1"],
"timeseries_cidv1": ts_bundle["ipld_dag_json_cidv1"]["/"],
"isolation_all_unchanged": payload["isolation_receipt"]["all_unchanged"],
},
indent=2,
+779
View File
@@ -0,0 +1,779 @@
"""
hyperstitionstud_io.quant.timeseries — Lens-Neutral Periodic Quantitative Financial & Memetic Gematria Time-Series Engine.
Enforces the Strict Periodicity Qualification Gate:
- Ingests ONLY timestamp-indexed periodic sources (`21:30 UTC` `us-closing-bell` market bars,
`00:00 UTC` `*-dossier-news-YYYY-MM-DD.md` wire harvests, daily `M1-M7+` regime vectors, and
dated `quantitative-economic-anchors.json` step revisions).
- Strictly excludes non-periodic/static corpora (`01-lexicon`, `10-19-ledgers`, undated dossiers
`20-24`, `26-45`, `65-69`, 22-volume Encyclopedia, proposals, lectures, podcasts, `db.json`).
- Persists 100% lens-neutral mathematical keys (`struct_*` & `ts_*`) and projects interpretive
registers (`fund_manager`, `neutral_math`, `corporate_board`, `tierzoo_ecology`,
`fantasy_sabermetrics`, `pokedex_scanner`) at runtime via `hyperstitionstud_io.lenses`.
"""
from __future__ import annotations
import datetime
import hashlib
import json
import math
import re
from pathlib import Path
from typing import Any
from hyperstitionstud_io import __version__ as CURRENT_VERSION
from hyperstitionstud_io.ciphers import (
compute_aq,
expand_quant_spoken,
int_to_spoken_words,
is_repdigit_37,
prime_rank,
)
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.phonetics import translate_batch
from hyperstitionstud_io.quant.collector import (
CANONICAL_WATCHLIST_24,
S1_S6_SIGNATURE_RINGS,
)
# Canonical TradingView Superchart Symbol & URL Resolver (Opened in new window; 0 external script embeds)
TRADINGVIEW_SYMBOL_MAP: dict[str, tuple[str, str]] = {
"NVDA": ("NASDAQ:NVDA", "https://www.tradingview.com/chart/?symbol=NASDAQ%3ANVDA"),
"ASML": ("NASDAQ:ASML", "https://www.tradingview.com/chart/?symbol=NASDAQ%3AASML"),
"TSM": ("NYSE:TSM", "https://www.tradingview.com/chart/?symbol=NYSE%3ATSM"),
"ANTHR-PVT": ("NASDAQ:GOOGL", "https://www.tradingview.com/chart/?symbol=NASDAQ%3AGOOGL"),
"MSFT": ("NASDAQ:MSFT", "https://www.tradingview.com/chart/?symbol=NASDAQ%3AMSFT"),
"GOOGL": ("NASDAQ:GOOGL", "https://www.tradingview.com/chart/?symbol=NASDAQ%3AGOOGL"),
"META": ("NASDAQ:META", "https://www.tradingview.com/chart/?symbol=NASDAQ%3AMETA"),
"ORCL": ("NYSE:ORCL", "https://www.tradingview.com/chart/?symbol=NYSE%3AORCL"),
"AVGO": ("NASDAQ:AVGO", "https://www.tradingview.com/chart/?symbol=NASDAQ%3AAVGO"),
"ARM": ("NASDAQ:ARM", "https://www.tradingview.com/chart/?symbol=NASDAQ%3AARM"),
"AMD": ("NASDAQ:AMD", "https://www.tradingview.com/chart/?symbol=NASDAQ%3AAMD"),
"PLTR": ("NASDAQ:PLTR", "https://www.tradingview.com/chart/?symbol=NASDAQ%3APLTR"),
"LMT": ("NYSE:LMT", "https://www.tradingview.com/chart/?symbol=NYSE%3ALMT"),
"RTX": ("NYSE:RTX", "https://www.tradingview.com/chart/?symbol=NYSE%3ARTX"),
"HG=F": ("COMEX:HG1!", "https://www.tradingview.com/chart/?symbol=COMEX%3AHG1%21"),
"^VIX": ("TVC:VIX", "https://www.tradingview.com/chart/?symbol=TVC%3AVIX"),
"BTC-USD": ("COINBASE:BTCUSD", "https://www.tradingview.com/chart/?symbol=COINBASE%3ABTCUSD"),
"ETH-USD": ("COINBASE:ETHUSD", "https://www.tradingview.com/chart/?symbol=COINBASE%3AETHUSD"),
"SOL-USD": ("COINBASE:SOLUSD", "https://www.tradingview.com/chart/?symbol=COINBASE%3ASOLUSD"),
"COIN": ("NASDAQ:COIN", "https://www.tradingview.com/chart/?symbol=NASDAQ%3ACOIN"),
"CEG": ("NASDAQ:CEG", "https://www.tradingview.com/chart/?symbol=NASDAQ%3ACEG"),
"LLY": ("NYSE:LLY", "https://www.tradingview.com/chart/?symbol=NYSE%3ALLY"),
"^TNX": ("TVC:US10Y", "https://www.tradingview.com/chart/?symbol=TVC%3AUS10Y"),
"BLK": ("NYSE:BLK", "https://www.tradingview.com/chart/?symbol=NYSE%3ABLK"),
}
EXCLUDED_NON_PERIODIC_SOURCES: list[str] = [
"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",
]
_SPARK_BLOCKS = "▁▂▃▄▅▆▇█"
_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)`")
def resolve_tradingview_target(symbol: str) -> dict[str, str]:
tv_sym, tv_url = TRADINGVIEW_SYMBOL_MAP.get(
symbol.upper(),
(f"NASDAQ:{symbol.upper()}", f"https://www.tradingview.com/chart/?symbol={symbol.upper()}"),
)
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)
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))])
return "".join(out)
def _pearson_corr(xs: list[float], ys: list[float]) -> float:
n = min(len(xs), len(ys))
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)))
if dx < 1e-9 or dy < 1e-9:
return 0.0
return round(num / (dx * dy), 3)
def _extract_dated_news_dossiers(archive_dir: Path) -> dict[str, dict[str, Any]]:
"""
Scan ingglish-aq-archive strictly for periodic dated news dossiers (*-dossier-news-YYYY-MM-DD.md).
Asserts zero non-periodic files enter the returned map.
"""
dossiers_by_date: dict[str, dict[str, Any]] = {}
search_dir = archive_dir / "ingglish-aq-archive" if (archive_dir / "ingglish-aq-archive").is_dir() else archive_dir
if not search_dir.is_dir():
return dossiers_by_date
for p in sorted(search_dir.glob("*-dossier-news-*.md")):
m = _DATED_NEWS_RE.match(p.name)
if not m:
continue
dos_num, dt_str = int(m.group(1)), m.group(2)
txt = p.read_text(encoding="utf-8")
txt_low = txt.lower()
eqs: list[dict[str, Any]] = []
counts_by_target = {333: 0, 666: 0, 777: 0}
coords_hit: set[int] = set()
for line in txt.splitlines():
em = _EQ_LINE_RE.match(line.strip())
if em:
ing_p, eng_p, breakdown, tgt_s = em.group(1), em.group(2), em.group(3), int(em.group(4))
counts_by_target[tgt_s] = counts_by_target.get(tgt_s, 0) + 1
token_vals = [int(v) for v in re.findall(r"\((\d+)", breakdown)]
for tv in token_vals:
if tv in S1_S6_SIGNATURE_RINGS:
coords_hit.add(tv)
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)),
})
for c_ring in S1_S6_SIGNATURE_RINGS:
if f"`{c_ring}`" in txt or f"== {c_ring}" in txt or f"({c_ring})" in txt:
coords_hit.add(c_ring)
co_present_syms: list[str] = []
for item in CANONICAL_WATCHLIST_24:
sym = item["symbol"]
ent_low = item["entity_eng"].lower()
sym_clean = sym.split("-")[0].replace("^", "").replace("=F", "").lower()
if ent_low in txt_low or (len(sym_clean) >= 3 and f" {sym_clean} " in f" {txt_low} "):
co_present_syms.append(sym)
dossiers_by_date[dt_str] = {
"date_utc": dt_str,
"dossier_number": dos_num,
"dossier_file": p.name,
"archive_route": f"/archive/{p.name}",
"equation_counts": {
"eq_333": counts_by_target[333],
"eq_666": counts_by_target[666],
"eq_777": counts_by_target[777],
"total": len(eqs),
},
"active_ring_coordinates": sorted(coords_hit),
"co_present_symbols": sorted(co_present_syms),
"sample_equations": eqs[:12],
}
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]:
"""
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.
"""
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,
}
def compute_timeseries_moments(
daily_points: list[float],
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],
regime_series: list[set[str]],
baseline_replacement_pts: float = 18.0,
) -> dict[str, Any]:
"""
Compute the 6 canonical lens-neutral longitudinal time-series moments (`ts_*`).
"""
n = max(1, len(daily_points))
duty_pct = round(100.0 * sum(1 for f in active_flags if f) / n, 1)
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
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)
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
std_pt = math.sqrt(var_pt)
cv = round(std_pt / max(0.25, mean_pt), 2)
# 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)
# Lead-lag cross-correlation profile across tau in [-5 .. +5] days
lag_corrs: dict[str, float] = {}
best_lag = 0
best_abs_r = -1.0
for tau in range(-5, 6):
if tau >= 0:
xs = wire_vel_series[: n - tau]
ys = abs_bps_series[tau:]
else:
k = -tau
xs = wire_vel_series[k:]
ys = abs_bps_series[: n - k]
r_val = _pearson_corr(xs, ys)
lag_corrs[str(tau)] = r_val
if abs(r_val) > best_abs_r:
best_abs_r = abs(r_val)
best_lag = tau
# Conditional regime splits
regime_splits: dict[str, float] = {}
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]]
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
return {
"ts_duty_cycle_pct": duty_pct,
"ts_weighted_resonance": weighted_res,
"ts_excess_over_null": loe,
"ts_excess_over_replacement": excess_over_repl,
"ts_quantile_profile": {
"p20_floor": p20_norm,
"p90_ceiling": p90_norm,
"boom_pct": boom_pct,
"bust_pct": bust_pct,
"cv": cv,
},
"ts_optimal_lag_days": best_lag,
"ts_lag_correlation_curve": lag_corrs,
"ts_regime_splits": regime_splits,
"ts_sparkline_30d": _make_sparkline(daily_points),
}
def derive_pokedex_specimen_profile(
symbol: str,
inst_record: dict[str, Any],
) -> dict[str, Any]:
"""
Project a lens-neutral instrument record into a Gen IV INFO Pokedex specimen card.
"""
sv = inst_record["structural_vector"]
tm = inst_record["timeseries_moments"]
proj = (inst_record.get("lens_projections") or {}).get("pokedex_scanner") or apply_all_lenses(
sv, tm, inst_record["composite_score"], ("pokedex_scanner",)
)["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)")
)
return {
"dex_number": f"DEX #{inst_record['entity_ing_aq']:03d}",
"symbol": symbol,
"entity_eng": inst_record["entity_eng"],
"entity_ing": inst_record["entity_ing"],
"guilds": inst_record["guilds"],
"level": level,
"evolution_stage": proj["tier_classification"],
"nature": qual["archetype"],
"ability": qual["regime_specialization"],
"ev_yield": qual["causal_role"],
"encounter_rarity": rarity,
"base_stats_6": proj["labeled_structural"],
"timeseries_telemetry": proj["labeled_timeseries"],
"sparkline_30d": tm["ts_sparkline_30d"],
"tradingview_symbol": inst_record["tradingview_symbol"],
"tradingview_url": inst_record["tradingview_url"],
}
def build_quant_timeseries_bundle(
enabled_lenses: tuple[str, ...] | list[str] = ENABLED_LENSES,
write_files: bool = True,
) -> dict[str, Any]:
"""
Build the lens-neutral periodic time-series bundle across the 30-day November 2026 UTC calendar
(2026-11-01 .. 2026-11-30), cross-joining the 24 S1-S6 market tickers with the 21 dated
00:00 GMT news wire dossiers.
"""
cfg = load_workspace_config()
active_lenses = tuple(lid for lid in enabled_lenses if lid in LENS_REGISTRY)
if not active_lenses:
active_lenses = ("neutral_math",)
with ReadOnlyIsolationGuard(cfg.read_only_files) as guard:
dated_dossiers = _extract_dated_news_dossiers(cfg.archive_dir)
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]]] = {}
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)
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"])))
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] = []
for dt_s in dates_utc:
dos = dated_dossiers.get(dt_s)
if dos:
daily_wire_series.append(dos)
wire_vel_global.append(float(dos["equation_counts"]["total"]))
else:
daily_wire_series.append({
"date_utc": dt_s,
"dossier_number": None,
"dossier_file": None,
"archive_route": None,
"equation_counts": {"eq_333": 0, "eq_666": 0, "eq_777": 0, "total": 0},
"active_ring_coordinates": [],
"co_present_symbols": [],
"sample_equations": [],
})
wire_vel_global.append(0.0)
# 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)]
daily_total_locked_displacement: list[float] = [0.0 for _ in range(num_days)]
per_sym_series: dict[str, list[dict[str, Any]]] = {}
for item in CANONICAL_WATCHLIST_24:
sym = item["symbol"]
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)
series_rows: list[dict[str, Any]] = []
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"])
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)
scope1_locks: list[str] = []
scope2_coords: list[int] = []
if close_int == ent_ing_aq or close_int == ent_eng_aq:
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:
scope1_locks.append(f"BPS_SELF_LOCK ({bps_abs}=={ent_ing})")
for c_val in (close_int, close_sp_aq, bps_abs):
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:
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):
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")
pts = (
3.0 * len(scope1_locks)
+ 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
daily_total_locked_displacement[d_idx] += locked_disp
series_rows.append({
"date_utc": dt_s,
"close_usd": b["close_usd"],
"change_pct": chg_pct,
"change_bps": b["change_bps"],
"volume_ratio_20d": vol_r,
"market_cap_str": mcap_s,
"close_digit_aq": close_dig_aq,
"close_spoken_ing": close_sp_ing,
"close_spoken_ing_aq": close_sp_aq,
"scaled_cap_spoken_ing": mcap_sp_ing,
"scaled_cap_spoken_ing_aq": mcap_sp_aq,
"bps_digit_aq": bps_dig_aq,
"bps_spoken_ing": bps_sp_ing,
"bps_spoken_ing_aq": bps_sp_aq,
"scope1_locks": scope1_locks,
"scope2_ring_coordinates": scope2_coords,
"co_present_in_news_wire": co_present,
"contingent_points": round(pts, 2),
"_locked_disp": locked_disp,
})
per_sym_series[sym] = series_rows
# Finalize per-instrument structural vectors, time-series moments, and lens projections
instruments_out: list[dict[str, Any]] = []
for item in CANONICAL_WATCHLIST_24:
sym = item["symbol"]
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)
s_rows = per_sym_series[sym]
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]
wire_shares: list[float] = []
cap_shares: list[float] = []
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
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)
# 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
struct_vec = {
"struct_isometric_armor": 92.0 if is_iso else 76.0,
"struct_drift_velocity": max(55.0, min(98.0, 95.0 - abs(ent_ing_aq - ent_eng_aq) * 0.6)),
"struct_variance_collapse": 91.0 if ent_ing_aq in S1_S6_SIGNATURE_RINGS else 74.0,
"struct_trophic_capture": 94.0 if ("S6" in item["guilds"] and len(item["guilds"]) >= 2) else (84.0 if len(item["guilds"]) >= 2 else 68.0),
"struct_prime_density": 95.0 if (is_p_ing and is_p_eng) else (86.0 if is_p_ing else 64.0),
"struct_repricing_resilience": min(98.0, round(58.0 + 1.2 * tot_locks, 1)),
}
comp_score = round(
0.20 * struct_vec["struct_trophic_capture"]
+ 0.18 * struct_vec["struct_variance_collapse"]
+ 0.18 * struct_vec["struct_isometric_armor"]
+ 0.16 * struct_vec["struct_prime_density"]
+ 0.14 * struct_vec["struct_drift_velocity"]
+ 0.14 * struct_vec["struct_repricing_resilience"],
1,
)
ts_moments = compute_timeseries_moments(
daily_points=daily_pts,
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,
wire_vel_series=wire_vel_global,
abs_bps_series=abs_bps,
regime_series=daily_regimes,
)
tv_info = resolve_tradingview_target(sym)
inst_obj: dict[str, Any] = {
"symbol": sym,
"entity_eng": ent_eng,
"entity_ing": ent_ing,
"entity_eng_aq": ent_eng_aq,
"entity_ing_aq": ent_ing_aq,
"isometric_entity": is_iso,
"guilds": item["guilds"],
"tradingview_symbol": tv_info["tradingview_symbol"],
"tradingview_url": tv_info["tradingview_url"],
"composite_score": comp_score,
"structural_vector": struct_vec,
"timeseries_moments": ts_moments,
"lens_projections": apply_all_lenses(struct_vec, ts_moments, comp_score, active_lenses),
"bars": s_rows,
}
if "pokedex_scanner" in active_lenses:
inst_obj["pokedex_profile"] = derive_pokedex_specimen_profile(sym, inst_obj)
instruments_out.append(inst_obj)
# Aggregate guild / assemblage build time-series profiles (connecting to TierZoo assemblage-builds-tier-list.json)
tl_path = cfg.zoology_dir / "taxonomy" / "assemblage-builds-tier-list.json"
builds_out: list[dict[str, Any]] = []
if tl_path.is_file():
tl_data = json.loads(tl_path.read_text(encoding="utf-8"))
for row in tl_data.get("rows", []):
s6 = row.get("stats_6") or {}
b_struct = {
"struct_isometric_armor": float(s6.get("ARM_chokepoint_armor", 70)),
"struct_drift_velocity": float(s6.get("VEL_teleoplexic_velocity", 70)),
"struct_variance_collapse": float(s6.get("COL_variance_collapse", 70)),
"struct_trophic_capture": float(s6.get("CAP_trophic_capture", 70)),
"struct_prime_density": float(s6.get("PRM_prime_mutation_iq", 70)),
"struct_repricing_resilience": float(s6.get("RES_repricing_resilience", 70)),
}
b_code = str(row.get("eval_file", "S1"))
g_prefix = b_code[:2]
matching_insts = [inst for inst in instruments_out if g_prefix in inst["guilds"]]
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_locks = sum(
len(inst["bars"][d_i]["scope1_locks"]) + len(inst["bars"][d_i]["scope2_ring_coordinates"])
for inst in matching_insts
for d_i in range(num_days)
) // max(1, len(matching_insts))
b_ts = compute_timeseries_moments(
daily_points=b_daily_pts,
active_flags=b_active,
wire_shares=b_wire_sh,
cap_shares=b_cap_sh,
expected_null_locks=round(num_days * 0.32, 2),
observed_locks=b_locks,
wire_vel_series=wire_vel_global,
abs_bps_series=b_abs_bps,
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),
),
)
builds_out.append({
"rank": row.get("rank"),
"build_code": b_code,
"title": row.get("title"),
"roster_slot": row.get("roster_slot"),
"base_composite_score": base_eti,
"live_timeseries_score": live_eti,
"structural_vector": b_struct,
"timeseries_moments": b_ts,
"lens_projections": apply_all_lenses(b_struct, b_ts, live_eti, active_lenses),
})
anchor_revision_series = [
{
"anchor_id": "lazarus_heist_6b",
"date_utc": "2026-11-01",
"symbol": "BTC-USD",
"q_old_digit": "$6B",
"q_new_digit": "$6B",
"coordinate": 211,
"description": "Lazarus $6B heist ('siks bilyan' = 211 [47th PRIME] == wor masheen == koper waier).",
},
{
"anchor_id": "anthropic_ipo_price_83_baseline",
"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.",
},
{
"anchor_id": "bangladesh_factories_481",
"date_utc": "2026-11-24",
"symbol": "TSM",
"q_old_digit": "481",
"q_new_digit": "841",
"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]).",
},
]
receipt = guard.audit_receipt()
bundle: dict[str, Any] = {
"$schema": "./schemas/v1/quant-timeseries.schema.json",
"$id": "urn:io:hyperstitionstud:schema:v1:quant-timeseries",
"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"),
"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,
},
"enabled_lenses": list(active_lenses),
"default_lens": DEFAULT_LENS if DEFAULT_LENS in active_lenses else active_lenses[0],
"lens_registry_meta": {
lid: {
"lens_id": LENS_REGISTRY[lid]["lens_id"],
"title": LENS_REGISTRY[lid]["title"],
"short_label": LENS_REGISTRY[lid]["short_label"],
"structural_labels": LENS_REGISTRY[lid]["structural_labels"],
"timeseries_labels": LENS_REGISTRY[lid]["timeseries_labels"],
}
for lid in active_lenses
},
"dates_utc": dates_utc,
"instruments": instruments_out,
"builds": builds_out,
"daily_wire_series": daily_wire_series,
"anchor_revision_series": anchor_revision_series,
"isolation_receipt": receipt,
}
bundle["ipld_dag_json_cidv1"] = {"/": compute_dag_json_cidv1(bundle)}
if write_files:
quant_site_dir = cfg.core_dir / "site" / "quant"
quant_site_dir.mkdir(parents=True, exist_ok=True)
json_path = quant_site_dir / "quant-timeseries.json"
js_path = quant_site_dir / "quant-timeseries-data.js"
write_pretty_and_dag_json(json_path, bundle)
js_content = (
"// Auto-generated synchronous time-series bundle for file:// and https:// portability\n"
"window.HyperstitionStudio = window.HyperstitionStudio || {};\n"
f"window.HyperstitionStudio.QuantTimeSeries = {json.dumps(bundle, ensure_ascii=False)};\n"
)
js_path.write_text(js_content, encoding="utf-8")
return bundle
+23 -4
View File
@@ -56,10 +56,6 @@ def get_version_targets(ws_root: Path | None = None) -> list[tuple[Path, list[tu
core / "workspace.example.toml",
[(rf'schema_version\s*=\s*"{SEMVER_RE}"', 'schema_version = "{V}"')],
),
(
cfg.workspace_root / "workspace.toml",
[(rf'schema_version\s*=\s*"{SEMVER_RE}"', 'schema_version = "{V}"')],
),
(
core / "site" / "index.html",
[
@@ -79,6 +75,19 @@ def get_version_targets(ws_root: Path | None = None) -> list[tuple[Path, list[tu
(rf'version:\s*"{SEMVER_RE}"', 'version: "{V}"'),
],
),
(
core / "site" / "quant" / "index.html",
[
(rf'urn:io:hyperstitionstud:quant-timeseries:v{SEMVER_RE}\)', "urn:io:hyperstitionstud:quant-timeseries:v{V})"),
(rf'hyperstitionstud\.io/quant v{SEMVER_RE}', "hyperstitionstud.io/quant v{V}"),
],
),
(
core / "site" / "quant" / "quant-app.js",
[
(rf'Time-Series Workbench \(v{SEMVER_RE}\)', "Time-Series Workbench (v{V})"),
],
),
(
core / "site" / "gallery" / "index.html",
[
@@ -140,6 +149,7 @@ def sync_workspace_version(target_version: str, check_only: bool = False, ws_roo
if not re.match(rf"^{SEMVER_RE}$", v):
raise ValueError(f"Invalid semantic version '{target_version}' (expected X.Y.Z)")
cfg = load_workspace_config(workspace_root=ws_root)
targets = get_version_targets(ws_root=ws_root)
modified_files: list[str] = []
mismatched_files: list[str] = []
@@ -161,6 +171,15 @@ def sync_workspace_version(target_version: str, check_only: bool = False, ws_roo
path.write_text(updated, encoding="utf-8")
modified_files.append(str(path))
if not check_only:
ws_toml = cfg.workspace_root / "workspace.toml"
if ws_toml.is_file():
orig_ws = ws_toml.read_text(encoding="utf-8")
upd_ws = re.sub(rf'schema_version\s*=\s*"{SEMVER_RE}"', f'schema_version = "{v}"', orig_ws, flags=re.M)
if upd_ws != orig_ws:
ws_toml.write_text(upd_ws, encoding="utf-8")
modified_files.append(str(ws_toml))
return {
"target_version": v,
"check_only": check_only,
+55 -1
View File
@@ -11,6 +11,7 @@ Tests:
from __future__ import annotations
import json
import re
import sys
from pathlib import Path
@@ -45,6 +46,7 @@ def test_offline_urn_namespaces_and_no_external_https_fonts() -> None:
for html_p in (
cfg.core_dir / "site" / "index.html",
cfg.core_dir / "site" / "learn" / "index.html",
cfg.core_dir / "site" / "quant" / "index.html",
cfg.core_dir / "site" / "gallery" / "index.html",
cfg.knowledge_graph_dir / "index.html",
cfg.knowledge_graph_dir / "docs" / "cross-repo-dependency-and-audit-flow-diagram.html",
@@ -183,7 +185,7 @@ def test_ipld_quant_and_mcp_server() -> None:
assert init_resp and init_resp["result"]["serverInfo"]["name"] == "hyperstitionstudio-mcp"
t_list = dispatch_jsonrpc({"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
assert t_list and len(t_list["result"]["tools"]) == 11
assert t_list and len(t_list["result"]["tools"]) == 12
t_call = dispatch_jsonrpc({
"jsonrpc": "2.0",
@@ -221,6 +223,58 @@ def test_ipld_quant_and_mcp_server() -> None:
})
assert p_get and len(p_get["result"]["messages"]) == 1
# 4. Periodic Time-Series Bundle, LENS_REGISTRY Reversibility & REST API v1 (/api/v1/*)
from hyperstitionstud_io.mcp.rest import dispatch_rest_v1
from hyperstitionstud_io.quant.timeseries import build_quant_timeseries_bundle
ts_full = build_quant_timeseries_bundle(write_files=False)
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
nvda_ts = next(x for x in ts_full["instruments"] if x["symbol"] == "NVDA")
assert nvda_ts["tradingview_symbol"] == "NASDAQ:NVDA"
assert "tradingview.com/chart/?symbol=NASDAQ%3ANVDA" in nvda_ts["tradingview_url"]
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"]
# 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"]
nvda_stripped = next(x for x in ts_stripped["instruments"] if x["symbol"] == "NVDA")
assert set(nvda_stripped["lens_projections"].keys()) == {"neutral_math", "fund_manager"}
assert "pokedex_profile" not in nvda_stripped
assert ts_stripped["isolation_receipt"]["all_unchanged"] is True
# Verify REST API v1 endpoints (/api/v1/*)
st_code, _, st_body = dispatch_rest_v1("GET", "/api/v1/status")
assert st_code == 200 and st_body["ok"] is True and st_body["isolation_verified"] is True
oa_code, _, oa_body = dispatch_rest_v1("GET", "/api/v1/openapi.json")
assert oa_code == 200 and oa_body["openapi"] == "3.1.0" and "/api/v1/ciphers/evaluate" in oa_body["paths"]
ev_code, _, ev_body = dispatch_rest_v1("GET", "/api/v1/ciphers/evaluate?terms=schizoanalysis,abstract%20machine,synthetic%20data")
assert ev_code == 200 and ev_body["data"]["exact_gen1_singularity"] is True
qi_code, _, qi_body = dispatch_rest_v1("GET", "/api/v1/quant/instruments/NVDA?raw=1")
assert qi_code == 200 and len(qi_body["instruments"]) == 1 and qi_body["instruments"][0]["symbol"] == "NVDA"
gn_code, _, gn_body = dispatch_rest_v1("GET", "/api/v1/graph/nodes/aq:125")
assert gn_code == 200 and gn_body["ok"] is True
pk_code, _, pk_body = dispatch_rest_v1("GET", "/api/v1/zoology/pokedex/NVDA")
assert pk_code == 200 and pk_body["data"]["instruments"][0]["pokedex_profile"]["dex_number"] == "DEX #137"
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
err_code, _, err_body = dispatch_rest_v1("GET", "/api/v1/ciphers/evaluate")
assert err_code == 422 and err_body["ok"] is False
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.15"
schema_version = "2.0.18"
namespace_urn = "urn:io:hyperstitionstud"
[paths]